USE [master]
GO
CREATE DATABASE [BASEDADOSEMPRESAGIDWIN] ON  PRIMARY 
( NAME = N'BASEDADOSEMPRESAGIDWIN_Data', FILENAME = N'DIRECTORIABASEGIDWINBASEDADOSEMPRESAGIDWIN\BASEDADOSEMPRESAGIDWIN_Data.MDF' , SIZE = 37824KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
 LOG ON 
( NAME = N'BASEDADOSEMPRESAGIDWIN_Log', FILENAME = N'DIRECTORIABASEGIDWINBASEDADOSEMPRESAGIDWIN\BASEDADOSEMPRESAGIDWIN_Log.LDF' , SIZE = 34752KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
GO
EXEC dbo.sp_dbcmptlevel @dbname=N'BASEDADOSEMPRESAGIDWIN', @new_cmptlevel=90
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
BEGIN
	EXEC [BASEDADOSEMPRESAGIDWIN].[sp_fulltext_database] @action = 'disable'
END
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET ANSI_NULLS OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET ANSI_PADDING OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET ARITHABORT OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET AUTO_SHRINK ON
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET  ENABLE_BROKER
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET  READ_WRITE
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET RECOVERY FULL
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET  MULTI_USER
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET PAGE_VERIFY TORN_PAGE_DETECTION
GO
ALTER DATABASE [BASEDADOSEMPRESAGIDWIN] SET DB_CHAINING OFF
GO
USE [BASEDADOSEMPRESAGIDWIN]
GO
/****** Object:  User [GIDWin]    Script Date: 04-11-2025 10:22:19 ******/
CREATE USER [GIDWin] WITHOUT LOGIN WITH DEFAULT_SCHEMA=[dbo]
ALTER ROLE [db_owner] ADD MEMBER [GIDWin]
/****** Object:  XmlSchemaCollection [XMLSC_declaracoesDARToGIDWin]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_declaracoesDARToGIDWin] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:attribute name="acao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="I" /><xsd:enumeration value="U" /></xsd:restriction></xsd:simpleType></xsd:attribute><xsd:element name="adicao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroAdicao" /><xsd:element ref="codigoPautal" /><xsd:element ref="designacao" /><xsd:element ref="adicionalRegimeB" minOccurs="0" /><xsd:element ref="paisOrigem" minOccurs="0" /><xsd:element ref="metodoPagamento" minOccurs="0" /><xsd:element ref="exportador" minOccurs="0" /><xsd:element ref="massaBruta" /><xsd:element ref="unidades" /><xsd:element ref="volumes" /><xsd:element ref="paisMoedaFatura" /><xsd:element ref="montante" /><xsd:element ref="paisMoedaCustosTransporte" /><xsd:element ref="custosTransporte" /><xsd:element ref="codigoBarras" minOccurs="0" /><xsd:element ref="numeroObjeto" minOccurs="0" /><xsd:element ref="documentosECertificados" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="adicionalRegime"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="3" /><xsd:enumeration value="C07" /><xsd:enumeration value="C08" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="adicionalRegimeB" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="3" /><xsd:enumeration value="F48" /><xsd:enumeration value="F49" /><xsd:enumeration value="4II" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="adicoes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="adicao" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="aeroportoOrigem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="80" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="armazemDTP" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoBarras" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoDeclarante"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoFollowUp" type="xsd:integer" /><xsd:element name="codigoIncidencia"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoMencao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPautal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="22" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPostalOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="condEntrega" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="condicaoEntrega" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="contacto"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="descricaoContacto" /><xsd:element ref="utilizadorContacto" /><xsd:element ref="dataContacto" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="contactos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="contacto" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="custosTransporte"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="dadosAWB"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="miniCPA" minOccurs="0" /><xsd:element ref="dataVoo" minOccurs="0" /><xsd:element ref="aeroportoOrigem" minOccurs="0" /><xsd:element ref="numeroVoo" minOccurs="0" /><xsd:element ref="posicaoAviao" minOccurs="0" /><xsd:element ref="tracking" minOccurs="0" /><xsd:element ref="tipoCarga" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="dadosEntidades"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroContaExpedidor" minOccurs="0" /><xsd:element ref="numeroContaDestinatario" minOccurs="0" /><xsd:element ref="nomeOriginalDestinatario" minOccurs="0" /><xsd:element ref="moradaOriginalDestinatario" minOccurs="0" /><xsd:element ref="localidadeOriginalDestinatario" minOccurs="0" /><xsd:element ref="codigoPostalOriginalDestinatario" minOccurs="0" /><xsd:element ref="localidadePostalOriginalDestinatario" minOccurs="0" /><xsd:element ref="referenciaExterna1" minOccurs="0" /><xsd:element ref="referenciaExterna2" minOccurs="0" /><xsd:element ref="shipID" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="dadosEspecificos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="locID" minOccurs="0" /><xsd:element ref="gateway" minOccurs="0" /><xsd:element ref="serviceLevel" minOccurs="0" /><xsd:element ref="portesAcc" minOccurs="0" /><xsd:element ref="portes" minOccurs="0" /><xsd:element ref="despachoAcc" minOccurs="0" /><xsd:element ref="freteOriginal" minOccurs="0" /><xsd:element ref="moedafreteOriginal" minOccurs="0" /><xsd:element ref="despesas" minOccurs="0" /><xsd:element ref="condicaoEntrega" minOccurs="0" /><xsd:element ref="nomeFicheiro" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="data" type="xsd:date" /><xsd:element name="dataContacto" type="xsd:dateTime" /><xsd:element name="dataDocumentoTransporte" type="xsd:date" nillable="true" /><xsd:element name="dataFim" type="xsd:dateTime" /><xsd:element name="dataFollowUp" type="xsd:dateTime" /><xsd:element name="dataInicio" type="xsd:dateTime" /><xsd:element name="dataVoo" type="xsd:date" nillable="true" /><xsd:element name="declaracao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="data" /><xsd:element ref="regimeIVA" /><xsd:element ref="adicionalRegime" /><xsd:element ref="regimeIOSS" minOccurs="0" /><xsd:element ref="natureza" /><xsd:element ref="documentoTransporte" /><xsd:element ref="exportador" minOccurs="0" /><xsd:element ref="importador" /><xsd:element ref="declarante" /><xsd:element ref="estancia" /><xsd:element ref="tipoDeclaracao" /><xsd:element ref="vossaReferencia" minOccurs="0" /><xsd:element ref="condEntrega" minOccurs="0" /><xsd:element ref="meioTransporte" minOccurs="0" /><xsd:element ref="localizacaoMercadorias" /><xsd:element ref="paisMoedaFatura" /><xsd:element ref="paisMoedaCustosTransporte" /><xsd:element ref="followUp" minOccurs="0" /><xsd:element ref="utilizadorNomeado" minOccurs="0" /><xsd:element ref="depositoTemporario" minOccurs="0" /><xsd:element ref="dadosEspecificos" minOccurs="0" /><xsd:element ref="dadosEntidades" minOccurs="0" /><xsd:element ref="dadosAWB" minOccurs="0" /><xsd:element ref="outrosDados" minOccurs="0" /><xsd:element ref="documentosECertificados" minOccurs="0" /><xsd:element ref="informacoesAdicionais" minOccurs="0" /><xsd:element ref="documentosPrecedentes" minOccurs="0" /><xsd:element ref="adicoes" /><xsd:element ref="incidencias" minOccurs="0" /><xsd:element ref="manifestos" minOccurs="0" /><xsd:element ref="followUps" minOccurs="0" /><xsd:element ref="contactos" minOccurs="0" /></xsd:sequence><xsd:attribute ref="acao" use="required" /></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="declaracoesDARToGIDWin"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="declaracao" minOccurs="0" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="declarante"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoDeclarante" /><xsd:element ref="estatuto" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="depositoTemporario"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroPDDT" minOccurs="0" /><xsd:element ref="numeroPDDTDEV" minOccurs="0" /><xsd:element ref="numeroTD" minOccurs="0" /><xsd:element ref="numeroACTM" minOccurs="0" /><xsd:element ref="numeroSequencia" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="descricao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="descricaoContacto"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="200" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="designacao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="260" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="despachoAcc" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="despesas" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="documento"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoDocumento" /><xsd:element ref="codigoDocumento" /><xsd:element ref="numeroDocumento" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="documentoPrecedente"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoDocumento" /><xsd:element ref="numeroDocumento" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="documentoTransporte"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="documentosECertificados"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="documento" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="documentosPrecedentes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="documentoPrecedente" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="dutyType" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="email" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="estancia"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="estatuto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="1" /><xsd:maxInclusive value="1" /><xsd:enumeration value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="exportador"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="nif" minOccurs="0" /><xsd:element ref="nome" /><xsd:element ref="morada" /><xsd:element ref="localidade" /><xsd:element ref="codigoPostal" /><xsd:element ref="localidadePostal" /><xsd:element ref="pais" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="followUp" type="xsd:integer" nillable="true" /><xsd:element name="followUpData"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoFollowUp" /><xsd:element ref="utilizadorFollowUp" /><xsd:element ref="dataFollowUp" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="followUps"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="followUpData" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="freteOriginal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="funcao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="3" /><xsd:enumeration value="FR1" /><xsd:enumeration value="FR5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="gateway" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="importador"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="nif" /><xsd:element ref="nome" /><xsd:element ref="morada" /><xsd:element ref="localidade" /><xsd:element ref="codigoPostal" /><xsd:element ref="localidadePostal" /><xsd:element ref="pais" /><xsd:element ref="telefone" minOccurs="0" /><xsd:element ref="email" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="incidencia"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoIncidencia" /><xsd:element ref="dataInicio" /><xsd:element ref="dataFim" /><xsd:element ref="observacoes" minOccurs="0" /><xsd:element ref="tipoIncidencia" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="incidencias"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="incidencia" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="informacoesAdicionais"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="mencao" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="locID" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidade"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadeOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadePostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadePostalOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localizacaoMercadorias"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoLocalizacao" /><xsd:element ref="qualificador" /><xsd:choice minOccurs="0"><xsd:element ref="armazemDTP" /><xsd:element ref="estancia" /></xsd:choice></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="manifesto"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoManifesto" /><xsd:element ref="paisManifesto" minOccurs="0" /><xsd:element ref="descricao" minOccurs="0" /><xsd:element ref="valor" /><xsd:element ref="paisMoedaManifesto" minOccurs="0" /><xsd:element ref="totalFatura" /><xsd:element ref="numeroCPA" minOccurs="0" /><xsd:element ref="peso" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="manifestos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="manifesto" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="massaBruta"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="meioTransporte" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="mencao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoMencao" /><xsd:element ref="texto" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="metodoPagamento" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="A" /><xsd:enumeration value="B" /><xsd:enumeration value="C" /><xsd:enumeration value="D" /><xsd:enumeration value="H" /><xsd:enumeration value="Y" /><xsd:enumeration value="Z" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="miniCPA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="moedafreteOriginal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="montante"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="morada"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="moradaOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="natureza"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nif"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nome"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nomeFicheiro" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nomeOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroACTM" type="xsd:integer" nillable="true" /><xsd:element name="numeroAdicao"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroCPA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroContaDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroContaExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroIdentificacaoIVA"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroObjeto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroPDDT" type="xsd:integer" nillable="true" /><xsd:element name="numeroPDDTDEV" type="xsd:integer" nillable="true" /><xsd:element name="numeroSequencia" type="xsd:int" nillable="true" /><xsd:element name="numeroTD" type="xsd:integer" nillable="true" /><xsd:element name="numeroVoo" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="observacoes" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="500" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="outrosDados"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="dutyType" minOccurs="0" /><xsd:element ref="payment" minOccurs="0" /><xsd:element ref="dataDocumentoTransporte" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="pais"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisManifesto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisMoedaCustosTransporte"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisMoedaFatura"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisMoedaManifesto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisOrigem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="payment" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="peso"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="portes" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="13" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="portesAcc" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="posicaoAviao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="13" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="qualificador"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="T" /><xsd:enumeration value="U" /><xsd:enumeration value="V" /><xsd:enumeration value="W" /><xsd:enumeration value="X" /><xsd:enumeration value="Y" /><xsd:enumeration value="Z" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="referenciaExterna1" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="referenciaExterna2" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="regimeIOSS"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="funcao" /><xsd:element ref="numeroIdentificacaoIVA" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="regimeIVA"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="1" /><xsd:maxInclusive value="3" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /><xsd:enumeration value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="serviceLevel" type="xsd:integer" nillable="true" /><xsd:element name="shipID" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="11" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="telefone" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="15" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="texto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="512" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoCarga" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoDeclaracao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="A" /><xsd:enumeration value="D" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoDocumento"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoIncidencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="R" /><xsd:enumeration value="H" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoLocalizacao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="A" /><xsd:enumeration value="B" /><xsd:enumeration value="C" /><xsd:enumeration value="D" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoManifesto"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="totalFatura"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tracking" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="unidades"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="utilizadorContacto"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="utilizadorFollowUp"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="utilizadorNomeado" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valor"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="volumes"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="vossaReferencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:schema>'
/****** Object:  XmlSchemaCollection [XMLSC_DeclaracoesExpToGIDWin]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_DeclaracoesExpToGIDWin] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:attribute name="Acao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="I" /><xsd:enumeration value="U" /></xsd:restriction></xsd:simpleType></xsd:attribute><xsd:element name="Adicao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="NumeroAdicao" /><xsd:element ref="CodArtigo" /><xsd:element ref="DesignacaoArtigo" /><xsd:element ref="CodPaisOrigem" minOccurs="0" /><xsd:element ref="MassaBruta" /><xsd:element ref="MassaLiquida" /><xsd:element ref="Regime" /><xsd:element ref="Desdobramento" minOccurs="0" /><xsd:element ref="QtdUnidades" /><xsd:element ref="ValorAdicao" /><xsd:element ref="ValorFrete" /><xsd:element ref="ValorSeguro" /><xsd:element ref="DocsPrecedentes" minOccurs="0" /><xsd:element ref="RegimesEconomicos" minOccurs="0" /><xsd:element ref="Documentos" minOccurs="0" /><xsd:element ref="MencoesEspeciais" minOccurs="0" /><xsd:element ref="MarcasEVolumes" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="AdicaoDocPrecedente"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Adicoes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Adicao" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Anotacoes" type="xsd:string" nillable="true" /><xsd:element name="Armazem"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodArmazem" /><xsd:element ref="CodTipoArmazem" /><xsd:element ref="CodEstadoMembro" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Arquivo"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="NomeArquivo" /><xsd:element ref="DescricaoArquivo" /><xsd:element ref="TipoArquivo" minOccurs="0" /><xsd:element ref="OrigemArquivo" /><xsd:element ref="FicheiroBase64" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Arquivos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Arquivo" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="CampoExtra"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodigoCampoExtra" /><xsd:element ref="ValorCampoExtra" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="CamposExtra"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CampoExtra" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="CodAeroporto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodArmazem"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodArtigo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="22" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodArtigoPautal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="22" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodClienteServico" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodCondEntrega" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodEstadoMembro"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodEstancia30" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodEstanciaA"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodEstanciaTAC"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodEstanciaTN" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodLocalAutorizado" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodLocalEmbarque" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="25" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodMeioTransporte" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodMeioTransporte25" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodMeioTransporte26" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodMencao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodNatureza"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodNaturezaTransacao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodNaturezaVols"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodOperador"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais15A" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais17A" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisOrigem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPostal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPostalExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodStatusIncidencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="4" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodTipoArmazem"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodTipoDeclaracao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="4" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodUnidMedida"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Codigo" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodigoCampoExtra"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Contentor"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="NumeroContentor" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Contentores"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Contentor" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DadosManifesto"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodExpedidor" minOccurs="0" /><xsd:element ref="NomeExpedidor" minOccurs="0" /><xsd:element ref="MoradaExpedidor" minOccurs="0" /><xsd:element ref="LocalidadeExpedidor" minOccurs="0" /><xsd:element ref="CodPostalExpedidor" minOccurs="0" /><xsd:element ref="LocPostalExpedidor" minOccurs="0" /><xsd:element ref="CodPaisExpedidor" minOccurs="0" /><xsd:element ref="NIFExpedidor" minOccurs="0" /><xsd:element ref="CodDestinatario" minOccurs="0" /><xsd:element ref="NomeDestinatario" minOccurs="0" /><xsd:element ref="MoradaDestinatario" minOccurs="0" /><xsd:element ref="LocalidadeDestinatario" minOccurs="0" /><xsd:element ref="CodPaisDestinatario" minOccurs="0" /><xsd:element ref="Montante" minOccurs="0" /><xsd:element ref="CodPais" minOccurs="0" /><xsd:element ref="MassaLiqTotal" minOccurs="0" /><xsd:element ref="MassaBrtTotal" minOccurs="0" /><xsd:element ref="MiniCPA" minOccurs="0" /><xsd:element ref="DutyType" minOccurs="0" /><xsd:element ref="NomeFicheiro" minOccurs="0" /><xsd:element ref="PPouFC" minOccurs="0" /><xsd:element ref="NumeroVoo" minOccurs="0" /><xsd:element ref="Referencia1" minOccurs="0" /><xsd:element ref="Referencia2" minOccurs="0" /><xsd:element ref="Tracking" minOccurs="0" /><xsd:element ref="Shipping" minOccurs="0" /><xsd:element ref="VolsDirty" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Data" type="xsd:date" /><xsd:element name="DataDocumento" type="xsd:date" nillable="true" /><xsd:element name="DataEmissao" type="xsd:date" nillable="true" /><xsd:element name="DataFimValidade" type="xsd:date" nillable="true" /><xsd:element name="DataVoo" type="xsd:date" nillable="true" /><xsd:element name="Declaracao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="TipoProcedimento" /><xsd:element ref="CodNatureza" /><xsd:element ref="CodOperador" /><xsd:element ref="Data" /><xsd:element ref="VossaReferencia" minOccurs="0" /><xsd:element ref="CodEstanciaA" /><xsd:element ref="CodStatusIncidencia" minOccurs="0" /><xsd:element ref="CodTipoDeclaracao" /><xsd:element ref="NumeroCPA" minOccurs="0" /><xsd:element ref="TipoCarga" minOccurs="0" /><xsd:element ref="DataVoo" minOccurs="0" /><xsd:element ref="Expedidor" /><xsd:element ref="CodClienteServico" minOccurs="0" /><xsd:element ref="NumeroComercialRef" minOccurs="0" /><xsd:element ref="Destinatario" /><xsd:element ref="CodPais15A" minOccurs="0" /><xsd:element ref="CodPais17A" minOccurs="0" /><xsd:element ref="ICE" minOccurs="0" /><xsd:element ref="MeioTransportePartida" minOccurs="0" /><xsd:element ref="MeioTransporteFronteira" minOccurs="0" /><xsd:element ref="CodEstanciaTAC" /><xsd:element ref="CodEstanciaTN" minOccurs="0" /><xsd:element ref="LocalizacaoMercadorias" minOccurs="0" /><xsd:element ref="CodLocalEmbarque" minOccurs="0" /><xsd:element ref="CodCondEntrega" minOccurs="0" /><xsd:element ref="Lugar" minOccurs="0" /><xsd:element ref="CodNaturezaTransacao" minOccurs="0" /><xsd:element ref="CodPais" /><xsd:element ref="TotalFrete" /><xsd:element ref="TotalSeguro" /><xsd:element ref="HVLV" minOccurs="0" /><xsd:element ref="Origem" minOccurs="0" /><xsd:element ref="Anotacoes" minOccurs="0" /><xsd:element ref="CamposExtra" minOccurs="0" /><xsd:element ref="DadosManifesto" minOccurs="0" /><xsd:element ref="Contentores" minOccurs="0" /><xsd:element ref="Adicoes" /><xsd:element ref="Arquivos" minOccurs="0" /></xsd:sequence><xsd:attribute ref="Acao" use="required" /></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DeclaracoesExpToGIDWin"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Declaracao" minOccurs="0" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DescricaoArquivo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Desdobramento" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DesignacaoArtigo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Destinatario" type="EstruturaDadosEntidade" /><xsd:element name="DocPrecedente"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Tipo" /><xsd:element ref="CodDocumento" /><xsd:element ref="RefDocumento" /><xsd:element ref="CodPais" /><xsd:element ref="DataDocumento" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DocsPrecedentes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="DocPrecedente" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Documento"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodDocumento" /><xsd:element ref="NumeroReferencia" minOccurs="0" /><xsd:element ref="DataEmissao" minOccurs="0" /><xsd:element ref="DataFimValidade" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Documentos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Documento" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DutyType" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Expedidor" type="EstruturaDadosEntidade" /><xsd:element name="FicheiroBase64" type="xsd:string" /><xsd:element name="HVLV" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ICE" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="1" /><xsd:enumeration value="A" /><xsd:enumeration value="B" /><xsd:enumeration value="E" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocPostal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocPostalExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Localidade" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocalidadeDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocalidadeExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocalizacaoMercadorias"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:choice><xsd:element ref="CodEstancia30" minOccurs="0" /><xsd:element ref="CodLocalEmbarque" minOccurs="0" /><xsd:element ref="CodLocalAutorizado" minOccurs="0" /><xsd:element ref="OutroLocal" minOccurs="0" /><xsd:element ref="Armazem" minOccurs="0" /></xsd:choice></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Lugar" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Marca"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="44" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MarcaEVolume"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Marca" minOccurs="0" /><xsd:element ref="CodNaturezaVols" /><xsd:element ref="NumeroVols" /><xsd:element ref="P" /><xsd:element ref="R" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="MarcasEVolumes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="MarcaEVolume" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="MassaBrtTotal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MassaBruta"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MassaLiqTotal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MassaLiquida"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MatriculaMT" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="27" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MeioTransporteFronteira"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodMeioTransporte" minOccurs="0" /><xsd:element ref="MatriculaMT" minOccurs="0" /><xsd:element ref="TipoMT" minOccurs="0" /><xsd:element ref="CodPais" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="MeioTransportePartida"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodMeioTransporte" minOccurs="0" /><xsd:element ref="MatriculaMT" minOccurs="0" /><xsd:element ref="TipoMT" minOccurs="0" /><xsd:element ref="CodMeioTransporte25" minOccurs="0" /><xsd:element ref="CodMeioTransporte26" minOccurs="0" /><xsd:element ref="CodAeroporto" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="MencaoEspecial"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodMencao" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="MencoesEspeciais"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="MencaoEspecial" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="MiniCPA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Montante" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Morada"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MoradaDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MoradaExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NIF" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NIFExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Nome"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeArquivo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeFicheiro" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroAdicao"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroCPA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroComercialRef" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroContentor"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroDocPrecedente"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroReferencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroVols"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroVoo" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Origem" type="xsd:int" nillable="true" /><xsd:element name="OrigemArquivo"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="OutroLocal"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Morada" /><xsd:element ref="CodPostal" minOccurs="0" /><xsd:element ref="LocPostal" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="P" type="xsd:boolean" /><xsd:element name="PPouFC" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="QtdUnidades"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Quantidade"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="R" type="xsd:boolean" /><xsd:element name="RefDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Referencia1" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Referencia2" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Regime"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="4" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="RegimeEconomico"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="NumeroDocPrecedente" /><xsd:element ref="AdicaoDocPrecedente" /><xsd:element ref="CodArtigoPautal" /><xsd:element ref="Quantidade" /><xsd:element ref="CodUnidMedida" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="RegimesEconomicos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="RegimeEconomico" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Shipping" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="11" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Tipo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="Y" /><xsd:enumeration value="Z" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TipoArquivo" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /><xsd:enumeration value="FATURA" /><xsd:enumeration value="FTINTERN" /><xsd:enumeration value="DOCTRANS" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TipoCarga" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TipoMT" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /><xsd:enumeration value="VA" /><xsd:enumeration value="EM" /><xsd:enumeration value="AE" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TipoProcedimento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="A" /><xsd:enumeration value="B" /><xsd:enumeration value="C" /><xsd:enumeration value="D" /><xsd:enumeration value="E" /><xsd:enumeration value="F" /><xsd:enumeration value="X" /><xsd:enumeration value="Y" /><xsd:enumeration value="Z" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TotalFrete"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TotalSeguro"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Tracking" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ValorAdicao"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ValorCampoExtra"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2500" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ValorFrete"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ValorSeguro"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="VolsDirty" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="VossaReferencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:complexType name="EstruturaDadosEntidade"><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Codigo" minOccurs="0" /><xsd:element ref="Nome" /><xsd:element ref="Morada" /><xsd:element ref="Localidade" minOccurs="0" /><xsd:element ref="CodPostal" minOccurs="0" /><xsd:element ref="LocPostal" minOccurs="0" /><xsd:element ref="NIF" minOccurs="0" /><xsd:element ref="CodPais" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:schema>'
/****** Object:  XmlSchemaCollection [XMLSC_DeclaracoesIMPCAUToGIDWin]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_DeclaracoesIMPCAUToGIDWin] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:attribute name="acao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="I" /><xsd:enumeration value="U" /></xsd:restriction></xsd:simpleType></xsd:attribute><xsd:element name="adicao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroAdicao" /><xsd:element ref="codigoPautal" /><xsd:element ref="designacao" /><xsd:element ref="regimeAdicional" minOccurs="0" /><xsd:element ref="paisOrigem" minOccurs="0" /><xsd:element ref="preferencia" minOccurs="0" /><xsd:element ref="metodoAvaliacao" minOccurs="0" /><xsd:element ref="massaLiquida" /><xsd:element ref="massaBruta" /><xsd:element ref="unidades" minOccurs="0" /><xsd:element ref="montanteAd" /><xsd:element ref="valorFrete" minOccurs="0" /><xsd:element ref="valorSeguro" minOccurs="0" /><xsd:element ref="taxaIVA" minOccurs="0" /><xsd:element ref="documentosECertificados" minOccurs="0" /><xsd:element ref="documentosPrecedentes" minOccurs="0" /><xsd:element ref="pedidos" minOccurs="0" /><xsd:element ref="marcasEVolumes" minOccurs="0" /><xsd:element ref="contentores" minOccurs="0" /><xsd:element ref="veiculos" minOccurs="0" /></xsd:sequence><xsd:attribute ref="acao" /></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="adicionalISV" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="4" /><xsd:enumeration value="1600" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="adicoes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="adicao" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="aeroportoOrigem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="80" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="anexoB"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="2" /><xsd:enumeration value="H1" /><xsd:enumeration value="H2" /><xsd:enumeration value="H3" /><xsd:enumeration value="H4" /><xsd:enumeration value="H5" /><xsd:enumeration value="H6" /><xsd:enumeration value="I1" /><xsd:enumeration value="I2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="anotacoes" type="xsd:string" nillable="true" /><xsd:element name="armazem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="armazemDTP" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="arquivo"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="nomeArquivo" /><xsd:element ref="descricaoArquivo" /><xsd:element ref="tipoArquivo" /><xsd:element ref="origemArquivo" /><xsd:element ref="ficheiroBase64" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="arquivos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="arquivo" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="autonomia" type="xsd:int" nillable="true" /><xsd:element name="campoExtra"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoCampoExtra" /><xsd:element ref="valorCampoExtra" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="camposExtra"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="campoExtra" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="categoria" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="chassi"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="matricula" minOccurs="0" /><xsd:element ref="dataMatricula" minOccurs="0" /><xsd:element ref="numeroChassi" minOccurs="0" /><xsd:element ref="dataChassi" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="chassis"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="chassi" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="cilindrada" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="co2" type="xsd:int" nillable="true" /><xsd:element name="codigoBarras" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoCampoExtra"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoDeclarante"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoFollowUp" type="xsd:int" /><xsd:element name="codigoIncidencia"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPautal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="22" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPedido"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPostalOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="combustivel" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="condEntrega" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="condicaoEntrega"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="contacto"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="descricaoContacto" /><xsd:element ref="utilizador" /><xsd:element ref="dataHora" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="contactos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="contacto" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="contentor"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroContentor" /><xsd:element ref="tipoContentor" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="contentores"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="contentor" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="contentorizada"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="1" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="dadosAWB"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="miniCPA" minOccurs="0" /><xsd:element ref="dataVoo" minOccurs="0" /><xsd:element ref="aeroportoOrigem" minOccurs="0" /><xsd:element ref="numeroVoo" minOccurs="0" /><xsd:element ref="posicaoAviao" minOccurs="0" /><xsd:element ref="tracking" minOccurs="0" /><xsd:element ref="tipoCarga" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="dadosEntidades"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroContaExpedidor" minOccurs="0" /><xsd:element ref="numeroContaDestinatario" minOccurs="0" /><xsd:element ref="nomeOriginalDestinatario" minOccurs="0" /><xsd:element ref="moradaOriginalDestinatario" minOccurs="0" /><xsd:element ref="localidadeOriginalDestinatario" minOccurs="0" /><xsd:element ref="codigoPostalOriginalDestinatario" minOccurs="0" /><xsd:element ref="localidadePostalOriginalDestinatario" minOccurs="0" /><xsd:element ref="referenciaExterna1" minOccurs="0" /><xsd:element ref="referenciaExterna2" minOccurs="0" /><xsd:element ref="shipID" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="dadosEspecificos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="locID" minOccurs="0" /><xsd:element ref="gateway" minOccurs="0" /><xsd:element ref="serviceLevel" minOccurs="0" /><xsd:element ref="portesAcc" minOccurs="0" /><xsd:element ref="portes" minOccurs="0" /><xsd:element ref="despachoAcc" minOccurs="0" /><xsd:element ref="freteOriginal" minOccurs="0" /><xsd:element ref="moedafreteOriginal" minOccurs="0" /><xsd:element ref="despesas" minOccurs="0" /><xsd:element ref="condEntrega" minOccurs="0" /><xsd:element ref="nomeFicheiro" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="data" type="xsd:date" /><xsd:element name="dataChassi" type="xsd:date" nillable="true" /><xsd:element name="dataDocumentoTransporte" type="xsd:date" nillable="true" /><xsd:element name="dataEntrada" type="xsd:date" nillable="true" /><xsd:element name="dataFim" type="xsd:dateTime" /><xsd:element name="dataHora" type="xsd:dateTime" /><xsd:element name="dataInicio" type="xsd:dateTime" /><xsd:element name="dataMatricula" type="xsd:date" nillable="true" /><xsd:element name="dataValidade" type="xsd:date" nillable="true" /><xsd:element name="dataVoo" type="xsd:date" nillable="true" /><xsd:element name="declaracao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="data" /><xsd:element ref="despachoCentralizado" /><xsd:element ref="anexoB" /><xsd:element ref="natureza" /><xsd:element ref="documentoTransporte" minOccurs="0" /><xsd:element ref="descricaoGenerica" minOccurs="0" /><xsd:element ref="operadores" /><xsd:element ref="vossaReferencia" minOccurs="0" /><xsd:element ref="estancia" /><xsd:element ref="tipoDeclaracao" /><xsd:element ref="naturezaTransacao" minOccurs="0" /><xsd:element ref="condicaoEntrega" /><xsd:choice minOccurs="0"><xsd:element ref="localizacao" /><xsd:element ref="portoAeroporto" /></xsd:choice><xsd:element ref="totais" /><xsd:element ref="transporte" /><xsd:element ref="localizacaoMercadorias" minOccurs="0" /><xsd:element ref="armazem" minOccurs="0" /><xsd:element ref="dadosEspecificos" minOccurs="0" /><xsd:element ref="depositoTemporario" minOccurs="0" /><xsd:element ref="dadosAWB" minOccurs="0" /><xsd:element ref="dadosEntidades" minOccurs="0" /><xsd:element ref="outrosDados" minOccurs="0" /><xsd:element ref="anotacoes" minOccurs="0" /><xsd:element ref="followUp" minOccurs="0" /><xsd:element ref="camposExtra" minOccurs="0" /><xsd:element ref="documentosECertificados" minOccurs="0" /><xsd:element ref="documentosPrecedentes" minOccurs="0" /><xsd:element ref="pedidos" minOccurs="0" /><xsd:element ref="adicoes" /><xsd:element ref="incidencias" minOccurs="0" /><xsd:element ref="followUps" minOccurs="0" /><xsd:element ref="contactos" minOccurs="0" /><xsd:element ref="manifestos" minOccurs="0" /><xsd:element ref="arquivos" minOccurs="0" /></xsd:sequence><xsd:attribute ref="acao" use="required" /></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="declaracoesIMPToGIDWin"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="declaracao" minOccurs="0" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="declarante"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoDeclarante" /><xsd:element ref="estatuto" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="depositoTemporario"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroPDDT" minOccurs="0" /><xsd:element ref="dataEntrada" minOccurs="0" /><xsd:element ref="numeroPDDTDEV" minOccurs="0" /><xsd:element ref="numeroTD" minOccurs="0" /><xsd:element ref="numeroACTM" minOccurs="0" /><xsd:element ref="numeroSequencia" minOccurs="0" /><xsd:element ref="posicaoArmazem" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="descricao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="104" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="descricaoArquivo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="descricaoContacto"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="200" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="descricaoGenerica" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="40" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="designacao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="despachoAcc" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="despachoCentralizado" type="xsd:boolean" /><xsd:element name="despesas" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="documento"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoDocumento" /><xsd:element ref="codigoDocumento" /><xsd:element ref="numeroDocumento" minOccurs="0" /><xsd:element ref="qualificadorDC" minOccurs="0" /><xsd:element ref="dataValidade" minOccurs="0" /><xsd:element ref="pais" minOccurs="0" /><xsd:element ref="montante" minOccurs="0" /><xsd:element ref="entidadeEmissora" minOccurs="0" /><xsd:element ref="unidadeMedida" minOccurs="0" /><xsd:element ref="quantidade" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="documentoIMT" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="5" /><xsd:enumeration value="G1HTV" /><xsd:enumeration value="G1CHV" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="documentoPrecedente"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoDocumento" /><xsd:element ref="numeroDocumento" /><xsd:element ref="qualificadorDC" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="documentoTransporte" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="documentosECertificados"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="documento" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="documentosPrecedentes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="documentoPrecedente" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="dutyType" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="email" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="200" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="endereco"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="morada" /><xsd:element ref="localidade" /><xsd:element ref="codigoPostal" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="entidadeEmissora" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="estancia"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="estatuto" type="xsd:int" nillable="true" /><xsd:element name="exportador"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="nif" minOccurs="0" /><xsd:element ref="nome" /><xsd:element ref="morada" /><xsd:element ref="localidade" /><xsd:element ref="codigoPostal" /><xsd:element ref="localidadePostal" /><xsd:element ref="pais" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="fatura"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="pais" /><xsd:element ref="valorTotal" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="ficheiroBase64" type="xsd:string" /><xsd:element name="followUp"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoFollowUp" /><xsd:element ref="utilizadorNomeado" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="followUpData"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoFollowUp" /><xsd:element ref="utilizador" /><xsd:element ref="dataHora" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="followUps"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="followUpData" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="frete"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="pais" /><xsd:element ref="valorTotal" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="freteOriginal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="fronteira"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="meioTransporte" /><xsd:element ref="pais" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="gateway" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="homologacaoTecnica" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="identificacao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="importador"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="nif" /><xsd:element ref="tipoNIF" /><xsd:element ref="nome" /><xsd:element ref="morada" /><xsd:element ref="localidade" /><xsd:element ref="codigoPostal" /><xsd:element ref="localidadePostal" /><xsd:element ref="pais" /><xsd:element ref="telefone" minOccurs="0" /><xsd:element ref="email" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="incidencia"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoIncidencia" /><xsd:element ref="dataInicio" /><xsd:element ref="dataFim" /><xsd:element ref="observacoes" minOccurs="0" /><xsd:element ref="tipoIncidencia" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="incidencias"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="incidencia" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="locID" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidade"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadeCE"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadeOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadePostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadePostalOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localizacao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="localidadeCE" /><xsd:element ref="paisCE" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="localizacaoMercadorias"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoLocalizacao" /><xsd:element ref="qualificador" minOccurs="0" /><xsd:choice minOccurs="0"><xsd:element ref="armazemDTP" /><xsd:element ref="estancia" /><xsd:element ref="nifOperadorEconomico" /><xsd:element ref="endereco" /></xsd:choice></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="manifesto"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoManifesto" /><xsd:element ref="paisManifesto" minOccurs="0" /><xsd:element ref="descricao" minOccurs="0" /><xsd:element ref="valor" /><xsd:element ref="paisMoeda" minOccurs="0" /><xsd:element ref="totalFatura" /><xsd:element ref="numeroCPA" minOccurs="0" /><xsd:element ref="pesoBruto" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="manifestos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="manifesto" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="marca"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="marcaEVolume"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="unidadeMedida" minOccurs="0" /><xsd:element ref="volumes" /><xsd:element ref="marcas" minOccurs="0" /><xsd:element ref="numeroObjeto" minOccurs="0" /><xsd:element ref="codigoBarras" minOccurs="0" /><xsd:element ref="parte" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="marcas" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="512" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="marcasEVolumes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="marcaEVolume" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="massaBruta"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="massaLiquida"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="matricula" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="meioTransporte"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="meioTransporteChegada"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="meioTransporteInterior" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="metodoAvaliacao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /><xsd:maxInclusive value="6" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /><xsd:enumeration value="3" /><xsd:enumeration value="4" /><xsd:enumeration value="5" /><xsd:enumeration value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="miniCPA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="modelo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="moedafreteOriginal" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="montante" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="montanteAd"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="morada"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="moradaOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="natureza"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="naturezaTransacao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nif"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nifOperadorEconomico" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nome"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nomeArquivo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nomeFicheiro" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nomeOriginalDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroACTM" type="xsd:int" nillable="true" /><xsd:element name="numeroAdicao"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroCPA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroChassi" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="22" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroContaDestinatario" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroContaExpedidor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroContentor"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroDURetorno" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroNRUR" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroObjeto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroPDDT" type="xsd:int" nillable="true" /><xsd:element name="numeroPDDTDEV" type="xsd:int" nillable="true" /><xsd:element name="numeroPedido" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="512" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroRequerimento" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroSequencia" type="xsd:int" nillable="true" /><xsd:element name="numeroT1Retorno" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroTD" type="xsd:int" nillable="true" /><xsd:element name="numeroVoo" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="observacoes" type="xsd:string" nillable="true" /><xsd:element name="operadores"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="exportador" minOccurs="0" /><xsd:element ref="paisExpedicao" minOccurs="0" /><xsd:element ref="importador" /><xsd:element ref="paisDestino" /><xsd:element ref="regiao" minOccurs="0" /><xsd:element ref="declarante" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="origemArquivo"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="outrosDados"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="dutyType" minOccurs="0" /><xsd:element ref="payment" minOccurs="0" /><xsd:element ref="dataDocumentoTransporte" minOccurs="0" /><xsd:element ref="numeroRequerimento" minOccurs="0" /><xsd:element ref="numeroDURetorno" minOccurs="0" /><xsd:element ref="numeroT1Retorno" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="pais"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisCE"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisDestino"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisExpedicao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisManifesto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisMoeda" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="paisOrigem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="parte" type="xsd:boolean" /><xsd:element name="particulas" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="payment" type="xsd:int" nillable="true" /><xsd:element name="pedido"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoPedido" /><xsd:element ref="numeroPedido" minOccurs="0" /><xsd:element ref="qualificadorDC" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="pedidos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="pedido" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="pesoBruto"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="pesos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="massaLiquida" /><xsd:element ref="massaBruta" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="portes" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="13" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="portesAcc" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="portoAeroporto" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="posicaoArmazem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="4" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="posicaoAviao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="13" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="preferencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="qualificador"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="T" /><xsd:enumeration value="U" /><xsd:enumeration value="V" /><xsd:enumeration value="X" /><xsd:enumeration value="Y" /><xsd:enumeration value="Z" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="qualificadorDC" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="qualificadorV" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="1" /><xsd:enumeration value="N" /><xsd:enumeration value="U" /><xsd:enumeration value="A" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="quantidade" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="referenciaExterna1" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="referenciaExterna2" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="regiao" type="xsd:int" nillable="true" /><xsd:element name="regimeAdicional" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="seguro"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="pais" /><xsd:element ref="valorTotal" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="serviceLevel" type="xsd:int" nillable="true" /><xsd:element name="shipID" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="11" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tabela" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="1" /><xsd:enumeration value="A" /><xsd:enumeration value="B" /><xsd:enumeration value="C" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="taxaIVA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="telefone" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="14" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoArquivo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /><xsd:enumeration value="OUTRO" /><xsd:enumeration value="FATURA" /><xsd:enumeration value="FTINTERN" /><xsd:enumeration value="NC" /><xsd:enumeration value="ND" /><xsd:enumeration value="OR" /><xsd:enumeration value="DOCTRANS" /><xsd:enumeration value="DOCTRANT" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoCO2"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="4" /><xsd:enumeration value="NEDC" /><xsd:enumeration value="WLTP" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoCarga" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoContentor" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /><xsd:enumeration value="22GP" /><xsd:enumeration value="42GP" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoDeclaracao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="4" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoDocumento"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoIncidencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="R" /><xsd:enumeration value="H" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoLocalizacao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="A" /><xsd:enumeration value="B" /><xsd:enumeration value="C" /><xsd:enumeration value="D" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoManifesto"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoNIF"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="6" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /><xsd:enumeration value="3" /><xsd:enumeration value="4" /><xsd:enumeration value="5" /><xsd:enumeration value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoVeiculo" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="totais"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="fatura" /><xsd:element ref="frete" /><xsd:element ref="seguro" /><xsd:element ref="pesos" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="totalFatura"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tracking" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="transporte"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroNRUR" minOccurs="0" /><xsd:element ref="fronteira" minOccurs="0" /><xsd:element ref="meioTransporteInterior" minOccurs="0" /><xsd:element ref="meioTransporteChegada" /><xsd:element ref="identificacao" minOccurs="0" /><xsd:element ref="contentorizada" /><xsd:element ref="numeroContentor" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="unidadeMedida" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="unidades" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="utilizador"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="utilizadorNomeado" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valor"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valorCampoExtra"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2500" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valorFrete" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valorISV" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valorSeguro" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valorTotal"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="3" /><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="veiculo"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="homologacaoTecnica" minOccurs="0" /><xsd:element ref="adicionalISV" minOccurs="0" /><xsd:element ref="tabela" minOccurs="0" /><xsd:element ref="marca" /><xsd:element ref="modelo" /><xsd:element ref="qualificadorV" minOccurs="0" /><xsd:element ref="categoria" minOccurs="0" /><xsd:element ref="tipoVeiculo" minOccurs="0" /><xsd:element ref="combustivel" minOccurs="0" /><xsd:element ref="cilindrada" minOccurs="0" /><xsd:element ref="co2" minOccurs="0" /><xsd:element ref="tipoCO2" minOccurs="0" /><xsd:element ref="particulas" minOccurs="0" /><xsd:element ref="autonomia" minOccurs="0" /><xsd:element ref="documentoIMT" minOccurs="0" /><xsd:element ref="valorISV" minOccurs="0" /><xsd:element ref="chassis" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="veiculos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="veiculo" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="volumes"><xsd:simpleType><xsd:restriction base="xsd:integer"><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="vossaReferencia" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:schema>'
/****** Object:  XmlSchemaCollection [XMLSC_DeclaracoesImpToDARP]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_DeclaracoesImpToDARP] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:element name="DARP"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="cabecalho" /><xsd:element ref="adicoes" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Loptica" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="accao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="I" /><xsd:enumeration value="U" /><xsd:enumeration value="D" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="adicao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroAdicao" /><xsd:element ref="codigoMercadorias" /><xsd:element ref="designacaoMercadorias" /><xsd:element ref="preferencia" /><xsd:element ref="codigoPaisOrigem" /><xsd:element ref="volume" maxOccurs="unbounded" /><xsd:element ref="documentosCertificados" /><xsd:element ref="liquidacaoDefinitiva" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="adicoes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="adicao" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="baseTributacao"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="cabecalho"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="accao" /><xsd:element ref="utilizadorCriacao" /><xsd:element ref="numeroLocalObjecto" /><xsd:element ref="nomePDF" minOccurs="0" /><xsd:element ref="numeroReferenciaLocal" /><xsd:element ref="numeroRegistoLiquidacao" minOccurs="0" /><xsd:element ref="numeroOrdem" /><xsd:element ref="dataNumeroOrdem" /><xsd:element ref="dataAutorizacaoSaida" /><xsd:element ref="natureza" /><xsd:element ref="numeroTotalAdicoes" /><xsd:element ref="numeroTotalVolumes" /><xsd:element ref="totalDespesas" /><xsd:element ref="totalVDA" /><xsd:element ref="totalRecapitulativo" /><xsd:element ref="montante" /><xsd:element ref="frete" minOccurs="0" /><xsd:element ref="seguro" minOccurs="0" /><xsd:element ref="destinatario" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="codigoMencao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoMercadorias"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="22" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoMoedaFacturacao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoMoedaFrete"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoMoedaSeguro"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPaisOrigem"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="dataAutorizacaoSaida" type="xsd:date" /><xsd:element name="dataNumeroOrdem" type="xsd:date" /><xsd:element name="descricaoRubrica"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="designacaoMercadorias"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="destinatario"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numeroIdentificacao" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="documentosCertificados"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="mencaoEspecial" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="frete"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoMoedaFrete" /><xsd:element ref="montanteFrete" /><xsd:element ref="taxaCambio" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="imposicoes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="rubricaReceita" /><xsd:element ref="descricaoRubrica" /><xsd:element ref="tipoImposicao" /><xsd:element ref="baseTributacao" /><xsd:element ref="taxaImposicao" /><xsd:element ref="montanteImposicao" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="liquidacaoDefinitiva"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="imposicoes" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="marca"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="mencaoEspecial"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoMencao" /><xsd:element ref="montanteVDA" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="montante"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoMoedaFacturacao" /><xsd:element ref="montanteTotalFacturado" /><xsd:element ref="taxaCambio" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="montanteFrete"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="montanteImposicao"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="montanteSeguro"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="montanteTotalFacturado"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="montanteVDA"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="natureza"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="naturezaVolumes"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nomePDF" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroAdicao"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /><xsd:maxInclusive value="2147483647" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroIdentificacao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroLocalObjecto"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="objecto" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="numeroOrdem"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroReferenciaLocal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="22" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroRegistoLiquidacao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroTotalAdicoes"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /><xsd:maxInclusive value="2147483647" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeroTotalVolumes"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /><xsd:maxInclusive value="2147483647" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numeros"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="objecto"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="preferencia"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="quantidadeMercadoria"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /><xsd:maxInclusive value="2147483647" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="rubricaReceita"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="seguro"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoMoedaSeguro" /><xsd:element ref="montanteSeguro" /><xsd:element ref="taxaCambio" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="taxaCambio"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:maxInclusive value="2147483647" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="taxaImposicao"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="4" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoImposicao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="totalDespesas"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="totalRecapitulativo"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="totalVDA"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2147483647" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="utilizadorCriacao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="volume"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="marca" /><xsd:element ref="numeros" /><xsd:element ref="Loptica" minOccurs="0" /><xsd:element ref="naturezaVolumes" /><xsd:element ref="quantidadeMercadoria" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element></xsd:schema>'
/****** Object:  XmlSchemaCollection [XMLSC_DeclaracoesImpToGIDWin]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_DeclaracoesImpToGIDWin] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"><xsd:attribute name="Acao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="I" /><xsd:enumeration value="U" /></xsd:restriction></xsd:simpleType></xsd:attribute><xsd:element name="Adicao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="NumAdicao"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodArtigoPautal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="22" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Designacao" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisOrigem" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPreferencia" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="RegimeB" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MassaBruta"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MassaLiquida"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="QtdUnidades" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="PrecoAdicao"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Frete" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Seguro" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MetodoAvaliacao" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /><xsd:maxInclusive value="6" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /><xsd:enumeration value="3" /><xsd:enumeration value="4" /><xsd:enumeration value="5" /><xsd:enumeration value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MarcasEVolumes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="MarcaEVolume" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DeclaracoesSumaria" minOccurs="0"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="DeclaracaoSumaria" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Documentos" minOccurs="0"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Documento" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element></xsd:sequence><xsd:attribute ref="Acao" /></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Arquivos"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Ficheiro" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="CamposExtra"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="CampoExtra" maxOccurs="unbounded"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="CodigoCampoExtra"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ValorCampoExtra"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2500" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DadosIncidencia"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="CodStatusIncidencia"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DataInicio" type="xsd:dateTime" minOccurs="0" nillable="true" /><xsd:element name="DataFim" type="xsd:dateTime" minOccurs="0" nillable="true" /><xsd:element name="Observacoes" type="xsd:string" minOccurs="0" nillable="true" /><xsd:element name="TipoIncidencia" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="R" /><xsd:enumeration value="H" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DadosManifesto"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="CodPais" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Descricao" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="104" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Valor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Moeda" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TotalFatura" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroCPA"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Peso" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Tipo"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Declaracao"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="Data" type="xsd:date" /><xsd:element name="CodNatureza"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumDocTransporte" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodTipoDeclaracao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="4" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodEstancia"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodDeclarante"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais15A" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais16" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais17" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodMeioTransporte18" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="IdMeioTransporte" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodMeioTransporte21" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais21" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TemContentores"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="1" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodCondEntrega"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DescricaoCondEntrega" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodNaturezaTransacao" minOccurs="0"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:choice><xsd:element name="CodEstanciaAduaneira"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodLocalAutorizado"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:choice><xsd:element name="CodArmazem" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPais22"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisFrete" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisSeguro" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MoradaExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocalidadeExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPostalExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocPostalExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NIFExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MoradaDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocalidadeDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPostalDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocPostalDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TelefoneDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="14" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="EmailDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="200" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NIFDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TipoDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPaisDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodRegiaoDestinatario" type="xsd:int" minOccurs="0" nillable="true" /><xsd:element name="ObsDesalfandegamento" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string" /></xsd:simpleType></xsd:element><xsd:element name="NumRequerimento" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumDURetorno" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="T1Retorno" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DataPrevVoo" type="xsd:date" minOccurs="0" nillable="true" /><xsd:element name="Payment" type="xsd:int" minOccurs="0" nillable="true" /><xsd:element name="NumVossaReferencia" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumContaExpedidor" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumContaDestinatario" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="10" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Aeroporto" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="80" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="PPouFC" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumVoo" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MiniCPA" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Referencia1" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Referencia2" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ShipID" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="11" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Tracking" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DType" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="PosicaoAviao" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="9" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="TipoCarga" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeFileUPS" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NomeDestinatario2" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MoradaDestinatario2" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocalidadeDestinatario2" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodPostalDestinatario2" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="LocPostalDestinatario2" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Gateway" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Delegacao" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="EDeclaracaoImportacao" default="0"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="0" /><xsd:maxInclusive value="2" /><xsd:enumeration value="0" /><xsd:enumeration value="1" /><xsd:enumeration value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="ValorFreteCompanhia" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MoedaFreteCompanhia" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NivelServico" type="xsd:int" minOccurs="0" nillable="true" /><xsd:element name="CodFollowUp" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:int" /></xsd:simpleType></xsd:element><xsd:element name="CodUtilizadorNomeado" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DataDocCPA" type="xsd:date" minOccurs="0" nillable="true" /><xsd:element name="TipoManifesto" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="D" /><xsd:enumeration value="C" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DespesasDHL" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroDGASDS" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Observacoes" type="xsd:string" minOccurs="0" nillable="true" /><xsd:element ref="CamposExtra" minOccurs="0" /><xsd:element name="DepositoTemporario" minOccurs="0"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="NumeroPDDT" type="xsd:int" minOccurs="0" nillable="true" /><xsd:element name="NumeroPDDTDev" type="xsd:int" minOccurs="0" nillable="true" /><xsd:element name="NumeroTD" type="xsd:int" minOccurs="0" nillable="true" /><xsd:element name="NumeroACTM" type="xsd:int" minOccurs="0" nillable="true" /><xsd:element name="NumeroSequencia" type="xsd:int" minOccurs="0" nillable="true" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Adicoes"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Adicao" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Manifestos" minOccurs="0"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="DadosManifesto" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element ref="Incidencias" minOccurs="0" /><xsd:element ref="Arquivos" minOccurs="0" /></xsd:sequence><xsd:attribute ref="Acao" use="required" /></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DeclaracaoSumaria"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="Tipo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="4" /><xsd:enumeration value="X" /><xsd:enumeration value="Z" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroDeclSumaria"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DataApresentacao" type="xsd:date" /><xsd:element name="CodEstancia" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Regime" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="DeclaracoesImpToGIDWin"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Declaracao" minOccurs="0" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Documento"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="CodDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="5" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroDocumento" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="DataEmissao" type="xsd:date" minOccurs="0" nillable="true" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Ficheiro"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="Nome"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="100" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Descricao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Tipo" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8" /><xsd:enumeration value="FATURA" /><xsd:enumeration value="DOCTRANS" /><xsd:enumeration value="FTINTERN" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Origem" type="xsd:int" /><xsd:element name="Base64" type="xsd:string" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Incidencias"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="DadosIncidencia" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="MarcaEVolume"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element name="Marca" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Numero" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="QtdVolumes"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /><xsd:minInclusive value="0.000000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="CodUnidMedida"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="P" default="0"><xsd:simpleType><xsd:restriction base="xsd:boolean" /></xsd:simpleType></xsd:element><xsd:element name="R" default="0"><xsd:simpleType><xsd:restriction base="xsd:boolean" /></xsd:simpleType></xsd:element><xsd:element name="C" default="0"><xsd:simpleType><xsd:restriction base="xsd:boolean" /></xsd:simpleType></xsd:element><xsd:element name="LOptica" minOccurs="0" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="30" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element></xsd:schema>'
/****** Object:  XmlSchemaCollection [XMLSC_DocsVendaToGIDWin]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_DocsVendaToGIDWin] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:element name="DocsVendaToGIDWIN"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="Documento" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Documento"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoDocumento" /><xsd:element ref="data" /><xsd:element ref="idExterno" /><xsd:element ref="observacoes" minOccurs="0" /><xsd:element ref="documentoOrigem" minOccurs="0" /><xsd:element ref="cliente" /><xsd:element ref="linhas" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="cliente"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="codigoCliente" /><xsd:element ref="infoCliente" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="codigoArtigo" type="xsd:int" /><xsd:element name="codigoCliente"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoIsencaoIVA" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="codigoPostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="data" type="xsd:date" /><xsd:element name="descricaoArtigo"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="500" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="documentoOrigem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="idExterno"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="50" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="infoCliente"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="nome" /><xsd:element ref="morada" /><xsd:element ref="localidade" /><xsd:element ref="codigoPostal" /><xsd:element ref="localidadePostal" /><xsd:element ref="regiao" /><xsd:element ref="pais" /><xsd:element ref="nif" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="linha"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="numero" /><xsd:element ref="codigoArtigo" /><xsd:element ref="descricaoArtigo" /><xsd:element ref="quantidade" /><xsd:element ref="valorUnitario" /><xsd:element ref="taxaIVA" /><xsd:element ref="codigoIsencaoIVA" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="linhas"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="linha" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="localidade"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadePostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="morada"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nif"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nome"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numero"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="observacoes" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="8000" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="pais"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="quantidade"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="regiao" type="xsd:int" /><xsd:element name="taxaIVA"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /><xsd:minInclusive value="0" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="4" /><xsd:minLength value="1" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="valorUnitario"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:totalDigits value="18" /><xsd:fractionDigits value="2" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:schema>'
/****** Object:  XmlSchemaCollection [XMLSC_FaturasACreditarToGIDWin]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_FaturasACreditarToGIDWin] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:element name="FaturasACreditarInGIDWIN"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="fatura" minOccurs="0" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="codigoPostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="12" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="data" type="xsd:date" /><xsd:element name="email"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="200" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="fatura"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="tipoDocumento" /><xsd:element ref="numero" /><xsd:element ref="data" /><xsd:element ref="infoCliente" minOccurs="0" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="infoCliente"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="nif" /><xsd:element ref="nome" /><xsd:element ref="morada" /><xsd:element ref="localidade" /><xsd:element ref="codigoPostal" /><xsd:element ref="localidadePostal" /><xsd:element ref="email" /><xsd:element ref="pais" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="localidade"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="localidadePostal"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="morada"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nif"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="nome"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="numero" type="xsd:int" /><xsd:element name="pais"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="2" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="tipoDocumento"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="4" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:schema>'
/****** Object:  XmlSchemaCollection [XMLSC_SaidasAEXToGIDWin]    Script Date: 04-11-2025 10:22:20 ******/
CREATE XML SCHEMA COLLECTION [XMLSC_SaidasAEXToGIDWin] AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:attribute name="Acao"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:length value="1" /><xsd:enumeration value="I" /><xsd:enumeration value="U" /></xsd:restriction></xsd:simpleType></xsd:attribute><xsd:element name="AnoEntradaAEX" type="xsd:int" /><xsd:element name="Anulado" type="xsd:boolean" /><xsd:element name="AutorizacaoSaida" type="xsd:boolean" /><xsd:element name="CodLocalizacaoMercadorias"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="17" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Data" type="xsd:dateTime" /><xsd:element name="DataAS" type="xsd:dateTime" nillable="true" /><xsd:element name="DataIntegracaoAS" type="xsd:dateTime" nillable="true" /><xsd:element name="DataOrdem" type="xsd:date" nillable="true" /><xsd:element name="EstadoOperacao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="3" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Informacao1" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Informacao2" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="70" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="MotivoAnulacao" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="10" /><xsd:maxLength value="150" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroContramarca" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroDocumentoTransporte" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="18" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroEntradaAEX" type="xsd:int" /><xsd:element name="NumeroExterno" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="20" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroOrdem" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="NumeroSDS" nillable="true"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:maxLength value="35" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="PesoBruto"><xsd:simpleType><xsd:restriction base="xsd:decimal"><xsd:minInclusive value="0.000000" /><xsd:totalDigits value="28" /><xsd:fractionDigits value="6" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="Regime"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:minLength value="1" /><xsd:maxLength value="4" /></xsd:restriction></xsd:simpleType></xsd:element><xsd:element name="SaidaAEX"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="CodLocalizacaoMercadorias" /><xsd:element ref="Data" /><xsd:element ref="AnoEntradaAEX" /><xsd:element ref="NumeroEntradaAEX" /><xsd:element ref="Volumes" /><xsd:element ref="PesoBruto" /><xsd:element ref="NumeroContramarca" minOccurs="0" /><xsd:element ref="NumeroSDS" minOccurs="0" /><xsd:element ref="NumeroOrdem" minOccurs="0" /><xsd:element ref="DataOrdem" minOccurs="0" /><xsd:element ref="Regime" /><xsd:element ref="AutorizacaoSaida" /><xsd:element ref="DataAS" minOccurs="0" /><xsd:element ref="DataIntegracaoAS" minOccurs="0" /><xsd:element ref="Anulado" /><xsd:element ref="MotivoAnulacao" minOccurs="0" /><xsd:element ref="Informacao1" minOccurs="0" /><xsd:element ref="Informacao2" minOccurs="0" /><xsd:element ref="NumeroDocumentoTransporte" minOccurs="0" /><xsd:element ref="EstadoOperacao" minOccurs="0" /><xsd:element ref="NumeroExterno" minOccurs="0" /></xsd:sequence><xsd:attribute ref="Acao" /></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="SaidasAEXToGIDWin"><xsd:complexType><xsd:complexContent><xsd:restriction base="xsd:anyType"><xsd:sequence><xsd:element ref="SaidaAEX" minOccurs="0" maxOccurs="unbounded" /></xsd:sequence></xsd:restriction></xsd:complexContent></xsd:complexType></xsd:element><xsd:element name="Volumes"><xsd:simpleType><xsd:restriction base="xsd:int"><xsd:minInclusive value="1" /></xsd:restriction></xsd:simpleType></xsd:element></xsd:schema>'
/****** Object:  UserDefinedFunction [fn_DeclaracoesDAR_ObtemContramarca]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_DeclaracoesDAR_ObtemContramarca](@Id int) RETURNS varchar(6) AS
BEGIN
-- declaração de variáveis
	DECLARE @Contramarca varchar(6)
-- obtem a contramarca no 1º documento precedente existente na declaração DAR
	SET @Contramarca = (SELECT TOP 1 (CASE doc.DOC_CODI WHEN 'N337' THEN SUBSTRING(dpr.numero, 14, 6) ELSE  SUBSTRING(dpr.numero, 1, 6) END)
		FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
		WHERE id_declaracaoDAR = @Id)
	RETURN @Contramarca
END

ALTER AUTHORIZATION ON [fn_DeclaracoesDAR_ObtemContramarca] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_DeclaracoesDAR_ObtemContramarca] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao](@EstadoOperacao varchar(3)) RETURNS varchar(50) AS
BEGIN
-- declaração de variáveis
	DECLARE @DescricaoEstadoOperacao varchar(50)
-- obtém a descrição de cada estado de operação
	IF @EstadoOperacao = 'AP' 
		SET @DescricaoEstadoOperacao = 'Operação Aceite'
	ELSE
		IF @EstadoOperacao = 'RE' 
			SET @DescricaoEstadoOperacao = 'Operação Rejeitada'
		ELSE
			IF @EstadoOperacao = 'CAP' 
				SET @DescricaoEstadoOperacao = 'Controlo Aduaneiro à Posteriori'
			ELSE
				IF @EstadoOperacao = 'CA' 
					SET @DescricaoEstadoOperacao = 'Controlo Aduaneiro'
				ELSE
					IF @EstadoOperacao = 'AS' 
						SET @DescricaoEstadoOperacao = 'Autorização de Saída'
					ELSE
						IF @EstadoOperacao = 'SNA' 
							SET @DescricaoEstadoOperacao = 'Saída Não Autorizada'
						ELSE
							IF @EstadoOperacao = 'LED' 
								SET @DescricaoEstadoOperacao = 'Lembrete de Envio de Documentos'
							ELSE
								IF @EstadoOperacao = 'LDC' 
									SET @DescricaoEstadoOperacao = 'Lembrete de Expiração Prazo DC'
								ELSE
									IF @EstadoOperacao = 'PDA' 
										SET @DescricaoEstadoOperacao = 'Pedido Documentos Adicionais'
									ELSE
										IF @EstadoOperacao = 'PIL' 
											SET @DescricaoEstadoOperacao = 'Pedido de Localização'
										ELSE
											IF @EstadoOperacao = 'CS' 
												SET @DescricaoEstadoOperacao = 'Certificação de Saída'
											ELSE												
												SET @DescricaoEstadoOperacao = NULL
-- devolve a descrição obtida
	RETURN @DescricaoEstadoOperacao
END

ALTER AUTHORIZATION ON [fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_Faturacao_ConstroiInvoiceNumber]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_Faturacao_ConstroiInvoiceNumber](@CodTipoDoc varchar(4), @Serie varchar(20), @Numero int) RETURNS varchar(60) AS
BEGIN
-- declaração de variáveis
	DECLARE @InvoiceNumber varchar(60)
-- constroi o invoice number a atribuir aos documentos de faturação
	SET @InvoiceNumber = (SELECT SUBSTRING((@CodTipoDoc + ' ' + @Serie + '/' + CAST(@Numero AS varchar(20))), 1, 60))
	RETURN @InvoiceNumber
END

ALTER AUTHORIZATION ON [fn_Faturacao_ConstroiInvoiceNumber] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_Faturacao_ConstroiInvoiceNumber] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_Geral_ConverteJson2Xml]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_Geral_ConverteJson2Xml](@Json varchar(MAX)) RETURNS xml AS
BEGIN
-- Declaração de variáveis
	DECLARE @output varchar(MAX), @key varchar(MAX), @value varchar(MAX), @recursion_counter int, @offset int, @array bit
-- Clean up the JSON syntax by removing line breaks and tabs and trimming the results of leading and trailing spaces:
    SET @json=LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(@json, CHAR(13), ''), CHAR(10), ''), CHAR(9), '')))
-- Sanity check: If this is not valid JSON syntax, exit here.
	IF (LEFT(@json, 1) <> '{') OR (RIGHT(@json, 1) <> '}')
		RETURN NULL
-- Because the first and last characters will, by definition, be curly brackets, we can remove them here, and trim the result.
    SET @json = LTRIM(RTRIM(SUBSTRING(@json, 2, LEN(@json) - 2)))
-- Decompõe o json
	SET @output = ''
	WHILE (@json <> '') 
	BEGIN
-- Look for the first key which should start with a quote.
		IF LEFT(@json, 1) <> '"'
			RETURN 'Expected quote (start of key name), found "' + LEFT(@json, 1)+'"!'
-- and end with the next quote (that isn't escaped with and backslash).
		SET @key = SUBSTRING(@json, 2, PATINDEX('%[^\\]"%', SUBSTRING(@json, 2, LEN(@json)) + ' "'))
-- Truncate @json with the length of the key.
		SET @json = LTRIM(SUBSTRING(@json, LEN(@key) + 3, LEN(@json)))
-- The next character should be a colon.
		IF LEFT(@json, 1) <> ':'
			RETURN 'Expected ":" after key name, found "' + LEFT(@json, 1) + '"!';
-- Truncate @json to skip past the colon:
		SET @json = LTRIM(SUBSTRING(@json, 2, LEN(@json)))
-- If the next character is an angle bracket, this is an array.
		IF LEFT(@json, 1) = '['
		BEGIN
			SET @array = 1
			SET @json = LTRIM(SUBSTRING(@json, 2, LEN(@json)))
		END		
		IF @array IS NULL 
			SET @array = 0
		WHILE (@array IS NOT NULL) 
		BEGIN
			SET @value = NULL
-- The first character of the remainder of @json indicates what type of value this is. Set @value, depending on what type of value we're looking at:
-- 1. A new JSON object: To be sent recursively back into the parser:
			IF (@value IS NULL) AND (LEFT(@json, 1) = '{') 
			BEGIN
				SELECT @recursion_counter = 1, @offset = 1
				WHILE (@recursion_counter <> 0 AND @offset < LEN(@json)) 
				BEGIN
					SET @offset = @offset + PATINDEX('%[{}]%', SUBSTRING(@json, @offset + 1, LEN(@json)))
					SET @recursion_counter = @recursion_counter + (CASE SUBSTRING(@json, @offset, 1) WHEN '{' THEN 1 WHEN '}' THEN -1 END)
				END
				SET @value = CAST(dbo.fn_Geral_ConverteJson2Xml(LEFT(@json, @offset)) AS varchar(MAX))
				SET @json = SUBSTRING(@json, @offset + 1, LEN(@json))				
			END
--- 2a. Blank text (quoted)
			IF (@value IS NULL) AND (LEFT(@json, 2) = '""')
			BEGIN
				SET @value = ''
				SET @json = LTRIM(SUBSTRING(@json, 3, LEN(@json)))
			END
-- 2b. Other text (quoted, but not blank)
			IF (@value IS NULL) AND (LEFT(@json, 1) = '"') 
			BEGIN
				SET @value = SUBSTRING(@json, 2, PATINDEX('%[^\\]"%', SUBSTRING(@json, 2, LEN(@json)) + ' "'))
				SET @json = LTRIM(SUBSTRING(@json, LEN(@value) + 3, LEN(@json)))
			END
-- 3. Blank (not quoted)
			IF (@value IS NULL) AND (LEFT(@json, 1) = ',')
				SET @value = ''
-- 4. Or unescaped numbers or text.
			IF @value IS NULL 
			BEGIN
				SET @value = LEFT(@json, PATINDEX('%[,}]%', REPLACE(@json, ']', '}') + '}') - 1)
				SET @json = SUBSTRING(@json, LEN(@value) + 1, LEN(@json))
			END
-- Append @key and @value to @output:
			SET @output = @output + '<' + @key + '>'
			SET @output = @output + ISNULL(REPLACE(REPLACE(@value, '\"', '"'), '\\', '\'), '')
			SET @output = @output + '</'+@key+'>'
-- And again, error checks:
-- 1. If these are multiple values, the next character should be a comma:
			IF (@array = 0) AND (@json <> '') AND (LEFT(@json, 1) <> ',')
				RETURN @output + 'Expected "," after value, found "' + LEFT(@json, 1)+'"!'
-- 2. or, if this is an array, the next character should be a comma or a closing angle bracket:
			IF (@array = 1) AND (LEFT(@json, 1) NOT IN (',', ']'))
				RETURN @output + 'In array, expected "]" or "," after value, found "' + LEFT(@json, 1)+'"!'
-- If this is where the array is closed (i.e. if it's a closing angle bracket)..
			IF (@array = 1) AND (LEFT(@json, 1) = ']') 
			BEGIN
				SET @array = NULL
				SET @json = LTRIM(SUBSTRING(@json, 2, LEN(@json)))
-- After a closed array, there should be a comma:
				IF LEFT(@json, 1) NOT IN ('', ',') 
					RETURN 'Closed array, expected ","!'				
			END
			SET @json = LTRIM(SUBSTRING(@json, 2, LEN(@json) + 1))
			IF @array = 0 
				SET @array = NULL
		END
	END
-- Return the output:
	RETURN CAST(@output AS xml)
END

ALTER AUTHORIZATION ON [fn_Geral_ConverteJson2Xml] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_Geral_ConverteJson2Xml] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_Geral_ConverteTabelaXMLParaLista]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_Geral_ConverteTabelaXMLParaLista](@XMLDados xml, @FieldSeparator varchar(10), @RecordSeparator varchar(10)) RETURNS varchar(MAX) AS
BEGIN
-- declaração de variáveis
	DECLARE @ListaDados varchar(MAX), @Field1Value varchar(100), @Field2Value varchar(100), @Field3Value varchar(100), @Field4Value varchar(100), @Field5Value varchar(100), 
		@Field6Value varchar(100), @Field7Value varchar(100), @Field8Value varchar(100), @Field9Value varchar(100), @DadosRegisto varchar(1000)
-- inicia variável
	SET @ListaDados = ''
-- obtem a lista de dados da tabela
	DECLARE Dados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
		SELECT 
			ISNULL(LTRIM(RTRIM(t.c.value('field1Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field2Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field3Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field4Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field5Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field6Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field7Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field8Value[1]', 'varchar(100)'))), ''), 
			ISNULL(LTRIM(RTRIM(t.c.value('field9Value[1]', 'varchar(100)'))), '')
		FROM @XMLDados.nodes('table/record') AS t(c)
	OPEN Dados
	FETCH NEXT FROM Dados INTO @Field1Value, @Field2Value, @Field3Value, @Field4Value, @Field5Value, @Field6Value, @Field7Value, @Field8Value, @Field9Value
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @DadosRegisto = ''
-- constroi os dados do registo para os 9 campos existentes
		IF @Field1Value <> ''
			SET @DadosRegisto = @DadosRegisto + @Field1Value
		IF @Field2Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field2Value
		END
		IF @Field3Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field3Value
		END
		IF @Field4Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field4Value
		END
		IF @Field5Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field5Value
		END
		IF @Field6Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field6Value
		END
		IF @Field7Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field7Value
		END
		IF @Field8Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field8Value
		END
		IF @Field9Value <> ''
		BEGIN
			IF @DadosRegisto <> ''
				SET @DadosRegisto = @DadosRegisto + ISNULL(@FieldSeparator, '/')
			SET @DadosRegisto = @DadosRegisto + @Field9Value
		END		
-- adiciona os dados do registo à lista de dados da tabela
		IF @DadosRegisto <> ''
		BEGIN
			IF @ListaDados <> ''
				SET @ListaDados = @ListaDados + ISNULL(@RecordSeparator, ' ; ')		
			SET @ListaDados = @ListaDados + @DadosRegisto
		END
		FETCH NEXT FROM Dados INTO @Field1Value, @Field2Value, @Field3Value, @Field4Value, @Field5Value, @Field6Value, @Field7Value, @Field8Value, @Field9Value
	END
	CLOSE Dados
	DEALLOCATE Dados
-- devolve a lista de dados da tabela
	RETURN NULLIF(@ListaDados, '')
END

ALTER AUTHORIZATION ON [fn_Geral_ConverteTabelaXMLParaLista] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_Geral_ConverteTabelaXMLParaLista] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_Geral_ObtemHonorariosImportacao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_Geral_ObtemHonorariosImportacao](@ValorMercadoria decimal(18, 2)) RETURNS decimal(18, 2) AS
BEGIN
-- declaração de variáveis
	DECLARE @ValorHonorarios decimal(18, 2)
-- obtem o valor de honorários de acordo com o valor da mercadoria
	IF @ValorMercadoria <= (SELECT (MAX(valorMercadoria) + 9) FROM tb_TBL_HonorariosIMP WITH(NOLOCK))
	BEGIN
		SELECT TOP 1 @ValorHonorarios = valorHonorarios 
		FROM tb_TBL_HonorariosIMP WITH(NOLOCK)
		WHERE valorMercadoria <= @ValorMercadoria 
		ORDER BY valorMercadoria DESC
	END
	ELSE
	BEGIN
		SELECT @ValorHonorarios = ROUND((MAX(valorHonorarios) + (ROUND(((@ValorMercadoria - MAX(valorMercadoria)) / 10.00), 0, 1) * 0.02)), 2)
		FROM tb_TBL_HonorariosIMP WITH(NOLOCK)
	END
	RETURN @ValorHonorarios
END

ALTER AUTHORIZATION ON [fn_Geral_ObtemHonorariosImportacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_Geral_ObtemHonorariosImportacao] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_Geral_ObtemRegiaoEstatisiticaDeCodPostal]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_Geral_ObtemRegiaoEstatisiticaDeCodPostal](@CodPostal varchar(12)) RETURNS int AS
BEGIN
-- declaração de variáveis
	DECLARE @Regioes TABLE(CPO_LINF int NOT NULL, CPO_LSUP int NOT NULL, CPO_CREG int NOT NULL)
	DECLARE @CodRegiaoEstatistica int
-- insere mapeamento de códigos postais c/ regiões respetivas
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(2000, 2399, 36)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(2400, 2599, 92)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(3000, 3099, 91)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(3100, 3199, 92)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(3200, 3499, 91)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(3500, 3699, 93)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(3700, 3899, 90)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(4000, 4699, 81)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(4700, 4999, 10)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(5000, 5199, 84)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(5200, 5399, 85)	
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(5400, 5499, 84)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(6000, 6199, 94)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(6200, 6499, 95)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(7000, 7099, 44)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(7100, 7199, 45)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(7200, 7499, 44)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(7500, 7599, 40)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(7600, 7999, 43)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(8000, 8999, 50)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(9000, 9499, 70)
	INSERT INTO @Regioes(CPO_LINF, CPO_LSUP, CPO_CREG) VALUES(9500, 9999, 60)	
-- se código postal for numérico, obtem a respetiva região estatistica
	IF ISNUMERIC(SUBSTRING(RTRIM(LTRIM(@CodPostal)), 1, 4)) = 1
		SET @CodRegiaoEstatistica = ISNULL((SELECT CPO_CREG FROM @Regioes WHERE CAST(SUBSTRING(RTRIM(LTRIM(@CodPostal)), 1, 4) AS int) BETWEEN CPO_LINF AND CPO_LSUP), 35)
	ELSE 
		SET @CodRegiaoEstatistica = NULL
	RETURN @CodRegiaoEstatistica
END

ALTER AUTHORIZATION ON [fn_Geral_ObtemRegiaoEstatisiticaDeCodPostal] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_Geral_ObtemRegiaoEstatisiticaDeCodPostal] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaAjustamento]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaAjustamento](@Formula varchar(70), @TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6), @CambioSeguro numeric(38, 6), @Frete numeric(38, 6), @Seguro numeric(38, 6), 
	@Direitos numeric(38, 6), @Acrescimos numeric(38, 6), @Deducoes numeric(38, 6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @SeguroEUR numeric(38, 6), @FreteEUR numeric(38, 6), @FormulaNegativa bit, @Ajustamento numeric(38, 6)
-- calcula o seguro em EUR
	IF @CambioSeguro > 0
		SET @SeguroEUR = ROUND(@Seguro / @CambioSeguro, 2)
	ELSE
		SET @SeguroEUR = 0
-- calcula o frete em EUR
	IF @CambioFrete > 0
		SET @FreteEUR = ROUND(@Frete / @CambioFrete, 2)
	ELSE
		SET @FreteEUR = 0
-- aplica taxa FDA
	IF @TaxaFDA > 0 
		SET @FreteEUR = ROUND(@FreteEUR * @TaxaFDA / 100, 2)		
-- determina se formula é negativa
	IF ISNULL(NULLIF(CHARINDEX('+', ISNULL(@Formula, '')), 0), 999999) > ISNULL(NULLIF(CHARINDEX('-', ISNULL(@Formula, '')), 0), 999999) 
		SET @FormulaNegativa = 1
	ELSE 
		SET @FormulaNegativa = 0
-- efetua calculo em função do primeiro caracter operador constante na formula	
	IF @FormulaNegativa = 1 
		SET @Ajustamento = ROUND((@FreteEUR * (-1)) - @SeguroEUR - @Direitos + @Acrescimos - @Deducoes, 2)
	ELSE
		SET @Ajustamento = ROUND(@FreteEUR + @SeguroEUR + @Direitos + @Acrescimos - @Deducoes, 2)
-- Devolve valor do ajustamento
	RETURN @Ajustamento
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaAjustamento] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaAjustamento] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaBaseTributacaoDireitos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaBaseTributacaoDireitos](@BaseManual bit, @BaseTributacao numeric(38, 6), @TipoTributacao int, @MassaLiquida numeric(38, 6), @Unidades numeric(38, 6), 
	@ValorEstatistico numeric(38, 6), @CodUnidadeMedida varchar(3)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @BaseTributacaoDireitos numeric(38, 6), @Factor numeric(38, 6)
-- efetua calculo em função da base manual 
	IF @BaseManual = 1
		SET @BaseTributacaoDireitos = @BaseTributacao
	ELSE	
-- efetua calculo em função do tipo de tributação
		IF @TipoTributacao = 0 --unidades suplementares
			SET @BaseTributacaoDireitos = @Unidades
		ELSE
			IF @TipoTributacao = 1 --peso líquido
			BEGIN
				SET @Factor = ISNULL(
					(SELECT NULLIF(UME_FACT, 0)
					FROM TAB_UMED WITH(NOLOCK)
					WHERE UME_CODI = @CodUnidadeMedida), 1)
				SET @BaseTributacaoDireitos = ROUND(@MassaLiquida / @Factor, 2)
			END
			ELSE
				IF @TipoTributacao = 3 --valor
					SET @BaseTributacaoDireitos = @ValorEstatistico
				ELSE
					SET @BaseTributacaoDireitos = 0		
-- Devolve valor da base tributação direitos
	RETURN @BaseTributacaoDireitos
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaBaseTributacaoDireitos] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaBaseTributacaoDireitos] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaBaseTributacaoIVA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaBaseTributacaoIVA](@Formula varchar(70), @TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6), @Frete numeric(38, 6), @Ajustamento numeric(38, 6), 
	@ValorEstatistico numeric(38, 6), @VerbaTransitario numeric(38, 6), @Optativas numeric(38, 6), @MontanteDireitos numeric(38, 6), @ISV numeric(38, 6), @AjusteBTI numeric(38, 6), 
	@MontanteIVAImposicoes numeric(38, 6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @BaseTributacaoIVA numeric(38, 6), @FormulaNegativa bit, @FreteEUR numeric(38, 6), @RemanescenteFreteEUR numeric(38, 6)
-- determina se formula é negativa
	IF ISNULL(NULLIF(CHARINDEX('+', ISNULL(@Formula, '')), 0), 999999) > ISNULL(NULLIF(CHARINDEX('-', ISNULL(@Formula, '')), 0), 999999) 
		SET @FormulaNegativa = 1
	ELSE 
		SET @FormulaNegativa = 0
-- calcula o remanescente do frete em EUR
	IF @TaxaFDA > 0 
	BEGIN
		IF @CambioFrete > 0
			SET @FreteEUR = ROUND(@Frete / @CambioFrete, 2)
		ELSE
			SET @FreteEUR = 0
		SET @RemanescenteFreteEUR = ROUND(@FreteEUR * (1 - (@TaxaFDA / 100)), 2)
	END
	ELSE
		SET @RemanescenteFreteEUR = 0
-- efetua calculo em função do primeiro caracter operador constante na formula
	SET @BaseTributacaoIVA = ROUND(@ValorEstatistico + @RemanescenteFreteEUR + @VerbaTransitario + @Optativas + @MontanteDireitos + @ISV + @AjusteBTI + @MontanteIVAImposicoes, 2)
	IF @FormulaNegativa = 1 
		SET @BaseTributacaoIVA = ROUND(@BaseTributacaoIVA - @Ajustamento, 2)
-- Devolve valor da base tributação IVA
	RETURN @BaseTributacaoIVA
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaBaseTributacaoIVA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaBaseTributacaoIVA] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaMontanteDireitos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaMontanteDireitos](@BaseManual bit, @Montante numeric(38, 6), @Percentagem bit, @TaxaValor numeric(38, 6), @BaseTributacao numeric(38, 6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @MontanteDireitos numeric(38, 6), @Factor numeric(38, 6)
-- efetua calculo em função da base manual 
	IF @BaseManual = 1
		SET @MontanteDireitos = @Montante
	ELSE	
-- efetua calculo em função se é percentagem ou valor
		IF @Percentagem = 1 
			SET @MontanteDireitos = ROUND(@BaseTributacao * @TaxaValor / 100, 2)
		ELSE
			SET @MontanteDireitos = ROUND(@BaseTributacao * @TaxaValor, 2)
-- Devolve valor do montante de direitos
	RETURN @MontanteDireitos
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaMontanteDireitos] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaMontanteDireitos] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaTaxaValorDireitos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaTaxaValorDireitos](@DataRefTPT datetime, @CodArtigo varchar(22), @CodPaisOrigem varchar(2), @CodPaisOrigemPreferencial varchar(2), 
	@TipoTaxaPreferencia int, @Unidades numeric(38, 6), @Regime varchar(4), @Desdobramento1 varchar(6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @TaxaValorDireitos numeric(38, 6), @CodPais varchar(2)
-- valida se regime/desdobramento isenta a taxa/valor de direitos
	IF (LEFT(ISNULL(@Regime, ''), 2) IN ('51', '53', '71')) 
	OR (ISNULL(@Desdobramento1, '') IN ('C01', 'C02', 'C03', 'C04', 'C06', 'C07', 'C08', 'C09', 'C10', 'C11', 'C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C19', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C26', 'C27', 'C28', 'C29', 'C30', 'C31', 'C32', 'C33', 'C34', 'C35', 'C36', 'C37', 'C38', 'C39', 'C40', 'C41', 'C42', 'C43', 'C44', 'C45', 'C46', 'C47', 'C48', 'C49', 'C50', 'C51', 'C52', 'C53', 'C54', 'C55', 'C56', 'C57', 'C58', 'C59', 'C60', 'C61', 'F01', 'F02', 'F03', 'F05', 'F21', 'F22', '4FD'))
		SET @TaxaValorDireitos = 0
	ELSE
	BEGIN
-- obtem o país a considerar 
		IF ISNULL(@CodPaisOrigemPreferencial, '') <> ''
			SET @CodPais = @CodPaisOrigemPreferencial
		ELSE
			SET @CodPais = @CodPaisOrigem
-- obtem a taxa/valor de direitos do artigo
		SET @TaxaValorDireitos = ISNULL(
			(SELECT (CASE apa.APA_TRIB 
					WHEN 0 THEN (CASE apa.APA_TXCO 
									WHEN 1 THEN 0 
									ELSE @Unidades 
								END) --Unidades Suplementares
					WHEN 1 THEN (CASE @TipoTaxaPreferencia 
									WHEN 1 THEN ISNULL(apa.APA_TPT, 0) --TPT
									WHEN 2 THEN ISNULL((SELECT TOP 1 APS_SPMN 
														FROM TAB_APSP WITH(NOLOCK) 														
														WHERE APA_CHVE = apa.APA_CHVE AND PAI_CODI = @CodPais), ISNULL(apa.APA_SPMN, 0)) --SPG
									WHEN 3 THEN ISNULL((SELECT TOP 1 APE_EFMN
														FROM TAB_APEF WITH(NOLOCK)														
														WHERE APA_CHVE = apa.APA_CHVE AND PAI_CODI = @CodPais), ISNULL(apa.APA_EFMN, 0)) --EFTA
									ELSE 0
								END) --Peso Líquido
						WHEN 3 THEN (CASE @TipoTaxaPreferencia 
										WHEN 1 THEN (ISNULL((SELECT TOP 1 (ISNULL(APT_TFT, 0) + DATEDIFF(MONTH, APT_DATA, @DataRefTPT) * ISNULL(APT_INCR, 0))
															FROM TAB_APTF WITH(NOLOCK)															
															WHERE APA_CHVE = apa.APA_CHVE AND PAI_CODI = @CodPais), 0) + ISNULL(apa.APA_TPT, 0)) --TPT
										WHEN 2 THEN ISNULL((SELECT TOP 1 APS_SPG 
															FROM TAB_APSP WITH(NOLOCK) 															
															WHERE APA_CHVE = apa.APA_CHVE AND PAI_CODI = @CodPais), ISNULL(apa.APA_SPG, 0)) --SPG
										WHEN 3 THEN ISNULL((SELECT TOP 1 APE_EFTA
															FROM TAB_APEF WITH(NOLOCK)															
															WHERE APA_CHVE = apa.APA_CHVE AND PAI_CODI = @CodPais), ISNULL(apa.APA_EFTA, 0)) --EFTA
										ELSE 0
									END) --Valor
						ELSE 0 
					END)		
			FROM TAB_APAU AS apa WITH(NOLOCK)
			WHERE APA_CODI = @CodArtigo), 0)
	END
-- Devolve valor da taxa/valor dos direitos
	RETURN @TaxaValorDireitos
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaTaxaValorDireitos] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaTaxaValorDireitos] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaValorEstatistico]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaValorEstatistico](@MontanteEUR numeric(38, 6), @Ajustamento numeric(38, 6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @ValorEstatistico numeric(38, 6)
-- efetua calculo 
	SET @ValorEstatistico = ROUND(@MontanteEUR + @Ajustamento, 2)
-- Devolve valor estatístico
	RETURN @ValorEstatistico
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaValorEstatistico] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaValorEstatistico] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaValorOptativas]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaValorOptativas](@AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @CodMeioTransporte varchar(2), @TotalAdicoes int, @TotalVolumes numeric(38, 6), 
	@TotalOptativas numeric(38, 6), @TotalMassaBruta numeric(38, 6), @TotalValorAduaneiro numeric(38, 6), @MassaBruta numeric(38, 6), @ValorAduaneiro numeric(38, 6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @ValorOptativas numeric(38, 6), @Volumes numeric(38, 6)
-- efetua calculo em função se o meio de transporte é por "Volumes"
	IF EXISTS(SELECT MTR_CODI FROM TAB_MTRA WITH(NOLOCK) WHERE MTR_CODI = @CodMeioTransporte AND MTR_VPVL = 2)
	BEGIN
		IF (EXISTS(SELECT D31_IDEN FROM PRO_DU31 WITH(NOLOCK) WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = 1 AND D31_CASP = 1)) OR (@TotalAdicoes > 1)
		BEGIN
			IF (@TotalAdicoes > 1) AND (@NumAdicao = @TotalAdicoes)
				SET @ValorOptativas = ROUND(((@TotalVolumes * @TotalOptativas) - (SELECT SUM(DUA_VOPT) 
																				FROM PRO_DUAD WITH(NOLOCK) 
																				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI <> @NumAdicao)), 2) 
			ELSE 
				SET @ValorOptativas = ROUND(@TotalVolumes * @TotalOptativas * @ValorAduaneiro / @TotalValorAduaneiro, 2)
		END
		ELSE
		BEGIN
			SET @Volumes = ISNULL((SELECT SUM(D31_QNTD)
							FROM PRO_DU31 WITH(NOLOCK)
							WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND D31_CASP = 0), @TotalVolumes)
			SET @ValorOptativas = ROUND(@Volumes * @TotalOptativas, 2)
		END
	END
	ELSE
	BEGIN			
		SET @ValorOptativas = @TotalOptativas * CEILING(@TotalMassaBruta / 100)		
		SET @ValorOptativas = ROUND((@ValorOptativas * @MassaBruta / @TotalMassaBruta), 2)
	END		
-- Devolve valor das optativas
	RETURN @ValorOptativas
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaValorOptativas] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaValorOptativas] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_CalculaValorTotalOptativas]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_CalculaValorTotalOptativas](@IdMeioTransporte int, @CodMeioTransporte varchar(2), @TotalMassaBruta numeric(38, 6), @TotalValorEUR numeric(38, 6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @ValorTotalOptativas numeric(38, 6)
-- obtem o valor das optativas configurado no meio de transporte
	SELECT @ValorTotalOptativas = (CASE mtr.MTR_OPAU 
									WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
														FROM TAB_MTRO WITH(NOLOCK) 
														WHERE MTR_IDTY = mtr.MTR_IDTY AND @TotalMassaBruta BETWEEN MTO_LMNP AND MTO_LMXP AND @TotalValorEUR BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
									ELSE ISNULL(mtr.MTR_VOP1, 0) 
								END) 
	FROM TAB_MTRA AS mtr WITH(NOLOCK) 
	WHERE mtr.MTR_CODI = @CodMeioTransporte OR mtr.MTR_IDTY = @IdMeioTransporte
-- Devolve valor total das optativas
	RETURN ISNULL(@ValorTotalOptativas, 0)
END

ALTER AUTHORIZATION ON [fn_IMP_CalculaValorTotalOptativas] TO  SCHEMA OWNER 
GRANT EXECUTE ON [fn_IMP_CalculaValorTotalOptativas] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [fn_IMP_ObtemErrosSubmissaoWS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [fn_IMP_ObtemErrosSubmissaoWS](@IdDeclaracao int) RETURNS @TblErrosSubmissao TABLE 
(
	numero smallint, 
	codigo varchar(25), 
	descricao varchar(250)
)
AS
BEGIN
-- declaração de variáveis
	DECLARE @Ano int, @Numero int, @TotalVols numeric(38, 6), @CodPaisDestino varchar(2), @Contentorizada int, @TotalMontante numeric(38, 6), @TipoNIFCliente int, 
		@AnexoB varchar(2), @Contentor varchar(17), @Regime varchar(4)
-- obtem dados da declaração
	SELECT @Ano = DUC_EANO, @Numero = DUC_PNUM, @TotalVols = ISNULL(DUC_TVL6, 0), @CodPaisDestino = ISNULL(PAI_PA17, ''), @Contentorizada = DUC_CT19, 
		@TotalMontante = ISNULL(DUC_MT22, 0), @TipoNIFCliente = ISNULL(DUC_TPDS, -1), @AnexoB = DUC_ANXB, @Contentor = ISNULL(DUC_CONT, ''), @Regime = ISNULL(DUC_REGI, '')
	FROM PRO_DUCG WITH(NOLOCK)
	WHERE DUC_IDTY = @IdDeclaracao
-- verifica condição de total diferente da soma das adições
	IF NOT EXISTS(SELECT 1 FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero HAVING SUM(DUA_VA42) = @TotalMontante)
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(1, 'INV_MONTANTETOTAL', 'A soma do montante das adições diferente do total declarado.')
	END
-- verifica condição se existe artigo genérico nas adições
	IF EXISTS(SELECT 1 FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND APA_CP33 = '9999999999')
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(2, 'INV_CPARTIGOADICOES', 'Existem adições com artigo pautal genérico "9999999999" atribuído.')
	END	
-- verifica condição se existem volumes definidos
	IF (@TotalVols = 0) AND (NOT EXISTS(SELECT 1 FROM PRO_DU31 WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = 1 AND D31_TTVL = 1))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(3, 'NO_VOLUMES', 'Não existem volumes definidos.')
	END		
-- verifica condição se existem documentos suporte/transporte sem número
	IF EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK) WHERE id_declaracaoIMP = @IdDeclaracao AND tipo IN (0, 1) AND ISNULL(numero, '') = '')
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(4, 'INV_NUMDOCUMENTOS', 'Existem documentos/certificados sem número atribuído.')
	END		
-- verifica condição se existem documentos transporte definidos
	IF (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK) WHERE id_declaracaoIMP = @IdDeclaracao AND tipo = 1))
		AND (NOT EXISTS(SELECT 1 FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = 1 AND DDO_TIPO = 1))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(5, 'NO_DOCSTRANSPORTE', 'Não existe, pelo menos, um documento de transporte.')
	END		
-- verifica condição se existem documentos obrigatórios definidos
	IF (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoIMP = @IdDeclaracao AND doc.DOC_CODI IN ('9E06', 'N203', 'N315', 'N325', 'N380', 'N381', 'N395')))
		AND (NOT EXISTS(SELECT 1 FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = 1 AND DOC_CODI IN ('9E06', 'N203', 'N315', 'N325', 'N380', 'N381', 'N395')))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(6, 'NO_DOCSOBRIGATORIOS', 'Não existe, pelo menos, um dos seguintes documentos obrigatórios "9E06", "N203", "N315", "N325", "N380", "N381", "N395".')
	END	
-- verifica condição se existem documentos precedentes definidos
	IF (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesPrecedentes WITH(NOLOCK) WHERE id_declaracaoIMP = @IdDeclaracao))
		AND (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesAdicoesPrecedentes AS dap WITH(NOLOCK) INNER JOIN PRO_DUAD AS dad WITH(NOLOCK) ON dap.id_adicao = dad.DUA_IDEN WHERE dad.DUC_EANO = @Ano AND dad.DUC_PNUM = @Numero AND dad.DUA_CODI = 1))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(7, 'NO_DOCSPRECEDENTES', 'Não existe, pelo menos, um documento precedente.')
	END
-- verifica condição se existe contentor definido
	IF (@Contentorizada > 0) AND (@Contentor = '') AND (NOT EXISTS(SELECT 1 FROM PRO_DCON WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(8, 'NO_CONTENTORES', 'Não existe, pelo menos, um contentor.')
	END	
-- verifica condição se existem referências fiscais definidas
	IF (@AnexoB IN ('H1', 'H6', 'I1')) AND ((@CodPaisDestino <> 'PT') OR (LEFT(@Regime, 2) = '42') OR (@TipoNIFCliente IN (3, 4, 6)))
		AND (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesReferenciasFiscais WITH(NOLOCK) WHERE id_declaracaoIMP = @IdDeclaracao))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(9, 'NO_REFSFISCAIS', 'Não existe, pelo menos, uma referência fiscal.')
	END
-- verifica condição se existem acréscimos/deduções obrigatórios definidos
	IF (@AnexoB IN ('H1', 'H5', 'I1', 'I2')) 
		AND (EXISTS(SELECT 1 FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = 1 AND (ISNULL(DUA_VFRE, 0) > 0 OR ISNULL(DUA_VSEG, 0) > 0)))
		AND (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes AS aad WITH(NOLOCK) INNER JOIN PRO_DUAD AS dad WITH(NOLOCK) ON aad.id_adicao = dad.DUA_IDEN WHERE dad.DUC_EANO = @Ano AND dad.DUC_PNUM = @Numero AND dad.DUA_CODI = 1 AND aad.codigo IN ('AK', 'BA')))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(10, 'NO_ACRESCIMOSDEDUCOES', 'Não existe, pelo menos, o acréscimo "AK" ou a dedução "BA" obrigatórios.')
	END
-- verifica condição se existem estâncias de apuramento definidas
	IF (@AnexoB = 'H3') AND (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesEstancias WITH(NOLOCK) WHERE id_declaracaoIMP = @IdDeclaracao))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(11, 'NO_ESTANCIASAPURAMENTO', 'Não existe, pelo menos, uma estância de apuramento.')
	END
-- verifica condição se existem locais de transformação definidas
	IF (@AnexoB = 'H3') AND (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesLocaisTransformacao WITH(NOLOCK) WHERE id_declaracaoIMP = @IdDeclaracao))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(12, 'NO_LOCAISTRANSFORMACAO', 'Não existe, pelo menos, um local de transformação.')
	END
-- verifica condição se existem identificação de mercadorias definidas
	IF (@AnexoB = 'H3') AND (NOT EXISTS(SELECT 1 FROM tb_IMP_DeclaracoesMeiosIdentificacao WITH(NOLOCK) WHERE id_declaracaoIMP = @IdDeclaracao))
	BEGIN
		INSERT INTO @TblErrosSubmissao(numero, codigo, descricao)
		VALUES(13, 'NO_IDMERCADORIAS', 'Não existe, pelo menos, uma identificação das mercadorias.')
	END
-- devolve a tabela	dos erros de submissão	
	RETURN 
END

ALTER AUTHORIZATION ON [fn_IMP_ObtemErrosSubmissaoWS] TO  SCHEMA OWNER 
GRANT SELECT ON [fn_IMP_ObtemErrosSubmissaoWS] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_CalculaDifDiasUteis]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_CalculaDifDiasUteis](@DataInicial date, @DataFinal date, @PrimeiroDiaConta bit, @TodosDias bit) RETURNS int AS
BEGIN
-- declaração de variaveis
	DECLARE @DataAux date, @NumDiasUteis int	
-- cria tabela temporária de feriados
	DECLARE @Feriados TABLE(Dia int NOT NULL, Mes int NOT NULL)
-- insere na tabela de feriados, os feriados variaveis de Sexta-Feira Santa e Corpo de Deus
	INSERT INTO @Feriados(Dia, Mes)	VALUES(29, 3)		-- Sexta-Feira Santa
	INSERT INTO @Feriados(Dia, Mes)	VALUES(30, 5)		-- Corpo de Deus
-- insere na tabela de feriados, os feriados fixos de 01/01, 25/04, 01/05, 10/06, 15/08, 05/10, 01/11, 01/12, 08/12 e 25/12
	INSERT INTO @Feriados(Dia, Mes)	VALUES(1, 1)		-- Ano Novo
	INSERT INTO @Feriados(Dia, Mes)	VALUES(25, 4)		-- 25 de Abril
	INSERT INTO @Feriados(Dia, Mes)	VALUES(1, 5)		-- Dia do Trabalhador
	INSERT INTO @Feriados(Dia, Mes)	VALUES(10, 6)		-- Dia de Portugal
	INSERT INTO @Feriados(Dia, Mes)	VALUES(15, 8)		-- Dia de Assunção Nossa Senhora
	INSERT INTO @Feriados(Dia, Mes)	VALUES(5, 10)		-- Implantação da Republica
	INSERT INTO @Feriados(Dia, Mes)	VALUES(1, 11)		-- Dia de Todos os Santos
	INSERT INTO @Feriados(Dia, Mes)	VALUES(1, 12)		-- Restauração da Independencia
	INSERT INTO @Feriados(Dia, Mes)	VALUES(8, 12)		-- Dia da Imaculada Conceição
	INSERT INTO @Feriados(Dia, Mes)	VALUES(25, 12)		-- Natal
-- inicia variaveis
	SET @NumDiasUteis = 0
	SET @DataAux = @DataInicial
-- incrementa numero dias uteis se for para ter em conta o proprio dia da data inicial
	IF (@PrimeiroDiaConta = 1) AND ((@TodosDias = 1) OR ((@TodosDias = 0) AND (DATEPART(dw, @DataAux) NOT IN (1, 7)) AND ((SELECT COUNT(*) FROM @Feriados WHERE Dia = DAY(@DataAux) AND Mes = MONTH(@DataAux)) = 0)))
		SET @NumDiasUteis = @NumDiasUteis + 1
-- incrementa numero dias uteis se não for sabado ou domingo e não for feriado
	WHILE @DataAux < @DataFinal
	BEGIN
		SET @DataAux = DATEADD(DAY, 1, @DataAux)
		IF (@TodosDias = 1) OR ((@TodosDias = 0) AND (DATEPART(dw, @DataAux) NOT IN (1, 7)) AND ((SELECT COUNT(*) FROM @Feriados WHERE Dia = DAY(@DataAux) AND Mes = MONTH(@DataAux)) = 0))
			SET @NumDiasUteis = @NumDiasUteis + 1
	END
	RETURN @NumDiasUteis
END

ALTER AUTHORIZATION ON [FNT_CalculaDifDiasUteis] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_CalculaDifDiasUteis] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_CalculaLstDocsAdicoesDUImportacao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_CalculaLstDocsAdicoesDUImportacao](@NumProcesso int, @AnoProcesso int, @NumAdicao int) RETURNS varchar(8000) AS
BEGIN
	DECLARE @LstDocs varchar(8000), @CodDocumento varchar(5), @NumDocumento varchar(70), @DataDocumento datetime, @ValorDocumento numeric(38, 6)
-- inicia variaveis
	select @LstDocs = ''
-- obtem a lista de documentos associados ao processo e adição referidos
	DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
		select DOC_CODI, isnull(DDO_NUME, ''), DDO_DINI, isnull(DDO_MONT, 0)
		from PRO_DDOC
		where DUC_PNUM = @NumProcesso and DUC_EANO = @AnoProcesso and DUA_CODI = @NumAdicao
	OPEN Documentos
	FETCH NEXT from Documentos into @CodDocumento, @NumDocumento, @DataDocumento, @ValorDocumento
	WHILE @@FETCH_STATUS = 0
	BEGIN
		select @LstDocs = @LstDocs + @CodDocumento
		if @NumDocumento <> ''
			select @LstDocs = @LstDocs + ' NR ' + @NumDocumento
		if @DataDocumento is not null
			select @LstDocs = @LstDocs + ' DE ' + convert(varchar(10), @DataDocumento, 105)
		if @ValorDocumento > 0
			select @LstDocs = @LstDocs + ', ' + ltrim(str(@ValorDocumento, 40, 2)) 
		select @LstDocs = @LstDocs + '; '
		FETCH NEXT from Documentos into @CodDocumento, @NumDocumento, @DataDocumento, @ValorDocumento
	END
	CLOSE Documentos
	DEALLOCATE Documentos
	RETURN(@LstDocs)
END

ALTER AUTHORIZATION ON [FNT_CalculaLstDocsAdicoesDUImportacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_CalculaLstDocsAdicoesDUImportacao] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_CustomsBilling_CalculaValorTarifa]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_CustomsBilling_CalculaValorTarifa](@IDTarifa int, @ValorReferencia numeric(38, 6), @ValorBaseCalculo numeric(38, 6), @ValorIL numeric(38, 6), @TipoDespesa int, @CodCliente varchar(18), @NIFColetivo bit) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variaveis
	DECLARE @ValorTarifa numeric(38, 6), @ValorExcecao numeric(38, 6), @PercDesconto numeric(38, 6), @ValorLimite numeric(38, 6), @ValorMinimo numeric(38, 6)
-- obtem valor dos limites da tarifa	
	SELECT TOP 1 @ValorLimite = (CASE @TipoDespesa WHEN 1 THEN (CASE WHEN CBL_PHON > 0 THEN ROUND((@ValorBaseCalculo * CBL_PHON / 100) , 2) ELSE CBL_VHON END)
		WHEN 2 THEN (CASE WHEN CBL_PCAU > 0 THEN ROUND((@ValorBaseCalculo * CBL_PCAU / 100) , 2) ELSE CBL_VCAU END)
		ELSE 0 END), @ValorMinimo = CBL_MHON
	FROM TAB_PCBL
	WHERE (CBT_IDEN = @IDTarifa) and (@ValorReferencia BETWEEN CBL_LINF and CBL_LSUP) and ((CBL_TIPO = 0) or (CBL_TIPO = (CASE @NIFColetivo WHEN 1 THEN 1 ELSE 2 END)))
-- se existir valor minimo definido no limite e o valor de limite inferior ao valor minimo, aplica valor minimo
	IF (@ValorMinimo > 0) and (@ValorLimite < @ValorMinimo)
		SET @ValorLimite = @ValorMinimo
-- obtem valor da exceção e % desconto que possam existir na Tarifa para o Cliente em causa
	SELECT @ValorExcecao = (CASE @TipoDespesa WHEN 1 THEN (CASE WHEN CBE_PVIL > 0 THEN (CASE WHEN ROUND((@ValorIL * CBE_PVIL / 100) , 2) <= CBE_VHON THEN CBE_VHON
				ELSE ROUND((@ValorIL * CBE_PVIL / 100) , 2) END)
			WHEN CBE_UDTL = 1 THEN ISNULL((SELECT (CASE WHEN CBX_PDES > 0 THEN ROUND((@ValorLimite * CBX_PDES / 100), 2) WHEN CBX_PHON > 0 THEN ROUND((@ValorBaseCalculo * CBX_PHON / 100) , 2) ELSE CBX_VHON END) FROM TAB_PCBX WHERE CBE_IDEN = TAB_PCBE.CBE_IDEN and @ValorReferencia BETWEEN CBX_LINF and CBX_LSUP), 0)
			WHEN CBE_PHON > 0 THEN ROUND((@ValorBaseCalculo * CBE_PHON / 100) , 2) 
			ELSE CBE_VHON END)
		WHEN 2 THEN (CASE WHEN CBE_PCAU > 0 THEN ROUND((@ValorBaseCalculo * CBE_PCAU / 100) , 2) ELSE CBE_VCAU END)
		ELSE 0 END), @PercDesconto = (CASE @TipoDespesa WHEN 1 THEN (100 - CBE_PDES) ELSE 100 END)
	FROM TAB_PCBE 
	WHERE CBT_IDEN = @IDTarifa and CLI_CODI = @CodCliente and (CASE @TipoDespesa WHEN 1 THEN CBE_AHON WHEN 2 THEN CBE_ACAU ELSE 0 END) = 1 		
-- não há exceção na Tarifa para o Cliente em causa ou há exceção de desconto para o Cliente em causa, aplica desconto
	IF (@ValorExcecao IS NULL) or ((@ValorExcecao = 0) and (@PercDesconto > 0))
		SET @ValorTarifa = ROUND((ISNULL(@ValorLimite, 0) * ISNULL(@PercDesconto, 100) / 100) , 2)			
	ELSE
		SET @ValorTarifa = @ValorExcecao	
-- devolve valor da tarifa obtido
	RETURN @ValorTarifa
END

ALTER AUTHORIZATION ON [FNT_CustomsBilling_CalculaValorTarifa] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_CustomsBilling_CalculaValorTarifa] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_DeclImportacao_CalculaFreteAcordado]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_DeclImportacao_CalculaFreteAcordado](@CodCondEntrega varchar(3), @CodPais varchar(2), @MassaBrtTotal numeric(38, 6), @Frete numeric(38, 6)) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @ValorCalculado numeric(38, 6), @Limite numeric(38, 6), @ValorLimite numeric(38, 6), @ValorAdicional numeric(38, 6)	
-- verifica se Cond. Entrega utiliza tabela de Fretes Acordados
	IF (@CodCondEntrega IS NULL) OR (EXISTS(SELECT CEN_CODI FROM TAB_CENT WHERE CEN_USFR = 1 and CEN_CODI = @CodCondEntrega))
	BEGIN
-- inicializa variaveis
		SELECT @Limite = 0, @ValorLimite = 0, @ValorAdicional = 0, @ValorCalculado = -1
-- obtem valores dos fretes acordados relacionados com o País	
		SELECT @Limite = ISNULL(f.FTA_LIMI, 0), @ValorLimite = ISNULL(f.FTA_VLIM, 0), @ValorAdicional = ISNULL(f.FTA_VADI, 0), 
			@ValorCalculado = ISNULL((SELECT FAL_VALO FROM TAB_FALM WHERE FTA_CODI = f.FTA_CODI and @MassaBrtTotal BETWEEN FAL_LIMD AND FAL_LIMA), -1)
		FROM TAB_PAIS AS p WITH(NOLOCK) INNER JOIN TAB_FTAC AS f WITH(NOLOCK) ON p.FTA_CODI = f.FTA_CODI
		WHERE p.PAI_CODI = @CodPais
-- se Massa Bruta Total fora das gamas de Pesos definidas, aplica valores limite e adicional
		IF @ValorCalculado < 0
			SELECT @ValorCalculado = @ValorLimite + (@MassaBrtTotal - @Limite) * @ValorAdicional
	END
	ELSE
		SELECT @ValorCalculado = @Frete
-- Devolve valor do frete calculado
	RETURN @ValorCalculado
END

ALTER AUTHORIZATION ON [FNT_DeclImportacao_CalculaFreteAcordado] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_DeclImportacao_CalculaFreteAcordado] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_DocUnico_Resumo_IVA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_DocUnico_Resumo_IVA] (@Codigo int, @Ano int) RETURNS @ReportIVA TABLE (
		TAXA_IVA numeric(38,6) NULL, -- Taxa de i.v.a.
		VTT_ADUA numeric(38,6) NULL, -- Valor total aduaneiro
		VIN_ADUA numeric(38,6) NULL, -- Valor de incidência do i.v.a. do total aduaneiro
		IVA_ADUA numeric(38,6) NULL, -- Valor do i.v.a. do total aduaneiro		
		VTT_OPTA numeric(38,6) NULL, -- Valor total optativas
		VIN_OPTA numeric(38,6) NULL, -- Valor de incidência do i.v.a. do total optativas
		IVA_OPTA numeric(38,6) NULL, -- Valor do i.v.a. do total optativas
		VTT_TRAN numeric(38,6) NULL, -- Valor total verba de transitário
		VIN_TRAN numeric(38,6) NULL, -- Valor de incidência do i.v.a. do total verba de transitário
		IVA_TRAN numeric(38,6) NULL, -- Valor do i.v.a. do total verba de transitário
		VTT_OIMP numeric(38,6) NULL, -- Valor total outras imposições
		VIN_OIMP numeric(38,6) NULL, -- Valor de incidência do i.v.a. das outras imposições
		IVA_OIMP numeric(38,6) NULL, -- Valor do i.v.a. das outras imposições
		VTT_DIRE numeric(38,6) NULL, -- Valor total direitos
		VIN_DIRE numeric(38,6) NULL, -- Valor de incidência do i.v.a. dos direitos
		IVA_DIRE numeric(38,6) NULL, -- Valor do i.v.a. dos direitos
		VTT_IA	 numeric(38,6) NULL, -- Valor do i.s.v. 
		LST_ADIC varchar(2000) NULL ) AS -- Lista com as adições 
BEGIN
-- declaracao de variaveis
	declare @TAXA_IVA numeric(38,6), @VTT_ADUA numeric(38,6), @VIN_ADUA numeric(38,6), @IVA_ADUA numeric(38,6), @VTT_OPTA numeric(38,6), @VIN_OPTA numeric(38,6), @IVA_OPTA numeric(38,6), 
		@VTT_TRAN numeric(38,6), @VIN_TRAN numeric(38,6), @IVA_TRAN numeric(38,6), @VTT_OIMP numeric(38,6), @VIN_OIMP numeric(38,6), @IVA_OIMP numeric(38,6), @VTT_DIRE numeric(38,6), @VIN_DIRE numeric(38,6),
		@IVA_DIRE numeric(38,6), @LST_ADIC varchar(2000), @TAXA_IV1 numeric(38,6), @ADI_IVA1 varchar(2000), @OUT_IMP1 numeric(38,6), @TAXA_IV2 numeric(38,6), @ADI_IVA2 varchar(2000), @OUT_IMP2 numeric(38,6), 
		@TAXA_IV3 numeric(38,6), @ADI_IVA3 varchar(2000), @OUT_IMP3 numeric(38,6), @TAXA_IV4 numeric(38,6), @ADI_IVA4 varchar(2000), @OUT_IMP4 numeric(38,6), @OUT_IMPO numeric(38,6), @DUA_CODI varchar(10), 
		@VALOR_ISV numeric(38,6)
	-- inicializa valores auxiliares
	SELECT @TAXA_IV1=-1
	SELECT @ADI_IVA1=''
	SELECT @OUT_IMP1=0
	SELECT @TAXA_IV2=-1
	SELECT @ADI_IVA2=''
	SELECT @OUT_IMP2=0
	SELECT @TAXA_IV3=-1
	SELECT @ADI_IVA3=''
	SELECT @OUT_IMP3=0
	SELECT @TAXA_IV4=-1
	SELECT @ADI_IVA4=''
	SELECT @OUT_IMP4=0
	SELECT @VALOR_ISV=0
	-- busca valores referêntes às adições ----------------------------------------------------------------------
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT DUA_TIVA, ROUND(SUM(DUA_BTIV - DUA_VOPT - DUA_MTRI - DUA_VTRA), 3), 
			ROUND(SUM(DUA_BTIV - DUA_VOPT - DUA_MTRI - DUA_VTRA) * (DUA_TIVA / 100), 3),
			ROUND(SUM(DUA_BTIV - DUA_VOPT - DUA_MTRI - DUA_VTRA) + SUM(DUA_BTIV - DUA_VOPT - DUA_MTRI - DUA_VTRA) * (DUA_TIVA / 100), 3),
			ROUND(SUM(DUA_VOPT), 3), ROUND(SUM(DUA_VOPT * (DUA_TIVA / 100)), 3), ROUND(SUM(DUA_VOPT) + SUM(DUA_VOPT * (DUA_TIVA / 100)), 3),
			ROUND(SUM(DUA_VTRA), 3), ROUND(SUM(DUA_VTRA * (DUA_TIVA / 100)), 3),
			ROUND(SUM(DUA_VTRA) + SUM(DUA_VTRA * (DUA_TIVA / 100)), 3),
			ROUND(SUM(DUA_MTRI), 3), ROUND(SUM(DUA_MTRI * (DUA_TIVA/100)), 3),
			ROUND(SUM(DUA_MTRI) + SUM(DUA_MTRI * (DUA_TIVA/100)), 3),
			ROUND(SUM(DUA_IVAV), 3)
		FROM PRO_DUAD
		WHERE DUC_PNUM = @Codigo AND DUC_EANO = @Ano
		GROUP BY DUA_TIVA
		ORDER BY DUA_TIVA
	OPEN Adicoes
	FETCH NEXT from Adicoes into @TAXA_IVA, @VIN_ADUA, @IVA_ADUA, @VTT_ADUA, @VIN_OPTA, @IVA_OPTA, @VTT_OPTA, @VIN_TRAN, @IVA_TRAN, @VTT_TRAN, @VIN_DIRE, @IVA_DIRE, @VTT_DIRE, @VALOR_ISV	
	WHILE @@FETCH_STATUS=0
	BEGIN
		-- Trata taxas de i.v.a. ----------------------------------------------------------------------------
		IF @TAXA_IV1=-1
			SELECT @TAXA_IV1=@TAXA_IVA
		ELSE 
		IF @TAXA_IV2=-1
			SELECT @TAXA_IV2=@TAXA_IVA
		ELSE 
		IF @TAXA_IV3=-1
			SELECT @TAXA_IV3=@TAXA_IVA
		ELSE 
		IF @TAXA_IV4=-1
			SELECT @TAXA_IV4=@TAXA_IVA		
		-- preenche query com valores dos totais, incidências e valores do i.v.a. -----------------------------------
		INSERT INTO @ReportIVA(TAXA_IVA,VTT_ADUA,VIN_ADUA,IVA_ADUA,VTT_OPTA,VIN_OPTA,IVA_OPTA,VTT_TRAN,VIN_TRAN,IVA_TRAN,VTT_DIRE,VIN_DIRE,IVA_DIRE,VTT_IA)
		VALUES(@TAXA_IVA,@VTT_ADUA,@VIN_ADUA,@IVA_ADUA,@VTT_OPTA,@VIN_OPTA,@IVA_OPTA,@VTT_TRAN,@VIN_TRAN,@IVA_TRAN,@VTT_DIRE,@VIN_DIRE,@IVA_DIRE,@VALOR_ISV)
		FETCH NEXT from Adicoes into @TAXA_IVA, @VIN_ADUA, @IVA_ADUA, @VTT_ADUA, @VIN_OPTA, @IVA_OPTA, @VTT_OPTA, @VIN_TRAN, @IVA_TRAN, @VTT_TRAN, @VIN_DIRE, @IVA_DIRE, @VTT_DIRE, @VALOR_ISV
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes
	-- Trata código da adição por taxa de i.v.a.
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT a.DUA_TIVA, cast(a.DUA_CODI as varchar(10)),
			(SELECT ISNULL(SUM(DUO_MONT), 0) 
			FROM PRO_DUOI o
			WHERE o.DUC_PNUM = a.DUC_PNUM AND o.DUC_EANO = a.DUC_EANO AND o.DUA_CODI = a.DUA_CODI)
		FROM PRO_DUAD a
		WHERE a.DUC_PNUM = @Codigo AND a.DUC_EANO = @Ano
		ORDER BY a.DUA_TIVA
	OPEN Adicoes
	FETCH NEXT from Adicoes into @TAXA_IVA, @DUA_CODI, @OUT_IMPO
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- Trata taxas de i.v.a.
		IF @TAXA_IV1 = @TAXA_IVA
		BEGIN
			IF @ADI_IVA1 <> ''
			BEGIN
				SELECT @ADI_IVA1 = @ADI_IVA1 + ', '
			END
			SELECT @ADI_IVA1 = @ADI_IVA1 + @DUA_CODI
			SELECT @OUT_IMP1 = @OUT_IMP1 + @OUT_IMPO
		END
		ELSE 
		IF @TAXA_IV2 = @TAXA_IVA
		BEGIN
			IF @ADI_IVA2 <> ''
			BEGIN
				SELECT @ADI_IVA2 = @ADI_IVA2 + ', '
			END
			SELECT @ADI_IVA2 = @ADI_IVA2 + @DUA_CODI
			SELECT @OUT_IMP2 = @OUT_IMP2 + @OUT_IMPO	
		END
		ELSE 
		IF @TAXA_IV3 = @TAXA_IVA
		BEGIN
			IF @ADI_IVA3 <> ''
			BEGIN
				SELECT @ADI_IVA3 = @ADI_IVA3 + ', '
			END
			SELECT @ADI_IVA3 = @ADI_IVA3 + @DUA_CODI
			SELECT @OUT_IMP3 = @OUT_IMP3 + @OUT_IMPO	
		END
		ELSE 
		IF @TAXA_IV4 = @TAXA_IVA
		BEGIN
			IF @ADI_IVA4 <> ''
			BEGIN
				SELECT @ADI_IVA4 = @ADI_IVA4 + ', '
			END
			SELECT @ADI_IVA4 = @ADI_IVA4 + @DUA_CODI
			SELECT @OUT_IMP4 = @OUT_IMP4 + @OUT_IMPO	
		END		
		FETCH NEXT from Adicoes into @TAXA_IVA, @DUA_CODI, @OUT_IMPO
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes
	-- insere na query
	IF @TAXA_IV1 <> -1
	BEGIN
		UPDATE @ReportIVA SET LST_ADIC = @ADI_IVA1, 
			VIN_ADUA = VIN_ADUA - ROUND(@OUT_IMP1, 3),	
			IVA_ADUA = IVA_ADUA - ROUND(@OUT_IMP1*(@TAXA_IV1/100), 3),
			VTT_ADUA = VTT_ADUA - ROUND(@OUT_IMP1 + @OUT_IMP1*(@TAXA_IV1/100), 3), 
			VIN_OIMP = ROUND(@OUT_IMP1, 3),		
			IVA_OIMP = ROUND(@OUT_IMP1*(@TAXA_IV1/100), 3),
			VTT_OIMP = ROUND(@OUT_IMP1 + @OUT_IMP1*(@TAXA_IV1/100), 3) 
		WHERE TAXA_IVA = @TAXA_IV1
	END
	IF @TAXA_IV2 <> -1
	BEGIN
		UPDATE @ReportIVA SET LST_ADIC = @ADI_IVA2, 
			VIN_ADUA = VIN_ADUA - ROUND(@OUT_IMP2, 3),	
			IVA_ADUA = IVA_ADUA - ROUND(@OUT_IMP2*(@TAXA_IV2/100), 3),
			VTT_ADUA = VTT_ADUA - ROUND(@OUT_IMP2 + @OUT_IMP2*(@TAXA_IV2/100), 3),
			VIN_OIMP = @OUT_IMP2,
			IVA_OIMP = ROUND(@OUT_IMP2*(@TAXA_IV2/100), 3),
			VTT_OIMP = ROUND(@OUT_IMP2 + @OUT_IMP2*(@TAXA_IV2/100), 3) 
		WHERE TAXA_IVA = @TAXA_IV2
	END
	IF @TAXA_IV3 <> -1
	BEGIN
		UPDATE @ReportIVA SET LST_ADIC = @ADI_IVA3, 
			VIN_ADUA = VIN_ADUA - ROUND(@OUT_IMP3, 3),	
			IVA_ADUA = IVA_ADUA - ROUND(@OUT_IMP3*(@TAXA_IV3/100), 3),
			VTT_ADUA = VTT_ADUA - ROUND(@OUT_IMP3 + @OUT_IMP3*(@TAXA_IV3/100), 3),		
			VIN_OIMP = @OUT_IMP3,
			IVA_OIMP = ROUND(@OUT_IMP3*(@TAXA_IV3/100), 3),
			VTT_OIMP = ROUND(@OUT_IMP3 + @OUT_IMP3*(@TAXA_IV3/100), 3) 
		WHERE TAXA_IVA = @TAXA_IV3
	END
	IF @TAXA_IV4 <> -1
	BEGIN
		UPDATE @ReportIVA SET LST_ADIC = @ADI_IVA4, 
			VIN_ADUA = VIN_ADUA - ROUND(@OUT_IMP4, 3),	
			IVA_ADUA = IVA_ADUA - ROUND(@OUT_IMP4*(@TAXA_IV4/100), 3),
			VTT_ADUA = VTT_ADUA - ROUND(@OUT_IMP4 + @OUT_IMP4*(@TAXA_IV4/100), 3),	
			VIN_OIMP = @OUT_IMP4,
			IVA_OIMP = ROUND(@OUT_IMP4*(@TAXA_IV4/100), 3),
			VTT_OIMP = ROUND(@OUT_IMP4 + @OUT_IMP4*(@TAXA_IV4/100), 3)
		WHERE TAXA_IVA = @TAXA_IV4
	END
	-- devolve a query criada 
	RETURN
END

ALTER AUTHORIZATION ON [FNT_DocUnico_Resumo_IVA] TO  SCHEMA OWNER 
GRANT SELECT ON [FNT_DocUnico_Resumo_IVA] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Extenso_Centenas]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE FUNCTION [FNT_Extenso_Centenas] (@valor int) RETURNS varchar(12)
AS
BEGIN
	DECLARE @extenso varchar(12)

	SELECT @extenso = CASE @valor WHEN 1 THEN 'cento'
		    		      WHEN 2 THEN 'duzentos'
		    		      WHEN 3 THEN 'trezentos'
		    		      WHEN 4 THEN 'quatrocentos'
		    		      WHEN 5 THEN 'quinhentos'
		    		      WHEN 6 THEN 'seiscentos'
		    		      WHEN 7 THEN 'setecentos'
		    		      WHEN 8 THEN 'oitocentos'
		    		      WHEN 9 THEN 'novecentos'
		    		      ELSE ''
			  END

	RETURN(@extenso)
END





ALTER AUTHORIZATION ON [FNT_Extenso_Centenas] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Extenso_Centenas] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Extenso_Dezenas]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE FUNCTION [FNT_Extenso_Dezenas] (@valor int) RETURNS varchar(9)
AS
BEGIN
	DECLARE @extenso varchar(9)

	SELECT @extenso = CASE @valor WHEN 2 THEN 'vinte'
		    		      WHEN 3 THEN 'trinta'
		    		      WHEN 4 THEN 'quarenta'
		    		      WHEN 5 THEN 'cinquenta'
		    		      WHEN 6 THEN 'sessenta'
		    		      WHEN 7 THEN 'setenta'
		    		      WHEN 8 THEN 'oitenta'
		    		      WHEN 9 THEN 'noventa'
		    		      ELSE ''
			  END
	RETURN(@extenso)
END





ALTER AUTHORIZATION ON [FNT_Extenso_Dezenas] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Extenso_Dezenas] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Extenso_EntreDezEVinte]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Extenso_EntreDezEVinte] (@valor int) RETURNS varchar(9) AS
BEGIN
	DECLARE @extenso varchar(9)

	SELECT @extenso = (CASE @valor 
						WHEN 10 THEN 'dez'
		    		    WHEN 11 THEN 'onze'
		    		    WHEN 12 THEN 'doze'
		    		    WHEN 13 THEN 'treze'
		    		    WHEN 14 THEN 'catorze'
		    		    WHEN 15 THEN 'quinze'
		    		    WHEN 16 THEN 'dezasseis'
		    		    WHEN 17 THEN 'dezassete'
		    		    WHEN 18 THEN 'dezoito'
						WHEN 19 THEN 'dezanove'
					ELSE '' END)
	RETURN (@extenso)
END

ALTER AUTHORIZATION ON [FNT_Extenso_EntreDezEVinte] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Extenso_EntreDezEVinte] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Extenso_TrataNumeros]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Extenso_TrataNumeros] (@num int, @extenso varchar(2000) ) RETURNS varchar(2000)
AS
BEGIN
	DECLARE @valor varchar(2000), @tam int, @unidade int, @dezena int, @centena int

	SELECT @valor = CAST(@num as varchar(2000))
	SELECT @tam = LEN(@valor)

	IF @tam = 1
	BEGIN
		SELECT @extenso = @extenso + (SELECT dbo.FNT_Extenso_Unidades(@num))
	END
	ELSE IF @tam = 2
	BEGIN 
		IF @num < 20 
		BEGIN
			SELECT @extenso = @extenso + (SELECT dbo.FNT_Extenso_EntreDezEVinte(@num))
		END
		ELSE
		BEGIN
			SELECT @unidade = CAST(SUBSTRING(@valor, 2, LEN(@valor)-1) as int)
			SELECT @dezena = CAST(SUBSTRING(@valor, 1, 1) as int)
			
			IF @unidade = 0
			BEGIN
				SELECT @extenso = @extenso + (SELECT dbo.FNT_Extenso_Dezenas(@dezena))
			END
			ELSE
			BEGIN
				SELECT @extenso = @extenso + (SELECT dbo.FNT_Extenso_Dezenas(@dezena)) + ' e ' + (SELECT dbo.FNT_Extenso_Unidades(@unidade))
			END
		END
	END
	ELSE IF @tam = 3
	BEGIN 
		IF @num < 101
		BEGIN
			SELECT @extenso = @extenso + 'cem'
		END
		ELSE
		BEGIN
			SELECT @centena = CAST(SUBSTRING(@valor, 1, 1) as int)
			SELECT @extenso = @extenso + (SELECT dbo.FNT_Extenso_Centenas(@centena))
			IF (@num <> 200) AND (@num <> 300) AND (@num <> 400) AND (@num <> 500) AND (@num <> 600) AND (@num <> 700) AND (@num <> 800) AND (@num <> 900)
				SELECT @extenso = @extenso + ' e '
			SELECT @num = CAST(SUBSTRING(@valor, 2, LEN(@valor)-1) as int) 	
 			SELECT @extenso = (SELECT dbo.FNT_Extenso_TrataNumeros(@num, @extenso))
		END
	END

	RETURN(@extenso)
END

ALTER AUTHORIZATION ON [FNT_Extenso_TrataNumeros] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Extenso_TrataNumeros] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Extenso_Unidades]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Extenso_Unidades] (@valor int) RETURNS varchar(8)
AS
BEGIN
	DECLARE @extenso varchar(8)

	SELECT @extenso = CASE @valor WHEN 1 THEN 'um'
		    		      WHEN 2 THEN 'dois'
		    		      WHEN 3 THEN 'três'
		    		      WHEN 4 THEN 'quatro'
		    		      WHEN 5 THEN 'cinco'
		    		      WHEN 6 THEN 'seis'
		    		      WHEN 7 THEN 'sete'
		    		      WHEN 8 THEN 'oito'
				      WHEN 9 THEN 'nove'
				      ELSE ''
			  END

	RETURN(@extenso)
END

ALTER AUTHORIZATION ON [FNT_Extenso_Unidades] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Extenso_Unidades] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Extenso_ValorPorExtenso]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE FUNCTION [FNT_Extenso_ValorPorExtenso] (@numerico varchar(2000), @unidades varchar(2000), 
@subunidades varchar(2000)) RETURNS varchar(2000) -- Valor em extenso.
AS
BEGIN
	DECLARE @NumCentenas int, @NumMilhares int, @NumMilhoes int, @NumBilioes int, @valor varchar(2000), 
	@posDecimal int, @strFinal varchar(2000), @FNT_Extenso_ValorPorExtenso varchar(2000), @tam int

	SELECT @NumCentenas = -1
	SELECT @NumMilhares = -1
	SELECT @NumMilhoes = -1
	SELECT @NumBilioes = -1
	SELECT @valor = @numerico
	-- verifica se existe parte décimal --------------------------------------------------------------------------
	SELECT @posDecimal = CHARINDEX('.', @numerico)
	
	-- trata apenas a parte inteira do valor ---------------------------------------------------------------------
	IF @posDecimal > 0
	BEGIN
	    SELECT @valor = SUBSTRING(@numerico, 1, @posDecimal - 1)
	END

	SELECT @tam = LEN(@valor)
	IF @tam <= 3 
	BEGIN
	   	SELECT @NumCentenas = CAST(@valor as int)
	END
	ELSE IF @tam <= 6 
	BEGIN
		SELECT @NumMilhares = CAST(SUBSTRING(@valor, 1, LEN(@valor) - 3) as int)
		SELECT @valor = SUBSTRING(@valor, LEN(@valor) - 2, 3 );
		SELECT @NumCentenas = CAST(@valor as int)
  	END
	ELSE IF @tam <= 9 
	BEGIN
		SELECT @NumMilhoes = CAST(SUBSTRING(@valor, 1, LEN(@valor) - 6) as int)
		SELECT @valor = SUBSTRING(@valor, LEN(@valor) - 5, 6);
		SELECT @NumMilhares = CAST(SUBSTRING(@valor, 1, LEN(@valor) - 3) as int)
		SELECT @valor = SUBSTRING(@valor, LEN(@valor) - 2, 3 );
		SELECT @NumCentenas = CAST(@valor as int)
  	END
	ELSE IF @tam <= 12 
	BEGIN
		SELECT @NumBilioes = CAST(SUBSTRING(@valor, 1, LEN(@valor) - 9) as int)
		SELECT @valor = SUBSTRING(@valor, LEN(@valor) - 8, 9);
		SELECT @NumMilhoes = CAST(SUBSTRING(@valor, 1, LEN(@valor) - 6) as int)
		SELECT @valor = SUBSTRING(@valor, LEN(@valor) - 5, 6);
		SELECT @NumMilhares = CAST(SUBSTRING(@valor, 1, LEN(@valor) - 3) as int)
		SELECT @valor = SUBSTRING(@valor, LEN(@valor) - 2, 3 );
		SELECT @NumCentenas = CAST(@valor as int)
  	END

	SELECT @strFinal = ''
	IF (@NumBilioes <> -1) AND (@NumBilioes <> 0)
  	BEGIN
		SELECT @strFinal = (SELECT dbo.FNT_Extenso_TrataNumeros(@NumBilioes, @strFinal))
		IF @NumBilioes = 1 
		BEGIN
			SELECT @strFinal = @strFinal + ' bilião '
		END
		ELSE
		BEGIN
			SELECT @strFinal = @strFinal + ' biliões '
		END
  	END
	IF (@NumMilhoes <> -1) AND (@NumMilhoes <> 0)
	BEGIN
		IF (@strFinal<>'') AND (@NumMilhoes < 101)
		BEGIN
			SELECT @strFinal = @strFinal + 'e '
		END
		SELECT @strFinal = (SELECT dbo.FNT_Extenso_TrataNumeros(@NumMilhoes, @strFinal))
		IF (@NumMilhoes = 1) AND ((@NumBilioes = -1) OR (@NumBilioes = 0))
		BEGIN
			SELECT @strFinal = @strFinal + ' milhão '
    		END
		ELSE
		BEGIN
			SELECT @strFinal = @strFinal + ' milhões '
		END
	END
	IF (@NumMilhares <> -1) AND (@NumMilhares <> 0)
	BEGIN
		IF (@strFinal <> '')
		BEGIN
		      SELECT @strFinal = @strFinal + 'e '
		END
		IF (@NumMilhares <> 1)
		BEGIN
			SELECT @strFinal = (SELECT dbo.FNT_Extenso_TrataNumeros(@NumMilhares, @strFinal))
			SELECT @strFinal = @strFinal + ' '
		END
		SELECT @strFinal = @strFinal + 'mil '
	END
	IF (@NumCentenas <> -1) AND (@NumCentenas <> 0)
	BEGIN
		IF (@strFinal <> '') AND (@NumCentenas < 101)
		BEGIN
			SELECT @strFinal = @strFinal + 'e '
		END
		SELECT @strFinal = (SELECT dbo.FNT_Extenso_TrataNumeros(@NumCentenas, @strFinal))
	END
  	ELSE
	BEGIN
		IF @strFinal = ''
		BEGIN
			SELECT @strFinal = 'zero'
		END
	END

	SELECT @FNT_Extenso_ValorPorExtenso = @strFinal + ' ' + @unidades

	IF (@posDecimal > 0)
  	BEGIN
		SELECT @valor = SUBSTRING(@numerico, @posDecimal + 1, 2);
		SELECT @valor = (SELECT dbo.FNT_Extenso_ValorPorExtenso(@valor, '', ''))
		SELECT @FNT_Extenso_ValorPorExtenso = UPPER(SUBSTRING(@FNT_Extenso_ValorPorExtenso, 1,1)) + SUBSTRING(@FNT_Extenso_ValorPorExtenso, 2,LEN(@FNT_Extenso_ValorPorExtenso))	
		IF (@valor <> 'zero ')
		BEGIN
			SELECT @FNT_Extenso_ValorPorExtenso = (@FNT_Extenso_ValorPorExtenso + ' e ' + @valor + @subunidades)
		END
	END

	RETURN( @FNT_Extenso_ValorPorExtenso)
END

ALTER AUTHORIZATION ON [FNT_Extenso_ValorPorExtenso] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Extenso_ValorPorExtenso] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Facturacao_CalculaReferenciaMB]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Facturacao_CalculaReferenciaMB](@Entidade varchar(5), @Subentidade varchar(3), @IdDocumento int, @Valor numeric(8, 2)) RETURNS varchar(9) AS
BEGIN
-- declaração de variaveis
	DECLARE @Base varchar(20), @IdDocumentoStr varchar(4), @ValorStr varchar(8), @Fator int, @CheckDigit int, @CheckDigitStr varchar(2) 
-- converte id e valor do documento para varchar dentro dos limites aceites
	SET @IdDocumentoStr = RIGHT(CAST(@IdDocumento AS varchar(10)), 4)
	SET @IdDocumentoStr = REPLICATE('0', 4 - LEN(@IdDocumentoStr)) + @IdDocumentoStr
	SET @ValorStr = RIGHT(REPLACE(CAST(@Valor AS varchar(10)), '.', ''), 8)
	SET @ValorStr = REPLICATE('0', 8 - LEN(@ValorStr)) + @ValorStr	
-- constroi a expressão para a base de calculo
	SET @Base = @Entidade + @Subentidade + @IdDocumentoStr + @ValorStr
-- processa o calculo do fator p/ obtenção do checkdigit
	SET @Fator = 0
	SET @Fator = @Fator + (51 * SUBSTRING(@Base, 1, 1))
	SET @Fator = @Fator + (73 * SUBSTRING(@Base, 2, 1))
	SET @Fator = @Fator + (17 * SUBSTRING(@Base, 3, 1))
	SET @Fator = @Fator + (89 * SUBSTRING(@Base, 4, 1))
	SET @Fator = @Fator + (38 * SUBSTRING(@Base, 5, 1))
	SET @Fator = @Fator + (62 * SUBSTRING(@Base, 6, 1))
	SET @Fator = @Fator + (45 * SUBSTRING(@Base, 7, 1))
	SET @Fator = @Fator + (53 * SUBSTRING(@Base, 8, 1))
	SET @Fator = @Fator + (15 * SUBSTRING(@Base, 9, 1))
	SET @Fator = @Fator + (50 * SUBSTRING(@Base, 10, 1))
	SET @Fator = @Fator + (5 * SUBSTRING(@Base, 11, 1))
	SET @Fator = @Fator + (49 * SUBSTRING(@Base, 12, 1))
	SET @Fator = @Fator + (34 * SUBSTRING(@Base, 13, 1))
	SET @Fator = @Fator + (81 * SUBSTRING(@Base, 14, 1))
	SET @Fator = @Fator + (76 * SUBSTRING(@Base, 15, 1))
	SET @Fator = @Fator + (27 * SUBSTRING(@Base, 16, 1))
	SET @Fator = @Fator + (90 * SUBSTRING(@Base, 17, 1))
	SET @Fator = @Fator + (9 * SUBSTRING(@Base, 18, 1))
	SET @Fator = @Fator + (30 * SUBSTRING(@Base, 19, 1))
	SET @Fator = @Fator + (3 * SUBSTRING(@Base, 20, 1))
-- calcula o checkdigit
	SET @CheckDigit = 98 - (@Fator % 97)
-- converte checkdigit para varchar
	SET @CheckDigitStr = RIGHT(CAST(@CheckDigit AS varchar(10)), 2)
	SET @CheckDigitStr = REPLICATE('0', 2 - LEN(@CheckDigitStr)) + @CheckDigitStr
-- devolve a referência MB
	RETURN (@Subentidade + @IdDocumentoStr + @CheckDigitStr)
END

ALTER AUTHORIZATION ON [FNT_Facturacao_CalculaReferenciaMB] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Facturacao_CalculaReferenciaMB] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Facturacao_ObtemDadosQRCode]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Facturacao_ObtemDadosQRCode](@CtxDocumento int, @IDDocumento int) RETURNS varchar(MAX) AS
BEGIN
-- declaração de variaveis
	DECLARE @CodigoQR varchar(MAX), @NIFEmpresa varchar(20), @EspacoFiscalEmpresa varchar(5), @TipoDocSAFT varchar(2), @NIFCliente varchar(20), @CodPaisCliente varchar(2), @AnuladoDoc bit, 
		@DataDoc datetime, @IDUnicoDoc varchar(60), @CodUnicoDoc varchar(100), @TotalImpostosDoc numeric(38, 6), @TotalDoc numeric(38, 6), @TotalRetencoesDoc numeric(38, 6), 
		@TotalNaoSujeitoIVADoc numeric(38, 6), @HashDoc varchar(200), @BaseIVATxIsenta numeric(38, 6), @BaseIVATxNormal numeric(38, 6), @TotalIVATxNormal numeric(38, 6), 
		@EspacoFiscalDoc varchar(5)
-- obtem NIF da empresa
	SELECT @NIFEmpresa = EMP_NIF, @EspacoFiscalEmpresa = EMP_ESPF
	FROM GIDWIN.dbo.FAP_EMPR WITH(NOLOCK)
	WHERE EMP_CODI = DB_NAME()		
-- obtem os dados necessários do documento de Conta para gerar o código QR 
	IF @CtxDocumento = 0
	BEGIN
		SELECT @TipoDocSAFT = tdo.TDO_TDSF, @DataDoc = cdo.CDO_DTEM, @AnuladoDoc = cdo.CDO_ANUL, @IDUnicoDoc = cdo.CDO_INVN, @HashDoc = cdo.CDO_HASH, @CodUnicoDoc = cdo.CDO_ATCU, 
			@TotalImpostosDoc = ISNULL(cdo.CDO_IVA, 0), @TotalRetencoesDoc = ISNULL(cdo.CDO_TTRF, 0), @TotalDoc = ISNULL(cdo.CDO_TTPR, 0), @TotalNaoSujeitoIVADoc = ISNULL(cdo.CDO_IN01, 0), 
			@NIFCliente = cdo.CDO_CNIF, @CodPaisCliente = cdo.CDO_CPAI, @BaseIVATxIsenta = ISNULL(cdo.CDO_IN01, 0), @BaseIVATxNormal = ISNULL(cdo.CDO_IN04, 0), 
			@TotalIVATxNormal = ISNULL(cdo.CDO_VI04, 0),
			@EspacoFiscalDoc = (CASE ISNULL(cdo.CDO_TXIV, 0) 
									WHEN 23.000000 THEN 'PT' 
									WHEN 22.000000 THEN 'PT-MA' 
									WHEN 16.000000 THEN 'PT-AC' 
									ELSE @EspacoFiscalEmpresa 
								END)
		FROM FAC_CDOC AS cdo WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU			
		WHERE cdo.CDO_IDTY = @IDDocumento	
	END
	ELSE
-- obtem os dados necessários do documento de Venda para gerar o código QR 
	IF @CtxDocumento = 1
	BEGIN
		SELECT @TipoDocSAFT = tdo.TDO_TDSF, @DataDoc = dve.DVE_DATA, @AnuladoDoc = dve.DVE_ANUL, @IDUnicoDoc = dve.DVE_INVN, @HashDoc = dve.DVE_HASH, @CodUnicoDoc = dve.DVE_ATCU, 
			@TotalImpostosDoc = dve.DVE_VIVA, @TotalRetencoesDoc = 0, @TotalDoc = dve.DVE_VTOT, @TotalNaoSujeitoIVADoc = ISNULL(dve.DVE_IN01, 0), @NIFCliente = dve.DVE_CNIF, 
			@CodPaisCliente = dve.PAI_CLIV, @BaseIVATxIsenta = ISNULL(dve.DVE_IN01, 0), @BaseIVATxNormal = ISNULL(dve.DVE_IN04, 0), @TotalIVATxNormal = ISNULL(dve.DVE_VI04, 0), 
			@EspacoFiscalDoc = (CASE (SELECT MAX(ISNULL(DVD_IVA, 0)) FROM FAC_DVDT WITH(NOLOCK) WHERE DVD_LCRB = 1 AND DVE_TDOC = dve.DVE_TDOC AND DVE_NDOC = dve.DVE_NDOC AND DVE_EANO = dve.DVE_EANO) 
									WHEN 23.000000 THEN 'PT' 
									WHEN 22.000000 THEN 'PT-MA' 
									WHEN 16.000000 THEN 'PT-AC' 
									ELSE @EspacoFiscalEmpresa 
								END)
		FROM FAC_DVEN AS dve WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU			
		WHERE dve.DVE_IDTY = @IDDocumento	
	END
	ELSE
-- obtem os dados necessários do documento de Recibo para gerar o código QR 
	IF @CtxDocumento = 2
	BEGIN
		SELECT @TipoDocSAFT = 'RG', @DataDoc = rec.REC_DATA, @AnuladoDoc = 0, @IDUnicoDoc = rec.REC_INVN, @HashDoc = '0', @CodUnicoDoc = rec.REC_ATCU, 
			@TotalImpostosDoc = SUM(ROUND(ABS(red.REC_VPAG + red.REC_VDES) * ISNULL(mcc.MVC_VIVA, 0) / ABS(red.REC_VTOT), 2)), @TotalRetencoesDoc = 0, @TotalDoc = rec.REC_VTOT, 
			@TotalNaoSujeitoIVADoc = SUM(ROUND(ABS(red.REC_VPAG + red.REC_VDES) * ISNULL(mcc.MVC_IN01, 0) / ABS(red.REC_VTOT), 2)), @NIFCliente = rec.REC_CNIF, @CodPaisCliente = rec.PAI_CLIV, 
			@BaseIVATxIsenta = SUM(ROUND(ABS(red.REC_VPAG + red.REC_VDES) * ISNULL(mcc.MVC_IN01, 0) / ABS(red.REC_VTOT), 2)), 
			@BaseIVATxNormal = SUM(ROUND(ABS(red.REC_VPAG + red.REC_VDES) * ISNULL(mcc.MVC_IN04, 0) / ABS(red.REC_VTOT), 2)), 
			@TotalIVATxNormal = SUM(ROUND(ABS(red.REC_VPAG + red.REC_VDES) * ISNULL(mcc.MVC_VIVA, 0) / ABS(red.REC_VTOT), 2)), 
			@EspacoFiscalDoc = (CASE MAX((CASE mcc.MVC_CTXT 
											WHEN 0 THEN ISNULL(cdo.CDO_TXIV, 0)  
											WHEN 1 THEN ISNULL(DVD_IVA, 0)
											ELSE 0 
										END)) 
									WHEN 23.000000 THEN 'PT' 
									WHEN 22.000000 THEN 'PT-MA' 
									WHEN 16.000000 THEN 'PT-AC' 
									ELSE @EspacoFiscalEmpresa 
								END)
		FROM FAC_RECC AS rec WITH(NOLOCK) INNER JOIN FAC_RECD AS red WITH(NOLOCK) ON rec.REC_TDOC = red.REC_TDOC AND rec.REC_NDOC = red.REC_NDOC AND rec.REC_EANO = red.REC_EANO
			INNER JOIN FAC_MVCC AS mcc WITH(NOLOCK) ON red.MVC_TDOC = mcc.MVC_TDOC AND red.MVC_NDOC = mcc.MVC_NDOC AND red.MVC_EANO = mcc.MVC_EANO 
			LEFT OUTER JOIN FAC_CDOC AS cdo WITH(NOLOCK) ON mcc.MVC_CTXT = 0 AND mcc.MVC_EANO = cdo.CDO_EANO AND mcc.MVC_TDOC = cdo.CDO_TDOC AND mcc.MVC_NDOC = cdo.CDO_CNUM
			LEFT OUTER JOIN FAC_DVDT AS dvt WITH(NOLOCK) ON mcc.MVC_CTXT = 1 AND dvt.DVD_LCRB = 1 AND mcc.MVC_TDOC = dvt.DVE_TDOC AND mcc.MVC_NDOC = dvt.DVE_NDOC AND mcc.MVC_EANO = dvt.DVE_EANO
		WHERE rec.REC_IDTY = @IDDocumento
		GROUP BY rec.REC_TDOC, rec.REC_NDOC, rec.REC_DATA, rec.REC_VTOT, rec.REC_CNIF, rec.PAI_CLIV, rec.REC_INVN, rec.REC_ATCU
	END
-- constroi codigo QR com a respetiva nomenclatura
	SET @CodigoQR = 'A:' + @NIFEmpresa + '*'
	SET @CodigoQR = @CodigoQR + 'B:' + @NIFCliente + '*'
	SET @CodigoQR = @CodigoQR + 'C:' + @CodPaisCliente + '*'
	SET @CodigoQR = @CodigoQR + 'D:' + @TipoDocSAFT + '*'
	SET @CodigoQR = @CodigoQR + 'E:' + (CASE @AnuladoDoc WHEN 1 THEN 'A' ELSE 'N' END) + '*'
	SET @CodigoQR = @CodigoQR + 'F:' + CONVERT(varchar(10), @DataDoc, 112) + '*'
	SET @CodigoQR = @CodigoQR + 'G:' + @IDUnicoDoc + '*'
	SET @CodigoQR = @CodigoQR + 'H:' + @CodUnicoDoc + '*'		
	SET @CodigoQR = @CodigoQR + 'I1:' + @EspacoFiscalDoc + '*'
	SET @CodigoQR = @CodigoQR + 'I2:' + LTRIM(STR(CAST(@BaseIVATxIsenta AS numeric(38, 2)), 16, 2)) + '*'		
	SET @CodigoQR = @CodigoQR + 'I7:' + LTRIM(STR(CAST(@BaseIVATxNormal AS numeric(38, 2)), 16, 2)) + '*'
	SET @CodigoQR = @CodigoQR + 'I8:' + LTRIM(STR(CAST(@TotalIVATxNormal AS numeric(38, 2)), 16, 2)) + '*'	
	IF @TotalNaoSujeitoIVADoc > 0
		SET @CodigoQR = @CodigoQR + 'L:' + LTRIM(STR(CAST(@TotalNaoSujeitoIVADoc AS numeric(38, 2)), 16, 2)) + '*'	
	SET @CodigoQR = @CodigoQR + 'N:' + LTRIM(STR(CAST(@TotalImpostosDoc AS numeric(38, 2)), 16, 2)) + '*'
	SET @CodigoQR = @CodigoQR + 'O:' + LTRIM(STR(CAST(@TotalDoc AS numeric(38, 2)), 16, 2)) + '*'
	IF @TotalRetencoesDoc > 0
		SET @CodigoQR = @CodigoQR + 'P:' + LTRIM(STR(CAST(@TotalRetencoesDoc AS numeric(38, 2)), 16, 2)) + '*'			
	SET @CodigoQR = @CodigoQR + 'Q:' + SUBSTRING(@HashDoc, 1, 1) + SUBSTRING(@HashDoc, 11, 1) + SUBSTRING(@HashDoc, 21, 1) + SUBSTRING(@HashDoc, 31, 1) + '*'
	SET @CodigoQR = @CodigoQR + 'R:' + (SELECT GIDWIN.dbo.FNT_Geral_ObtemNumeroCertificacao())
	RETURN @CodigoQR
END

ALTER AUTHORIZATION ON [FNT_Facturacao_ObtemDadosQRCode] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Facturacao_ObtemDadosQRCode] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Facturacao_ObtemExpressaoImpressao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Facturacao_ObtemExpressaoImpressao](@Hash varchar(200), @NumDoc int) RETURNS varchar(100) AS
BEGIN
-- declaração de variaveis
	declare @Expressao varchar(100)
-- constroi expressão p/ impressão diferente em função se o documento foi assinado ou não
	if isnull(@Hash, '') <> ''
	begin
-- obtem as posições do hash numero 1, 11, 21 e 31
		select @Expressao = substring(@Hash, 1, 1) + substring(@Hash, 11, 1) + substring(@Hash, 21, 1) + substring(@Hash, 31, 1)
-- adiciona o numero do certificado
		select @Expressao = @Expressao + ' - Processado por programa certificado nº. ' + GIDWIN.dbo.FNT_Geral_ObtemNumeroCertificacao() + '/AT'
	end
	else
		if @NumDoc is not null
			select @Expressao = 'Cópia do Documento Original ou Documento não Certificado'
		else
			select @Expressao = 'Documento em Preparação - Este Documento não Serve de Factura'
	RETURN @Expressao
END

ALTER AUTHORIZATION ON [FNT_Facturacao_ObtemExpressaoImpressao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Facturacao_ObtemExpressaoImpressao] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Geral_IncrementaPacoteEnvio]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Geral_IncrementaPacoteEnvio](@Pacote varchar(3)) RETURNS varchar(3) AS
BEGIN
-- declaração de variáveis
	DECLARE @ProxCaracter char(1), @Index int, @MudarNivel bit
-- verifica se pacote preenchido	
	IF ISNULL(@Pacote, '') <> ''
	BEGIN		
		SET @Index = 3
		SET @MudarNivel = 1
		WHILE (@Index >= 1) and (@MudarNivel = 1)
		BEGIN			
-- incrementa 3º caracter do pacote de envio	
			SET @ProxCaracter = CHAR(ASCII(SUBSTRING(@Pacote, @Index, 1)) + 1)				
-- verifica se caracter obtido é exceção (":") ou final ("[")		
			IF @ProxCaracter = ':'
			BEGIN
				SET @ProxCaracter = CHAR(ASCII(@ProxCaracter) + 7)		
				SET @MudarNivel = 0
			END
			ELSE
				IF @ProxCaracter = '['
				BEGIN
					SET @ProxCaracter = '0'
					SET @MudarNivel = 1
				END				
				ELSE
					SET @MudarNivel = 0
-- altera pacote de envio		
			SET @Pacote = STUFF(@Pacote, @Index, 1, @ProxCaracter)
			SET @Index = @Index - 1
		END
	END
	ELSE
		SET @Pacote = '000'
	RETURN(@Pacote)
END

ALTER AUTHORIZATION ON [FNT_Geral_IncrementaPacoteEnvio] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Geral_IncrementaPacoteEnvio] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Geral_ObtemCambio]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Geral_ObtemCambio](@CambioCompra bit, @CodPais varchar(2), @Data datetime) RETURNS numeric(38, 6) AS
BEGIN
-- declaração de variáveis
	DECLARE @DataAtual datetime, @Cambio numeric(38, 6)
-- obtem a data actual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem cambio de compra ou venda para o país e data especificados
	SET @Cambio = ISNULL(NULLIF((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) 
							WHEN @CodPais THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
							ELSE (SELECT TOP 1 ISNULL((CASE @CambioCompra WHEN 1 THEN CPA_COMP ELSE CPA_VEND END), 1) 
								FROM TAB_CPAI WITH(NOLOCK)
								WHERE PAI_CODI = @CodPais AND CAST(CONVERT(varchar(10), CPA_DATA, 105) AS datetime) <= CAST(CONVERT(varchar(10), ISNULL(@Data, @DataAtual), 105) AS datetime)
								ORDER BY CPA_DATA DESC) 
						END), 0), 1)
-- devolve valor do cambio
	RETURN @Cambio
END

ALTER AUTHORIZATION ON [FNT_Geral_ObtemCambio] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Geral_ObtemCambio] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Geral_RemoveCaracteresXMLInvalidos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Geral_RemoveCaracteresXMLInvalidos](@InputString varchar(MAX)) RETURNS varchar(MAX) AS
BEGIN
-- declaração de variáveis
	DECLARE @Counter int, @TestString varchar(40)
-- se string a verificar estiver preenchida	
	IF @InputString IS NOT NULL
	BEGIN		
-- inicia lista de caracteres XML inválidos
		SET @TestString = '%[' + CHAR(0) + CHAR(1) + CHAR(2) + CHAR(3) + CHAR(4) + CHAR(5) + CHAR(6) + CHAR(7) + CHAR(8) + CHAR(11) + CHAR(12) + CHAR(14) + CHAR(15) + CHAR(16) + CHAR(17) + CHAR(18) + CHAR(19) + CHAR(20) + CHAR(21) + CHAR(22) + CHAR(23) + CHAR(24) + CHAR(25) + CHAR(26) + CHAR(27) + CHAR(28) + CHAR(29) + CHAR(30) + CHAR(31) + ']%'
-- procede à 1ª verificação da existência de caracters XML inválidos na string
		SELECT @Counter = PATINDEX(@TestString, @InputString COLLATE Latin1_General_BIN)
-- enquanto existirem caracteres XML inválidos, procede à sua substituição pelo CHAR(32) (Espaço)
		WHILE @Counter <> 0
		BEGIN
			SELECT @InputString = STUFF(@InputString, @Counter, 1, CHAR(32))
			SELECT @Counter = PATINDEX(@TestString, @InputString COLLATE Latin1_General_BIN)
		END
	END
	RETURN(@InputString)
END

ALTER AUTHORIZATION ON [FNT_Geral_RemoveCaracteresXMLInvalidos] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Geral_RemoveCaracteresXMLInvalidos] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Geral_SeparaTexto]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Geral_SeparaTexto] (@Texto varchar(MAX), @Separador varchar(50)) RETURNS @Tbl TABLE 
(
	id int primary key identity(1, 1),
    valor varchar(MAX)
)
AS
BEGIN
-- declaração de variáveis
	DECLARE @Xml xml
-- converte texto em xml
	SET @Xml = CAST('<d>' + REPLACE(@Texto, @Separador, '</d><d>') + '</d>' AS xml)
-- insere na tabela os valores separados
    INSERT INTO @Tbl(valor)
    SELECT a.split.value('.', 'varchar(MAX)') 
    FROM @Xml.nodes('/d') AS a(split)
	WHERE a.split.value('.', 'varchar(MAX)') <> ''
-- devolve a tabela	
	RETURN 
END

ALTER AUTHORIZATION ON [FNT_Geral_SeparaTexto] TO  SCHEMA OWNER 
GRANT SELECT ON [FNT_Geral_SeparaTexto] TO [public] AS [dbo]
/****** Object:  UserDefinedFunction [FNT_Geral_SubstituiCaracteresXMLInvalidos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [FNT_Geral_SubstituiCaracteresXMLInvalidos] (@InputString varchar(MAX)) RETURNS varchar(MAX) AS
BEGIN
-- declaração de variáveis
	DECLARE @Counter int, @Char varchar(1)
-- se string a verificar estiver preenchida	
	IF @InputString IS NOT NULL
	BEGIN		
-- substitui os caracteres XML inválidos
		SET @InputString = REPLACE(@InputString, '''', '')
		SET @InputString = REPLACE(@InputString, '"', '')		
-- percorre a string à procura de caracters XML inválidos (<32 ou >127) para remover e os caracteres especiais para substituir
		SET @Counter = 1
		WHILE @Counter <= LEN(@InputString)
		BEGIN
			SET @Char = SUBSTRING(@InputString, @Counter, 1)			
			IF ASCII(@Char) = 170 --'ª'
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'a') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) = 186 --'º'
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'o') 
				SET @Counter = @Counter + 1
			END
			ELSE	
			IF ASCII(@Char) IN (192, 193, 194, 195, 196, 197) --('À', 'Á', 'Â', 'Ã', 'Ä', 'Å')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'A') 
				SET @Counter = @Counter + 1
			END
			ELSE			
			IF ASCII(@Char) = 199 --'Ç'
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'C') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) IN (200, 201, 202, 203) --('È', 'É', 'Ê', 'Ë')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'E') 
				SET @Counter = @Counter + 1
			END			
			ELSE
			IF ASCII(@Char) IN (204, 205, 206, 207) --('Ì', 'Í', 'Î', 'Ï')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'I') 
				SET @Counter = @Counter + 1
			END			
			ELSE		
			IF ASCII(@Char) = 209 --'Ñ'
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'N') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) IN (210, 211, 212, 213, 214, 216) --('Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'O') 
				SET @Counter = @Counter + 1
			END			
			ELSE			
			IF ASCII(@Char) IN (217, 218, 219, 220) --('Ù', 'Ú', 'Û', 'Ü')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'U') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) IN (159, 221) --('Ÿ', 'Ý')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'Y') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) IN (224, 225, 226, 227, 228, 229) --('à', 'á', 'â', 'ã', 'ä', 'å')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'a') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) = 231 --'ç'
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'c') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) IN (232, 233, 234, 235) --('è', 'é', 'ê', 'ë')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'e') 
				SET @Counter = @Counter + 1
			END
			ELSE			
			IF ASCII(@Char) IN (236, 237, 238, 239) --('ì', 'í', 'î', 'ï')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'i') 
				SET @Counter = @Counter + 1
			END
			ELSE			
			IF ASCII(@Char) = 241 --'ñ'
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'n') 
				SET @Counter = @Counter + 1
			END
			ELSE
			IF ASCII(@Char) IN (242, 243, 244, 245, 246, 248) --('ò', 'ó', 'ô', 'õ', 'ö', 'ø')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'o') 
				SET @Counter = @Counter + 1
			END			
			ELSE
			IF ASCII(@Char) IN (249, 250, 251, 252) --('ù', 'ú', 'û', 'ü')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'u') 
				SET @Counter = @Counter + 1
			END
			ELSE			
			IF ASCII(@Char) IN (253, 255) --('ý', 'ÿ')
			BEGIN
				SET @InputString = STUFF(@InputString, @Counter, 1, 'y') 
				SET @Counter = @Counter + 1
			END			
			ELSE	
			IF (ASCII(@Char) < 32) OR (ASCII(@Char) > 127)					
				SET @InputString = STUFF(@InputString, @Counter, 1, '')
			ELSE
				SET @Counter = @Counter + 1			
		END			
	END
	RETURN(@InputString)
END

ALTER AUTHORIZATION ON [FNT_Geral_SubstituiCaracteresXMLInvalidos] TO  SCHEMA OWNER 
GRANT EXECUTE ON [FNT_Geral_SubstituiCaracteresXMLInvalidos] TO [public] AS [dbo]
/****** Object:  Table [AEX_ENDG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [AEX_ENDG](
	[EDG_EANO] [int] NOT NULL,
	[LME_CODI] [varchar](17) NOT NULL,
	[EDG_NUME] [int] NOT NULL,
	[EDG_IDST] [varchar](20) NOT NULL,
	[EDG_DATA] [datetime] NOT NULL,
	[EDG_TVOL] [int] NOT NULL,
	[EDG_TPBR] [numeric](38, 6) NOT NULL,
	[EDG_TMCU] [numeric](38, 6) NOT NULL,
	[EDG_TVAL] [numeric](38, 6) NOT NULL,
	[EDG_PTRN] [varchar](20) NULL,
	[EDG_TRNP] [varchar](20) NULL,
	[EDG_REFI] [varchar](30) NOT NULL,
	[EDG_SVOL] [int] NOT NULL,
	[EDG_SPBR] [numeric](38, 6) NOT NULL,
	[CLI_CODI] [varchar](18) NULL,
	[EDG_ENOM] [varchar](75) NOT NULL,
	[EDG_EMOR] [varchar](100) NULL,
	[EDG_ELOC] [varchar](35) NULL,
	[EDG_ECPO] [varchar](12) NULL,
	[EDG_ELPO] [varchar](35) NULL,
	[EDG_ENIF] [varchar](50) NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[FOR_CODI] [varchar](18) NULL,
	[EDG_DNOM] [varchar](75) NOT NULL,
	[EDG_DMOR] [varchar](100) NULL,
	[EDG_DLOC] [varchar](35) NULL,
	[PAI_CODI1] [varchar](2) NOT NULL,
	[EDG_OBSE] [varchar](150) NULL,
	[EDG_ORIG] [int] NOT NULL,
	[EDG_UCRI] [varchar](30) NOT NULL,
	[EDG_DCRI] [datetime] NOT NULL,
	[EDG_UALT] [varchar](30) NULL,
	[EDG_DALT] [datetime] NULL,
	[EXM_EANO] [int] NULL,
	[EXM_CODI] [int] NULL,
	[DEC_CODI] [varchar](6) NULL,
	[EDG_NEXT] [varchar](20) NULL,
	[AGE_CODI] [varchar](18) NULL,
	[EDG_EXPO] [bit] NOT NULL,
	[EDG_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_AEX_ENDG] PRIMARY KEY CLUSTERED 
(
	[EDG_EANO] ASC,
	[LME_CODI] ASC,
	[EDG_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_AEX_ENDG] UNIQUE NONCLUSTERED 
(
	[EDG_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [AEX_ENDG] TO  SCHEMA OWNER 
GRANT DELETE ON [AEX_ENDG] TO [public] AS [dbo]
GRANT INSERT ON [AEX_ENDG] TO [public] AS [dbo]
GRANT SELECT ON [AEX_ENDG] TO [public] AS [dbo]
GRANT UPDATE ON [AEX_ENDG] TO [public] AS [dbo]
/****** Object:  Table [AEX_ENLN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [AEX_ENLN](
	[EDG_EANO] [int] NOT NULL,
	[LME_CODI] [varchar](17) NOT NULL,
	[EDG_NUME] [int] NOT NULL,
	[ELN_NLIN] [int] NOT NULL,
	[ELN_VOLS] [int] NOT NULL,
	[ELN_PART] [bit] NOT NULL,
	[TEM_CODI] [varchar](2) NOT NULL,
	[ELN_MARC] [varchar](25) NULL,
	[APA_CODI] [varchar](22) NULL,
	[ELN_DMER] [varchar](150) NOT NULL,
	[ELN_PLIQ] [numeric](38, 6) NOT NULL,
	[ELN_PBRT] [numeric](38, 6) NOT NULL,
	[ELN_VALO] [numeric](38, 6) NOT NULL,
	[ELN_LOCA] [varchar](31) NOT NULL,
	[ELN_EADU] [varchar](3) NOT NULL,
	[ELN_ALTU] [numeric](38, 6) NOT NULL,
	[ELN_COMP] [numeric](38, 6) NOT NULL,
	[ELN_LARG] [numeric](38, 6) NOT NULL,
	[ELN_UCRI] [varchar](30) NOT NULL,
	[ELN_DCRI] [datetime] NOT NULL,
	[ELN_UALT] [varchar](30) NULL,
	[ELN_DALT] [datetime] NULL,
 CONSTRAINT [PK_AEX_ENLN] PRIMARY KEY CLUSTERED 
(
	[EDG_EANO] ASC,
	[LME_CODI] ASC,
	[EDG_NUME] ASC,
	[ELN_NLIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [AEX_ENLN] TO  SCHEMA OWNER 
GRANT DELETE ON [AEX_ENLN] TO [public] AS [dbo]
GRANT INSERT ON [AEX_ENLN] TO [public] AS [dbo]
GRANT SELECT ON [AEX_ENLN] TO [public] AS [dbo]
GRANT UPDATE ON [AEX_ENLN] TO [public] AS [dbo]
/****** Object:  Table [AEX_SADG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [AEX_SADG](
	[SDG_EANO] [int] NOT NULL,
	[LME_CODI] [varchar](17) NOT NULL,
	[SDG_NUME] [int] NOT NULL,
	[SDG_DATA] [datetime] NOT NULL,
	[EDG_EANO] [int] NOT NULL,
	[EDG_NUME] [int] NOT NULL,
	[EDG_IDST] [varchar](20) NOT NULL,
	[SDG_VOLS] [int] NOT NULL,
	[SDG_PBRT] [numeric](38, 6) NOT NULL,
	[SDG_NCTM] [varchar](6) NULL,
	[SDG_NSDS] [varchar](35) NULL,
	[SDG_NNRM] [varchar](35) NULL,
	[SDG_DNRM] [datetime] NULL,
	[SDG_ASAI] [bit] NOT NULL,
	[SDG_REGI] [varchar](4) NOT NULL,
	[SDG_INF1] [varchar](70) NULL,
	[SDG_INF2] [varchar](70) NULL,
	[SDG_ANUL] [bit] NOT NULL,
	[SDG_MOTI] [varchar](150) NULL,
	[SDG_ORIG] [int] NOT NULL,
	[SDG_UCRI] [varchar](30) NOT NULL,
	[SDG_DCRI] [datetime] NOT NULL,
	[SDG_UALT] [varchar](30) NULL,
	[SDG_DALT] [datetime] NULL,
	[SDG_DTAS] [datetime] NULL,
	[SDG_DT6A] [datetime] NULL,
 CONSTRAINT [PK_AEX_SADG] PRIMARY KEY CLUSTERED 
(
	[SDG_EANO] ASC,
	[LME_CODI] ASC,
	[SDG_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [AEX_SADG] TO  SCHEMA OWNER 
GRANT DELETE ON [AEX_SADG] TO [public] AS [dbo]
GRANT INSERT ON [AEX_SADG] TO [public] AS [dbo]
GRANT SELECT ON [AEX_SADG] TO [public] AS [dbo]
GRANT UPDATE ON [AEX_SADG] TO [public] AS [dbo]
/****** Object:  Table [DHL_CCOD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [DHL_CCOD](
	[CCO_CODI] [varchar](4) NOT NULL,
	[CCO_DESC] [varchar](50) NOT NULL,
 CONSTRAINT [PK_DHL_CCOD] PRIMARY KEY CLUSTERED 
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [DHL_CCOD] TO  SCHEMA OWNER 
GRANT DELETE ON [DHL_CCOD] TO [public] AS [dbo]
GRANT INSERT ON [DHL_CCOD] TO [public] AS [dbo]
GRANT SELECT ON [DHL_CCOD] TO [public] AS [dbo]
GRANT UPDATE ON [DHL_CCOD] TO [public] AS [dbo]
/****** Object:  Table [DHL_CEAN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [DHL_CEAN](
	[DHL_ACCT] [varchar](9) NOT NULL,
	[DHL_NOME] [varchar](45) NOT NULL,
 CONSTRAINT [PK_DHL_CEAN] PRIMARY KEY CLUSTERED 
(
	[DHL_ACCT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [DHL_CEAN] TO  SCHEMA OWNER 
GRANT DELETE ON [DHL_CEAN] TO [public] AS [dbo]
GRANT INSERT ON [DHL_CEAN] TO [public] AS [dbo]
GRANT SELECT ON [DHL_CEAN] TO [public] AS [dbo]
GRANT UPDATE ON [DHL_CEAN] TO [public] AS [dbo]
/****** Object:  Table [FAC_CDDO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_CDDO](
	[CDO_EANO] [int] NOT NULL,
	[CDO_TDOC] [varchar](4) NOT NULL,
	[CDO_IDEN] [int] NOT NULL,
	[CDD_LINH] [int] NOT NULL,
	[CDD_TDOC] [int] NULL,
	[CDD_NDOC] [varchar](100) NULL,
	[CDD_DTEN] [datetime] NULL,
	[CDD_ENVI] [bit] NOT NULL,
	[CDD_RECE] [bit] NOT NULL,
	[CDD_DTRE] [datetime] NULL,
 CONSTRAINT [PK_FAC_CDDO] PRIMARY KEY CLUSTERED 
(
	[CDO_EANO] ASC,
	[CDO_TDOC] ASC,
	[CDO_IDEN] ASC,
	[CDD_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_CDDO] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_CDDO] TO [public] AS [dbo]
GRANT INSERT ON [FAC_CDDO] TO [public] AS [dbo]
GRANT SELECT ON [FAC_CDDO] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_CDDO] TO [public] AS [dbo]
/****** Object:  Table [FAC_CDOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_CDOC](
	[CDO_EANO] [int] NOT NULL,
	[CDO_TDOC] [varchar](4) NOT NULL,
	[CDO_IDEN] [int] NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[CDO_NPRO] [int] NULL,
	[CDO_PANO] [int] NULL,
	[CDO_TCNT] [bit] NOT NULL,
	[DEC_CODI] [varchar](6) NULL,
	[ALF_CODI] [varchar](8) NULL,
	[CDO_NORD] [varchar](25) NULL,
	[CDO_DTAC] [datetime] NULL,
	[CDO_STAT] [int] NOT NULL,
	[CDO_CNUM] [int] NULL,
	[CDO_DTEM] [datetime] NULL,
	[CDO_DTAB] [datetime] NULL,
	[CDO_DTIN] [datetime] NULL,
	[CDO_DTFI] [datetime] NULL,
	[CLI_DESP] [varchar](18) NOT NULL,
	[CLI_CCOR] [varchar](18) NOT NULL,
	[CLI_ENDC] [varchar](18) NOT NULL,
	[DIN_HONO] [int] NULL,
	[CDO_AGRA] [numeric](38, 6) NULL,
	[CDO_DESA] [numeric](38, 6) NULL,
	[CDO_FORH] [text] NULL,
	[CDO_TTDC] [numeric](38, 6) NULL,
	[CDO_TTIN] [numeric](38, 6) NULL,
	[CDO_TTHO] [numeric](38, 6) NULL,
	[CDO_TTRF] [numeric](38, 6) NULL,
	[CDO_BIVA] [numeric](38, 6) NULL,
	[CDO_IVA] [numeric](38, 6) NULL,
	[CDO_TXIV] [numeric](38, 6) NULL,
	[CDO_RTFO] [numeric](38, 6) NULL,
	[CDO_TTPR] [numeric](38, 6) NULL,
	[CDO_ISIV] [varchar](100) NULL,
	[CDO_QUNT] [numeric](38, 6) NULL,
	[CDO_QUAL] [varchar](35) NULL,
	[CDO_DESC] [varchar](40) NULL,
	[CDO_PBRT] [numeric](38, 6) NULL,
	[CDO_PLIQ] [numeric](38, 6) NULL,
	[CDO_VADU] [numeric](38, 6) NULL,
	[CDO_MARC] [varchar](44) NULL,
	[CDO_NFIA] [varchar](20) NULL,
	[CDO_CTMR] [varchar](20) NULL,
	[CDO_VREF] [varchar](50) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[CDO_MTRA] [varchar](30) NULL,
	[PAI_MTRA] [varchar](2) NULL,
	[CDO_DTEN] [datetime] NULL,
	[CDO_DTSA] [datetime] NULL,
	[CDO_PROC] [varchar](20) NULL,
	[CDO_UCRI] [varchar](30) NOT NULL,
	[CDO_DTCR] [datetime] NOT NULL,
	[CDO_UALT] [varchar](30) NULL,
	[CDO_DTAL] [datetime] NULL,
	[CDO_ANUL] [bit] NOT NULL,
	[CDO_IMPR] [bit] NOT NULL,
	[CDO_DEST] [varchar](20) NULL,
	[CDO_ARQU] [varchar](15) NULL,
	[CDO_TONE] [numeric](38, 6) NULL,
	[CDO_OPER] [varchar](15) NULL,
	[CDO_NREC] [varchar](10) NULL,
	[CDO_DTRE] [datetime] NULL,
	[CDO_RGPR] [varchar](20) NULL,
	[CDO_OBSR] [text] NULL,
	[CDO_IN01] [numeric](38, 6) NULL,
	[CDO_IN02] [numeric](38, 6) NULL,
	[CDO_IN03] [numeric](38, 6) NULL,
	[CDO_IN04] [numeric](38, 6) NULL,
	[CDO_VI01] [numeric](38, 6) NULL,
	[CDO_VI02] [numeric](38, 6) NULL,
	[CDO_VI03] [numeric](38, 6) NULL,
	[CDO_VI04] [numeric](38, 6) NULL,
	[CDO_CPRO] [bit] NOT NULL,
	[CDO_CFED] [bit] NOT NULL,
	[CDO_DPOC] [bit] NOT NULL,
	[CDO_IPOC] [bit] NOT NULL,
	[CDO_PALT] [bit] NOT NULL,
	[CDO_REGL] [varchar](20) NULL,
	[CDO_DTRL] [datetime] NULL,
	[CDO_MPAG] [int] NULL,
	[CDO_OKPI] [bit] NOT NULL,
	[DVE_TDOC] [varchar](4) NULL,
	[DVE_NDOC] [int] NULL,
	[DVE_EANO] [int] NULL,
	[EXM_OPER] [varchar](6) NULL,
	[CDO_IMEX] [bit] NOT NULL,
	[CDO_ORID] [int] NULL,
	[CDO_ORNR] [int] NULL,
	[CDO_ORDT] [datetime] NULL,
	[CDO_PAGO] [bit] NOT NULL,
	[CDO_OBSE] [text] NULL,
	[CDO_2ENV] [bit] NOT NULL,
	[CDO_2EDT] [datetime] NULL,
	[CDO_CTIP] [varchar](3) NULL,
	[CDO_CPRT] [varchar](18) NULL,
	[CDO_NUGL] [varchar](10) NULL,
	[CDO_CNOM] [varchar](70) NULL,
	[CDO_CMOR] [varchar](70) NULL,
	[CDO_CLOC] [varchar](35) NULL,
	[CDO_CCPO] [varchar](12) NULL,
	[CDO_CLPO] [varchar](35) NULL,
	[CDO_CNIF] [varchar](18) NULL,
	[CDO_CPAI] [varchar](2) NULL,
	[CDO_HASH] [varchar](200) NULL,
	[CDO_HCTR] [int] NULL,
	[CDO_CEAN] [varchar](13) NULL,
	[IIV_CODI] [varchar](3) NULL,
	[CDO_ANOG] [int] NULL,
	[CDO_TDOG] [varchar](4) NULL,
	[CDO_IDEG] [int] NULL,
	[FOR_CODI] [varchar](18) NULL,
	[FOR_NOME] [varchar](70) NULL,
	[CDO_IVAA] [numeric](38, 6) NOT NULL,
	[CCO_CODI] [varchar](4) NULL,
	[COP_CODI] [int] NULL,
	[CDO_ORIG] [int] NOT NULL,
	[CDO_PENH] [bit] NOT NULL,
	[CDO_DTPE] [datetime] NULL,
	[CDO_CPAG] [int] NULL,
	[CDO_EADC] [int] NOT NULL,
	[CDO_MBEN] [varchar](5) NULL,
	[CDO_MBRF] [varchar](9) NULL,
	[CDO_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
	[CDO_ATCU] [varchar](100) NOT NULL,
	[id_declaracaoDAR] [int] NULL,
	[CDO_SERI] [varchar](20) NULL,
	[CDO_INVN] [varchar](60) NULL,
	[CDO_PMRP] [bit] NOT NULL,
	[CDO_PMRD] [datetime] NULL,
	[CDO_ESAF] [bit] NOT NULL,
	[CDO_DSAF] [datetime] NULL,
 CONSTRAINT [PK_FAC_CDOC] PRIMARY KEY CLUSTERED 
(
	[CDO_EANO] ASC,
	[CDO_TDOC] ASC,
	[CDO_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_FAC_CDOC_CDO_IDTY] UNIQUE NONCLUSTERED 
(
	[CDO_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_CDOC] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_CDOC] TO [public] AS [dbo]
GRANT INSERT ON [FAC_CDOC] TO [public] AS [dbo]
GRANT SELECT ON [FAC_CDOC] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_CDOC] TO [public] AS [dbo]
/****** Object:  Table [FAC_DCDO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_DCDO](
	[CDO_EANO] [int] NOT NULL,
	[CDO_TDOC] [varchar](4) NOT NULL,
	[CDO_IDEN] [int] NOT NULL,
	[DCD_LINH] [int] NOT NULL,
	[DDO_CODI] [int] NULL,
	[DCD_DESC] [varchar](70) NULL,
	[DCD_VTOT] [numeric](38, 6) NULL,
	[CCO_CODI] [varchar](4) NULL,
	[DCD_DNOW] [datetime] NOT NULL,
	[DCD_VFCX] [bit] NOT NULL,
	[DCD_PMRP] [bit] NOT NULL,
	[DCD_PMRD] [datetime] NULL,
 CONSTRAINT [PK_FAC_DCDO] PRIMARY KEY CLUSTERED 
(
	[CDO_EANO] ASC,
	[CDO_TDOC] ASC,
	[CDO_IDEN] ASC,
	[DCD_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_DCDO] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_DCDO] TO [public] AS [dbo]
GRANT INSERT ON [FAC_DCDO] TO [public] AS [dbo]
GRANT SELECT ON [FAC_DCDO] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_DCDO] TO [public] AS [dbo]
/****** Object:  Table [FAC_DDCD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_DDCD](
	[CDO_EANO] [int] NOT NULL,
	[CDO_TDOC] [varchar](4) NOT NULL,
	[CDO_IDEN] [int] NOT NULL,
	[DCD_LINH] [int] NOT NULL,
	[DDC_ADIC] [int] NOT NULL,
	[DDC_DORI] [varchar](60) NULL,
	[DDC_DATA] [datetime] NULL,
	[DDC_IVA] [bit] NOT NULL,
	[DDC_TIVA] [numeric](38, 6) NULL,
	[DDC_VALO] [numeric](38, 6) NULL,
	[DDC_FORN] [varchar](50) NULL,
 CONSTRAINT [PK_FAC_DDCD] PRIMARY KEY CLUSTERED 
(
	[CDO_EANO] ASC,
	[CDO_TDOC] ASC,
	[CDO_IDEN] ASC,
	[DCD_LINH] ASC,
	[DDC_ADIC] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_DDCD] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_DDCD] TO [public] AS [dbo]
GRANT INSERT ON [FAC_DDCD] TO [public] AS [dbo]
GRANT SELECT ON [FAC_DDCD] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_DDCD] TO [public] AS [dbo]
/****** Object:  Table [FAC_DICD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_DICD](
	[CDO_EANO] [int] NOT NULL,
	[CDO_TDOC] [varchar](4) NOT NULL,
	[CDO_IDEN] [int] NOT NULL,
	[ICD_LINH] [int] NOT NULL,
	[DIC_ADIC] [int] NOT NULL,
	[DIC_DORI] [varchar](8) NULL,
	[DIC_DATA] [datetime] NULL,
	[DIC_IVA] [bit] NOT NULL,
	[DIC_TIVA] [numeric](38, 6) NULL,
	[DIC_VALO] [numeric](38, 6) NULL,
 CONSTRAINT [PK_FAC_DICD] PRIMARY KEY CLUSTERED 
(
	[CDO_EANO] ASC,
	[CDO_TDOC] ASC,
	[CDO_IDEN] ASC,
	[ICD_LINH] ASC,
	[DIC_ADIC] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_DICD] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_DICD] TO [public] AS [dbo]
GRANT INSERT ON [FAC_DICD] TO [public] AS [dbo]
GRANT SELECT ON [FAC_DICD] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_DICD] TO [public] AS [dbo]
/****** Object:  Table [FAC_DVDT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_DVDT](
	[DVE_TDOC] [varchar](4) NOT NULL,
	[DVE_NDOC] [int] NOT NULL,
	[DVE_EANO] [int] NOT NULL,
	[DVE_NLIN] [int] NOT NULL,
	[RFC_CODI] [int] NULL,
	[DVD_NOME] [varchar](500) NULL,
	[DVD_QUAN] [numeric](38, 6) NULL,
	[DVD_VALO] [numeric](38, 6) NULL,
	[DVD_IVA] [numeric](38, 6) NULL,
	[DVD_LCRB] [bit] NOT NULL,
	[DVD_CTXT] [int] NOT NULL,
	[DVD_FORN] [varchar](18) NULL,
	[DVD_LHON] [bit] NOT NULL,
	[IIV_CODI] [varchar](3) NULL,
	[IIV_MENC] [varchar](100) NULL,
	[CCO_CODI] [varchar](4) NULL,
	[DVD_PMRP] [bit] NOT NULL,
	[DVD_PMRD] [datetime] NULL,
 CONSTRAINT [PK_FAC_DVDT] PRIMARY KEY CLUSTERED 
(
	[DVE_TDOC] ASC,
	[DVE_NDOC] ASC,
	[DVE_EANO] ASC,
	[DVE_NLIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_DVDT] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_DVDT] TO [public] AS [dbo]
GRANT INSERT ON [FAC_DVDT] TO [public] AS [dbo]
GRANT SELECT ON [FAC_DVDT] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_DVDT] TO [public] AS [dbo]
/****** Object:  Table [FAC_DVEN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_DVEN](
	[DVE_TDOC] [varchar](4) NOT NULL,
	[DVE_NDOC] [int] NOT NULL,
	[DVE_EANO] [int] NOT NULL,
	[DVE_CTXT] [int] NOT NULL,
	[DVE_DATA] [datetime] NOT NULL,
	[CLI_CODI] [varchar](18) NULL,
	[DVE_CNOM] [varchar](70) NOT NULL,
	[DVE_CMOR] [varchar](70) NOT NULL,
	[DVE_CLOC] [varchar](35) NULL,
	[DVE_CCPO] [varchar](12) NULL,
	[DVE_CLPO] [varchar](35) NULL,
	[DVE_CNIF] [varchar](18) NOT NULL,
	[PAI_CLIV] [varchar](2) NOT NULL,
	[NDE_CODI] [varchar](3) NULL,
	[DVE_NPRO] [int] NULL,
	[DVE_OBSV] [text] NULL,
	[DVE_UTIC] [varchar](30) NULL,
	[DVE_DTCR] [datetime] NULL,
	[DVE_UTIA] [varchar](30) NULL,
	[DVE_DTAL] [datetime] NULL,
	[DVE_IN01] [numeric](38, 6) NULL,
	[DVE_IN02] [numeric](38, 6) NULL,
	[DVE_IN03] [numeric](38, 6) NULL,
	[DVE_IN04] [numeric](38, 6) NULL,
	[DVE_VI01] [numeric](38, 6) NULL,
	[DVE_VI02] [numeric](38, 6) NULL,
	[DVE_VI03] [numeric](38, 6) NULL,
	[DVE_VI04] [numeric](38, 6) NULL,
	[DVE_ANUL] [bit] NOT NULL,
	[DVE_VLIQ] [numeric](38, 6) NOT NULL,
	[DVE_VIVA] [numeric](38, 6) NOT NULL,
	[DVE_VTOT] [numeric](38, 6) NOT NULL,
	[DVE_IMPR] [bit] NOT NULL,
	[DVE_STAT] [int] NULL,
	[DVE_DIPS] [datetime] NOT NULL,
	[DVE_DFPS] [datetime] NOT NULL,
	[DVE_NDOR] [int] NULL,
	[DVE_PANO] [int] NULL,
	[DVE_IMEX] [bit] NOT NULL,
	[DVE_HASH] [varchar](200) NULL,
	[DVE_HCTR] [int] NULL,
	[TDO_TDSF] [varchar](2) NULL,
	[MVC_IDEN] [int] NULL,
	[MCR_CODI] [int] NULL,
	[DVE_MCRE] [varchar](50) NULL,
	[DVE_NEXT] [varchar](50) NULL,
	[DVE_NRDO] [varchar](60) NULL,
	[DVE_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
	[DVE_ATCU] [varchar](100) NOT NULL,
	[DEC_CODI] [varchar](6) NULL,
	[DVE_IDAR] [int] NULL,
	[DVE_CPRT] [varchar](35) NULL,
	[DVE_SERI] [varchar](20) NOT NULL,
	[DVE_INVN] [varchar](60) NULL,
	[DVE_PMRP] [bit] NOT NULL,
	[DVE_PMRD] [datetime] NULL,
	[DVE_ESAF] [bit] NOT NULL,
	[DVE_DSAF] [datetime] NULL,
 CONSTRAINT [PK_FAC_DVEN1] PRIMARY KEY CLUSTERED 
(
	[DVE_TDOC] ASC,
	[DVE_NDOC] ASC,
	[DVE_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_FAC_DVEN_DVE_IDTY] UNIQUE NONCLUSTERED 
(
	[DVE_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_DVEN] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_DVEN] TO [public] AS [dbo]
GRANT INSERT ON [FAC_DVEN] TO [public] AS [dbo]
GRANT SELECT ON [FAC_DVEN] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_DVEN] TO [public] AS [dbo]
/****** Object:  Table [FAC_FCDT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_FCDT](
	[FCX_NDOC] [int] NOT NULL,
	[FCX_DATA] [datetime] NOT NULL,
	[FCX_EANO] [int] NOT NULL,
	[FCD_NREG] [int] NOT NULL,
	[FCD_TDOC] [varchar](4) NOT NULL,
	[FCD_CTXT] [int] NOT NULL,
	[FCD_TIPO] [varchar](1) NOT NULL,
	[FCD_NPRO] [varchar](18) NULL,
	[FCD_DORI] [varchar](20) NOT NULL,
	[FCD_DINT] [varchar](20) NULL,
	[FCD_COMP] [varchar](50) NULL,
	[FCD_VTOT] [numeric](38, 6) NOT NULL,
	[FCD_SINA] [int] NOT NULL,
	[FCD_SLIS] [int] NOT NULL,
	[FCD_CCOD] [varchar](18) NOT NULL,
	[FCD_CNOM] [varchar](70) NOT NULL,
	[FCD_CMOR] [varchar](70) NOT NULL,
	[FCD_CLOC] [varchar](35) NULL,
	[FCD_CCPO] [varchar](12) NULL,
	[FCD_CLPO] [varchar](35) NULL,
	[FCD_CNIF] [varchar](18) NOT NULL,
	[PAI_LIVR] [varchar](2) NULL,
	[FCD_TIVA] [bit] NOT NULL,
	[FCD_TXIV] [numeric](38, 6) NULL,
	[FCD_TPAG] [int] NOT NULL,
	[FCD_BANC] [varchar](50) NULL,
	[FCD_NCHE] [varchar](18) NULL,
	[FCD_DTCH] [datetime] NULL,
	[FCD_LPRO] [bit] NOT NULL,
	[FCD_FORN] [varchar](50) NULL,
	[FCD_NDES] [varchar](3) NULL,
	[FCD_DESC] [varchar](50) NULL,
	[FCD_DOMO] [varchar](10) NOT NULL,
	[FCD_ENVI] [bit] NOT NULL,
	[FCD_IDEN] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_FAC_FCDT] PRIMARY KEY CLUSTERED 
(
	[FCX_NDOC] ASC,
	[FCX_DATA] ASC,
	[FCX_EANO] ASC,
	[FCD_NREG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_FCDT] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_FCDT] TO [public] AS [dbo]
GRANT INSERT ON [FAC_FCDT] TO [public] AS [dbo]
GRANT SELECT ON [FAC_FCDT] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_FCDT] TO [public] AS [dbo]
/****** Object:  Table [FAC_FCXA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_FCXA](
	[FCX_NDOC] [int] NOT NULL,
	[FCX_DATA] [datetime] NOT NULL,
	[FCX_EANO] [int] NOT NULL,
	[FCX_TDOC] [varchar](4) NOT NULL,
	[FCX_CTXT] [int] NOT NULL,
	[FCX_ANUL] [bit] NOT NULL,
	[FCX_IMPR] [bit] NOT NULL,
	[FCX_STAT] [int] NOT NULL,
	[FCX_UTIC] [varchar](30) NULL,
	[FCX_DTCR] [datetime] NULL,
	[FCX_UTIA] [varchar](30) NULL,
	[FCX_DTAL] [datetime] NULL,
	[FCX_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_FAC_FCXA] PRIMARY KEY CLUSTERED 
(
	[FCX_NDOC] ASC,
	[FCX_DATA] ASC,
	[FCX_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_FAC_FCXA_FCX_IDTY] UNIQUE NONCLUSTERED 
(
	[FCX_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_FCXA] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_FCXA] TO [public] AS [dbo]
GRANT INSERT ON [FAC_FCXA] TO [public] AS [dbo]
GRANT SELECT ON [FAC_FCXA] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_FCXA] TO [public] AS [dbo]
/****** Object:  Table [FAC_ICDO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_ICDO](
	[CDO_EANO] [int] NOT NULL,
	[CDO_TDOC] [varchar](4) NOT NULL,
	[CDO_IDEN] [int] NOT NULL,
	[ICD_LINH] [int] NOT NULL,
	[DIN_CODI] [int] NULL,
	[ICD_DESC] [varchar](70) NULL,
	[ICD_VTOT] [numeric](38, 6) NULL,
	[CCO_CODI] [varchar](4) NULL,
	[ICD_ISEN] [bit] NOT NULL,
	[IIV_CODI] [varchar](3) NULL,
	[IIV_MENC] [varchar](100) NULL,
	[ICD_PMRP] [bit] NOT NULL,
	[ICD_PMRD] [datetime] NULL,
 CONSTRAINT [PK_FAC_ICDO] PRIMARY KEY CLUSTERED 
(
	[CDO_EANO] ASC,
	[CDO_TDOC] ASC,
	[CDO_IDEN] ASC,
	[ICD_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_ICDO] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_ICDO] TO [public] AS [dbo]
GRANT INSERT ON [FAC_ICDO] TO [public] AS [dbo]
GRANT SELECT ON [FAC_ICDO] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_ICDO] TO [public] AS [dbo]
/****** Object:  Table [FAC_LCCT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_LCCT](
	[LCC_TDOC] [varchar](4) NOT NULL,
	[LCC_NDOC] [int] NOT NULL,
	[LCC_EANO] [int] NOT NULL,
	[LCC_CTXT] [int] NOT NULL,
	[LCC_DATA] [datetime] NOT NULL,
	[CLI_CODI] [varchar](18) NULL,
	[LCC_CNOM] [varchar](70) NOT NULL,
	[LCC_CMOR] [varchar](70) NOT NULL,
	[LCC_CLOC] [varchar](35) NULL,
	[LCC_CCPO] [varchar](12) NULL,
	[LCC_CLPO] [varchar](35) NOT NULL,
	[LCC_CNIF] [varchar](18) NOT NULL,
	[PAI_CLIV] [varchar](2) NOT NULL,
	[LCC_DINT] [varchar](20) NULL,
	[LCC_DORI] [varchar](20) NULL,
	[LCC_COMP] [varchar](50) NULL,
	[LCC_VTOT] [numeric](38, 6) NOT NULL,
	[LCC_CTPT] [varchar](20) NULL,
	[LCC_OBSV] [text] NULL,
	[LCC_UTIC] [varchar](30) NOT NULL,
	[LCC_DTCR] [datetime] NOT NULL,
	[LCC_UTIA] [varchar](30) NOT NULL,
	[LCC_DTAL] [datetime] NOT NULL,
	[LCC_ANUL] [bit] NOT NULL,
	[LCC_IMPR] [bit] NOT NULL,
	[LCC_SINA] [int] NOT NULL,
	[LCC_SANT] [numeric](38, 6) NOT NULL,
	[LCC_SAPO] [numeric](38, 6) NOT NULL,
	[LCC_SSAN] [varchar](2) NOT NULL,
	[LCC_SSAP] [varchar](2) NOT NULL,
	[LCC_STAT] [int] NOT NULL,
	[LCC_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
	[LCC_CONF] [bit] NOT NULL,
	[LCC_SERI] [varchar](20) NOT NULL,
 CONSTRAINT [PK_FAC_LCCT] PRIMARY KEY CLUSTERED 
(
	[LCC_TDOC] ASC,
	[LCC_NDOC] ASC,
	[LCC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_FAC_LCCT_LCC_IDTY] UNIQUE NONCLUSTERED 
(
	[LCC_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_LCCT] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_LCCT] TO [public] AS [dbo]
GRANT INSERT ON [FAC_LCCT] TO [public] AS [dbo]
GRANT SELECT ON [FAC_LCCT] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_LCCT] TO [public] AS [dbo]
/****** Object:  Table [FAC_MVCC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_MVCC](
	[MVC_TDOC] [varchar](4) NOT NULL,
	[MVC_NDOC] [int] NOT NULL,
	[MVC_EANO] [int] NOT NULL,
	[MVC_CTXT] [int] NOT NULL,
	[MVC_DATA] [datetime] NULL,
	[MVC_DESC] [varchar](500) NULL,
	[MVC_TMOV] [int] NOT NULL,
	[MVC_TENT] [int] NOT NULL,
	[MVC_ENTI] [varchar](18) NOT NULL,
	[MVC_NCON] [varchar](18) NULL,
	[MVC_NDES] [varchar](3) NULL,
	[MVC_NPRO] [int] NULL,
	[MVC_VTOT] [numeric](38, 6) NULL,
	[MVC_VDEB] [numeric](38, 6) NULL,
	[MVC_VIVA] [numeric](38, 6) NULL,
	[MVC_VI01] [numeric](38, 6) NULL,
	[MVC_VI02] [numeric](38, 6) NULL,
	[MVC_VI03] [numeric](38, 6) NULL,
	[MVC_VI04] [numeric](38, 6) NULL,
	[MVC_IN01] [numeric](38, 6) NULL,
	[MVC_IN02] [numeric](38, 6) NULL,
	[MVC_IN03] [numeric](38, 6) NULL,
	[MVC_IN04] [numeric](38, 6) NULL,
	[MVC_RECA] [bit] NOT NULL,
	[MVC_UTIC] [varchar](30) NULL,
	[MVC_DTCR] [datetime] NULL,
	[MVC_UTIA] [varchar](30) NULL,
	[MVC_DTAL] [datetime] NULL,
	[MVC_IMPR] [bit] NOT NULL,
	[MVC_STAT] [int] NOT NULL,
	[MVC_DINT] [varchar](50) NULL,
	[MVC_DORI] [varchar](50) NULL,
	[MVC_COMP] [varchar](50) NULL,
	[MVC_GPOC] [bit] NOT NULL,
	[MVC_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[MVC_VRTF] [numeric](38, 6) NOT NULL,
	[MVC_SERI] [varchar](20) NOT NULL,
 CONSTRAINT [PK_FAC_MVCC] PRIMARY KEY CLUSTERED 
(
	[MVC_TDOC] ASC,
	[MVC_NDOC] ASC,
	[MVC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_MVCC] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_MVCC] TO [public] AS [dbo]
GRANT INSERT ON [FAC_MVCC] TO [public] AS [dbo]
GRANT SELECT ON [FAC_MVCC] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_MVCC] TO [public] AS [dbo]
/****** Object:  Table [FAC_RECC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_RECC](
	[REC_TDOC] [varchar](4) NOT NULL,
	[REC_NDOC] [int] NOT NULL,
	[REC_EANO] [int] NOT NULL,
	[REC_STAT] [int] NULL,
	[REC_CTXT] [int] NOT NULL,
	[REC_DATA] [datetime] NULL,
	[REC_ENTI] [varchar](18) NOT NULL,
	[REC_BANC] [varchar](80) NULL,
	[REC_NCHE] [varchar](20) NULL,
	[REC_DTCH] [datetime] NULL,
	[REC_OBSV] [text] NULL,
	[REC_VLIQ] [numeric](38, 6) NOT NULL,
	[REC_VDES] [numeric](38, 6) NULL,
	[REC_VTOT] [numeric](38, 6) NOT NULL,
	[REC_UTIC] [varchar](30) NULL,
	[REC_DTCR] [datetime] NULL,
	[REC_UTIA] [varchar](30) NULL,
	[REC_DTAL] [datetime] NULL,
	[REC_IMPR] [bit] NULL,
	[REC_FLIQ] [varchar](20) NOT NULL,
	[REC_CNOM] [varchar](70) NOT NULL,
	[REC_CMOR] [varchar](70) NULL,
	[REC_CLOC] [varchar](35) NULL,
	[REC_CCPO] [varchar](12) NULL,
	[REC_CLPO] [varchar](35) NULL,
	[REC_CNIF] [varchar](18) NOT NULL,
	[PAI_CLIV] [varchar](2) NULL,
	[REC_DOCL] [varchar](7000) NULL,
	[REC_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
	[REC_ATCU] [varchar](100) NOT NULL,
	[REC_SERI] [varchar](20) NOT NULL,
	[REC_INVN] [varchar](60) NULL,
 CONSTRAINT [PK_FAC_RECC] PRIMARY KEY CLUSTERED 
(
	[REC_TDOC] ASC,
	[REC_NDOC] ASC,
	[REC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_FAC_RECC_REC_IDTY] UNIQUE NONCLUSTERED 
(
	[REC_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_RECC] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_RECC] TO [public] AS [dbo]
GRANT INSERT ON [FAC_RECC] TO [public] AS [dbo]
GRANT SELECT ON [FAC_RECC] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_RECC] TO [public] AS [dbo]
/****** Object:  Table [FAC_RECD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [FAC_RECD](
	[REC_TDOC] [varchar](4) NOT NULL,
	[REC_NDOC] [int] NOT NULL,
	[REC_EANO] [int] NOT NULL,
	[MVC_TDOC] [varchar](4) NOT NULL,
	[MVC_NDOC] [int] NOT NULL,
	[MVC_EANO] [int] NOT NULL,
	[REC_DATA] [datetime] NOT NULL,
	[REC_VTOT] [numeric](38, 6) NOT NULL,
	[REC_VDEB] [numeric](38, 6) NOT NULL,
	[REC_VPAG] [numeric](38, 6) NOT NULL,
	[REC_VDES] [numeric](38, 6) NOT NULL,
	[REC_PGTD] [bit] NOT NULL,
	[REC_VRTF] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_FAC_RECD] PRIMARY KEY CLUSTERED 
(
	[REC_TDOC] ASC,
	[REC_NDOC] ASC,
	[REC_EANO] ASC,
	[MVC_TDOC] ASC,
	[MVC_NDOC] ASC,
	[MVC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [FAC_RECD] TO  SCHEMA OWNER 
GRANT DELETE ON [FAC_RECD] TO [public] AS [dbo]
GRANT INSERT ON [FAC_RECD] TO [public] AS [dbo]
GRANT SELECT ON [FAC_RECD] TO [public] AS [dbo]
GRANT UPDATE ON [FAC_RECD] TO [public] AS [dbo]
/****** Object:  Table [HST_SDSI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [HST_SDSI](
	[DSI_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DSI_CODI] [int] NOT NULL,
	[DSI_DATA] [datetime] NOT NULL,
	[DSI_MSGI] [varchar](50) NOT NULL,
	[DSI_MSGD] [xml] NOT NULL,
	[DSI_STAT] [int] NOT NULL,
	[DSI_DTST] [datetime] NOT NULL,
	[DSI_TMSG] [int] NULL,
	[DSI_RDES] [bit] NOT NULL,
	[DSI_NCTM] [varchar](14) NULL,
	[DSI_RESG] [varchar](10) NULL,
	[DSC_EANO] [int] NULL,
	[DSC_NPRO] [int] NULL,
 CONSTRAINT [PK_HST_SDSI] PRIMARY KEY CLUSTERED 
(
	[DSI_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [HST_SDSI] TO  SCHEMA OWNER 
GRANT DELETE ON [HST_SDSI] TO [public] AS [dbo]
GRANT INSERT ON [HST_SDSI] TO [public] AS [dbo]
GRANT SELECT ON [HST_SDSI] TO [public] AS [dbo]
GRANT UPDATE ON [HST_SDSI] TO [public] AS [dbo]
/****** Object:  Table [IMP_DUI2]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [IMP_DUI2](
	[DU2_CPRT] [varchar](18) NOT NULL,
	[DU2_AERP] [varchar](3) NOT NULL,
	[DU2_AERD] [varchar](3) NOT NULL,
	[DU2_TMAN] [varchar](1) NOT NULL,
	[DU2_DTVO] [datetime] NOT NULL,
	[DU2_GTWY] [varchar](6) NOT NULL,
	[DU2_DTIN] [datetime] NOT NULL,
	[DU2_ALFA] [varchar](8) NOT NULL,
	[DU2_CIEX] [varchar](10) NULL,
	[DU2_ENOM] [varchar](70) NOT NULL,
	[DU2_EMOR] [varchar](70) NOT NULL,
	[DU2_ELOC] [varchar](30) NOT NULL,
	[DU2_ECPO] [varchar](12) NULL,
	[DU2_ELPO] [varchar](30) NULL,
	[DU2_CEAN] [varchar](13) NULL,
	[DU2_DNIF] [varchar](18) NULL,
	[DU2_DNOM] [varchar](70) NOT NULL,
	[DU2_DMOR] [varchar](70) NOT NULL,
	[DU2_DLOC] [varchar](30) NOT NULL,
	[DU2_DCPO] [varchar](12) NOT NULL,
	[DU2_DLPO] [varchar](30) NOT NULL,
	[DU2_TVL6] [int] NOT NULL,
	[DU2_PA15] [varchar](2) NOT NULL,
	[DU2_PA16] [varchar](2) NOT NULL,
	[DU2_PA17] [varchar](2) NOT NULL,
	[DU2_TR18] [varchar](2) NOT NULL,
	[DU2_MT18] [varchar](30) NULL,
	[DU2_TR21] [varchar](2) NOT NULL,
	[DU2_PA21] [varchar](2) NULL,
	[DU2_CT19] [int] NOT NULL,
	[DU2_CO20] [varchar](3) NOT NULL,
	[DU2_PR22] [varchar](3) NOT NULL,
	[DU2_MT22] [numeric](38, 6) NOT NULL,
	[DU2_CO24] [varchar](2) NOT NULL,
	[DU2_CO30] [varchar](17) NOT NULL,
	[DU2_MBRT] [numeric](38, 6) NOT NULL,
	[DU2_MLQT] [numeric](38, 6) NOT NULL,
	[DU2_NVOO] [varchar](20) NULL,
	[DU2_DTYP] [varchar](2) NULL,
	[DU2_TPCG] [varchar](2) NULL,
	[DU2_AERO] [varchar](80) NULL,
	[DU2_PAYM] [int] NULL,
	[DU2_NVRF] [varchar](50) NULL,
	[DU2_CIDE] [varchar](10) NULL,
	[DU2_PPFC] [varchar](2) NULL,
	[DU2_MCPA] [varchar](20) NULL,
	[DU2_REF1] [varchar](50) NULL,
	[DU2_REF2] [varchar](50) NULL,
	[DU2_SHIP] [varchar](11) NULL,
	[DU2_TRAC] [varchar](35) NULL,
	[DU2_DELG] [varchar](6) NULL,
	[DU2_NVSR] [int] NULL,
	[DU2_CO33] [varchar](22) NULL,
	[DU2_DESG] [varchar](150) NULL,
	[DU2_US41] [numeric](38, 6) NOT NULL,
	[DU2_SINT] [bit] NOT NULL,
	[DU2_DTEX] [datetime] NULL,
 CONSTRAINT [PK_IMP_DUI2] PRIMARY KEY CLUSTERED 
(
	[DU2_CPRT] ASC,
	[DU2_AERP] ASC,
	[DU2_AERD] ASC,
	[DU2_TMAN] ASC,
	[DU2_DTVO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [IMP_DUI2] TO  SCHEMA OWNER 
GRANT DELETE ON [IMP_DUI2] TO [public] AS [dbo]
GRANT INSERT ON [IMP_DUI2] TO [public] AS [dbo]
GRANT SELECT ON [IMP_DUI2] TO [public] AS [dbo]
GRANT UPDATE ON [IMP_DUI2] TO [public] AS [dbo]
/****** Object:  Table [INT_LNCC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [INT_LNCC](
	[LNC_EANO] [int] NOT NULL,
	[LNC_NUME] [int] NOT NULL,
	[LNC_DATA] [datetime] NOT NULL,
	[LNC_TMOV] [int] NOT NULL,
	[LNC_MESR] [int] NOT NULL,
	[LNC_DINR] [int] NULL,
	[LNC_STAT] [int] NOT NULL,
	[CLI_CODI] [varchar](18) NOT NULL,
	[CLI_NOME] [varchar](70) NOT NULL,
	[FOR_CODI] [varchar](18) NULL,
	[FOR_NOME] [varchar](70) NULL,
	[LNC_FTNR] [varchar](35) NULL,
	[LNC_FTDT] [datetime] NULL,
	[DEC_CODI] [varchar](6) NOT NULL,
	[DEC_NOME] [varchar](70) NOT NULL,
	[LNC_OBSE] [text] NULL,
	[LNC_TFAC] [numeric](38, 6) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_PREF] [varchar](3) NOT NULL,
	[LNC_CAMB] [numeric](38, 6) NOT NULL,
	[LNC_TFRE] [numeric](38, 6) NOT NULL,
	[PAI_CODI1] [varchar](2) NOT NULL,
	[PAI_PREF1] [varchar](3) NOT NULL,
	[LNC_CMBF] [numeric](38, 6) NOT NULL,
	[LNC_TDES] [numeric](38, 6) NOT NULL,
	[LNC_TMLQ] [numeric](38, 6) NOT NULL,
	[LNC_TUNS] [int] NOT NULL,
	[LNC_VEST] [numeric](38, 6) NOT NULL,
	[LNC_UCRI] [varchar](30) NOT NULL,
	[LNC_DCRI] [datetime] NOT NULL,
	[LNC_UALT] [varchar](30) NOT NULL,
	[LNC_DALT] [datetime] NOT NULL,
	[LNC_IVCB] [bit] NOT NULL,
	[LNC_PACO] [int] NULL,
 CONSTRAINT [PK_INT_LNCC] PRIMARY KEY CLUSTERED 
(
	[LNC_EANO] ASC,
	[LNC_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [INT_LNCC] TO  SCHEMA OWNER 
GRANT DELETE ON [INT_LNCC] TO [public] AS [dbo]
GRANT INSERT ON [INT_LNCC] TO [public] AS [dbo]
GRANT SELECT ON [INT_LNCC] TO [public] AS [dbo]
GRANT UPDATE ON [INT_LNCC] TO [public] AS [dbo]
/****** Object:  Table [INT_LNCD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [INT_LNCD](
	[LNC_EANO] [int] NOT NULL,
	[LNC_NUME] [int] NOT NULL,
	[LND_NUME] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](35) NULL,
	[PAI_CODI1] [varchar](2) NOT NULL,
	[PAI_NOME1] [varchar](35) NULL,
	[CEN_CODI] [varchar](3) NOT NULL,
	[CEN_NOME] [varchar](35) NULL,
	[NTR_CODI] [varchar](2) NOT NULL,
	[NTR_NOME] [varchar](70) NOT NULL,
	[MTR_CODI] [varchar](2) NOT NULL,
	[MTR_NOME] [varchar](35) NULL,
	[PAE_CODI] [varchar](8) NULL,
	[PAE_NOME] [varchar](35) NULL,
	[RES_CODI] [int] NOT NULL,
	[RES_NOME] [varchar](35) NOT NULL,
	[NC8_CODI] [varchar](10) NOT NULL,
	[NC8_DESG] [text] NOT NULL,
	[LND_TIVA] [numeric](38, 6) NOT NULL,
	[LND_VALO] [numeric](38, 6) NOT NULL,
	[LND_MLIQ] [numeric](38, 6) NOT NULL,
	[LND_QUNS] [int] NOT NULL,
	[LND_VEST] [numeric](38, 6) NOT NULL,
	[LND_ORIG] [int] NOT NULL,
	[NC8_REFI] [int] NULL,
 CONSTRAINT [PK_INT_LNCD] PRIMARY KEY CLUSTERED 
(
	[LNC_EANO] ASC,
	[LNC_NUME] ASC,
	[LND_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [INT_LNCD] TO  SCHEMA OWNER 
GRANT DELETE ON [INT_LNCD] TO [public] AS [dbo]
GRANT INSERT ON [INT_LNCD] TO [public] AS [dbo]
GRANT SELECT ON [INT_LNCD] TO [public] AS [dbo]
GRANT UPDATE ON [INT_LNCD] TO [public] AS [dbo]
/****** Object:  Table [LOG_DCON]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DCON](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DCO_CODI] [int] NOT NULL,
	[DCO_CNUM] [varchar](20) NULL,
	[DCO_TIPO] [varchar](10) NULL,
 CONSTRAINT [PK_LOG_DCON] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DCON] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DCON] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DCON] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DCON] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DCON] TO [public] AS [dbo]
/****** Object:  Table [LOG_DDOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DDOC](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DDO_CODI] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DDO_NUME] [varchar](70) NULL,
	[DDO_DINI] [datetime] NULL,
	[DDO_DFIM] [datetime] NULL,
	[CEN_CODI] [varchar](3) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[DDO_MONT] [numeric](38, 6) NULL,
	[DDO_DPRZ] [int] NULL,
	[DDO_NINV] [varchar](25) NULL,
	[DDO_AUTO] [int] NOT NULL,
 CONSTRAINT [PK_LOG_DDOC] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DDOC] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DDOC] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DDOC] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DDOC] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DDOC] TO [public] AS [dbo]
/****** Object:  Table [LOG_DU31]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DU31](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[D31_CODI] [int] NOT NULL,
	[D31_MARC] [varchar](512) NULL,
	[D31_NUME] [varchar](20) NULL,
	[D31_QNTD] [numeric](38, 6) NOT NULL,
	[UME_CODI] [varchar](3) NULL,
	[D31_CASP] [bit] NOT NULL,
	[D31_CASR] [bit] NOT NULL,
	[D31_CASC] [bit] NOT NULL,
	[D31_TTVL] [bit] NOT NULL,
 CONSTRAINT [PK_LOG_DU31] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DU31] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DU31] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DU31] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DU31] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DU31] TO [public] AS [dbo]
/****** Object:  Table [LOG_DUAD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DUAD](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[APA_CO33] [varchar](22) NULL,
	[UME_CODI] [varchar](3) NULL,
	[DUA_TIVA] [numeric](38, 6) NULL,
	[DUA_TRIB] [int] NULL,
	[DUA_PLIQ] [numeric](38, 6) NULL,
	[DUA_GRAD] [numeric](38, 6) NULL,
	[PAI_CO34] [varchar](2) NULL,
	[DUA_MB35] [numeric](38, 6) NOT NULL,
	[PRE_CO36] [varchar](3) NULL,
	[RRE_PREF] [int] NULL,
	[DUA_RG37] [varchar](4) NULL,
	[DUA_R37B] [varchar](6) NULL,
	[DUA_ML38] [numeric](38, 6) NOT NULL,
	[DUA_CO39] [varchar](20) NULL,
	[DUA_US41] [numeric](38, 6) NULL,
	[USU_CO41] [varchar](10) NULL,
	[DUA_VA42] [numeric](38, 6) NOT NULL,
	[DUA_VFRE] [numeric](38, 6) NULL,
	[DUA_VSEG] [numeric](38, 6) NULL,
	[DUA_VTRA] [numeric](38, 6) NULL,
	[DUA_ROYA] [numeric](38, 6) NULL,
	[DUA_VROY] [numeric](38, 6) NULL,
	[DUA_VDIR] [numeric](38, 6) NULL,
	[DUA_VOPT] [numeric](38, 6) NULL,
	[DUA_DESG] [varchar](150) NULL,
	[DUA_LCMB] [int] NOT NULL,
	[DUA_CAUC] [varchar](24) NULL,
	[DUA_CANO] [varchar](4) NULL,
	[DUA_CTIP] [varchar](1) NULL,
	[DUA_CENT] [int] NULL,
	[ARM_CO49] [varchar](17) NULL,
	[AGE_CO50] [varchar](18) NULL,
	[ALF_CO53] [varchar](8) NULL,
	[DUA_VEST] [numeric](38, 6) NOT NULL,
	[DUA_AJUS] [numeric](38, 6) NOT NULL,
	[DUA_CORE] [int] NULL,
	[DUA_CONR] [varchar](20) NULL,
	[DUA_DANO] [int] NULL,
	[DUA_DNUM] [varchar](6) NULL,
	[DUA_DNRS] [varchar](2) NULL,
	[DUA_DDAT] [datetime] NULL,
	[DUA_LINH] [varchar](22) NULL,
	[DUA_VATO] [numeric](38, 6) NULL,
	[DUA_NEPO] [varchar](10) NULL,
	[DUA_BTRI] [numeric](38, 6) NULL,
	[DUA_TXCO] [bit] NOT NULL,
	[DUA_TXVL] [numeric](38, 6) NULL,
	[DUA_MTRI] [numeric](38, 6) NULL,
	[DUA_IVAV] [numeric](38, 6) NULL,
	[DUA_BTIV] [numeric](38, 6) NULL,
	[RRE_CODI] [int] NULL,
	[DUA_MPAG] [varchar](1) NULL,
	[FLE_CODI] [int] NULL,
	[DUA_VSEL] [numeric](38, 6) NULL,
	[DUA_VIVA] [numeric](38, 6) NULL,
	[DUA_VAEU] [numeric](38, 6) NULL,
	[APA_CP33] [varchar](22) NULL,
	[DUA_TC31] [varchar](120) NULL,
	[DUA_TC44] [varchar](120) NULL,
	[DUA_MTPR] [numeric](38, 6) NULL,
	[DUA_QUAL] [varchar](4) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[EAD_CODI] [varchar](8) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[DUA_IMPO] [varchar](3) NULL,
	[DUA_ATAR] [varchar](10) NULL,
	[DUA_AIVA] [int] NULL,
	[DUA_CS50] [int] NOT NULL,
	[DUA_R37C] [varchar](6) NULL,
	[DUA_ADRE] [varchar](2) NULL,
 CONSTRAINT [PK_LOG_DUAD] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DUAD] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DUAD] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DUAD] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DUAD] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DUAD] TO [public] AS [dbo]
/****** Object:  Table [LOG_DUBT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DUBT](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DBT_CODI] [int] NOT NULL,
	[UME_CODI] [varchar](3) NULL,
	[DBT_QTDE] [numeric](38, 6) NOT NULL,
	[DBT_NVEI] [int] NULL,
	[TVE_CODI] [varchar](3) NULL,
	[DBT_QUAL] [varchar](4) NULL,
	[DBT_VIEC] [varchar](4) NULL,
	[DBT_VCO2] [int] NULL,
	[CAT_CODI] [varchar](2) NULL,
	[TCO_CODI] [varchar](2) NULL,
	[DBT_OUTR] [varchar](10) NULL,
	[DBT_AUTO] [int] NOT NULL,
	[DBT_VLIA] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_LOG_DUBT] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DUBT] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DUBT] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DUBT] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DUBT] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DUBT] TO [public] AS [dbo]
/****** Object:  Table [LOG_DUCG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DUCG](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_DATA] [datetime] NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[DUC_CPRT] [varchar](18) NULL,
	[DUC_NORD] [varchar](20) NULL,
	[DUC_NDAT] [datetime] NULL,
	[DUC_CNTN] [int] NULL,
	[DUC_PENV] [varchar](20) NULL,
	[DUC_NPRO] [varchar](19) NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[DUC_ADI5] [int] NOT NULL,
	[DUC_TVL6] [numeric](38, 6) NULL,
	[DUC_REF7] [varchar](30) NULL,
	[PAI_P15A] [varchar](2) NULL,
	[PAI_PA16] [varchar](2) NULL,
	[PAI_PA17] [varchar](2) NULL,
	[PAI_P17B] [int] NULL,
	[MTR_PT18] [varchar](2) NULL,
	[DUC_MT18] [varchar](30) NULL,
	[PAI_PA18] [varchar](2) NULL,
	[MTR_FT21] [varchar](2) NULL,
	[DUC_MT21] [varchar](30) NULL,
	[PAI_PA21] [varchar](2) NULL,
	[DUC_CT19] [int] NOT NULL,
	[CEN_CO20] [varchar](3) NULL,
	[DUC_DE20] [varchar](30) NULL,
	[NTR_CO24] [varchar](2) NULL,
	[LME_CO30] [varchar](17) NULL,
	[DUC_LC30] [varchar](70) NULL,
	[DUC_MT22] [numeric](38, 6) NULL,
	[DUC_TX23] [numeric](38, 6) NULL,
	[DUC_FRET] [numeric](38, 6) NULL,
	[DUC_SEGU] [numeric](38, 6) NULL,
	[DUC_MLQT] [numeric](38, 6) NULL,
	[DUC_MBRT] [numeric](38, 6) NULL,
	[DUC_VTRN] [numeric](38, 6) NULL,
	[DUC_VEUR] [numeric](38, 6) NULL,
	[DUC_DIRT] [numeric](38, 6) NULL,
	[DUC_ENOM] [varchar](70) NULL,
	[DUC_DNIF] [varchar](18) NULL,
	[DUC_VLRC] [numeric](38, 6) NULL,
	[DUC_VATT] [numeric](38, 6) NULL,
	[PAI_MO22] [varchar](3) NULL,
	[DEC_CENI] [varchar](18) NULL,
	[DUC_NFOR] [int] NULL,
	[DUC_TREM] [numeric](38, 6) NULL,
	[DUC_ARTI] [int] NULL,
	[DUC_TPDS] [int] NULL,
	[DUC_TPDC] [int] NULL,
	[DUC_DTYP] [varchar](2) NULL,
	[DUC_VFRC] [numeric](38, 6) NULL,
	[DUC_ANXB] [varchar](2) NULL,
 CONSTRAINT [PK_LOG_DUCG] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DUCG] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DUCG] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DUCG] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DUCG] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DUCG] TO [public] AS [dbo]
/****** Object:  Table [LOG_DUOI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DUOI](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DUO_CODI] [int] NOT NULL,
	[RRE_CODI] [int] NULL,
	[DUO_TIPO] [bit] NOT NULL,
	[UME_CODI] [varchar](3) NULL,
	[DUO_BTRI] [numeric](38, 6) NULL,
	[DUO_TXVL] [numeric](38, 6) NULL,
	[DUO_MONT] [numeric](38, 6) NULL,
	[RRE_AGRO] [bit] NOT NULL,
	[RRE_LIVA] [bit] NULL,
	[DUO_IMPO] [varchar](3) NULL,
	[DUO_AUTO] [int] NOT NULL,
 CONSTRAINT [PK_LOG_DUOI] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DUOI] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DUOI] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DUOI] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DUOI] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DUOI] TO [public] AS [dbo]
/****** Object:  Table [LOG_DURA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_DURA](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DRA_CODI] [int] NOT NULL,
	[EAD_CODI] [varchar](8) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[DRA_APAN] [int] NOT NULL,
	[DRA_APC1] [varchar](20) NOT NULL,
	[DRA_APC2] [varchar](3) NOT NULL,
	[DOC_COD2] [varchar](5) NULL,
	[DRA_APRG] [varchar](2) NULL,
	[DRA_APDT] [datetime] NOT NULL,
 CONSTRAINT [PK_LOG_DURA] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_DURA] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_DURA] TO [public] AS [dbo]
GRANT INSERT ON [LOG_DURA] TO [public] AS [dbo]
GRANT SELECT ON [LOG_DURA] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_DURA] TO [public] AS [dbo]
/****** Object:  Table [LOG_EXAD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_EXAD](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXA_LINH] [int] NOT NULL,
	[APA_CP33] [varchar](22) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[EXA_MBRT] [numeric](38, 6) NULL,
	[EXA_DESD] [varchar](3) NULL,
	[EXA_MLQD] [numeric](38, 6) NULL,
	[EXA_QUSU] [numeric](38, 6) NULL,
	[EXA_VALO] [numeric](38, 6) NULL,
	[EXA_VEST] [numeric](38, 6) NULL,
	[EXA_IVEI] [int] NULL,
	[EXA_IRES] [varchar](2) NULL,
	[TDE_REGI] [varchar](4) NULL,
 CONSTRAINT [PK_LOG_EXAD] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_EXAD] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_EXAD] TO [public] AS [dbo]
GRANT INSERT ON [LOG_EXAD] TO [public] AS [dbo]
GRANT SELECT ON [LOG_EXAD] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_EXAD] TO [public] AS [dbo]
/****** Object:  Table [LOG_EXDA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_EXDA](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[EXD_CHVE] [int] NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[EXD_NREF] [varchar](70) NULL,
	[EXD_DTEM] [datetime] NULL,
	[EXD_DTFV] [datetime] NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXA_LINH] [int] NOT NULL,
 CONSTRAINT [PK_LOG_EXDA] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_EXDA] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_EXDA] TO [public] AS [dbo]
GRANT INSERT ON [LOG_EXDA] TO [public] AS [dbo]
GRANT SELECT ON [LOG_EXDA] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_EXDA] TO [public] AS [dbo]
/****** Object:  Table [LOG_EXML]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_EXML](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[DEC_CODI] [varchar](6) NOT NULL,
	[EXM_TPRO] [varchar](1) NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[EXM_DATA] [datetime] NOT NULL,
	[EXM_NRII] [int] NOT NULL,
	[EXM_NRIN] [varchar](35) NOT NULL,
	[EXM_NRLO] [varchar](22) NOT NULL,
	[EXM_STAT] [int] NOT NULL,
	[EXM_CNUM] [int] NULL,
	[EXM_ESTO] [varchar](3) NULL,
	[EXM_NVRF] [varchar](50) NULL,
	[EXM_DTCD] [datetime] NULL,
	[EXM_NDGA] [varchar](21) NULL,
	[EXM_DDGA] [datetime] NULL,
	[EXM_VERS] [int] NULL,
	[EXM_REVI] [int] NULL,
	[EXM_PENV] [varchar](3) NULL,
	[EAD_CODA] [varchar](8) NOT NULL,
	[TDE_COD1] [varchar](4) NOT NULL,
	[CLI_NIF2] [varchar](18) NULL,
	[EXM_TP2A] [varchar](1) NULL,
	[EXM_TAD5] [int] NULL,
	[EXM_TVL6] [numeric](38, 6) NULL,
	[FOR_NOM8] [varchar](70) NULL,
	[EXM_IROR] [int] NOT NULL,
	[DEC_CO14] [varchar](6) NOT NULL,
	[EXM_TP14] [int] NULL,
	[EXM_P15A] [varchar](2) NULL,
	[EXM_P17A] [varchar](2) NULL,
	[EXM_C17C] [varchar](14) NULL,
	[EAD_C17C] [varchar](8) NULL,
	[EXM_D17C] [datetime] NULL,
	[EXM_CT19] [int] NULL,
	[MTR_CO18] [varchar](2) NULL,
	[EXM_MT18] [varchar](27) NULL,
	[MTR_CO21] [varchar](2) NULL,
	[EXM_MT21] [varchar](27) NULL,
	[PAI_CO21] [varchar](2) NULL,
	[CEN_CO20] [varchar](3) NULL,
	[EXM_LG20] [varchar](50) NULL,
	[NTR_CO24] [varchar](2) NULL,
	[PAI_MO22] [varchar](3) NULL,
	[EXM_MT22] [numeric](38, 6) NULL,
	[EXM_TX23] [numeric](38, 6) NULL,
	[EXM_TFRT] [numeric](38, 6) NULL,
	[EXM_TSEG] [numeric](38, 6) NULL,
	[EXM_TMLQ] [numeric](38, 6) NULL,
	[EXM_TMBR] [numeric](38, 6) NULL,
	[EXM_VEUR] [numeric](38, 6) NULL,
	[EXM_VATT] [numeric](38, 6) NULL,
	[EAD_CO29] [varchar](8) NULL,
	[EAD_C29A] [varchar](8) NULL,
	[EXM_DTIN] [datetime] NULL,
	[EXM_HRIN] [datetime] NULL,
	[EXM_DTFI] [datetime] NULL,
	[EXM_HRFI] [datetime] NULL,
	[EAD_CO30] [varchar](8) NULL,
	[LEM_CO30] [varchar](25) NULL,
	[LME_CO30] [varchar](17) NULL,
	[EXM_MR30] [varchar](35) NULL,
	[LEM_C30A] [varchar](25) NULL,
	[ARM_CO49] [varchar](17) NULL,
	[AGE_CO50] [varchar](18) NULL,
	[EXM_Q30C] [int] NULL,
	[EXM_CPRT] [varchar](18) NULL,
	[EXM_TPCG] [varchar](5) NULL,
	[EXM_DTVO] [datetime] NULL,
	[SIN_CODI] [varchar](4) NULL,
	[EXM_INCE] [varchar](1) NULL,
	[EXM_NCMR] [varchar](70) NULL,
	[EXM_DTMP] [varchar](1) NULL,
	[EXM_NRCO] [varchar](50) NULL,
	[EXM_DTCO] [datetime] NULL,
	[FUP_CODI] [int] NULL,
 CONSTRAINT [PK_LOG_EXML] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_EXML] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_EXML] TO [public] AS [dbo]
GRANT INSERT ON [LOG_EXML] TO [public] AS [dbo]
GRANT SELECT ON [LOG_EXML] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_EXML] TO [public] AS [dbo]
/****** Object:  Table [LOG_LOGS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_LOGS](
	[LOG_UTIL] [varchar](30) NOT NULL,
	[LOG_SPID] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
 CONSTRAINT [PK_LOG_LOGS] PRIMARY KEY CLUSTERED 
(
	[LOG_UTIL] ASC,
	[LOG_SPID] ASC,
	[LOG_DATA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_LOGS] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_LOGS] TO [public] AS [dbo]
GRANT INSERT ON [LOG_LOGS] TO [public] AS [dbo]
GRANT SELECT ON [LOG_LOGS] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_LOGS] TO [public] AS [dbo]
/****** Object:  Table [LOG_SDSC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_SDSC](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DSC_EANO] [int] NOT NULL,
	[DSC_NPRO] [int] NOT NULL,
	[DSC_TIPO] [int] NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[DSC_DTVO] [datetime] NOT NULL,
	[DSC_NCMF] [varchar](8) NOT NULL,
	[DSC_NCMV] [varchar](6) NOT NULL,
	[DSC_IXML] [bit] NOT NULL,
	[DSC_ACTI] [bit] NOT NULL,
 CONSTRAINT [PK_LOG_SDSC] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_SDSC] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_SDSC] TO [public] AS [dbo]
GRANT INSERT ON [LOG_SDSC] TO [public] AS [dbo]
GRANT SELECT ON [LOG_SDSC] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_SDSC] TO [public] AS [dbo]
/****** Object:  Table [LOG_SDSD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [LOG_SDSD](
	[LOG_IDEN] [uniqueidentifier] NOT NULL,
	[LOG_TIPO] [int] NOT NULL,
	[LOG_DATA] [datetime] NOT NULL,
	[LOG_USER] [varchar](30) NOT NULL,
	[LOG_PROG] [varchar](200) NOT NULL,
	[LOG_HOST] [varchar](200) NOT NULL,
	[DSC_EANO] [int] NOT NULL,
	[DSC_NPRO] [int] NOT NULL,
	[DSD_NUME] [int] NOT NULL,
	[DSD_NRMH] [varchar](30) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DSD_ORIG] [int] NOT NULL,
	[EXA_CHVE] [int] NULL,
	[DSD_NDAU] [varchar](22) NULL,
	[DSD_DTEN] [datetime] NULL,
	[DSD_IDNN] [int] NOT NULL,
	[DSD_ENVI] [bit] NOT NULL,
	[DSD_IDFC] [int] NULL,
	[DSD_ASAI] [bit] NOT NULL,
	[DSD_ESTA] [varchar](3) NULL,
	[DSD_STAT] [int] NULL,
	[DSD_AFRQ] [int] NULL,
	[DSD_EFRQ] [bit] NULL,
	[DSD_STRD] [int] NULL,
	[DSD_STMS] [int] NULL,
	[DSD_IDED] [varchar](50) NULL,
	[DSD_NOMD] [varchar](75) NULL,
	[DSD_PESO] [numeric](38, 6) NULL,
	[DSD_VOLS] [int] NULL,
	[DSD_VALO] [numeric](38, 6) NULL,
	[DSD_DEPO] [varchar](50) NULL,
	[DSD_JUST] [varchar](250) NULL,
	[DSD_DERD] [datetime] NULL,
	[DSD_SIRD] [int] NULL,
	[DSD_DIRD] [datetime] NULL,
 CONSTRAINT [PK_LOG_SDSD] PRIMARY KEY CLUSTERED 
(
	[LOG_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [LOG_SDSD] TO  SCHEMA OWNER 
GRANT DELETE ON [LOG_SDSD] TO [public] AS [dbo]
GRANT INSERT ON [LOG_SDSD] TO [public] AS [dbo]
GRANT SELECT ON [LOG_SDSD] TO [public] AS [dbo]
GRANT UPDATE ON [LOG_SDSD] TO [public] AS [dbo]
/****** Object:  Table [PRO_AATR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_AATR](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[AAT_CODI] [int] NOT NULL,
	[APA_CODI] [varchar](22) NULL,
	[AAT_DPAU] [varchar](150) NOT NULL,
	[AAT_PBRT] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_AATR] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[AAT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_AATR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_AATR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_AATR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_AATR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_AATR] TO [public] AS [dbo]
/****** Object:  Table [PRO_ADV1]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_ADV1](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[ADV_LINH] [int] NOT NULL,
	[ADV_C11A] [numeric](38, 6) NULL,
	[ADV_C11M] [varchar](3) NULL,
	[ADV_C11B] [numeric](38, 6) NULL,
	[ADV_CS12] [numeric](38, 6) NULL,
	[ADV_C13A] [numeric](38, 6) NULL,
	[ADV_C13B] [numeric](38, 6) NULL,
	[ADV_C13C] [numeric](38, 6) NULL,
	[ADV_C14A] [numeric](38, 6) NULL,
	[ADV_C14B] [numeric](38, 6) NULL,
	[ADV_C14C] [numeric](38, 6) NULL,
	[ADV_C14D] [numeric](38, 6) NULL,
	[ADV_C14T] [varchar](40) NULL,
	[ADV_CS15] [numeric](38, 6) NULL,
	[ADV_CS16] [numeric](38, 6) NULL,
	[ADV_C17A] [numeric](38, 6) NULL,
	[ADV_C17T] [varchar](30) NULL,
	[ADV_C17B] [numeric](38, 6) NULL,
	[ADV_C17C] [numeric](38, 6) NULL,
	[ADV_CS18] [numeric](38, 6) NULL,
	[ADV_CS19] [numeric](38, 6) NULL,
	[ADV_CS20] [numeric](38, 6) NULL,
	[ADV_CS21] [numeric](38, 6) NULL,
	[ADV_C21T] [varchar](40) NULL,
	[ADV_CS22] [numeric](38, 6) NULL,
	[ADV_CS23] [numeric](38, 6) NULL,
	[ADV_CS24] [numeric](38, 6) NULL,
 CONSTRAINT [PK_PRO_ADV1] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[ADV_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_ADV1] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_ADV1] TO [public] AS [dbo]
GRANT INSERT ON [PRO_ADV1] TO [public] AS [dbo]
GRANT SELECT ON [PRO_ADV1] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_ADV1] TO [public] AS [dbo]
/****** Object:  Table [PRO_AEUR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_AEUR](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DEC_CODI] [varchar](6) NOT NULL,
	[AEU_CODI] [int] NOT NULL,
	[APA_CODI] [varchar](22) NULL,
	[AEU_DPAU] [varchar](150) NOT NULL,
	[AEU_PBRT] [numeric](38, 6) NOT NULL,
	[AEU_TVOL] [numeric](38, 6) NULL,
	[AEU_PTRT] [int] NULL,
 CONSTRAINT [PK_PRO_AEUR] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DEC_CODI] ASC,
	[AEU_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_AEUR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_AEUR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_AEUR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_AEUR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_AEUR] TO [public] AS [dbo]
/****** Object:  Table [PRO_ATRC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_ATRC](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[ATR_DATA] [datetime] NOT NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[ATR_STAT] [int] NULL,
	[ATR_DTRN] [varchar](15) NULL,
	[ATR_DTDE] [varchar](15) NULL,
	[ATR_EXP1] [varchar](18) NULL,
	[ATR_DST3] [varchar](18) NULL,
	[PAI_COD5] [varchar](2) NOT NULL,
	[PAI_COD6] [varchar](2) NOT NULL,
	[ATR_INF7] [text] NULL,
	[ATR_OBS8] [text] NULL,
	[ATR_MC10] [varchar](20) NOT NULL,
	[ATR_QT10] [numeric](38, 6) NOT NULL,
	[UME_CO10] [varchar](3) NOT NULL,
	[ATR_PBTT] [numeric](38, 6) NOT NULL,
	[ATR_ENOM] [varchar](70) NULL,
	[ATR_EMOR] [varchar](70) NULL,
	[ATR_ELOC] [varchar](35) NULL,
	[ATR_ECPO] [varchar](12) NULL,
	[ATR_ELPO] [varchar](35) NULL,
	[ATR_ENIF] [varchar](18) NULL,
	[ATR_DNOM] [varchar](70) NULL,
	[ATR_DMOR] [varchar](70) NULL,
	[ATR_DLOC] [varchar](35) NULL,
	[ATR_DCPO] [varchar](12) NULL,
	[ATR_DLPO] [varchar](35) NULL,
	[ATR_DNIF] [varchar](18) NULL,
 CONSTRAINT [PK_PRO_ATRC] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_ATRC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_ATRC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_ATRC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_ATRC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_ATRC] TO [public] AS [dbo]
/****** Object:  Table [PRO_CCCA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_CCCA](
	[CCC_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[CCC_TENT] [int] NOT NULL,
	[CCC_ENTI] [varchar](18) NOT NULL,
	[CCC_NCAU] [varchar](24) NOT NULL,
	[CCC_CANO] [varchar](4) NULL,
	[CCC_CTIP] [varchar](1) NULL,
	[ALF_ORIG] [varchar](8) NOT NULL,
	[CCC_IORI] [int] NULL,
	[ALF_DEST] [varchar](8) NULL,
	[CAU_CODI] [varchar](5) NULL,
	[CCC_DATA] [datetime] NULL,
	[CCC_NDOC] [varchar](15) NULL,
	[CCC_NORD] [varchar](20) NULL,
	[CCC_DORD] [datetime] NULL,
	[CLI_DEST] [varchar](18) NULL,
	[CCC_OBSR] [varchar](50) NULL,
	[CCC_DBCR] [int] NULL,
	[CCC_PROV] [bit] NOT NULL,
	[CCC_LIQD] [bit] NOT NULL,
	[CCC_VATR] [numeric](38, 6) NOT NULL,
	[CCC_VUTI] [numeric](38, 6) NULL,
	[DUC_PNUM] [int] NULL,
	[DUC_EANO] [int] NULL,
	[DUC_TIPO] [int] NULL,
	[MCA_IDEN] [int] NULL,
 CONSTRAINT [PK_PRO_CCCA] PRIMARY KEY CLUSTERED 
(
	[CCC_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_CCCA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_CCCA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_CCCA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_CCCA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_CCCA] TO [public] AS [dbo]
/****** Object:  Table [PRO_CG15]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_CG15](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[CG1_LINH] [int] NOT NULL,
	[CG1_DESG] [varchar](20) NULL,
 CONSTRAINT [PK_PRO_CG15] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[CG1_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_CG15] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_CG15] TO [public] AS [dbo]
GRANT INSERT ON [PRO_CG15] TO [public] AS [dbo]
GRANT SELECT ON [PRO_CG15] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_CG15] TO [public] AS [dbo]
/****** Object:  Table [PRO_DAVE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DAVE](
	[DAV_CODI] [int] NOT NULL,
	[DAV_EANO] [int] NOT NULL,
	[DAV_DATA] [datetime] NOT NULL,
	[DAV_STAT] [int] NOT NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[CLI_SUJP] [varchar](18) NULL,
	[DAV_REGI] [int] NOT NULL,
	[DAV_CDAV] [bit] NULL,
	[DAV_CPL] [bit] NULL,
	[DAV_VUSN] [int] NOT NULL,
	[DAV_DEST] [int] NOT NULL,
	[DAV_RGIA] [int] NOT NULL,
	[HTE_ACOD] [varchar](20) NULL,
	[CAT_ACAT] [varchar](2) NOT NULL,
	[TVE_ATIP] [varchar](3) NOT NULL,
	[MAR_AMAR] [int] NOT NULL,
	[DAV_AMOD] [varchar](35) NULL,
	[DAV_AMBT] [int] NULL,
	[DAV_ATAR] [int] NULL,
	[TCO_ACMB] [varchar](2) NOT NULL,
	[COR_ACOR] [varchar](2) NOT NULL,
	[TCX_ACXA] [varchar](2) NOT NULL,
	[DAV_ANQD] [varchar](25) NULL,
	[DAV_ANMT] [varchar](25) NULL,
	[DAV_ANLG] [int] NOT NULL,
	[DAV_ACLD] [int] NOT NULL,
	[DAV_ACO2] [int] NULL,
	[DAV_ANKM] [int] NULL,
	[DAV_AEMT] [int] NULL,
	[DAV_ACCX] [int] NULL,
	[DAV_AACX] [int] NULL,
	[DAV_AATP] [varchar](2) NULL,
	[PAI_BPRV] [varchar](2) NULL,
	[DAV_BD1M] [datetime] NULL,
	[DAV_BMTA] [varchar](20) NULL,
	[DAV_BSBC] [varchar](1) NULL,
	[DAV_BDFV] [datetime] NULL,
	[DAV_BDTR] [datetime] NULL,
	[DAV_CDUN] [varchar](12) NULL,
	[DAV_CDDU] [datetime] NULL,
	[ALF_CALD] [varchar](8) NULL,
	[DEC_DCOD] [varchar](6) NOT NULL,
	[DEC_DNOM] [varchar](70) NULL,
	[DEC_DMOR] [varchar](70) NULL,
	[DEC_DNIF] [varchar](18) NULL,
	[DEC_DTIP] [int] NOT NULL,
	[DEC_DQLD] [varchar](18) NULL,
	[DAV_DSBC] [varchar](1) NOT NULL,
	[CLI_ECOD] [varchar](18) NULL,
	[CLI_EECV] [int] NULL,
	[CLI_EDNA] [datetime] NULL,
	[CLI_ENID] [varchar](9) NULL,
	[CLI_ESBC] [varchar](1) NULL,
	[CLI_EMOR] [varchar](70) NULL,
	[CLI_ECPS] [varchar](12) NULL,
	[CLI_ELPS] [varchar](35) NULL,
	[CLI_ENIF] [varchar](18) NULL,
	[CLI_ETIP] [int] NULL,
	[EJU_FRES] [varchar](8) NULL,
	[EJU_FDLE] [varchar](70) NULL,
	[EJU_FCNV] [int] NULL,
	[CLI_FNOM] [varchar](18) NULL,
	[CLI_FEEC] [int] NULL,
	[CLI_FDNA] [datetime] NULL,
	[CLI_FNID] [varchar](9) NULL,
	[CLI_FSBC] [varchar](1) NULL,
	[CLI_FMOR] [varchar](70) NULL,
	[CLI_FCPS] [varchar](12) NULL,
	[CLI_FLPS] [varchar](35) NULL,
	[CLI_FNIF] [varchar](18) NULL,
	[CLI_FTIP] [int] NULL,
	[TIA_GCOD] [int] NULL,
	[TIA_GTAX] [numeric](38, 6) NOT NULL,
	[DAV_GPAB] [numeric](38, 6) NOT NULL,
	[DAV_GPRD] [numeric](38, 6) NULL,
	[DAV_GMTR] [numeric](38, 6) NULL,
	[DAV_GTIA] [numeric](38, 6) NOT NULL,
	[DAV_HBTR] [numeric](38, 6) NULL,
	[DAV_HMIA] [numeric](38, 6) NULL,
	[DAV_HTTL] [numeric](38, 6) NULL,
	[DAV_HTXI] [numeric](38, 6) NULL,
	[DAV_HTLI] [numeric](38, 6) NULL,
	[DAV_HISE] [bit] NULL,
	[DAV_HOPT] [bit] NULL,
	[DAV_IMPA] [varchar](2) NULL,
	[DAV_IGAN] [int] NULL,
	[DAV_IGNU] [varchar](17) NULL,
	[DAV_IFLG] [int] NULL,
	[CSE_JDGV] [varchar](2) NOT NULL,
	[DAV_JMAT] [varchar](8) NULL,
	[DAV_JDAT] [datetime] NULL,
	[DAV_PNOM] [varchar](70) NULL,
	[DAV_PMOR] [varchar](70) NULL,
	[DAV_PLOC] [varchar](35) NULL,
	[DAV_PCPO] [varchar](12) NULL,
	[DAV_PLPO] [varchar](35) NULL,
	[DAV_PNIF] [varchar](18) NULL,
	[PAI_PLIV] [varchar](2) NULL,
	[CLI_ENOM] [varchar](70) NULL,
	[DAV_CTAX] [numeric](38, 6) NULL,
	[DAV_CABA] [numeric](38, 6) NULL,
	[DAV_CRED] [numeric](38, 6) NULL,
	[DAV_TRAN] [numeric](38, 6) NULL,
	[DAV_EMPC] [numeric](38, 6) NOT NULL,
	[DAV_PVPR] [numeric](38, 6) NOT NULL,
	[DAV_ISVR] [numeric](38, 6) NOT NULL,
	[DAV_VAVL] [numeric](38, 6) NOT NULL,
	[DAV_LCAV] [varchar](70) NULL,
	[DAV_NUAF] [varchar](10) NULL,
	[DAV_DTAF] [datetime] NULL,
	[DAV_EXCL] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_DAVE] PRIMARY KEY CLUSTERED 
(
	[DAV_CODI] ASC,
	[DAV_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DAVE] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DAVE] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DAVE] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DAVE] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DAVE] TO [public] AS [dbo]
/****** Object:  Table [PRO_DCON]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DCON](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DCO_CODI] [int] NOT NULL,
	[DCO_CNUM] [varchar](20) NULL,
	[DCO_TIPO] [varchar](10) NULL,
	[DCO_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DCO_PMRP] [bit] NOT NULL,
	[DCO_PMRD] [datetime] NULL,
 CONSTRAINT [PK_PRO_DCON] PRIMARY KEY CLUSTERED 
(
	[DUA_CODI] ASC,
	[DUC_PNUM] ASC,
	[DCO_CODI] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DCON] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DCON] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DCON] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DCON] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DCON] TO [public] AS [dbo]
/****** Object:  Table [PRO_DDOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DDOC](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DDO_CODI] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](150) NULL,
	[DDO_NUME] [varchar](70) NULL,
	[DDO_DINI] [datetime] NULL,
	[DDO_DFIM] [datetime] NULL,
	[CEN_CODI] [varchar](3) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[DDO_MONT] [numeric](38, 6) NULL,
	[DDO_DPRZ] [int] NULL,
	[DDO_NINV] [varchar](25) NULL,
	[DDO_AUTO] [int] NOT NULL,
	[DDO_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DDO_TIPO] [int] NOT NULL,
	[DDO_EEMI] [varchar](70) NULL,
	[UME_CODI] [varchar](3) NULL,
	[DDO_QTDE] [numeric](38, 6) NOT NULL,
	[DDO_DEST] [int] NOT NULL,
	[DDO_NLIN] [int] NULL,
	[DDO_NFCH] [varchar](100) NULL,
	[DDO_FICH] [varbinary](max) NULL,
 CONSTRAINT [PK_PRO_DDOC] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DDO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DDOC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DDOC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DDOC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DDOC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DDOC] TO [public] AS [dbo]
/****** Object:  Table [PRO_DESS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DESS](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DCS_NOME] [varchar](70) NOT NULL,
	[DSS_TDEC] [int] NOT NULL,
	[DSR_NOME] [varchar](70) NULL,
	[DSR_MORA] [varchar](70) NULL,
	[DSR_CPOS] [varchar](12) NULL,
	[DSR_LOCA] [varchar](35) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[DSR_NNIF] [varchar](17) NULL,
	[DSS_IESC] [varchar](1) NULL,
	[DSS_DATA] [datetime] NOT NULL,
	[DSS_CPRT] [varchar](18) NULL,
	[DSS_DTVO] [datetime] NULL,
	[DSS_NRLO] [varchar](22) NOT NULL,
	[DSS_STAT] [int] NOT NULL,
	[DSS_ESTA] [int] NULL,
	[DSS_VERS] [int] NOT NULL,
	[DSS_PENV] [varchar](3) NULL,
	[DSS_NADI] [int] NOT NULL,
	[DSS_TVOL] [int] NOT NULL,
	[DSS_MBRT] [numeric](38, 6) NOT NULL,
	[DSS_MCNT] [bit] NOT NULL,
	[LEM_CODI] [varchar](25) NULL,
	[LEM_DESC] [varchar](70) NULL,
	[LME_CODI] [varchar](17) NULL,
	[LME_NOME] [varchar](70) NULL,
	[DSS_DTDC] [datetime] NOT NULL,
	[DSS_LCDC] [varchar](35) NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[EAD_NOME] [varchar](35) NOT NULL,
	[EAD_COD2] [varchar](8) NOT NULL,
	[EAD_NOM2] [varchar](35) NOT NULL,
	[DSS_DTMP] [varchar](1) NULL,
	[DSS_NCRF] [varchar](70) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[DSS_CNOM] [varchar](70) NULL,
	[DSS_CMOR] [varchar](70) NULL,
	[DSS_CLOC] [varchar](35) NULL,
	[DSS_CCPO] [varchar](12) NULL,
	[DSS_CLPO] [varchar](35) NULL,
	[DSS_CPAI] [varchar](2) NULL,
	[DSS_CNIF] [varchar](18) NULL,
	[DSS_CTNF] [int] NULL,
	[FOR_CODI] [varchar](18) NULL,
	[DSS_FNOM] [varchar](70) NOT NULL,
	[DSS_FMOR] [varchar](70) NOT NULL,
	[DSS_FLOC] [varchar](35) NOT NULL,
	[DSS_FCPO] [varchar](12) NOT NULL,
	[DSS_FLPO] [varchar](35) NOT NULL,
	[DSS_FPAI] [varchar](2) NOT NULL,
	[DSS_FNIF] [varchar](18) NULL,
	[DSS_NDGA] [varchar](22) NULL,
	[DSS_DDGA] [datetime] NULL,
	[DSS_UCRI] [varchar](30) NOT NULL,
	[DSS_DCRI] [datetime] NOT NULL,
	[DSS_UALT] [varchar](30) NOT NULL,
	[DSS_DALT] [datetime] NOT NULL,
	[DSS_RESP] [text] NULL,
	[DSS_AUX0] [varchar](1000) NULL,
	[DSS_IDEN] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_PRO_DESS] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [IX_PRO_DESS_DSS_IDEN] UNIQUE NONCLUSTERED 
(
	[DSS_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DESS] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DESS] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DESS] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DESS] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DESS] TO [public] AS [dbo]
/****** Object:  Table [PRO_DEXP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DEXP](
	[DEX_CODI] [int] NOT NULL,
	[DEX_EANO] [int] NOT NULL,
	[DEX_DATA] [datetime] NOT NULL,
	[DEX_STAT] [int] NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[CLI_EXPE] [varchar](18) NULL,
	[DEX_CAPL] [varchar](25) NULL,
	[DEX_CNOM] [varchar](70) NOT NULL,
	[DEX_CMOR] [varchar](70) NULL,
	[DEX_CCPO] [varchar](12) NULL,
	[DEX_CLPO] [varchar](35) NULL,
	[DEX_CNIF] [varchar](18) NULL,
	[DEX_CTIP] [int] NULL,
	[DEX_NFAC] [varchar](35) NULL,
	[DEX_DTFC] [datetime] NULL,
	[FOR_DEST] [varchar](18) NULL,
	[DEX_DNOM] [varchar](70) NOT NULL,
	[DEX_DMOR] [varchar](70) NULL,
	[DEX_DPAI] [varchar](2) NOT NULL,
	[TVE_CODI] [varchar](3) NULL,
	[MAR_CODI] [int] NULL,
	[DEX_MODE] [varchar](35) NULL,
	[HTE_CODI] [varchar](20) NULL,
	[DEX_NQDR] [varchar](25) NULL,
	[DEX_NMTR] [varchar](25) NULL,
	[DEX_CLDD] [int] NULL,
	[DEX_MATD] [varchar](8) NOT NULL,
	[DEX_DTCL] [datetime] NULL,
	[DEX_NDVL] [varchar](20) NULL,
	[DEX_LANO] [int] NULL,
	[DEX_NMDU] [int] NULL,
	[DEX_UANO] [int] NULL,
	[DEX_MATE] [varchar](8) NULL,
	[DEX_DTVM] [datetime] NULL,
	[DEX_DADC] [varchar](20) NULL,
	[DEX_ESCE] [varchar](8) NULL,
	[DEX_ESSD] [varchar](8) NULL,
	[DEX_DTSD] [datetime] NULL,
	[DEX_DAPL] [varchar](25) NULL,
	[DEX_PCNO] [varchar](70) NULL,
	[DEX_PCMO] [varchar](70) NULL,
	[DEX_PCLO] [varchar](35) NULL,
	[DEX_PCCP] [varchar](12) NULL,
	[DEX_PCLP] [varchar](35) NULL,
	[DEX_PCNF] [varchar](18) NULL,
	[PAI_PCPL] [varchar](2) NULL,
	[DEX_PDNO] [varchar](70) NULL,
	[DEX_PDMO] [varchar](70) NULL,
	[DEX_PDLO] [varchar](35) NULL,
	[DEX_PDCP] [varchar](12) NULL,
	[DEX_PDLP] [varchar](35) NULL,
	[DEX_PDNF] [varchar](18) NULL,
	[PAI_PDPL] [varchar](2) NULL,
 CONSTRAINT [PK_PRO_DEXP] PRIMARY KEY CLUSTERED 
(
	[DEX_CODI] ASC,
	[DEX_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DEXP] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DEXP] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DEXP] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DEXP] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DEXP] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSAC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSAC](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSA_NUME] [int] NOT NULL,
	[DAC_NUME] [int] NOT NULL,
	[DAC_NCNT] [varchar](17) NOT NULL,
 CONSTRAINT [PK_PRO_DSAC] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSA_NUME] ASC,
	[DAC_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSAC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSAC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSAC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSAC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSAC] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSAD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSAD](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSA_NUME] [int] NOT NULL,
	[DAD_NUME] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
	[DAD_NDOC] [varchar](35) NULL,
	[DAD_DDOC] [datetime] NULL,
	[DAD_AUTO] [int] NOT NULL,
 CONSTRAINT [PK_PRO_DSAD] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSA_NUME] ASC,
	[DAD_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSAD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSAD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSAD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSAD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSAD] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSAM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSAM](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSA_NUME] [int] NOT NULL,
	[DAM_NUME] [int] NOT NULL,
	[DAM_MRNU] [varchar](42) NULL,
	[TEM_CODI] [varchar](2) NOT NULL,
	[TEM_NOME] [varchar](35) NOT NULL,
	[DAM_NVOL] [int] NOT NULL,
	[DAM_NPCS] [int] NOT NULL,
	[DAM_PART] [bit] NOT NULL,
	[DAM_AUTO] [int] NOT NULL,
	[DAM_TIPO] [int] NOT NULL,
 CONSTRAINT [PK_PRO_DSAM] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSA_NUME] ASC,
	[DAM_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSAM] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSAM] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSAM] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSAM] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSAM] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSAS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSAS](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSA_NUME] [int] NOT NULL,
	[DAS_NUME] [int] NOT NULL,
	[DAS_TIPO] [varchar](3) NOT NULL,
	[DAS_NDOC] [varchar](35) NULL,
	[DAS_CATE] [varchar](1) NULL,
	[DAS_DATA] [datetime] NULL,
	[DAS_AUTO] [int] NOT NULL,
	[DAS_IDCR] [varchar](20) NULL,
	[DAS_CODR] [varchar](20) NULL,
 CONSTRAINT [PK_PRO_DSAS] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSA_NUME] ASC,
	[DAS_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSAS] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSAS] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSAS] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSAS] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSAS] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSIM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSIM](
	[DSI_CODI] [int] NOT NULL,
	[DSI_EANO] [int] NOT NULL,
	[DSI_DATA] [datetime] NOT NULL,
	[DSI_STAT] [int] NULL,
	[DSI_AUTN] [varchar](25) NULL,
	[DSI_DAT2] [datetime] NULL,
	[DSI_CASA] [varchar](18) NOT NULL,
	[DSI_CASB] [varchar](50) NULL,
	[DSI_CASD] [varchar](22) NULL,
	[DSI_CASC] [varchar](50) NULL,
	[DSI_CASE] [varchar](50) NULL,
	[DSI_CASF] [varchar](60) NULL,
	[DSI_CASG] [varchar](60) NULL,
	[DSI_CASH] [varchar](60) NULL,
	[DSI_CASI] [varchar](50) NULL,
	[DSI_CASJ] [varchar](25) NULL,
	[DSI_CASK] [varchar](70) NOT NULL,
	[DSI_CASL] [varchar](8) NOT NULL,
	[DSI_CASM] [varchar](8) NULL,
	[DSI_CASN] [text] NULL,
	[DSI_PDNO] [varchar](70) NULL,
	[DSI_PDMO] [varchar](70) NULL,
	[DSI_PDLO] [varchar](35) NULL,
	[DSI_PDCP] [varchar](12) NULL,
	[DSI_PDLP] [varchar](35) NULL,
	[DSI_PDNF] [varchar](18) NULL,
	[PAI_PDPL] [varchar](2) NULL,
	[DSI_TRIB] [int] NULL,
	[DSI_PLIQ] [numeric](38, 6) NULL,
	[DSI_GRAD] [numeric](38, 6) NULL,
	[DSI_TIVA] [numeric](38, 6) NULL,
	[DSI_CPAU] [varchar](22) NULL,
 CONSTRAINT [PK_PRO_DSIM] PRIMARY KEY CLUSTERED 
(
	[DSI_CODI] ASC,
	[DSI_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSIM] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSIM] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSIM] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSIM] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSIM] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSSA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSSA](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSA_NUME] [int] NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[DSA_CPAU] [varchar](8) NULL,
	[DSA_DESG] [varchar](280) NULL,
	[DSA_MPUN] [varchar](4) NULL,
	[DSA_MBRT] [numeric](38, 6) NOT NULL,
	[DSD_IDNN] [int] NULL,
	[DSA_IDEN] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_PRO_DSSA] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSA_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [IX_PRO_DSSA_DSA_IDEN] UNIQUE NONCLUSTERED 
(
	[DSA_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSSA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSSA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSSA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSSA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSSA] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSSD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSSD](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSD_NUME] [int] NOT NULL,
	[DSD_DESC] [varchar](150) NOT NULL,
	[DSD_LINK] [varchar](500) NOT NULL,
	[DSD_NOMF] [varchar](100) NOT NULL,
	[DSD_UTIL] [varchar](30) NOT NULL,
	[DSD_DATA] [datetime] NOT NULL,
 CONSTRAINT [PK_PRO_DSSD] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSD_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSSD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSSD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSSD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSSD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSSD] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSSI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSSI](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSI_NUME] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](35) NULL,
 CONSTRAINT [PK_PRO_DSSI] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSI_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSSI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSSI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSSI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSSI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSSI] TO [public] AS [dbo]
/****** Object:  Table [PRO_DSSS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DSSS](
	[DSS_EANO] [int] NOT NULL,
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSS_NPRO] [int] NOT NULL,
	[DSS_NUME] [int] NOT NULL,
	[DSS_NSEL] [varchar](20) NOT NULL,
 CONSTRAINT [PK_PRO_DSSS] PRIMARY KEY CLUSTERED 
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC,
	[DSS_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DSSS] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DSSS] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DSSS] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DSSS] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DSSS] TO [public] AS [dbo]
/****** Object:  Table [PRO_DU31]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DU31](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[D31_CODI] [int] NOT NULL,
	[D31_MARC] [varchar](512) NULL,
	[D31_NUME] [varchar](20) NULL,
	[D31_QNTD] [numeric](38, 6) NOT NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[D31_CASP] [bit] NOT NULL,
	[D31_CASR] [bit] NOT NULL,
	[D31_CASC] [bit] NOT NULL,
	[D31_TTVL] [bit] NOT NULL,
	[D31_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[D31_AUTO] [int] NOT NULL,
	[D31_LOPT] [varchar](30) NULL,
	[DVC_IDEN] [bigint] NULL,
 CONSTRAINT [PK_PRO_DA31] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[D31_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DU31] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DU31] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DU31] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DU31] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DU31] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUAD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUAD](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[APA_CO33] [varchar](22) NULL,
	[UME_CODI] [varchar](3) NULL,
	[DUA_TIVA] [numeric](38, 6) NULL,
	[DUA_TRIB] [int] NULL,
	[DUA_PLIQ] [numeric](38, 6) NULL,
	[DUA_GRAD] [numeric](38, 6) NULL,
	[PAI_CO34] [varchar](2) NULL,
	[DUA_MB35] [numeric](38, 6) NOT NULL,
	[PRE_CO36] [varchar](3) NULL,
	[RRE_PREF] [int] NULL,
	[DUA_RG37] [varchar](4) NULL,
	[DUA_R37B] [varchar](6) NULL,
	[DUA_ML38] [numeric](38, 6) NOT NULL,
	[DUA_CO39] [varchar](6) NULL,
	[DUA_US41] [numeric](38, 6) NULL,
	[USU_CO41] [varchar](10) NULL,
	[DUA_VA42] [numeric](38, 6) NOT NULL,
	[DUA_VFRE] [numeric](38, 6) NULL,
	[DUA_VSEG] [numeric](38, 6) NULL,
	[DUA_VTRA] [numeric](38, 6) NULL,
	[DUA_ROYA] [numeric](38, 6) NULL,
	[DUA_VROY] [numeric](38, 6) NULL,
	[DUA_VDIR] [numeric](38, 6) NULL,
	[DUA_VOPT] [numeric](38, 6) NULL,
	[DUA_DESG] [varchar](150) NULL,
	[DUA_LCMB] [int] NOT NULL,
	[DUA_CAUC] [varchar](24) NULL,
	[DUA_CANO] [varchar](4) NULL,
	[DUA_CTIP] [varchar](1) NULL,
	[DUA_CENT] [int] NULL,
	[ARM_CO49] [varchar](17) NULL,
	[AGE_CO50] [varchar](18) NULL,
	[ALF_CO53] [varchar](8) NULL,
	[DUA_VEST] [numeric](38, 6) NOT NULL,
	[DUA_AJUS] [numeric](38, 6) NOT NULL,
	[DUA_CORE] [int] NULL,
	[DUA_CONR] [varchar](20) NULL,
	[DUA_DANO] [int] NULL,
	[DUA_DNUM] [varchar](6) NULL,
	[DUA_DNRS] [varchar](2) NULL,
	[DUA_DDAT] [datetime] NULL,
	[DUA_LINH] [varchar](22) NULL,
	[DUA_VATO] [numeric](38, 6) NULL,
	[DUA_NEPO] [varchar](10) NULL,
	[DUA_BTRI] [numeric](38, 6) NULL,
	[DUA_TXCO] [bit] NOT NULL,
	[DUA_TXVL] [numeric](38, 6) NULL,
	[DUA_MTRI] [numeric](38, 6) NULL,
	[DUA_IVAV] [numeric](38, 6) NULL,
	[DUA_BTIV] [numeric](38, 6) NULL,
	[RRE_CODI] [int] NULL,
	[DUA_MPAG] [varchar](1) NULL,
	[FLE_CODI] [int] NULL,
	[DUA_VSEL] [numeric](38, 6) NULL,
	[DUA_VIVA] [numeric](38, 6) NULL,
	[DUA_VAEU] [numeric](38, 6) NULL,
	[APA_CP33] [varchar](22) NULL,
	[PAI_NOME] [varchar](35) NULL,
	[PRE_NOME] [varchar](70) NULL,
	[USU_NOME] [varchar](10) NULL,
	[ARM_NOME] [varchar](70) NULL,
	[AGE_NOME] [varchar](70) NULL,
	[ALF_NOME] [varchar](70) NULL,
	[RRE_NOME] [varchar](70) NULL,
	[FLE_NOME] [varchar](70) NULL,
	[UME_NOTR] [varchar](35) NULL,
	[DUA_TC31] [varchar](120) NULL,
	[DUA_TC44] [varchar](120) NULL,
	[DUA_MTPR] [numeric](38, 6) NULL,
	[DUA_QUAL] [varchar](4) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[EAD_CODI] [varchar](8) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[DUA_IMPO] [varchar](3) NULL,
	[DUA_ATAR] [varchar](10) NULL,
	[DUA_AIVA] [int] NULL,
	[DUA_CS50] [int] NOT NULL,
	[DUA_R37C] [varchar](6) NULL,
	[DUA_ADRE] [varchar](2) NULL,
	[DUA_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DUA_2TAR] [varchar](4) NULL,
	[DUA_3TAR] [varchar](4) NULL,
	[DUA_MAVA] [int] NULL,
	[RRE_NOME1] [varchar](70) NULL,
	[DUA_BMAN] [bit] NOT NULL,
	[DUA_CAUD] [varchar](24) NULL,
	[DUA_CAND] [varchar](4) NULL,
	[DUA_CTID] [varchar](1) NULL,
	[DUA_CEND] [int] NULL,
	[DUA_IMPI] [varchar](3) NULL,
	[DUA_CAUI] [varchar](24) NULL,
	[DUA_CANI] [varchar](4) NULL,
	[DUA_CTII] [varchar](1) NULL,
	[DUA_CENI] [int] NULL,
	[DUA_1TAR] [varchar](4) NULL,
	[DUA_VIRT] [bit] NOT NULL,
	[PRE_CODI1] [varchar](3) NULL,
	[PRE_NOME1] [varchar](70) NULL,
	[DUA_VRA1] [varchar](2) NULL,
	[DUA_VRA2] [varchar](2) NULL,
	[DUA_VRGB] [varchar](6) NULL,
	[DUA_VRGC] [varchar](6) NULL,
	[DUA_VTXC] [bit] NOT NULL,
	[DUA_VVTV] [numeric](38, 6) NOT NULL,
	[DUA_VMTD] [numeric](38, 6) NOT NULL,
	[DUA_VMGD] [numeric](38, 6) NOT NULL,
	[DUA_VCAD] [varchar](24) NULL,
	[DUA_VCND] [varchar](4) NULL,
	[DUA_VCTD] [varchar](1) NULL,
	[DUA_VCED] [int] NULL,
	[DUA_VBTR] [numeric](38, 6) NOT NULL,
	[DUA_VTIV] [numeric](38, 6) NOT NULL,
	[RRE_CODI2] [int] NULL,
	[RRE_NOME2] [varchar](70) NULL,
	[DUA_VIMI] [varchar](3) NULL,
	[DUA_VVIV] [numeric](38, 6) NOT NULL,
	[DUA_VMGI] [numeric](38, 6) NOT NULL,
	[DUA_VCAI] [varchar](24) NULL,
	[DUA_VCNI] [varchar](4) NULL,
	[DUA_VCTI] [varchar](1) NULL,
	[DUA_VCEI] [int] NULL,
	[DUA_ABTI] [numeric](38, 6) NOT NULL,
	[APA_CODV] [varchar](22) NULL,
	[APA_CPAV] [varchar](22) NULL,
	[DUA_VCON] [varchar](6) NULL,
	[DUA_VQTD] [numeric](38, 6) NOT NULL,
	[DUA_TIVO] [numeric](38, 6) NOT NULL,
	[DUA_4TAR] [varchar](4) NULL,
	[DUA_5TAR] [varchar](4) NULL,
	[id_desdobramento] [int] NULL,
	[APA_CCUS] [varchar](9) NULL,
	[NTR_CODI] [varchar](2) NULL,
	[DUA_NRUR] [varchar](30) NULL,
	[DUA_TMER] [varchar](3) NULL,
	[DUA_IAVA] [varchar](4) NULL,
	[FOR_CODI] [varchar](18) NULL,
	[FOR_NOME] [varchar](70) NULL,
	[FOR_MORA] [varchar](70) NULL,
	[FOR_LOCA] [varchar](35) NULL,
	[FOR_CPOS] [varchar](12) NULL,
	[FOR_LPOS] [varchar](35) NULL,
	[FOR_NIF] [varchar](17) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAI_CODI1] [varchar](2) NULL,
	[PAI_CODI2] [varchar](2) NULL,
	[RES_CODI] [int] NULL,
	[FOR_CODI1] [varchar](18) NULL,
	[FOR_NOME1] [varchar](70) NULL,
	[FOR_MORA1] [varchar](70) NULL,
	[FOR_LOCA1] [varchar](35) NULL,
	[FOR_CPOS1] [varchar](12) NULL,
	[FOR_LPOS1] [varchar](35) NULL,
	[FOR_NIF1] [varchar](17) NULL,
	[PAI_CODI3] [varchar](2) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[CLI_NOME] [varchar](70) NULL,
	[CLI_MORA] [varchar](70) NULL,
	[CLI_LOCA] [varchar](35) NULL,
	[CLI_CPOS] [varchar](12) NULL,
	[CLI_LPOS] [varchar](35) NULL,
	[CLI_NIF] [varchar](17) NULL,
	[PAI_CODI4] [varchar](2) NULL,
	[DUA_ACRE] [numeric](38, 6) NOT NULL,
	[DUA_DEDU] [numeric](38, 6) NOT NULL,
	[DUA_CNRD] [varchar](17) NULL,
	[ALF_CODI] [varchar](8) NULL,
	[DUA_CCAD] [varchar](4) NULL,
	[DUA_CORD] [varchar](35) NULL,
	[DUA_CNRI] [varchar](17) NULL,
	[ALF_CODI1] [varchar](8) NULL,
	[DUA_CCAI] [varchar](4) NULL,
	[DUA_CORI] [varchar](35) NULL,
	[DUA_MIVI] [numeric](38, 6) NOT NULL,
	[DUA_QTDD] [numeric](38, 6) NOT NULL,
	[DUA_PMRP] [bit] NOT NULL,
	[DUA_PMRD] [datetime] NULL,
	[PAI_CODI5] [varchar](2) NULL,
 CONSTRAINT [PK_TAB_DUAD] PRIMARY KEY CLUSTERED 
(
	[DUA_CODI] ASC,
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_DUAD] UNIQUE NONCLUSTERED 
(
	[DUA_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUAD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUAD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUAD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUAD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUAD] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUBT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUBT](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DBT_CODI] [int] NOT NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[DBT_QTDE] [numeric](38, 6) NOT NULL,
	[DBT_NVEI] [int] NULL,
	[TVE_CODI] [varchar](3) NULL,
	[DBT_QUAL] [varchar](4) NULL,
	[DBT_VIEC] [varchar](4) NULL,
	[DBT_VCO2] [int] NULL,
	[CAT_CODI] [varchar](2) NULL,
	[TCO_CODI] [varchar](2) NULL,
	[DBT_OUTR] [varchar](10) NULL,
	[DBT_AUTO] [int] NOT NULL,
	[DBT_VLIA] [numeric](38, 6) NOT NULL,
	[DBT_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DBT_MARC] [varchar](20) NOT NULL,
	[DBT_MODE] [varchar](20) NOT NULL,
	[DBT_CODR] [varchar](20) NULL,
	[DBT_IDCR] [varchar](20) NULL,
	[HTE_CODI] [varchar](20) NULL,
	[DBT_HOMO] [varchar](20) NULL,
	[DBT_TABE] [varchar](1) NULL,
	[DBT_TCO2] [varchar](4) NULL,
	[DBT_AUTN] [int] NULL,
	[DBT_DIMT] [varchar](5) NULL,
 CONSTRAINT [PK_PRO_DUBT] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DBT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_DUBT] UNIQUE NONCLUSTERED 
(
	[DBT_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUBT] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUBT] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUBT] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUBT] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUBT] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUCC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUCC](
	[DUC_IDEN] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUC_NCPA] [varchar](35) NULL,
	[DUC_TRCK] [varchar](35) NULL,
	[DUC_TTVL] [numeric](38, 6) NULL,
	[DUC_DESC] [varchar](104) NULL,
	[DUC_PBRT] [numeric](38, 6) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[DUC_TCRG] [varchar](5) NULL,
	[DUC_DVOO] [datetime] NULL,
	[DUC_NVOO] [varchar](20) NULL,
	[DUC_NSEQ] [int] NULL,
 CONSTRAINT [PK_PRO_DUCC] PRIMARY KEY CLUSTERED 
(
	[DUC_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUCC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUCC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUCC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUCC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUCC] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUCG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUCG](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_DATA] [datetime] NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[DUC_CPRT] [varchar](18) NULL,
	[DUC_STAT] [int] NOT NULL,
	[DUC_DENV] [datetime] NULL,
	[DUC_NORD] [varchar](20) NULL,
	[DUC_NDAT] [datetime] NULL,
	[DUC_CNTN] [int] NULL,
	[DUC_PENV] [varchar](20) NULL,
	[DUC_NPRO] [varchar](19) NULL,
	[DUC_NALT] [int] NULL,
	[PFC_CODI] [int] NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[DUC_TIPO] [int] NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[DUC_ADI5] [int] NOT NULL,
	[DUC_TVL6] [numeric](38, 6) NULL,
	[DUC_REF7] [varchar](30) NULL,
	[PAI_PA10] [varchar](2) NULL,
	[PAI_PA11] [varchar](2) NULL,
	[DUC_PA13] [varchar](10) NULL,
	[DUC_EXP2] [varchar](18) NULL,
	[DUC_DST8] [varchar](18) NULL,
	[DEC_CO14] [varchar](6) NULL,
	[PAI_PA15] [varchar](2) NULL,
	[PAI_P15A] [varchar](2) NULL,
	[PAI_P15B] [int] NULL,
	[PAI_PA16] [varchar](2) NULL,
	[PAI_PA17] [varchar](2) NULL,
	[PAI_P17A] [varchar](2) NULL,
	[PAI_P17B] [int] NULL,
	[MTR_PT18] [varchar](2) NULL,
	[DUC_MT18] [varchar](30) NULL,
	[PAI_PA18] [varchar](2) NULL,
	[DUC_OP18] [numeric](38, 6) NULL,
	[DUC_CT18] [numeric](38, 6) NULL,
	[RRE_CO18] [int] NULL,
	[MTR_FT21] [varchar](2) NULL,
	[DUC_MT21] [varchar](30) NULL,
	[PAI_PA21] [varchar](2) NULL,
	[DUC_CT19] [int] NOT NULL,
	[CEN_CO20] [varchar](3) NULL,
	[DUC_FR20] [varchar](70) NULL,
	[DUC_DE20] [varchar](30) NULL,
	[NTR_CO24] [varchar](2) NULL,
	[MTR_PF25] [varchar](2) NULL,
	[MTR_PT26] [varchar](2) NULL,
	[LME_CO27] [varchar](17) NULL,
	[DUC_LC27] [varchar](70) NULL,
	[EAD_CO29] [varchar](8) NULL,
	[LME_CO30] [varchar](17) NULL,
	[DUC_LC30] [varchar](70) NULL,
	[PAI_PR22] [varchar](2) NULL,
	[DUC_MT22] [numeric](38, 6) NULL,
	[DUC_TX23] [numeric](38, 6) NULL,
	[DUC_FRET] [numeric](38, 6) NULL,
	[PAI_FRET] [varchar](2) NULL,
	[DUC_TXFR] [numeric](38, 6) NULL,
	[DUC_SEGU] [numeric](38, 6) NULL,
	[PAI_SEGU] [varchar](2) NULL,
	[DUC_TXSE] [numeric](38, 6) NULL,
	[DUC_MLQT] [numeric](38, 6) NULL,
	[DUC_MBRT] [numeric](38, 6) NULL,
	[DUC_VTRN] [numeric](38, 6) NULL,
	[PAI_VTRN] [varchar](2) NULL,
	[DUC_TXVT] [numeric](38, 6) NULL,
	[DUC_VEUR] [numeric](38, 6) NULL,
	[DUC_UFOB] [bit] NOT NULL,
	[DUC_VFOB] [numeric](38, 6) NULL,
	[DUC_DIRT] [numeric](38, 6) NULL,
	[DUC_TFDA] [numeric](38, 6) NULL,
	[DUC_ENOM] [varchar](70) NULL,
	[DUC_EMOR] [varchar](70) NULL,
	[DUC_ELOC] [varchar](35) NULL,
	[DUC_ECPO] [varchar](12) NULL,
	[DUC_ELPO] [varchar](35) NULL,
	[DUC_ENIF] [varchar](18) NULL,
	[PAI_ELIV] [varchar](2) NULL,
	[DUC_DNOM] [varchar](70) NULL,
	[DUC_DMOR] [varchar](70) NULL,
	[DUC_DLOC] [varchar](35) NULL,
	[DUC_DCPO] [varchar](12) NULL,
	[DUC_DLPO] [varchar](35) NULL,
	[DUC_DNIF] [varchar](18) NULL,
	[PAI_DLIV] [varchar](2) NULL,
	[DUC_TXT1] [text] NULL,
	[DUC_TXT2] [text] NULL,
	[DUC_TXT3] [text] NULL,
	[DUC_HIST] [text] NULL,
	[DUC_VLRC] [numeric](38, 6) NULL,
	[DUC_VLRE] [varchar](500) NULL,
	[DUC_VATT] [numeric](38, 6) NULL,
	[DUC_UCRI] [varchar](30) NULL,
	[DUC_DTCR] [datetime] NULL,
	[DUC_UALT] [varchar](30) NULL,
	[DUC_DTAL] [datetime] NULL,
	[NDE_NOME] [varchar](35) NULL,
	[TDE_NOME] [varchar](35) NULL,
	[ALF_NOME] [varchar](70) NULL,
	[PAI_NO10] [varchar](35) NULL,
	[PAI_NO11] [varchar](35) NULL,
	[PAI_NO15] [varchar](35) NULL,
	[PAI_NO16] [varchar](35) NULL,
	[PAI_NO17] [varchar](35) NULL,
	[PAI_MO22] [varchar](3) NULL,
	[PAI_MOFT] [varchar](3) NULL,
	[PAI_MOSG] [varchar](3) NULL,
	[PAI_MOVT] [varchar](3) NULL,
	[DEC_NOME] [varchar](70) NULL,
	[DEC_CENI] [varchar](18) NULL,
	[EAD_NOME] [varchar](35) NULL,
	[MTR_NO18] [varchar](35) NULL,
	[MTR_NO21] [varchar](35) NULL,
	[DUC_NFOR] [int] NULL,
	[DUC_MASC] [int] NULL,
	[DES_CODI] [varchar](25) NULL,
	[DES_DESC] [varchar](60) NULL,
	[DUC_DOBS] [text] NULL,
	[DUC_VFIS] [bit] NOT NULL,
	[DUC_PART] [bit] NOT NULL,
	[DUC_MOTI] [text] NULL,
	[DUC_DDES] [datetime] NULL,
	[DUC_NREQ] [varchar](30) NULL,
	[DUC_NDUR] [varchar](30) NULL,
	[DUC_T1RE] [varchar](30) NULL,
	[DUC_DSRE] [datetime] NULL,
	[DUC_DDTE] [datetime] NULL,
	[DUC_NDPR] [int] NULL,
	[DUC_DEEN] [datetime] NULL,
	[DUC_VCHE] [numeric](38, 6) NULL,
	[DUC_STBY] [bit] NOT NULL,
	[DUC_PRIO] [bit] NOT NULL,
	[DUC_EPRE] [bit] NOT NULL,
	[DEC_CEDE] [varchar](6) NULL,
	[DUC_CNOM] [varchar](70) NULL,
	[DUC_CMOR] [varchar](70) NULL,
	[DUC_CLOC] [varchar](35) NULL,
	[DUC_CCPO] [varchar](12) NULL,
	[DUC_CLPO] [varchar](35) NULL,
	[DUC_CNIF] [varchar](18) NULL,
	[PAI_CLIV] [varchar](2) NULL,
	[DUC_FUNC] [varchar](35) NULL,
	[DUC_DCED] [datetime] NULL,
	[DUC_CPRO] [bit] NOT NULL,
	[DUC_BUPS] [bit] NOT NULL,
	[DUC_BFFC] [bit] NOT NULL,
	[DUC_DTVO] [datetime] NULL,
	[DUC_PAYM] [int] NULL,
	[DUC_NPDT] [int] NULL,
	[DUC_NPDD] [int] NULL,
	[DUC_NTDP] [int] NULL,
	[DUC_PARM] [varchar](4) NULL,
	[DUC_NVRF] [varchar](50) NULL,
	[DUC_REGL] [varchar](20) NULL,
	[DUC_DTRL] [datetime] NULL,
	[DUC_TREM] [numeric](38, 6) NULL,
	[DUC_CIEX] [varchar](10) NULL,
	[DUC_CIDE] [varchar](10) NULL,
	[DUC_AERO] [varchar](80) NULL,
	[DUC_PPFC] [varchar](2) NULL,
	[DUC_NVOO] [varchar](20) NULL,
	[DUC_MCPA] [varchar](20) NULL,
	[DUC_NSEQ] [int] NULL,
	[DUC_REF1] [varchar](50) NULL,
	[DUC_REF2] [varchar](50) NULL,
	[DUC_RIUP] [bit] NOT NULL,
	[DUC_SHIP] [varchar](11) NULL,
	[DUC_TRAC] [varchar](35) NULL,
	[DUC_DTYP] [varchar](2) NULL,
	[DUC_VLRP] [numeric](38, 6) NOT NULL,
	[DUC_POSA] [varchar](13) NULL,
	[DUC_TPCG] [varchar](5) NULL,
	[DUC_FUPS] [varchar](100) NULL,
	[DUC_VLIL] [numeric](38, 6) NOT NULL,
	[DUC_VDIR] [numeric](38, 6) NULL,
	[DUC_VCLE] [numeric](38, 6) NULL,
	[DUC_D2NO] [varchar](70) NULL,
	[DUC_D2MO] [varchar](70) NULL,
	[DUC_D2LO] [varchar](35) NULL,
	[DUC_D2CP] [varchar](12) NULL,
	[DUC_D2LP] [varchar](35) NULL,
	[FIN_CODI] [int] NULL,
	[DUC_WSTA] [int] NULL,
	[DUC_WCAN] [varchar](1) NULL,
	[DUC_WTFC] [varchar](25) NULL,
	[DUC_ARTI] [int] NULL,
	[DUC_WCAI] [varchar](1) NULL,
	[DUC_WCAF] [varchar](1) NULL,
	[DUC_COMG] [text] NULL,
	[DUC_COMW] [text] NULL,
	[MNF_PESO] [numeric](38, 6) NULL,
	[MNF_PAIS] [varchar](2) NULL,
	[MNF_MOED] [varchar](3) NULL,
	[MNF_VALO] [numeric](38, 6) NULL,
	[DUC_NGLL] [int] NULL,
	[DUC_ASAI] [bit] NOT NULL,
	[DUC_PREC] [bit] NOT NULL,
	[DUC_TPDS] [int] NULL,
	[DUC_TPDC] [int] NULL,
	[DUC_TM21] [varchar](4) NULL,
	[TDE_1CAS] [varchar](5) NULL,
	[TDE_2CAS] [varchar](4) NULL,
	[DUC_NRVW] [int] NOT NULL,
	[DUC_PRVW] [bit] NOT NULL,
	[DUC_PALT] [bit] NOT NULL,
	[DUC_RTFW] [bit] NOT NULL,
	[DUC_FCHW] [bit] NOT NULL,
	[DUC_PRFW] [bit] NOT NULL,
	[DUC_NRFW] [int] NOT NULL,
	[DUC_DTAS] [datetime] NULL,
	[DUC_GTWY] [varchar](6) NULL,
	[DUC_DELG] [varchar](6) NULL,
	[DUC_TMSF] [int] NOT NULL,
	[TDO_DOCU] [varchar](4) NULL,
	[DUC_PDVU] [bit] NOT NULL,
	[TDO_DOCU1] [varchar](4) NULL,
	[NDE_CODI1] [varchar](3) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[CLI_NOME] [varchar](70) NULL,
	[DUC_NRUR] [varchar](70) NULL,
	[DUC_DTPP] [datetime] NULL,
	[DUC_NRCO] [varchar](50) NULL,
	[DUC_VERS] [int] NOT NULL,
	[DUC_REVI] [int] NOT NULL,
	[DUC_ESTO] [varchar](3) NULL,
	[DUC_DTCD] [datetime] NULL,
	[DUC_DTDC] [datetime] NULL,
	[DUC_CGLB] [bit] NOT NULL,
	[DUC_CAUC] [varchar](24) NULL,
	[DUC_CANO] [varchar](4) NULL,
	[DUC_CTIP] [varchar](1) NULL,
	[DUC_TLOC] [varchar](2) NULL,
	[ALF_CODI1] [varchar](8) NULL,
	[ALF_NOME1] [varchar](70) NULL,
	[DUC_LAMO] [varchar](70) NULL,
	[DUC_LALO] [varchar](35) NULL,
	[DUC_LACP] [varchar](50) NULL,
	[ARM_CODI] [varchar](17) NULL,
	[ARM_NOME] [varchar](70) NULL,
	[TAR_CODI] [varchar](1) NULL,
	[TAR_DESC] [varchar](35) NULL,
	[DUC_NRLO] [varchar](22) NOT NULL,
	[DUC_DUNO] [tinyint] NOT NULL,
	[DUC_CENT] [int] NULL,
	[NTR_NOME] [varchar](70) NULL,
	[DUC_VBAT] [bit] NOT NULL,
	[DUC_AUX0] [varchar](1000) NULL,
	[DUC_DTOP] [datetime] NULL,
	[DUC_VSCA] [numeric](38, 6) NOT NULL,
	[DUC_MTAT] [varchar](500) NULL,
	[DUC_CRTD] [bit] NOT NULL,
	[DUC_CRTF] [bit] NOT NULL,
	[DUC_CRTA] [bit] NOT NULL,
	[DUC_CTTR] [varchar](20) NULL,
	[DUC_VMUL] [numeric](38, 6) NOT NULL,
	[DUC_CNTL] [varchar](200) NULL,
	[DUC_VFRC] [numeric](38, 6) NOT NULL,
	[DUC_MFRC] [varchar](3) NULL,
	[DUC_NVSR] [int] NULL,
	[FUP_CODI] [int] NULL,
	[DUC_DDDT] [datetime] NULL,
	[DUC_UNMD] [varchar](30) NULL,
	[DUC_IMSR] [bit] NOT NULL,
	[DUC_EMSR] [bit] NOT NULL,
	[DUC_EMSU] [varchar](30) NULL,
	[DUC_EMSD] [datetime] NULL,
	[DUC_DCAT] [datetime] NULL,
	[DUC_DCAC] [datetime] NULL,
	[DUC_MOTM] [varchar](35) NULL,
	[DUC_DEBM] [varchar](15) NULL,
	[DUC_REEM] [varchar](3) NULL,
	[DUC_RTDT] [bit] NOT NULL,
	[DUC_TMAN] [varchar](1) NULL,
	[DUC_NACT] [int] NULL,
	[NST_CODI] [int] NULL,
	[NST_EANO] [int] NULL,
	[CLI_OPER] [varchar](18) NULL,
	[DUC_COBR] [bit] NOT NULL,
	[DUC_DTCO] [datetime] NULL,
	[DUC_BLOQ] [bit] NOT NULL,
	[DUC_BIVA] [bit] NOT NULL,
	[DUC_VERI] [varchar](200) NULL,
	[DUC_CJUS] [varchar](6) NULL,
	[DUC_VDES] [numeric](38, 6) NOT NULL,
	[DUC_EXPO] [bit] NOT NULL,
	[DUC_LADT] [bit] NOT NULL,
	[DUC_DADT] [datetime] NULL,
	[DUC_UADT] [varchar](30) NULL,
	[DUC_DDSC] [int] NOT NULL,
	[DUC_VLTR] [int] NULL,
	[DUC_DTEL] [varchar](14) NULL,
	[DUC_DEMA] [varchar](200) NULL,
	[DUC_MPRL] [varchar](1) NULL,
	[DUC_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
	[DUC_TSHI] [tinyint] NOT NULL,
	[DUC_VPRS] [numeric](38, 6) NOT NULL,
	[DUC_TMOO] [numeric](38, 6) NOT NULL,
	[DUC_TFRO] [numeric](38, 6) NOT NULL,
	[DUC_TSEO] [numeric](38, 6) NOT NULL,
	[DUC_TMLO] [numeric](38, 6) NOT NULL,
	[DUC_TMBO] [numeric](38, 6) NOT NULL,
	[DUC_TVEO] [numeric](38, 6) NOT NULL,
	[DUC_TVAO] [numeric](38, 6) NOT NULL,
	[DUC_TOPO] [numeric](38, 6) NOT NULL,
	[DUC_TLRO] [numeric](38, 6) NOT NULL,
	[DUC_ACAO] [tinyint] NOT NULL,
	[DUC_DCEN] [bit] NOT NULL,
	[DUC_ANXB] [varchar](2) NOT NULL,
	[DUC_DGEN] [varchar](40) NULL,
	[FOR_CODI] [varchar](18) NULL,
	[FOR_NOME] [varchar](70) NULL,
	[FOR_MORA] [varchar](70) NULL,
	[FOR_LOCA] [varchar](35) NULL,
	[FOR_CPOS] [varchar](12) NULL,
	[FOR_LPOS] [varchar](35) NULL,
	[FOR_NIF] [varchar](17) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[CLI_CODI1] [varchar](18) NULL,
	[CLI_NOME1] [varchar](70) NULL,
	[CLI_MORA] [varchar](70) NULL,
	[CLI_LOCA] [varchar](35) NULL,
	[CLI_CPOS] [varchar](12) NULL,
	[CLI_LPOS] [varchar](35) NULL,
	[CLI_NIF] [varchar](17) NULL,
	[PAI_CODI1] [varchar](2) NULL,
	[DEC_NIF] [varchar](17) NULL,
	[DUC_CNIR] [varchar](17) NULL,
	[ALF_CODI2] [varchar](8) NULL,
	[DUC_CCAC] [varchar](4) NULL,
	[DUC_CORF] [varchar](35) NULL,
	[ALF_CODI3] [varchar](8) NULL,
	[ALF_CODI4] [varchar](8) NULL,
	[PAI_CODI2] [varchar](2) NULL,
	[PAE_CODI] [varchar](8) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[MTR_TIPO] [int] NULL,
	[DUC_CONT] [varchar](17) NULL,
	[DUC_QUAL] [varchar](1) NULL,
	[DUC_IADI] [varchar](4) NULL,
	[DUC_ONIF] [varchar](17) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[DUC_NRAU] [varchar](35) NULL,
	[DUC_EORI] [varchar](17) NULL,
	[DUC_DPAG] [datetime] NULL,
	[DUC_REGI] [varchar](4) NULL,
	[DUC_INST] [int] NULL,
	[DUC_SERV] [bit] NOT NULL,
	[DUC_PMRP] [bit] NOT NULL,
	[DUC_PMRD] [datetime] NULL,
	[DUC_ATLO] [varchar](1) NULL,
	[DUC_AQUA] [varchar](1) NULL,
	[LME_CODI] [varchar](17) NULL,
	[DUC_AMOR] [varchar](70) NULL,
	[DUC_ALOC] [varchar](35) NULL,
	[DUC_ACPO] [varchar](17) NULL,
	[PAI_CODI3] [varchar](2) NULL,
	[DUC_APRZ] [tinyint] NULL,
	[DUC_APPR] [bit] NOT NULL,
	[DUC_ATXT] [varchar](512) NULL,
	[DUC_AAPR] [varchar](512) NULL,
	[DUC_AIAD] [varchar](512) NULL,
	[DUC_ACMD] [bit] NOT NULL,
 CONSTRAINT [PK_PRO_DUCA] PRIMARY KEY CLUSTERED 
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_DUCG_DUC_IDTY] UNIQUE NONCLUSTERED 
(
	[DUC_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUCG] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUCG] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUCG] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUCG] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUCG] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUCN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUCN](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DCN_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DCN_TEXT] [varchar](200) NOT NULL,
	[DCN_UCRI] [varchar](30) NOT NULL,
	[DCN_DTCR] [datetime] NOT NULL,
 CONSTRAINT [PK_PRO_DUCN] PRIMARY KEY CLUSTERED 
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[DCN_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUCN] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUCN] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUCN] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUCN] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUCN] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUDA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUDA](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DDA_CODI] [int] NOT NULL,
	[DDA_NNRM] [varchar](22) NOT NULL,
	[DDA_DATA] [datetime] NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[EAD_NOME] [varchar](35) NOT NULL,
 CONSTRAINT [PK_PRO_DUDA] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DDA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUDA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUDA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUDA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUDA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUDA] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUDD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [PRO_DUDD](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DDO_CODI] [int] NOT NULL,
	[DDD_VALO] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_DUDD] PRIMARY KEY CLUSTERED 
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[DDO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [PRO_DUDD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUDD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUDD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUDD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUDD] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUET]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUET](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DET_CODI] [int] NOT NULL,
	[DET_TIPO] [int] NOT NULL,
	[DET_CIEC] [varchar](4) NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_COD2] [varchar](6) NULL,
	[DET_QTDE] [numeric](38, 6) NOT NULL,
	[DET_AUTO] [int] NOT NULL,
	[DIT_IDST] [varchar](20) NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](70) NULL,
	[DET_IMPO] [varchar](3) NULL,
	[DET_TAXA] [bit] NOT NULL,
	[DET_TXVL] [numeric](38, 6) NOT NULL,
	[DET_IDST] [varchar](20) NOT NULL,
	[DET_IDEN] [bigint] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_PRO_DUET] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DET_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUET] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUET] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUET] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUET] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUET] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUFI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUFI](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[DUC_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DUF_DESC] [varchar](150) NULL,
	[DUF_LINK] [varchar](500) NULL,
	[DUF_ENVI] [bit] NOT NULL,
	[DUF_DATA] [datetime] NULL,
	[DUF_NOMF] [varchar](100) NULL,
	[DUF_UTIL] [varchar](30) NULL,
	[DUF_ISER] [bit] NOT NULL,
	[DUF_TMSG] [varchar](8) NULL,
	[DUF_ORIG] [int] NOT NULL,
	[DUF_FICH] [varbinary](max) NULL,
	[DUF_PMRP] [bit] NOT NULL,
	[DUF_PMRD] [datetime] NULL,
 CONSTRAINT [PK_PRO_DUFI] PRIMARY KEY CLUSTERED 
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[DUC_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUFI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUFI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUFI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUFI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUFI] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUFW]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUFW](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DFW_CODI] [int] NOT NULL,
	[DFW_DATA] [datetime] NOT NULL,
	[FUP_CODI] [int] NOT NULL,
	[UTI_UTIL] [varchar](30) NOT NULL,
 CONSTRAINT [PK_PRO_DUFW] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DFW_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUFW] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUFW] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUFW] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUFW] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUFW] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUIN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUIN](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUI_CODI] [int] NOT NULL,
	[SIN_CODI] [varchar](8) NULL,
	[SIN_DESC] [varchar](60) NULL,
	[DUI_DINI] [datetime] NULL,
	[DUI_HINI] [datetime] NULL,
	[DUI_DFIM] [datetime] NULL,
	[DUI_HFIM] [datetime] NULL,
	[DUI_OBSR] [text] NULL,
	[DUI_REHO] [int] NULL,
 CONSTRAINT [PK_PRO_DUIN] PRIMARY KEY CLUSTERED 
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[DUI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUIN] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUIN] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUIN] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUIN] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUIN] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUIT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUIT](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DMI_CODI] [int] NOT NULL,
	[DIT_CODI] [int] NOT NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_COD2] [varchar](6) NULL,
	[UME_NOME] [varchar](35) NOT NULL,
	[DIT_QTDE] [numeric](38, 6) NOT NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](70) NULL,
	[DIT_IMPO] [varchar](3) NULL,
	[DIT_TAXA] [bit] NOT NULL,
	[DIT_TXVL] [numeric](38, 6) NOT NULL,
	[DIT_IDST] [varchar](20) NOT NULL,
	[DIT_IDEN] [bigint] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_PRO_DUIT] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DMI_CODI] ASC,
	[DIT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUIT] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUIT] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUIT] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUIT] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUIT] TO [public] AS [dbo]
/****** Object:  Table [PRO_DULO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DULO](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[RRE_CODI] [int] NOT NULL,
	[RRE_NOME] [varchar](35) NOT NULL,
	[DUL_MONT] [numeric](38, 6) NOT NULL,
	[DUL_RPRO] [numeric](38, 6) NOT NULL,
	[DUL_MTAG] [numeric](38, 6) NOT NULL,
	[DUL_UCRI] [varchar](30) NOT NULL,
	[DUL_DTCR] [datetime] NOT NULL,
 CONSTRAINT [PK_PRO_DULO] PRIMARY KEY CLUSTERED 
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DULO] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DULO] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DULO] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DULO] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DULO] TO [public] AS [dbo]
/****** Object:  Table [PRO_DULR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DULR](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[RRE_CODI] [int] NOT NULL,
	[RRE_NOME] [varchar](70) NULL,
	[DUL_MONT] [numeric](38, 6) NULL,
	[DUL_RPRO] [numeric](38, 6) NULL,
	[DUL_MTAG] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_DULR] PRIMARY KEY CLUSTERED 
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DULR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DULR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DULR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DULR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DULR] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUMI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUMI](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DMI_CODI] [int] NOT NULL,
	[DMI_TIPO] [int] NOT NULL,
	[DMI_AIEC] [varchar](4) NULL,
	[DMI_MARC] [varchar](25) NULL,
	[DMI_CAPA] [numeric](38, 6) NOT NULL,
	[DMI_NEMB] [int] NOT NULL,
	[DMI_TEOR] [numeric](38, 6) NOT NULL,
	[TEM_CODI] [varchar](2) NULL,
	[DMI_CPED] [varchar](5) NULL,
	[DMI_TABH] [varchar](6) NULL,
	[DMI_IDEN] [bigint] IDENTITY(1,1) NOT NULL,
	[DMI_SELA] [varchar](1) NULL,
 CONSTRAINT [PK_PRO_DUMI] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DMI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUMI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUMI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUMI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUMI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUMI] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUOD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUOD](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUO_CODI] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NULL,
	[DUO_DESC] [varchar](104) NULL,
	[APA_CPAU] [varchar](22) NULL,
	[DUO_VALO] [numeric](38, 6) NULL,
	[DUO_MOED] [varchar](3) NULL,
	[DUO_TFAC] [numeric](38, 6) NULL,
	[DUO_CPA2] [varchar](35) NULL,
	[DUO_PES2] [numeric](38, 6) NULL,
	[DUO_TIPO] [int] NULL,
	[PAI_IDTY] [int] NULL,
 CONSTRAINT [PK_PRO_DUOD] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUOD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUOD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUOD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUOD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUOD] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUOI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUOI](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DUO_CODI] [int] NOT NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](70) NULL,
	[DUO_TIPO] [bit] NOT NULL,
	[UME_CODI] [varchar](3) NULL,
	[DUO_BTRI] [numeric](38, 6) NULL,
	[DUO_TXVL] [numeric](38, 6) NULL,
	[DUO_MONT] [numeric](38, 6) NULL,
	[RRE_AGRO] [bit] NOT NULL,
	[RRE_LIVA] [bit] NULL,
	[DUO_IMPO] [varchar](3) NULL,
	[DUO_AUTO] [int] NOT NULL,
	[DUO_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DUO_BMAN] [bit] NOT NULL,
	[DUO_CAUC] [varchar](24) NULL,
	[DUO_CANO] [varchar](4) NULL,
	[DUO_CTIP] [varchar](1) NULL,
	[DUO_CENT] [int] NULL,
	[DET_IDST] [varchar](20) NULL,
	[DUO_DEST] [int] NOT NULL,
	[DUO_MTAG] [numeric](38, 6) NOT NULL,
	[ALF_CODI] [varchar](8) NULL,
	[DUO_CCAC] [varchar](4) NULL,
	[DUO_CORF] [varchar](35) NULL,
	[DUO_CNRD] [varchar](17) NULL,
	[DUO_QTDE] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_DUOI] PRIMARY KEY CLUSTERED 
(
	[DUO_CODI] ASC,
	[DUA_CODI] ASC,
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUOI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUOI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUOI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUOI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUOI] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUPD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUPD](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DPD_CODI] [int] NOT NULL,
	[TXM_CODI] [varchar](5) NOT NULL,
	[DPD_DESC] [varchar](3000) NULL,
	[DPD_QUAL] [varchar](2) NULL,
	[DPD_ORIG] [int] NOT NULL,
	[DPD_IDEN] [bigint] IDENTITY(1,1) NOT NULL,
	[DPD_NFCH] [varchar](100) NULL,
	[DPD_FICH] [varbinary](max) NULL,
 CONSTRAINT [PK_PRO_DUPD] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DPD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUPD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUPD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUPD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUPD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUPD] TO [public] AS [dbo]
/****** Object:  Table [PRO_DURA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DURA](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DRA_CODI] [int] NOT NULL,
	[EAD_CODI] [varchar](8) NULL,
	[EAD_NOME] [varchar](35) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[DRA_APAN] [int] NOT NULL,
	[DRA_APC1] [varchar](20) NOT NULL,
	[DRA_APC2] [varchar](3) NOT NULL,
	[DOC_COD2] [varchar](5) NULL,
	[DRA_APRG] [varchar](2) NULL,
	[DRA_APDT] [datetime] NOT NULL,
	[DRA_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DRA_QUAL] [varchar](4) NOT NULL,
	[DRA_CODR] [varchar](20) NULL,
	[DRA_AUTO] [int] NOT NULL,
	[DRA_IDCR] [varchar](20) NULL,
 CONSTRAINT [PK_PRO_DURA] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DRA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DURA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DURA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DURA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DURA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DURA] TO [public] AS [dbo]
/****** Object:  Table [PRO_DURP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DURP](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DRP_CODI] [int] NOT NULL,
	[DRP_FLUX] [int] NOT NULL,
	[DRP_DATA] [datetime] NOT NULL,
	[DRP_OPER] [int] NOT NULL,
	[DRP_ESTO] [varchar](3) NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[TDE_NOME] [varchar](35) NOT NULL,
	[DRP_FICH] [varchar](255) NULL,
	[DRP_RESP] [text] NULL,
	[DRP_UTIL] [varchar](30) NULL,
	[DRP_EXPO] [bit] NOT NULL,
	[DRP_XPED] [xml] NULL,
	[DRP_XRES] [xml] NULL,
	[DRP_SUCE] [bit] NOT NULL,
	[DRP_NFCH] [varchar](100) NULL,
	[DRP_CFCH] [varbinary](max) NULL,
 CONSTRAINT [PK_PRO_DURP] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DRP_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DURP] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DURP] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DURP] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DURP] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DURP] TO [public] AS [dbo]
/****** Object:  Table [PRO_DUVE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DUVE](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[DBT_CODI] [int] NOT NULL,
	[DVC_CODI] [int] NOT NULL,
	[DVC_MATR] [varchar](10) NULL,
	[DVC_CHAS] [varchar](22) NULL,
	[DVC_IDEN] [bigint] IDENTITY(1,1) NOT NULL,
	[DVC_DMAT] [datetime] NULL,
	[DVC_DCHA] [datetime] NULL,
 CONSTRAINT [PK_PRO_DUVE] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DBT_CODI] ASC,
	[DVC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_DUVE] UNIQUE NONCLUSTERED 
(
	[DVC_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DUVE] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DUVE] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DUVE] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DUVE] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DUVE] TO [public] AS [dbo]
/****** Object:  Table [PRO_DV1C]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DV1C](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DV1_DATA] [datetime] NOT NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[DV1_STAT] [int] NOT NULL,
	[DV1_VEN1] [varchar](18) NULL,
	[DV1_COM2] [varchar](18) NULL,
	[DV1_DE2B] [varchar](6) NOT NULL,
	[CEN_COD3] [varchar](3) NOT NULL,
	[DV1_SUB3] [varchar](30) NULL,
	[DV1_NFC4] [varchar](35) NULL,
	[DV1_DAT4] [datetime] NULL,
	[DV1_NCT5] [varchar](20) NULL,
	[DV1_DAT5] [datetime] NULL,
	[DV1_C7AS] [bit] NOT NULL,
	[DV1_C7AN] [bit] NOT NULL,
	[DV1_C7BS] [bit] NOT NULL,
	[DV1_C7BN] [bit] NOT NULL,
	[DV1_C7CS] [bit] NOT NULL,
	[DV1_C7CN] [bit] NOT NULL,
	[DV1_C7TX] [varchar](70) NULL,
	[DV1_C8AS] [bit] NOT NULL,
	[DV1_C8AN] [bit] NOT NULL,
	[DV1_C8BS] [bit] NOT NULL,
	[DV1_C8BN] [bit] NOT NULL,
	[DV1_C8TX] [varchar](70) NULL,
	[DV1_C9AS] [bit] NOT NULL,
	[DV1_C9AN] [bit] NOT NULL,
	[DV1_C9BS] [bit] NOT NULL,
	[DV1_C9BN] [bit] NOT NULL,
	[DV1_C9TX] [varchar](70) NULL,
	[DV1_VNOM] [varchar](70) NULL,
	[DV1_VMOR] [varchar](70) NULL,
	[DV1_VLOC] [varchar](35) NULL,
	[DV1_VCPO] [varchar](12) NULL,
	[DV1_VLPO] [varchar](35) NULL,
	[DV1_VNIF] [varchar](18) NULL,
	[PAI_CODV] [varchar](2) NULL,
	[DV1_CNOM] [varchar](70) NULL,
	[DV1_CMOR] [varchar](70) NULL,
	[DV1_CLOC] [varchar](35) NULL,
	[DV1_CCPO] [varchar](12) NULL,
	[DV1_CLPO] [varchar](35) NULL,
	[DV1_CNIF] [varchar](18) NULL,
	[PAI_CODC] [varchar](2) NULL,
	[DV1_DNOM] [varchar](70) NULL,
 CONSTRAINT [PK_PRO_DV1C] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DV1C] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DV1C] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DV1C] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DV1C] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DV1C] TO [public] AS [dbo]
/****** Object:  Table [PRO_DVER]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DVER](
	[DVE_EANO] [int] NOT NULL,
	[DVE_PNUM] [int] NOT NULL,
	[DVE_STAT] [int] NOT NULL,
	[DVE_DATA] [datetime] NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[ALF_NOME] [varchar](60) NULL,
	[CLI_CODI] [varchar](18) NOT NULL,
	[CLI_NOME] [varchar](70) NULL,
	[CLI_MORA] [varchar](70) NULL,
	[CLI_LOCA] [varchar](35) NULL,
	[CLI_CPOS] [varchar](12) NULL,
	[CLI_LPOS] [varchar](35) NULL,
	[CLI_CNIF] [varchar](18) NULL,
	[PAI_CLIE] [varchar](2) NULL,
	[DVE_C2IP] [bit] NOT NULL,
	[DVE_C2IT] [bit] NOT NULL,
	[DVE_C2EX] [bit] NOT NULL,
	[DVE_C3QT] [numeric](38, 6) NOT NULL,
	[TEM_CCS3] [varchar](2) NOT NULL,
	[TEM_NCS3] [varchar](35) NOT NULL,
	[DVE_C3PB] [numeric](38, 6) NULL,
	[DVE_C4SP] [int] NOT NULL,
	[DVE_C4DS] [varchar](30) NOT NULL,
	[PAI_CCS5] [varchar](2) NOT NULL,
	[PAI_NCS5] [varchar](35) NULL,
	[PRE_CCS6] [varchar](3) NULL,
	[PRE_NCS6] [varchar](70) NULL,
	[RRE_CODI] [int] NULL,
	[DVE_CS14] [text] NULL,
	[DVE_CS15] [text] NULL,
	[DVE_TTRC] [numeric](38, 6) NOT NULL,
	[DVE_EXRC] [varchar](300) NOT NULL,
	[DVE_UCRI] [varchar](30) NULL,
	[DVE_DTCR] [datetime] NULL,
	[DVE_UALT] [varchar](30) NULL,
	[DVE_DTAL] [datetime] NULL,
 CONSTRAINT [PK_PRO_DVER] PRIMARY KEY CLUSTERED 
(
	[DVE_EANO] ASC,
	[DVE_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DVER] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DVER] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DVER] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DVER] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DVER] TO [public] AS [dbo]
/****** Object:  Table [PRO_DVIG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_DVIG](
	[DVI_CODI] [int] NOT NULL,
	[DVI_EANO] [int] NOT NULL,
	[DVI_DATA] [datetime] NOT NULL,
	[DVI_STAT] [int] NOT NULL,
	[DVI_NEMI] [varchar](20) NULL,
	[DVI_LODT] [varchar](50) NULL,
	[EOF_AUTC] [varchar](18) NOT NULL,
	[CLI_DEST] [varchar](18) NOT NULL,
	[DVI_PVAL] [varchar](30) NULL,
	[PAI_PPRO] [varchar](2) NULL,
	[PAI_PDES] [varchar](2) NULL,
	[APA_CNC8] [varchar](22) NOT NULL,
	[APA_DMER] [varchar](150) NOT NULL,
	[DVI_QUAN] [varchar](40) NOT NULL,
	[DVI_VCIF] [varchar](30) NULL,
	[DEC_CODI] [varchar](6) NULL,
	[TEX_MESP] [text] NULL,
 CONSTRAINT [PK_PRO_DVIG] PRIMARY KEY CLUSTERED 
(
	[DVI_CODI] ASC,
	[DVI_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_DVIG] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_DVIG] TO [public] AS [dbo]
GRANT INSERT ON [PRO_DVIG] TO [public] AS [dbo]
GRANT SELECT ON [PRO_DVIG] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_DVIG] TO [public] AS [dbo]
/****** Object:  Table [PRO_EUR1]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EUR1](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DEC_CODI] [varchar](6) NOT NULL,
	[EUR_DATA] [datetime] NOT NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[EUR_STAT] [int] NULL,
	[EUR_ENTA] [varchar](6) NULL,
	[EUR_ENTB] [varchar](35) NULL,
	[EUR_EXP1] [varchar](18) NULL,
	[EUR_DST3] [varchar](18) NULL,
	[EUR_PAI4] [varchar](6) NOT NULL,
	[PAI_COD5] [varchar](2) NOT NULL,
	[EUR_INF7] [text] NULL,
	[EUR_OBS8] [text] NULL,
	[EUR_MC10] [varchar](20) NULL,
	[EUR_QT10] [numeric](38, 6) NOT NULL,
	[UME_CO10] [varchar](3) NOT NULL,
	[EUR_PBTT] [numeric](38, 6) NOT NULL,
	[EUR_ENOM] [varchar](70) NULL,
	[EUR_EMOR] [varchar](70) NULL,
	[EUR_ELOC] [varchar](35) NULL,
	[EUR_ECPO] [varchar](12) NULL,
	[EUR_ELPO] [varchar](35) NULL,
	[EUR_ENIF] [varchar](18) NULL,
	[EUR_DNOM] [varchar](70) NULL,
	[EUR_DMOR] [varchar](70) NULL,
	[EUR_DLOC] [varchar](35) NULL,
	[EUR_DCPO] [varchar](12) NULL,
	[EUR_DLPO] [varchar](35) NULL,
	[EUR_DNIF] [varchar](18) NULL,
	[EUR_INDI] [text] NULL,
	[EUR_JUNT] [text] NULL,
	[EUR_NUMD] [varchar](500) NULL,
	[EUR_NDGA] [varchar](40) NULL,
	[EUR_DDGA] [datetime] NULL,
	[EUR_TPRO] [varchar](1) NULL,
	[EUR_TD1C] [varchar](5) NULL,
	[EUR_NUDD] [varchar](2000) NULL,
 CONSTRAINT [PK_PRO_EUR1] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DEC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EUR1] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EUR1] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EUR1] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EUR1] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EUR1] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXAD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXAD](
	[EXA_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXA_LINH] [int] NOT NULL,
	[APA_CO33] [varchar](22) NOT NULL,
	[APA_CP33] [varchar](22) NULL,
	[APA_DESG] [varchar](150) NOT NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAI_NOME] [varchar](35) NULL,
	[EXA_MBRT] [numeric](38, 6) NULL,
	[EXA_DESD] [varchar](3) NULL,
	[EXA_MLQD] [numeric](38, 6) NULL,
	[EXA_QUSU] [numeric](38, 6) NULL,
	[USU_CODI] [varchar](10) NULL,
	[USU_SIGL] [varchar](10) NULL,
	[EXA_VALO] [numeric](38, 6) NULL,
	[EXA_VFRE] [numeric](38, 6) NULL,
	[EXA_VSEG] [numeric](38, 6) NULL,
	[EXA_VEST] [numeric](38, 6) NULL,
	[EXA_PRAZ] [int] NULL,
	[EXA_DSOP] [varchar](260) NULL,
	[GPA_CODI] [varchar](6) NULL,
	[GPA_DESC] [varchar](35) NULL,
	[EXA_DTLM] [datetime] NULL,
	[EXA_IVEI] [int] NULL,
	[EXA_IRES] [varchar](2) NULL,
	[EXA_ANXC] [bit] NOT NULL,
	[EXA_ANXD] [bit] NOT NULL,
	[EXA_CPMV] [bit] NOT NULL,
	[TDE_REGI] [varchar](4) NULL,
	[EXM_CPRT] [varchar](50) NULL,
	[EXA_TSTP] [int] NULL,
	[EXA_ATAR] [varchar](10) NULL,
	[EXA_ORIG] [int] NOT NULL,
	[EXA_NFAC] [varchar](50) NULL,
	[EXA_DFAC] [datetime] NULL,
	[EXA_NARC] [varchar](50) NULL,
	[EXA_DARC] [datetime] NULL,
	[EXA_NGEP] [varchar](50) NULL,
	[EXA_DGEP] [datetime] NULL,
	[MIE_CODI] [varchar](25) NULL,
	[EXA_NUNI] [numeric](38, 6) NOT NULL,
	[EXA_NVOL] [numeric](38, 6) NOT NULL,
	[TEM_CODI] [varchar](2) NULL,
	[EXA_NDOC] [varchar](20) NULL,
	[EXA_DPAR] [datetime] NULL,
	[EXA_AUX0] [varchar](1000) NULL,
	[EXA_AUX1] [varchar](1000) NULL,
	[EXA_VEOR] [numeric](38, 6) NOT NULL,
	[EXA_ATA1] [varchar](4) NULL,
	[EXA_ATA2] [varchar](4) NULL,
	[EXA_ATA3] [varchar](4) NULL,
	[EXA_ATA4] [varchar](4) NULL,
	[EXA_ATA5] [varchar](4) NULL,
	[EXA_AIC1] [varchar](4) NULL,
	[EXA_AIC2] [varchar](4) NULL,
	[EXA_AIC3] [varchar](4) NULL,
	[EXA_AIC4] [varchar](4) NULL,
	[EXA_AIC5] [varchar](4) NULL,
	[EXA_CCUS] [varchar](9) NULL,
	[id_desdobramento] [int] NULL,
	[NTR_CODI] [varchar](2) NULL,
	[EXA_NRUR] [varchar](30) NULL,
	[EXA_MPAG] [varchar](1) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[CLI_NOME] [varchar](70) NULL,
	[CLI_MORA] [varchar](70) NULL,
	[CLI_LOCA] [varchar](35) NULL,
	[CLI_CPOS] [varchar](12) NULL,
	[CLI_LPOS] [varchar](35) NULL,
	[CLI_NIF] [varchar](17) NULL,
	[PAI_CODI1] [varchar](2) NULL,
	[PAI_CODI2] [varchar](2) NULL,
	[RES_CODI] [int] NULL,
	[FOR_CODI] [varchar](18) NULL,
	[FOR_NOME] [varchar](70) NULL,
	[FOR_MORA] [varchar](70) NULL,
	[FOR_LOCA] [varchar](35) NULL,
	[FOR_CPOS] [varchar](12) NULL,
	[FOR_LPOS] [varchar](35) NULL,
	[FOR_NIF] [varchar](17) NULL,
	[PAI_CODI3] [varchar](2) NULL,
	[PAI_CODI4] [varchar](2) NULL,
	[EXA_PMRP] [bit] NOT NULL,
	[EXA_PMRD] [datetime] NULL,
	[EXA_AJUS] [numeric](38, 6) NOT NULL,
	[CLI_TNIF] [varchar](1) NULL,
 CONSTRAINT [PK_PRO_EXAD] PRIMARY KEY CLUSTERED 
(
	[EXA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXAD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXAD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXAD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXAD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXAD] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXBT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXBT](
	[EXB_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[EXB_BTRI] [numeric](38, 6) NOT NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_NOME] [varchar](35) NULL,
	[EXB_QUAL] [varchar](1) NULL,
 CONSTRAINT [PK_PRO_EXBT] PRIMARY KEY CLUSTERED 
(
	[EXB_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXBT] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXBT] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXBT] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXBT] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXBT] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXCD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXCD](
	[EXD_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXC_LINH] [int] NOT NULL,
	[EXD_QTDE] [numeric](38, 6) NOT NULL,
	[TEM_CODI] [varchar](2) NOT NULL,
	[TEM_NOME] [varchar](35) NOT NULL,
	[EXD_PART] [bit] NOT NULL,
	[EXD_REST] [bit] NOT NULL,
 CONSTRAINT [PK_PRO_EXCD] PRIMARY KEY CLUSTERED 
(
	[EXD_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXCD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXCD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXCD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXCD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXCD] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXCE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXCE](
	[EXC_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXC_LINH] [int] NOT NULL,
	[EXC_FNIF] [varchar](18) NULL,
	[EXC_NFAC] [varchar](26) NULL,
	[EXC_DFAC] [datetime] NULL,
	[EXC_QNTD] [numeric](38, 6) NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[EXC_DCOM] [varchar](150) NULL,
	[EXC_PLIQ] [numeric](38, 6) NULL,
	[EXC_PBRT] [numeric](38, 6) NULL,
	[EXC_VALO] [numeric](38, 6) NULL,
 CONSTRAINT [PK_PRO_EXCE] PRIMARY KEY CLUSTERED 
(
	[EXC_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXCE] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXCE] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXCE] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXCE] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXCE] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXCR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXCR](
	[EXC_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[APA_CODI] [varchar](22) NULL,
	[APA_DESG] [varchar](150) NULL,
	[EXC_QNTD] [numeric](38, 6) NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[EXC_VCIF] [numeric](38, 6) NULL,
	[PRE_CODI] [varchar](3) NULL,
	[PRE_NOME] [varchar](70) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAI_NOME] [varchar](35) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[DOC_NOME] [varchar](70) NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](35) NULL,
	[EXC_BTRI] [numeric](38, 6) NULL,
	[UME_CTRI] [varchar](3) NULL,
	[UME_NTRI] [varchar](35) NULL,
	[EXC_QUAL] [varchar](1) NULL,
	[EXC_TAXA] [numeric](38, 6) NULL,
	[EXC_MONT] [numeric](38, 6) NULL,
	[EXC_LINH] [int] NULL,
	[EXC_NRDC] [varchar](26) NULL,
	[EXC_NADI] [int] NOT NULL,
 CONSTRAINT [PK_PRO_EXCR] PRIMARY KEY CLUSTERED 
(
	[EXC_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXCR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXCR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXCR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXCR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXCR] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXCT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXCT](
	[EXC_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXC_LINH] [int] NOT NULL,
	[EXC_CONT] [varchar](50) NOT NULL,
	[EXC_PMRP] [bit] NOT NULL,
	[EXC_PMRD] [datetime] NULL,
 CONSTRAINT [PK_PRO_EXCT] PRIMARY KEY CLUSTERED 
(
	[EXC_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXCT] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXCT] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXCT] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXCT] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXCT] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXDA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXDA](
	[EXD_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
	[EXD_NREF] [varchar](70) NULL,
	[EXD_DTEM] [datetime] NULL,
	[EXD_DTFV] [datetime] NULL,
	[EEM_CODI] [int] NULL,
	[EEM_DESC] [varchar](35) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAI_MOED] [varchar](3) NULL,
	[PAI_NOME] [varchar](35) NULL,
	[EXD_MONT] [numeric](38, 6) NULL,
	[EXD_QNTD] [numeric](38, 6) NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[EXM_CPRT] [varchar](50) NULL,
	[EXD_AUTO] [int] NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXA_LINH] [int] NOT NULL,
	[EXD_TSTP] [int] NULL,
	[EXD_TIPO] [tinyint] NULL,
	[EXD_NADI] [int] NULL,
 CONSTRAINT [PK_PRO_EXDA] PRIMARY KEY CLUSTERED 
(
	[EXD_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXDA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXDA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXDA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXDA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXDA] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXDM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXDM](
	[EXM_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXM_TPMN] [varchar](1) NULL,
	[EXM_CART] [varchar](50) NULL,
	[EXM_DESC] [varchar](150) NULL,
	[EXM_VALO] [numeric](38, 6) NOT NULL,
	[EXM_MOED] [varchar](2) NULL,
	[EXM_NCPT] [varchar](50) NULL,
	[EXM_PESO] [numeric](38, 6) NOT NULL,
	[EXM_CPRT] [varchar](50) NULL,
 CONSTRAINT [PK_PRO_EXDM] PRIMARY KEY CLUSTERED 
(
	[EXM_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXDM] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXDM] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXDM] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXDM] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXDM] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXDS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXDS](
	[EXD_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[EXD_TIMP] [varchar](1) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[EXD_DESC] [varchar](20) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](35) NULL,
	[EXD_DATA] [datetime] NULL,
	[EXD_NUME] [int] NOT NULL,
 CONSTRAINT [PK_PRO_EXDS] PRIMARY KEY CLUSTERED 
(
	[EXD_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXDS] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXDS] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXDS] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXDS] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXDS] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXEE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXEE](
	[EXE_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[APA_CPAU] [varchar](22) NULL,
	[APA_DESG] [varchar](150) NOT NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_NOME] [varchar](35) NULL,
	[EXE_QNTD] [numeric](38, 6) NOT NULL,
	[EXE_TXRE] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_EXEE] PRIMARY KEY CLUSTERED 
(
	[EXE_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXEE] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXEE] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXEE] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXEE] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXEE] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXFI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXFI](
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[DEC_CODI] [varchar](6) NOT NULL,
	[EXF_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[EXF_DESC] [varchar](150) NULL,
	[EXF_LINK] [varchar](500) NULL,
	[EXF_ENVI] [bit] NOT NULL,
	[EXF_DATA] [datetime] NULL,
	[EXF_UTIL] [varchar](30) NULL,
	[EXF_NOMF] [varchar](100) NULL,
	[EXF_ISER] [bit] NOT NULL,
	[EXF_TMSG] [varchar](8) NULL,
	[EXF_ODDM] [bit] NOT NULL,
	[EXF_ORIG] [int] NOT NULL,
	[EXF_FICH] [varbinary](max) NULL,
	[EXF_PMRP] [bit] NOT NULL,
	[EXF_PMRD] [datetime] NULL,
 CONSTRAINT [PK_PRO_EXFI] PRIMARY KEY CLUSTERED 
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[DEC_CODI] ASC,
	[EXF_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_EXFI_EXF_IDEN] UNIQUE NONCLUSTERED 
(
	[EXF_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXFI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXFI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXFI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXFI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXFI] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXFW]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXFW](
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EFW_CODI] [int] NOT NULL,
	[EFW_DATA] [datetime] NOT NULL,
	[FUP_CODI] [int] NOT NULL,
	[UTI_UTIL] [varchar](30) NOT NULL,
 CONSTRAINT [PK_PRO_EXFW] PRIMARY KEY CLUSTERED 
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[EXM_COPE] ASC,
	[EFW_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXFW] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXFW] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXFW] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXFW] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXFW] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXIC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXIC](
	[EXC_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[EXC_ICMP] [varchar](4) NOT NULL,
	[EXC_AUTO] [int] NOT NULL,
 CONSTRAINT [PK_PRO_EXIC] PRIMARY KEY CLUSTERED 
(
	[EXC_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXIC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXIC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXIC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXIC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXIC] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXIE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXIE](
	[EXI_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[EXI_NUME] [int] NOT NULL,
	[MIE_CODI] [varchar](25) NOT NULL,
	[MIE_DESC] [varchar](35) NULL,
	[EXI_QNTD] [numeric](38, 6) NOT NULL,
	[EXI_TIMP] [varchar](3) NOT NULL,
	[EXI_MPAG] [varchar](1) NULL,
	[EXI_MONT] [numeric](38, 6) NULL,
	[APA_CODI] [varchar](22) NULL,
	[APA_DESG] [varchar](150) NULL,
	[EXI_TART] [int] NULL,
	[TEM_CODI] [varchar](2) NULL,
	[TEM_NOME] [varchar](35) NULL,
	[EXI_CAPE] [numeric](38, 6) NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[EXI_TEOR] [numeric](38, 6) NULL,
 CONSTRAINT [PK_PRO_EXIE] PRIMARY KEY CLUSTERED 
(
	[EXI_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXIE] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXIE] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXIE] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXIE] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXIE] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXIV]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXIV](
	[EXI_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[EXI_NCHA] [varchar](25) NOT NULL,
	[EXI_DTPM] [datetime] NULL,
 CONSTRAINT [PK_PRO_EXIV] PRIMARY KEY CLUSTERED 
(
	[EXI_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXIV] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXIV] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXIV] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXIV] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXIV] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXME]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXME](
	[EXM_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[INF_CODI] [varchar](8) NOT NULL,
	[INF_DESI] [varchar](150) NULL,
 CONSTRAINT [PK_PRO_EXME] PRIMARY KEY CLUSTERED 
(
	[EXM_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXME] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXME] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXME] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXME] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXME] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXML]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXML](
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[DEC_CODI] [varchar](6) NOT NULL,
	[EXM_CODO] [int] NULL,
	[EXM_TOPE] [int] NULL,
	[EXM_TPRO] [varchar](1) NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[NDE_NOME] [varchar](35) NULL,
	[DEC_NOME] [varchar](70) NULL,
	[EXM_DATA] [datetime] NOT NULL,
	[EXM_NRIN] [varchar](35) NOT NULL,
	[EXM_NRLO] [varchar](22) NOT NULL,
	[EXM_STAT] [int] NOT NULL,
	[EXM_CNUM] [int] NULL,
	[EXM_ESTO] [varchar](3) NULL,
	[EXM_NDGA] [varchar](21) NULL,
	[EXM_DDGA] [datetime] NULL,
	[EXM_VERS] [int] NULL,
	[EXM_REVI] [int] NULL,
	[EXM_DCTP] [varchar](3) NULL,
	[EXM_PENV] [varchar](3) NULL,
	[EAD_CODA] [varchar](8) NOT NULL,
	[EAD_NOMA] [varchar](35) NULL,
	[TDE_COD1] [varchar](4) NOT NULL,
	[TDE_NOM1] [varchar](35) NULL,
	[CLI_COD2] [varchar](18) NOT NULL,
	[CLI_NOM2] [varchar](70) NULL,
	[CLI_MOR2] [varchar](70) NULL,
	[CLI_LOC2] [varchar](35) NULL,
	[CLI_CPO2] [varchar](12) NULL,
	[CLI_LPO2] [varchar](35) NULL,
	[CLI_NIF2] [varchar](18) NULL,
	[CLI_PAI2] [varchar](2) NULL,
	[EXM_TP2A] [varchar](1) NULL,
	[EXM_TI2B] [varchar](2) NULL,
	[EXM_TAD5] [int] NULL,
	[EXM_TVL6] [numeric](38, 6) NULL,
	[FOR_COD8] [varchar](18) NULL,
	[FOR_NOM8] [varchar](70) NULL,
	[FOR_MOR8] [varchar](70) NULL,
	[FOR_LOC8] [varchar](35) NULL,
	[FOR_CPO8] [varchar](12) NULL,
	[FOR_LPO8] [varchar](35) NULL,
	[FOR_NIF8] [varchar](18) NULL,
	[FOR_PAI8] [varchar](2) NULL,
	[EXM_IROR] [int] NOT NULL,
	[DEC_CO14] [varchar](6) NOT NULL,
	[DEC_NO14] [varchar](70) NULL,
	[EXM_TP14] [int] NULL,
	[EXM_P15A] [varchar](2) NULL,
	[EXM_P17A] [varchar](2) NULL,
	[EXM_C17C] [varchar](14) NULL,
	[EAD_C17C] [varchar](8) NULL,
	[EAD_N17C] [varchar](35) NULL,
	[EXM_D17C] [datetime] NULL,
	[EXM_CT19] [int] NULL,
	[MTR_CO18] [varchar](2) NULL,
	[MTR_NO18] [varchar](35) NULL,
	[EXM_TP18] [varchar](2) NULL,
	[EXM_MT18] [varchar](27) NULL,
	[MTR_C18A] [varchar](2) NULL,
	[MTR_N18A] [varchar](35) NULL,
	[EXM_M18A] [varchar](27) NULL,
	[EXM_T18B] [varchar](4) NULL,
	[EXM_I18B] [varchar](17) NULL,
	[EXM_P18C] [int] NULL,
	[EXM_I18C] [varchar](17) NULL,
	[MTR_CO21] [varchar](2) NULL,
	[MTR_NO21] [varchar](35) NULL,
	[EXM_TP21] [varchar](2) NULL,
	[EXM_MT21] [varchar](27) NULL,
	[PAI_CO21] [varchar](2) NULL,
	[PAI_NO21] [varchar](35) NULL,
	[MTR_CO25] [varchar](2) NULL,
	[MTR_CO26] [varchar](2) NULL,
	[MTR_C26A] [varchar](2) NULL,
	[CEN_CO20] [varchar](3) NULL,
	[CEN_NO20] [varchar](35) NULL,
	[EXM_FR20] [varchar](70) NULL,
	[EXM_LG20] [varchar](50) NULL,
	[NTR_CO24] [varchar](2) NULL,
	[NTR_NO24] [varchar](70) NULL,
	[PAI_CO22] [varchar](2) NULL,
	[PAI_MO22] [varchar](3) NULL,
	[EXM_MT22] [numeric](38, 6) NULL,
	[EXM_UFOB] [bit] NOT NULL,
	[EXM_VFOB] [numeric](38, 6) NULL,
	[EXM_TX23] [numeric](38, 6) NULL,
	[EXM_TFRT] [numeric](38, 6) NULL,
	[EXM_TSEG] [numeric](38, 6) NULL,
	[EXM_TMLQ] [numeric](38, 6) NULL,
	[EXM_TMBR] [numeric](38, 6) NULL,
	[EXM_TREM] [numeric](38, 6) NULL,
	[EXM_VEUR] [numeric](38, 6) NULL,
	[EXM_VATT] [numeric](38, 6) NULL,
	[EAD_CO29] [varchar](8) NULL,
	[EAD_NO29] [varchar](35) NULL,
	[EAD_C29A] [varchar](8) NULL,
	[EAD_N29A] [varchar](35) NULL,
	[EXM_DTIN] [datetime] NULL,
	[EXM_HRIN] [datetime] NULL,
	[EXM_DTFI] [datetime] NULL,
	[EXM_HRFI] [datetime] NULL,
	[EAD_CO30] [varchar](8) NULL,
	[EAD_NO30] [varchar](35) NULL,
	[LEM_CO30] [varchar](25) NULL,
	[LEM_NO30] [varchar](70) NULL,
	[LME_CO30] [varchar](17) NULL,
	[LME_NO30] [varchar](70) NULL,
	[EXM_MR30] [varchar](35) NULL,
	[EXM_CP30] [varchar](9) NULL,
	[EXM_LP30] [varchar](35) NULL,
	[LEM_C30A] [varchar](25) NULL,
	[LEM_N30A] [varchar](70) NULL,
	[EXM_NC48] [varchar](24) NULL,
	[EXM_AC48] [varchar](4) NULL,
	[EXM_TC48] [varchar](1) NULL,
	[ARM_CO49] [varchar](17) NULL,
	[ARM_NO49] [varchar](70) NULL,
	[TAR_CO49] [varchar](1) NULL,
	[TAR_DE49] [varchar](35) NULL,
	[EXM_ESTM] [varchar](2) NULL,
	[AGE_CO50] [varchar](18) NULL,
	[AGE_NO50] [varchar](70) NULL,
	[EXM_Q30C] [int] NULL,
	[EXM_UCRI] [varchar](30) NULL,
	[EXM_DTCR] [datetime] NULL,
	[EXM_UALT] [varchar](30) NULL,
	[EXM_DTAL] [datetime] NULL,
	[EXM_MASC] [int] NULL,
	[EXM_VLRC] [numeric](38, 6) NULL,
	[EXM_CA54] [varchar](1) NOT NULL,
	[EXM_RESP] [text] NULL,
	[FIN_CODI] [int] NULL,
	[EXM_NRII] [int] NOT NULL,
	[EXM_NVRF] [varchar](50) NULL,
	[EXM_EXNO] [varchar](70) NULL,
	[EXM_EXMO] [varchar](70) NULL,
	[EXM_EXLC] [varchar](35) NULL,
	[EXM_EXCP] [varchar](12) NULL,
	[EXM_EXLP] [varchar](35) NULL,
	[EXM_EXPS] [varchar](2) NULL,
	[EXM_EXCT] [varchar](18) NULL,
	[EXM_DENO] [varchar](70) NULL,
	[EXM_DEMO] [varchar](70) NULL,
	[EXM_DELC] [varchar](35) NULL,
	[EXM_DEPS] [varchar](2) NULL,
	[EXM_2P22] [varchar](2) NULL,
	[EXM_2M22] [numeric](38, 6) NOT NULL,
	[EXM_2MLQ] [numeric](38, 6) NOT NULL,
	[EXM_2MBR] [numeric](38, 6) NOT NULL,
	[EXM_CPRT] [varchar](18) NULL,
	[EXM_MCPA] [varchar](20) NULL,
	[EXM_TPCG] [varchar](5) NULL,
	[EXM_DTVO] [datetime] NULL,
	[EXM_DTYP] [varchar](2) NULL,
	[EXM_NSEQ] [int] NULL,
	[EXM_FUPS] [varchar](100) NULL,
	[EXM_CIEX] [varchar](10) NULL,
	[EXM_CIDE] [varchar](10) NULL,
	[EXM_PPFC] [varchar](3) NULL,
	[EXM_NVOO] [varchar](20) NULL,
	[EXM_REF1] [varchar](50) NULL,
	[EXM_REF2] [varchar](50) NULL,
	[EXM_TRAC] [varchar](35) NULL,
	[EXM_SHIP] [varchar](11) NULL,
	[EXM_VDIR] [int] NULL,
	[EXM_VCLE] [int] NULL,
	[EXM_NPRO] [varchar](20) NULL,
	[SIN_CODI] [varchar](4) NULL,
	[SIN_DESP] [varchar](60) NULL,
	[EXM_INCE] [varchar](1) NULL,
	[EXM_NCMR] [varchar](70) NULL,
	[EXM_DTMP] [varchar](1) NULL,
	[EXM_BLOQ] [bit] NOT NULL,
	[EXM_TMSF] [int] NOT NULL,
	[CLI_CODI] [varchar](18) NULL,
	[CLI_NOME] [varchar](70) NULL,
	[EXM_DTCD] [datetime] NULL,
	[PAE_CODI] [varchar](8) NULL,
	[PAE_NOME] [varchar](35) NULL,
	[EXM_NRCO] [varchar](50) NULL,
	[EXM_DTCO] [datetime] NULL,
	[EXM_CNTL] [varchar](200) NULL,
	[EXM_IMSR] [bit] NOT NULL,
	[EXM_EMSR] [bit] NOT NULL,
	[EXM_EMSU] [varchar](30) NULL,
	[EXM_EMSD] [datetime] NULL,
	[EXM_ANOT] [text] NULL,
	[EXM_CRTD] [bit] NOT NULL,
	[EXM_CRTF] [bit] NOT NULL,
	[EXM_CRTA] [bit] NOT NULL,
	[EXM_ASAI] [bit] NOT NULL,
	[EXM_DINC] [datetime] NULL,
	[FUP_CODI] [int] NULL,
	[EXM_PIUP] [bit] NOT NULL,
	[EXM_DPUP] [datetime] NULL,
	[EXM_HPUP] [datetime] NULL,
	[EXM_ARGW] [bit] NOT NULL,
	[EXM_HVLV] [varchar](6) NULL,
	[EXM_ENPC] [bit] NOT NULL,
	[EXM_DTAS] [datetime] NULL,
	[EXM_DT6A] [datetime] NULL,
	[DSD_IDNN] [int] NULL,
	[EXM_DSDS] [datetime] NULL,
	[EXM_FACI] [varchar](8) NULL,
	[EXM_AUX0] [varchar](1000) NULL,
	[EXM_AUX1] [varchar](1000) NULL,
	[EXM_DDDM] [bit] NOT NULL,
	[EXM_EMMA] [bit] NOT NULL,
	[EXM_DTLM] [datetime] NULL,
	[EXM_DENV] [datetime] NULL,
	[EXM_UENV] [varchar](30) NULL,
	[EXM_PLET] [bit] NOT NULL,
	[EXM_EXPE] [varchar](3) NOT NULL,
	[EXM_EXPK] [bit] NOT NULL,
	[NST_CODI] [int] NULL,
	[NST_EANO] [int] NULL,
	[CLI_OPER] [varchar](18) NULL,
	[EXM_CMPX] [xml] NULL,
	[EXM_EXPO] [int] NOT NULL,
	[EXM_IDTY] [bigint] IDENTITY(1,1) NOT NULL,
	[EXM_CNTX] [tinyint] NOT NULL,
	[EXM_SEGU] [tinyint] NOT NULL,
	[EXM_DGEN] [varchar](40) NULL,
	[EXM_DCMP] [datetime] NULL,
	[CLI_CODI1] [varchar](18) NULL,
	[CLI_NOME1] [varchar](70) NULL,
	[CLI_MORA1] [varchar](70) NULL,
	[CLI_LOCA1] [varchar](35) NULL,
	[CLI_CPOS1] [varchar](12) NULL,
	[CLI_LPOS1] [varchar](35) NULL,
	[CLI_NIF1] [varchar](18) NULL,
	[PAI_CODI1] [varchar](2) NULL,
	[EXM_NTRP] [varchar](17) NULL,
	[EAD_CODI] [varchar](8) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAE_CODI1] [varchar](8) NULL,
	[EXM_TXTC] [varchar](512) NULL,
	[PAI_CODI2] [varchar](2) NULL,
	[EXM_CFRE] [numeric](38, 6) NOT NULL,
	[PAI_CODI3] [varchar](2) NULL,
	[EXM_CSEG] [numeric](38, 6) NOT NULL,
	[EXM_VRBA] [bit] NOT NULL,
	[PAI_CODI4] [varchar](2) NULL,
	[EXM_TLOC] [varchar](1) NOT NULL,
	[EXM_QUAL] [varchar](1) NOT NULL,
	[PAI_CODI5] [varchar](2) NULL,
	[EXM_IADI] [varchar](4) NULL,
	[EXM_NAUT] [varchar](35) NULL,
	[EXM_ONIF] [varchar](17) NULL,
	[EAD_CODI1] [varchar](8) NULL,
	[EXM_PRZA] [varchar](512) NULL,
	[EXM_ATVP] [varchar](512) NULL,
	[EXM_INFA] [varchar](512) NULL,
	[EXM_PART] [bit] NOT NULL,
	[EXM_VMUL] [numeric](38, 6) NOT NULL,
	[EXM_MOTM] [varchar](35) NULL,
	[EXM_DEBM] [varchar](15) NULL,
	[EXM_REEM] [varchar](3) NULL,
	[EXM_VSCA] [int] NOT NULL,
	[EXM_ANXB] [varchar](2) NOT NULL,
	[EXM_INST] [int] NULL,
	[EXM_DTCS] [datetime] NULL,
	[EXM_PMRP] [bit] NOT NULL,
	[EXM_PMRD] [datetime] NULL,
	[EXM_REGI] [varchar](4) NULL,
	[EXM_DCEN] [bit] NOT NULL,
	[EXM_MTIT] [int] NULL,
	[EXM_MTFT] [int] NULL,
	[CLI_TNIF1] [varchar](1) NULL,
 CONSTRAINT [PK_PRO_EXML] PRIMARY KEY CLUSTERED 
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[DEC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_EXML_EXM_IDTY] UNIQUE NONCLUSTERED 
(
	[EXM_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXML] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXML] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXML] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXML] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXML] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXMV]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXMV](
	[EXM_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[EXM_MARN] [varchar](512) NULL,
	[TEM_CODI] [varchar](2) NOT NULL,
	[TEM_NOME] [varchar](35) NULL,
	[EXM_NVOL] [numeric](38, 6) NOT NULL,
	[EXM_PART] [bit] NOT NULL,
	[EXM_REST] [bit] NOT NULL,
	[EXM_TVOL] [bit] NOT NULL,
	[EXM_CPRT] [varchar](50) NULL,
	[EXM_TSTP] [int] NULL,
	[EXM_IDST] [varchar](20) NOT NULL,
	[EXM_IDSO] [varchar](20) NULL,
	[EXM_AUTO] [int] NOT NULL,
	[EXM_EANO] [int] NULL,
	[EXM_CODI] [int] NULL,
	[EXM_COPE] [varchar](6) NULL,
 CONSTRAINT [PK_PRO_EXMV] PRIMARY KEY CLUSTERED 
(
	[EXM_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXMV] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXMV] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXMV] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXMV] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXMV] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXPA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXPA](
	[EXP_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[EXP_LINH] [int] NOT NULL,
	[TXM_CODI] [varchar](5) NOT NULL,
	[TXM_DESC] [varchar](512) NULL,
	[EXP_ORIG] [tinyint] NOT NULL,
 CONSTRAINT [PK_PRO_EXPA] PRIMARY KEY CLUSTERED 
(
	[EXP_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXPA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXPA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXPA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXPA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXPA] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXPI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXPI](
	[EXP_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXM_EANO] [int] NOT NULL,
	[EXM_CODI] [int] NOT NULL,
	[EXM_COPE] [varchar](6) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](25) NULL,
	[EXP_ORIG] [tinyint] NOT NULL,
 CONSTRAINT [PK_PRO_EXPI] PRIMARY KEY CLUSTERED 
(
	[EXP_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXPI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXPI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXPI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXPI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXPI] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXPS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXPS](
	[EXP_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[MIA_CODI] [varchar](2) NOT NULL,
	[MIA_DESC] [varchar](150) NULL,
	[MIA_OBRI] [bit] NOT NULL,
 CONSTRAINT [PK_PRO_EXPS] PRIMARY KEY CLUSTERED 
(
	[EXP_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXPS] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXPS] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXPS] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXPS] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXPS] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXRC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXRC](
	[EXR_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[APA_DESG] [varchar](150) NOT NULL,
	[EXR_QNTD] [numeric](38, 6) NOT NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_NOME] [varchar](35) NULL,
 CONSTRAINT [PK_PRO_EXRC] PRIMARY KEY CLUSTERED 
(
	[EXR_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXRC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXRC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXRC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXRC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXRC] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXRF]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXRF](
	[EXR_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[FFA_CODI] [int] NOT NULL,
	[FFA_DESC] [varchar](35) NULL,
	[EXR_QNTD] [numeric](38, 6) NOT NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_NOME] [varchar](35) NULL,
 CONSTRAINT [PK_PRO_EXRF] PRIMARY KEY CLUSTERED 
(
	[EXR_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXRF] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXRF] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXRF] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXRF] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXRF] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXRM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXRM](
	[EXR_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[INF_CODI] [varchar](8) NOT NULL,
	[INF_DESI] [varchar](150) NULL,
 CONSTRAINT [PK_PRO_EXRM] PRIMARY KEY CLUSTERED 
(
	[EXR_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXRM] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXRM] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXRM] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXRM] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXRM] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXRP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXRP](
	[EXR_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[CTE_CODI] [varchar](3) NULL,
	[CTE_DESC] [varchar](35) NULL,
	[CPE_CODI] [varchar](3) NULL,
	[CPE_DESC] [varchar](35) NULL,
	[EXR_TEOR] [numeric](38, 6) NOT NULL,
	[EXR_PESO] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_EXRP] PRIMARY KEY CLUSTERED 
(
	[EXR_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXRP] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXRP] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXRP] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXRP] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXRP] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXRR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXRR](
	[EXR_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[APA_DESG] [varchar](150) NULL,
	[EXR_QNTD] [numeric](38, 6) NOT NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_NOME] [varchar](35) NULL,
 CONSTRAINT [PK_PRO_EXRR] PRIMARY KEY CLUSTERED 
(
	[EXR_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXRR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXRR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXRR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXRR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXRR] TO [public] AS [dbo]
/****** Object:  Table [PRO_EXRT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_EXRT](
	[EXR_CHVE] [int] IDENTITY(1,1) NOT NULL,
	[EXA_CHVE] [int] NOT NULL,
	[CTE_CODI] [varchar](3) NOT NULL,
	[CTE_DESC] [varchar](35) NULL,
	[EXR_VALO] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_PRO_EXRT] PRIMARY KEY CLUSTERED 
(
	[EXR_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_EXRT] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_EXRT] TO [public] AS [dbo]
GRANT INSERT ON [PRO_EXRT] TO [public] AS [dbo]
GRANT SELECT ON [PRO_EXRT] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_EXRT] TO [public] AS [dbo]
/****** Object:  Table [PRO_G156]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_G156](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[G15_TIPO] [int] NOT NULL,
	[G15_DATA] [datetime] NOT NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[G15_STAT] [int] NULL,
	[G15_DES1] [varchar](18) NULL,
	[G15_LDES] [varchar](70) NULL,
	[G15_DEC2] [varchar](18) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[G15_DADU] [varchar](30) NULL,
	[G15_MARC] [varchar](20) NULL,
	[G15_NUME] [varchar](20) NULL,
	[G15_QUNT] [numeric](38, 6) NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[G15_PBTT] [numeric](38, 6) NOT NULL,
	[APA_CODI] [varchar](22) NULL,
	[G15_DESG] [varchar](150) NOT NULL,
	[G15_NNAV] [varchar](30) NULL,
	[G15_1NOM] [varchar](70) NULL,
	[G15_1MOR] [varchar](70) NULL,
	[G15_1LOC] [varchar](35) NULL,
	[G15_1CPO] [varchar](12) NULL,
	[G15_1LPO] [varchar](35) NULL,
	[G15_1NIF] [varchar](18) NULL,
	[PAI_COD1] [varchar](2) NULL,
	[G15_2NOM] [varchar](70) NULL,
	[G15_2MOR] [varchar](70) NULL,
	[G15_2LOC] [varchar](35) NULL,
	[G15_2CPO] [varchar](12) NULL,
	[G15_2LPO] [varchar](35) NULL,
	[G15_2NIF] [varchar](18) NULL,
	[PAI_COD2] [varchar](2) NULL,
 CONSTRAINT [PK_PRO_G156] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_G156] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_G156] TO [public] AS [dbo]
GRANT INSERT ON [PRO_G156] TO [public] AS [dbo]
GRANT SELECT ON [PRO_G156] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_G156] TO [public] AS [dbo]
/****** Object:  Table [PRO_GEMO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_GEMO](
	[GEM_MODE] [varchar](5) NOT NULL,
	[GEM_R561] [numeric](38, 6) NULL,
	[GEM_R721] [numeric](38, 6) NULL,
	[GEM_R722] [numeric](38, 6) NULL,
	[GEM_R726] [numeric](38, 6) NULL,
	[GEM_REST] [numeric](38, 6) NOT NULL,
	[GEM_R371] [numeric](38, 6) NULL,
	[GEM_R372] [numeric](38, 6) NULL,
	[GEM_999T] [numeric](38, 6) NOT NULL,
	[GEM_EXTN] [varchar](150) NULL,
 CONSTRAINT [PK_PRO_GEMO] PRIMARY KEY CLUSTERED 
(
	[GEM_MODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_GEMO] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_GEMO] TO [public] AS [dbo]
GRANT INSERT ON [PRO_GEMO] TO [public] AS [dbo]
GRANT SELECT ON [PRO_GEMO] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_GEMO] TO [public] AS [dbo]
/****** Object:  Table [PRO_GREX]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_GREX](
	[GRE_CODI] [int] NOT NULL,
	[GRE_EANO] [int] NOT NULL,
	[GRE_DATA] [datetime] NOT NULL,
	[GRE_STAT] [int] NULL,
	[EOF_OREM] [varchar](18) NULL,
	[CLI_TITU] [varchar](18) NULL,
	[EOF_OEEX] [varchar](18) NULL,
	[PAI_PDES] [varchar](2) NULL,
	[GRE_DSIM] [bit] NULL,
	[GRE_DNAO] [bit] NULL,
	[GRE_FSIM] [bit] NULL,
	[GRE_FNAO] [bit] NULL,
	[GRE_ASIM] [bit] NULL,
	[GRE_ANAO] [bit] NULL,
	[GRE_DAPR] [datetime] NULL,
	[GRE_MTGA] [numeric](38, 6) NULL,
	[PAI_MOED] [varchar](2) NULL,
	[GRE_ULTD] [datetime] NULL,
	[APA_CNC8] [varchar](22) NOT NULL,
	[APA_DCOM] [varchar](50) NOT NULL,
	[APA_DNCB] [varchar](150) NULL,
	[GRE_QUAN] [numeric](38, 6) NULL,
	[UME_UMED] [varchar](3) NULL,
	[GRE_TOLE] [numeric](38, 6) NULL,
	[TEX_MESP] [text] NULL,
	[TEX_CESP] [text] NULL,
	[GRE_QEXT] [varchar](150) NULL,
 CONSTRAINT [PK_PRO_GREX] PRIMARY KEY CLUSTERED 
(
	[GRE_CODI] ASC,
	[GRE_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_GREX] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_GREX] TO [public] AS [dbo]
GRANT INSERT ON [PRO_GREX] TO [public] AS [dbo]
GRANT SELECT ON [PRO_GREX] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_GREX] TO [public] AS [dbo]
/****** Object:  Table [PRO_GRIM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_GRIM](
	[GRI_CODI] [int] NOT NULL,
	[GRI_EANO] [int] NOT NULL,
	[GRI_DATA] [datetime] NOT NULL,
	[GRI_STAT] [int] NULL,
	[EOF_OREM] [varchar](18) NULL,
	[CLI_TITU] [varchar](18) NULL,
	[EOF_OEEX] [varchar](18) NULL,
	[PAI_PPRO] [varchar](2) NULL,
	[GRI_PSIM] [bit] NULL,
	[GRI_PNAO] [bit] NULL,
	[PAI_PORI] [varchar](2) NULL,
	[GRI_OSIM] [bit] NULL,
	[GRI_ONAO] [bit] NULL,
	[GRI_DAPR] [datetime] NULL,
	[GRI_MTGA] [numeric](38, 6) NULL,
	[PAI_MOED] [varchar](2) NULL,
	[GRI_ULTD] [datetime] NULL,
	[APA_CNC8] [varchar](22) NOT NULL,
	[APA_DCOM] [varchar](300) NOT NULL,
	[APA_DNCB] [varchar](300) NULL,
	[GRI_QUAN] [numeric](38, 6) NULL,
	[UME_UMED] [varchar](3) NULL,
	[GRI_TOLE] [numeric](38, 6) NULL,
	[TEX_MESP] [text] NULL,
	[TEX_CESP] [text] NULL,
	[GRI_QEXT] [varchar](150) NULL,
 CONSTRAINT [PK_PRO_GRIM] PRIMARY KEY CLUSTERED 
(
	[GRI_CODI] ASC,
	[GRI_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_GRIM] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_GRIM] TO [public] AS [dbo]
GRANT INSERT ON [PRO_GRIM] TO [public] AS [dbo]
GRANT SELECT ON [PRO_GRIM] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_GRIM] TO [public] AS [dbo]
/****** Object:  Table [PRO_GSSL]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_GSSL](
	[SSL_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[SSL_STAT] [int] NOT NULL,
	[SSL_NSEL] [varchar](18) NOT NULL,
	[SSL_OBSE] [varchar](200) NULL,
	[SSL_DTEN] [datetime] NOT NULL,
	[SSL_UTEN] [varchar](30) NOT NULL,
	[SSL_DTCE] [datetime] NOT NULL,
	[SSL_DTDS] [datetime] NULL,
	[SSL_UTDS] [varchar](30) NULL,
	[SSL_DTCD] [datetime] NULL,
	[SSL_DTIN] [datetime] NULL,
	[SSL_UTIN] [varchar](30) NULL,
	[SSL_DTCI] [datetime] NULL,
	[SSL_DTSL] [datetime] NULL,
	[SSL_UTSL] [varchar](30) NULL,
	[SSL_DTCS] [datetime] NULL,
	[NST_CODI] [int] NULL,
	[NST_EANO] [int] NULL,
	[CLI_OPER] [varchar](18) NULL,
 CONSTRAINT [PK_PRO_GSSL] PRIMARY KEY CLUSTERED 
(
	[SSL_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_GSSL] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_GSSL] TO [public] AS [dbo]
GRANT INSERT ON [PRO_GSSL] TO [public] AS [dbo]
GRANT SELECT ON [PRO_GSSL] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_GSSL] TO [public] AS [dbo]
/****** Object:  Table [PRO_IL90]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_IL90](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUC_DATA] [datetime] NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[NDE_NOME] [varchar](35) NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[ALF_NOME] [varchar](70) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[CLI_NOME] [varchar](70) NULL,
	[IL9_LRVL] [numeric](38, 6) NULL,
	[IL9_LREX] [varchar](150) NULL,
	[IL9_UCRI] [varchar](30) NULL,
	[IL9_DTCR] [datetime] NULL,
	[IL9_UALT] [varchar](30) NULL,
	[IL9_DTAL] [datetime] NULL,
 CONSTRAINT [PK_PRO_IL90] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_IL90] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_IL90] TO [public] AS [dbo]
GRANT INSERT ON [PRO_IL90] TO [public] AS [dbo]
GRANT SELECT ON [PRO_IL90] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_IL90] TO [public] AS [dbo]
/****** Object:  Table [PRO_IL9A]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_IL9A](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[IL9_CODI] [int] NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[APA_CPAU] [varchar](22) NULL,
	[APA_DESG] [varchar](150) NULL,
	[PRE_CODI] [varchar](3) NULL,
	[RRE_PREF] [int] NULL,
	[IL9_BTRI] [numeric](38, 6) NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[IL9_TXVL] [bit] NOT NULL,
	[IL9_TAXA] [numeric](38, 6) NULL,
	[IL9_MNTT] [numeric](38, 6) NULL,
	[IL9_BTIV] [numeric](38, 6) NULL,
	[IL9_TXIV] [numeric](38, 6) NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](70) NULL,
	[IL9_MNIV] [numeric](38, 6) NULL,
	[IL9_MPAG] [varchar](1) NULL,
	[FLE_CODI] [int] NULL,
	[FLE_NOME] [varchar](70) NULL,
	[IL9_VSEL] [numeric](38, 6) NULL,
	[IL9_MONT] [numeric](38, 6) NULL
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_IL9A] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_IL9A] TO [public] AS [dbo]
GRANT INSERT ON [PRO_IL9A] TO [public] AS [dbo]
GRANT SELECT ON [PRO_IL9A] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_IL9A] TO [public] AS [dbo]
/****** Object:  Table [PRO_IL9L]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_IL9L](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[RRE_CODI] [int] NOT NULL,
	[RRE_NOME] [varchar](70) NULL,
	[IL9_MONT] [numeric](38, 6) NULL,
	[IL9_RPRO] [numeric](38, 6) NULL
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_IL9L] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_IL9L] TO [public] AS [dbo]
GRANT INSERT ON [PRO_IL9L] TO [public] AS [dbo]
GRANT SELECT ON [PRO_IL9L] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_IL9L] TO [public] AS [dbo]
/****** Object:  Table [PRO_ILAD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_ILAD](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUA_CODI] [int] NOT NULL,
	[ILA_CODI] [int] NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[APA_CPAU] [varchar](22) NULL,
	[APA_DESG] [varchar](150) NULL,
	[PRE_CODI] [varchar](3) NULL,
	[RRE_PREF] [int] NULL,
	[ILG_BTRI] [numeric](38, 6) NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[ILG_TXVL] [bit] NOT NULL,
	[ILG_TAXA] [numeric](38, 6) NULL,
	[ILG_MNTT] [numeric](38, 6) NULL,
	[ILG_BTIV] [numeric](38, 6) NULL,
	[ILG_TXIV] [numeric](38, 6) NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](70) NULL,
	[ILG_MNIV] [numeric](38, 6) NULL,
	[ILG_MPAG] [varchar](1) NULL,
	[FLE_CODI] [int] NULL,
	[FLE_NOME] [varchar](70) NULL,
	[ILG_VSEL] [numeric](38, 6) NULL,
	[ILG_MONT] [numeric](38, 6) NULL,
 CONSTRAINT [PK_PRO_ILGR] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_ILAD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_ILAD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_ILAD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_ILAD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_ILAD] TO [public] AS [dbo]
/****** Object:  Table [PRO_ILGA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_ILGA](
	[DUC_EANO] [int] NOT NULL,
	[DUC_PNUM] [int] NOT NULL,
	[DUC_DATA] [datetime] NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[NDE_NOME] [varchar](35) NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[ALF_NOME] [varchar](70) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[CLI_NOME] [varchar](70) NULL,
	[ILG_LRVL] [numeric](38, 6) NULL,
	[ILG_LREX] [varchar](150) NULL,
	[ILG_UCRI] [varchar](30) NULL,
	[ILG_DTCR] [datetime] NULL,
	[ILG_UALT] [varchar](30) NULL,
	[ILG_DTAL] [datetime] NULL,
 CONSTRAINT [PK_PRO_ILGA] PRIMARY KEY CLUSTERED 
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_ILGA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_ILGA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_ILGA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_ILGA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_ILGA] TO [public] AS [dbo]
/****** Object:  Table [PRO_ILLR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_ILLR](
	[DUC_PNUM] [int] NOT NULL,
	[DUC_EANO] [int] NOT NULL,
	[RRE_CODI] [int] NOT NULL,
	[RRE_NOME] [varchar](70) NULL,
	[ILL_MONT] [numeric](38, 6) NULL,
	[ILL_RPRO] [numeric](38, 6) NULL
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_ILLR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_ILLR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_ILLR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_ILLR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_ILLR] TO [public] AS [dbo]
/****** Object:  Table [PRO_LIMP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_LIMP](
	[LIM_CODI] [int] NOT NULL,
	[LIM_EANO] [int] NOT NULL,
	[LIM_DATA] [datetime] NOT NULL,
	[LIM_STAT] [int] NOT NULL,
	[LIM_NEMI] [varchar](20) NULL,
	[LIM_PCON] [varchar](20) NULL,
	[EOF_AUTC] [varchar](18) NOT NULL,
	[CLI_DEST] [varchar](18) NOT NULL,
	[LIM_PVAL] [varchar](30) NULL,
	[PAI_PPRO] [varchar](2) NULL,
	[PAI_PDES] [varchar](2) NULL,
	[APA_CNC8] [varchar](22) NOT NULL,
	[APA_DMER] [varchar](50) NOT NULL,
	[LIM_QUAN] [varchar](40) NOT NULL,
	[LIM_CAUC] [varchar](30) NULL,
	[DEC_CODI] [varchar](6) NULL,
	[TEX_MESP] [text] NULL,
 CONSTRAINT [PK_PRO_LIMP] PRIMARY KEY CLUSTERED 
(
	[LIM_CODI] ASC,
	[LIM_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_LIMP] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_LIMP] TO [public] AS [dbo]
GRANT INSERT ON [PRO_LIMP] TO [public] AS [dbo]
GRANT SELECT ON [PRO_LIMP] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_LIMP] TO [public] AS [dbo]
/****** Object:  Table [PRO_MCAU]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_MCAU](
	[MCA_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[MCA_TENT] [int] NOT NULL,
	[MCA_ENTI] [varchar](18) NOT NULL,
	[MCA_NCAU] [varchar](24) NULL,
	[MCA_CANO] [varchar](4) NULL,
	[MCA_CTIP] [varchar](1) NULL,
	[ALF_ORIG] [varchar](8) NOT NULL,
	[MCA_IORI] [int] NULL,
	[ALF_DEST] [varchar](8) NULL,
	[CAU_CODI] [varchar](5) NOT NULL,
	[MCA_DATA] [datetime] NULL,
	[MCA_NDOC] [varchar](15) NULL,
	[MCA_NORD] [varchar](20) NULL,
	[MCA_DORD] [datetime] NULL,
	[CLI_DEST] [varchar](18) NULL,
	[MCA_OBSR] [varchar](50) NULL,
	[MCA_VLTT] [numeric](38, 6) NULL,
	[MCA_DBCR] [int] NULL,
	[MCA_PROV] [bit] NOT NULL,
	[MCA_LIQD] [bit] NOT NULL,
	[MCA_ANUL] [bit] NOT NULL,
	[DUC_PNUM] [int] NULL,
	[DUC_EANO] [int] NULL,
	[DUC_TIPO] [int] NULL,
	[MCA_NDIA] [int] NOT NULL,
	[MCA_TAIV] [varchar](5) NULL,
	[MCA_AIVA] [int] NULL,
	[MCA_DTRL] [datetime] NULL,
	[id_declaracaoDAR] [int] NULL,
 CONSTRAINT [PK_PRO_MCAU] PRIMARY KEY CLUSTERED 
(
	[MCA_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_MCAU] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_MCAU] TO [public] AS [dbo]
GRANT INSERT ON [PRO_MCAU] TO [public] AS [dbo]
GRANT SELECT ON [PRO_MCAU] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_MCAU] TO [public] AS [dbo]
/****** Object:  Table [PRO_NACO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NACO](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NAD_CODI] [int] NOT NULL,
	[NAC_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[NAC_CNUM] [varchar](17) NULL,
 CONSTRAINT [PK_PRO_NACO] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NAD_CODI] ASC,
	[NAC_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NACO] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NACO] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NACO] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NACO] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NACO] TO [public] AS [dbo]
/****** Object:  Table [PRO_NADI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NADI](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NAD_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[TDT_CODI] [varchar](9) NOT NULL,
	[TDT_DESG] [varchar](9) NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[NAD_DESG] [varchar](260) NULL,
	[NAD_CPAU] [varchar](22) NULL,
	[NAD_MBRT] [numeric](38, 6) NOT NULL,
	[NAD_MLIQ] [numeric](38, 6) NULL,
	[PAI_DEST] [varchar](2) NULL,
	[PAI_EXPO] [varchar](2) NULL,
	[CLI_EXPE] [varchar](18) NULL,
	[FOR_DEST] [varchar](18) NULL,
	[NAD_TPSP] [int] NOT NULL,
	[NAD_VMER] [numeric](38, 6) NULL,
	[NAD_VALO] [int] NOT NULL,
	[NAD_TAXA] [numeric](38, 6) NULL,
	[NAD_MONT] [numeric](38, 6) NULL,
	[NAD_OIMP] [int] NOT NULL,
	[NAD_TAX1] [numeric](38, 6) NULL,
	[NAD_MTT1] [numeric](38, 6) NULL,
	[NAD_IVA] [int] NULL,
	[NAD_AGAR] [numeric](38, 6) NULL,
	[NAD_NTDC] [varchar](50) NULL,
	[NAD_NOPD] [varchar](50) NULL,
	[NAD_NOPE] [varchar](50) NULL,
	[NAD_NPDT] [varchar](50) NULL,
	[NAD_NPEX] [varchar](50) NULL,
	[NAD_ATAR] [varchar](10) NULL,
	[NAD_NCMR] [varchar](70) NULL,
	[NAD_DTMP] [varchar](1) NULL,
	[NAD_AJUS] [numeric](38, 6) NOT NULL,
	[NAD_MOPD] [varchar](35) NULL,
	[NAD_LOPD] [varchar](35) NULL,
	[NAD_COPD] [varchar](9) NULL,
	[NAD_POPD] [varchar](2) NULL,
	[NAD_MOPE] [varchar](35) NULL,
	[NAD_LOPE] [varchar](35) NULL,
	[NAD_COPE] [varchar](9) NULL,
	[NAD_POPE] [varchar](2) NULL,
	[NAD_FOPE] [varchar](17) NULL,
 CONSTRAINT [PK_PRO_NADI] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NAD_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NADI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NADI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NADI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NADI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NADI] TO [public] AS [dbo]
/****** Object:  Table [PRO_NADO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NADO](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NAD_CODI] [int] NOT NULL,
	[NDO_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[NDO_RFDA] [varchar](26) NULL,
	[NDO_INFC] [varchar](26) NULL,
	[DOC_NOME] [varchar](50) NULL,
 CONSTRAINT [PK_PRO_NADO] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NAD_CODI] ASC,
	[NDO_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NADO] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NADO] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NADO] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NADO] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NADO] TO [public] AS [dbo]
/****** Object:  Table [PRO_NAMA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NAMA](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NAD_CODI] [int] NOT NULL,
	[NMA_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[NMA_MARC] [varchar](50) NULL,
	[TEM_CODI] [varchar](2) NULL,
	[NMA_NVOL] [int] NULL,
	[NMA_NUNI] [int] NULL,
	[TEM_NOME] [varchar](50) NULL,
 CONSTRAINT [PK_PRO_NAMA] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NAD_CODI] ASC,
	[NMA_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NAMA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NAMA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NAMA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NAMA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NAMA] TO [public] AS [dbo]
/****** Object:  Table [PRO_NAME]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NAME](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NAD_CODI] [int] NOT NULL,
	[NME_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[INF_CODI] [varchar](70) NULL,
	[NME_CIA1] [varchar](3) NULL,
	[NME_ECE1] [int] NULL,
	[NME_EP11] [int] NULL,
	[INF_NOME] [varchar](150) NULL,
	[NAM_VALO] [numeric](38, 6) NULL,
 CONSTRAINT [PK_PRO_NAME] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NAD_CODI] ASC,
	[NME_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NAME] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NAME] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NAME] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NAME] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NAME] TO [public] AS [dbo]
/****** Object:  Table [PRO_NAMS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NAMS](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NAD_CODI] [int] NOT NULL,
	[NAM_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[MSE_CODI] [varchar](18) NULL,
	[NAM_QUAN] [numeric](38, 6) NULL,
	[MSE_NOME] [varchar](50) NULL,
 CONSTRAINT [PK_PRO_NAMS] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NAD_CODI] ASC,
	[NAM_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NAMS] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NAMS] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NAMS] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NAMS] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NAMS] TO [public] AS [dbo]
/****** Object:  Table [PRO_NARA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NARA](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NAD_CODI] [int] NOT NULL,
	[NRA_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[RAA_CODI] [varchar](8) NOT NULL,
	[NDO_RFDA] [varchar](35) NULL,
	[NDO_INFC] [varchar](26) NULL,
	[RAA_NOME] [varchar](50) NULL,
 CONSTRAINT [PK_PRO_NARA] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NAD_CODI] ASC,
	[NRA_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NARA] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NARA] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NARA] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NARA] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NARA] TO [public] AS [dbo]
/****** Object:  Table [PRO_NDOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NDOC](
	[NDO_CODI] [int] IDENTITY(1,1) NOT NULL,
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[NDO_DESC] [varchar](150) NULL,
	[NDO_LINK] [varchar](500) NULL,
 CONSTRAINT [PK_PRO_NDOC] PRIMARY KEY CLUSTERED 
(
	[NDO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NDOC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NDOC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NDOC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NDOC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NDOC] TO [public] AS [dbo]
/****** Object:  Table [PRO_NGAR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NGAR](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[PAI_NOME] [varchar](50) NULL,
 CONSTRAINT [PK_PRO_NGAR] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[PAI_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NGAR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NGAR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NGAR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NGAR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NGAR] TO [public] AS [dbo]
/****** Object:  Table [PRO_NOAD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NOAD](
	[NOA_CODI] [int] NOT NULL,
	[NOT_CODI] [int] NOT NULL,
	[NOT_EANO] [int] NOT NULL,
	[APA_CODI] [varchar](22) NULL,
	[NOA_MBRT] [numeric](38, 6) NULL,
	[NOA_VADI] [numeric](38, 6) NULL,
	[TEX_MNUM] [text] NULL,
	[NOA_DESG] [varchar](150) NULL,
	[NOA_CPAU] [varchar](22) NULL,
 CONSTRAINT [PK_PRO_NOAD] PRIMARY KEY CLUSTERED 
(
	[NOA_CODI] ASC,
	[NOT_CODI] ASC,
	[NOT_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NOAD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NOAD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NOAD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NOAD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NOAD] TO [public] AS [dbo]
/****** Object:  Table [PRO_NOTI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NOTI](
	[NOT_CODI] [int] NOT NULL,
	[NOT_EANO] [int] NOT NULL,
	[NOT_DATA] [datetime] NOT NULL,
	[NDES_CODI] [varchar](3) NOT NULL,
	[NOT_STAT] [int] NOT NULL,
	[NOT_DTEN] [datetime] NULL,
	[NOT_NORD] [varchar](15) NULL,
	[NOT_DTNO] [datetime] NULL,
	[NOT_NCON] [int] NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[CLI_NOTI] [varchar](18) NULL,
	[PAI_PORI] [varchar](2) NULL,
	[PAI_PPRO] [varchar](2) NULL,
	[PAI_PDES] [varchar](2) NULL,
	[LME_CODI] [varchar](17) NULL,
	[LME_NOME] [varchar](70) NULL,
	[TEX_RESP] [text] NULL,
	[NOT_DECS] [bit] NOT NULL,
	[NOT_DOCP] [bit] NOT NULL,
	[NOT_DESC] [varchar](60) NULL,
	[NOT_REEX] [bit] NOT NULL,
	[NOT_TINT] [bit] NOT NULL,
	[NOT_PDNO] [varchar](70) NULL,
	[NOT_PDMO] [varchar](70) NULL,
	[NOT_PDLO] [varchar](35) NULL,
	[NOT_PDCP] [varchar](12) NULL,
	[NOT_PDLP] [varchar](35) NULL,
	[NOT_PDNF] [varchar](18) NULL,
	[PAI_PDPL] [varchar](2) NULL,
 CONSTRAINT [PK_PRO_NOTI] PRIMARY KEY CLUSTERED 
(
	[NOT_CODI] ASC,
	[NOT_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NOTI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NOTI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NOTI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NOTI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NOTI] TO [public] AS [dbo]
/****** Object:  Table [PRO_NPIT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NPIT](
	[NPI_CODI] [int] IDENTITY(1,1) NOT NULL,
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](25) NOT NULL,
 CONSTRAINT [PK_PRO_NPIT] PRIMARY KEY CLUSTERED 
(
	[NPI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NPIT] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NPIT] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NPIT] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NPIT] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NPIT] TO [public] AS [dbo]
/****** Object:  Table [PRO_NSEL]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NSEL](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[NSE_CODI] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[NSE_IDEN] [varchar](20) NULL,
 CONSTRAINT [PK_PRO_NSEL] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[NSE_CODI] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NSEL] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NSEL] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NSEL] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NSEL] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NSEL] TO [public] AS [dbo]
/****** Object:  Table [PRO_NSTI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_NSTI](
	[NST_CODI] [int] NOT NULL,
	[NST_EANO] [int] NOT NULL,
	[CLI_OPER] [varchar](18) NOT NULL,
	[NST_DATA] [datetime] NOT NULL,
	[NST_REFI] [varchar](18) NULL,
	[NST_PENV] [varchar](12) NULL,
	[NST_DENV] [datetime] NULL,
	[NST_STAT] [int] NULL,
	[NST_REFA] [varchar](18) NULL,
	[NST_NRM1] [varchar](18) NULL,
	[NST_TDCB] [varchar](9) NULL,
	[TDT_CODI] [varchar](9) NOT NULL,
	[NST_REFN] [varchar](22) NOT NULL,
	[NST_LCRG] [int] NULL,
	[NST_ADIC] [int] NULL,
	[NST_TVOL] [int] NULL,
	[NST_MLTO] [numeric](38, 6) NULL,
	[NST_MBTO] [numeric](38, 6) NULL,
	[NST_DDEC] [datetime] NOT NULL,
	[NST_LDEC] [varchar](35) NOT NULL,
	[NST_REPR] [varchar](35) NULL,
	[NST_QUAL] [varchar](35) NULL,
	[CLI_EXPE] [varchar](18) NULL,
	[FOR_DEST] [varchar](18) NULL,
	[NST_AUTZ] [bit] NOT NULL,
	[NST_OPAU] [varchar](18) NULL,
	[PAI_DEST] [varchar](2) NULL,
	[PAI_EXPE] [varchar](2) NULL,
	[LME_CLAU] [varchar](17) NULL,
	[LME_DCLAU] [varchar](70) NULL,
	[LME_LAPM] [varchar](17) NULL,
	[LME_DLAPM] [varchar](70) NULL,
	[LME_CLAP] [varchar](17) NULL,
	[LME_DCLAP] [varchar](70) NULL,
	[LME_CLCG] [varchar](17) NULL,
	[LME_DCLCG] [varchar](70) NULL,
	[NST_SLAD] [varchar](17) NULL,
	[MTR_PART] [varchar](2) NULL,
	[NST_MTPT] [varchar](30) NULL,
	[PAI_MTPT] [varchar](2) NULL,
	[MTR_FRON] [varchar](2) NULL,
	[NST_MTFR] [varchar](30) NULL,
	[PAI_MTFR] [varchar](2) NULL,
	[MTR_MTPF] [varchar](2) NULL,
	[NST_CONT] [int] NOT NULL,
	[EAD_PART] [varchar](8) NOT NULL,
	[EAD_PASS] [varchar](8) NULL,
	[EAD_DEST] [varchar](8) NOT NULL,
	[ICO_RCON] [varchar](2) NULL,
	[NST_DTRC] [datetime] NULL,
	[NST_NSEL] [int] NULL,
	[TGA_CODI] [varchar](1) NOT NULL,
	[NST_NREF] [varchar](24) NULL,
	[NST_OUTR] [varchar](35) NULL,
	[NST_ACES] [varchar](4) NULL,
	[NST_NCEE] [bit] NOT NULL,
	[NST_PDNO] [varchar](70) NULL,
	[NST_PDMO] [varchar](70) NULL,
	[NST_PDLO] [varchar](35) NULL,
	[NST_PDCP] [varchar](12) NULL,
	[NST_PDLP] [varchar](35) NULL,
	[NST_PDNF] [varchar](18) NULL,
	[PAI_PDPL] [varchar](2) NULL,
	[NST_PENO] [varchar](70) NULL,
	[NST_PEMO] [varchar](70) NULL,
	[NST_PELO] [varchar](35) NULL,
	[NST_PECP] [varchar](12) NULL,
	[NST_PELP] [varchar](35) NULL,
	[NST_PENF] [varchar](18) NULL,
	[PAI_PEPL] [varchar](2) NULL,
	[NST_PANO] [varchar](70) NULL,
	[NST_PAMO] [varchar](70) NULL,
	[NST_PALO] [varchar](35) NULL,
	[NST_PACP] [varchar](12) NULL,
	[NST_PALP] [varchar](35) NULL,
	[NST_PANF] [varchar](18) NULL,
	[PAI_PAPL] [varchar](2) NULL,
	[NST_NROP] [varchar](50) NULL,
	[NST_NTDC] [varchar](50) NULL,
	[NST_NPDS] [varchar](50) NULL,
	[NST_NPDX] [varchar](50) NULL,
	[NST_NMTP] [varchar](50) NULL,
	[NST_NMTF] [varchar](50) NULL,
	[NST_NMPS] [varchar](50) NULL,
	[NST_NEPT] [varchar](50) NULL,
	[NST_NEPS] [varchar](50) NULL,
	[NST_NEDT] [varchar](50) NULL,
	[NST_NINC] [varchar](50) NULL,
	[NST_NTGA] [varchar](50) NULL,
	[NST_NTIN] [varchar](17) NULL,
	[NST_IDEM] [varchar](17) NULL,
	[NST_CACE] [varchar](4) NULL,
	[NST_CSEG] [bit] NOT NULL,
	[NST_INCE] [varchar](1) NULL,
	[NST_NCMR] [varchar](70) NULL,
	[NST_DTMP] [varchar](1) NULL,
	[NST_NRTR] [varchar](35) NULL,
	[NST_LDCG] [varchar](70) NULL,
	[NST_NOTI] [varchar](17) NULL,
	[NST_DHCG] [datetime] NULL,
	[NST_CDES] [varchar](18) NULL,
	[NST_NOES] [varchar](70) NULL,
	[NST_MOES] [varchar](70) NULL,
	[NST_LOES] [varchar](35) NULL,
	[NST_CPES] [varchar](12) NULL,
	[NST_LPES] [varchar](35) NULL,
	[NST_NIES] [varchar](18) NULL,
	[NST_PAES] [varchar](2) NULL,
	[NST_CDDS] [varchar](18) NULL,
	[NST_NODS] [varchar](70) NULL,
	[NST_MODS] [varchar](70) NULL,
	[NST_LODS] [varchar](35) NULL,
	[NST_CPDS] [varchar](12) NULL,
	[NST_LPDS] [varchar](35) NULL,
	[NST_NIDS] [varchar](18) NULL,
	[NST_PADS] [varchar](2) NULL,
	[NST_CDTS] [varchar](18) NULL,
	[NST_NOTS] [varchar](70) NULL,
	[NST_MOTS] [varchar](70) NULL,
	[NST_LOTS] [varchar](35) NULL,
	[NST_CPTS] [varchar](12) NULL,
	[NST_LPTS] [varchar](35) NULL,
	[NST_NITS] [varchar](18) NULL,
	[NST_PATS] [varchar](2) NULL,
	[NST_PZAP] [int] NOT NULL,
	[NST_DTAP] [datetime] NULL,
	[NST_NRMV] [bit] NOT NULL,
	[NST_UCRI] [varchar](30) NULL,
	[NST_DCRI] [datetime] NULL,
	[NST_UALT] [varchar](30) NULL,
	[NST_DALT] [datetime] NULL,
	[NST_TASA] [int] NULL,
	[NST_ESTO] [int] NULL,
	[NST_RESP] [text] NULL,
	[NST_AUX0] [varchar](1000) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[CLI_NOME] [varchar](70) NULL,
	[EAD_CODI] [varchar](8) NULL,
	[EAD_NOME] [varchar](35) NULL,
 CONSTRAINT [PK_PRO_NSTI] PRIMARY KEY CLUSTERED 
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_NSTI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_NSTI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_NSTI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_NSTI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_NSTI] TO [public] AS [dbo]
/****** Object:  Table [PRO_SDSC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_SDSC](
	[DSC_EANO] [int] NOT NULL,
	[DSC_NPRO] [int] NOT NULL,
	[DSC_TIPO] [int] NOT NULL,
	[DSC_IDRP] [varchar](20) NOT NULL,
	[DSC_IDTP] [varchar](20) NOT NULL,
	[DSC_IDTR] [varchar](20) NULL,
	[DSC_NRAP] [varchar](40) NOT NULL,
	[DSC_AEMI] [int] NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[EAD_NOME] [varchar](35) NOT NULL,
	[DSC_NVPR] [int] NOT NULL,
	[DSC_DTVO] [datetime] NOT NULL,
	[EAD_CODI1] [varchar](8) NOT NULL,
	[EAD_NOME1] [varchar](35) NOT NULL,
	[DSC_NCMF] [varchar](8) NOT NULL,
	[DSC_NCMV] [varchar](6) NOT NULL,
	[DSC_RESP] [text] NULL,
	[DSC_UCRI] [varchar](30) NOT NULL,
	[DSC_DCRI] [datetime] NOT NULL,
	[DSC_UALT] [varchar](30) NOT NULL,
	[DSC_DALT] [datetime] NOT NULL,
	[DSC_NREM] [int] NOT NULL,
	[DSC_UDEM] [datetime] NULL,
	[DSC_NRRR] [int] NOT NULL,
	[DSC_UDRR] [datetime] NULL,
	[DSC_IXML] [bit] NOT NULL,
	[DSC_ACTI] [bit] NOT NULL,
	[DSC_UINA] [varchar](30) NULL,
	[DSC_DINA] [datetime] NULL,
	[DSC_IDDP] [varchar](20) NULL,
	[DSC_STRD] [int] NOT NULL,
	[DSC_NRER] [int] NOT NULL,
	[DSC_UERC] [varchar](30) NULL,
	[DSC_DERC] [datetime] NULL,
	[DSC_UERF] [varchar](30) NULL,
	[DSC_DERF] [datetime] NULL,
	[DSC_NRRD] [int] NOT NULL,
	[DSC_URRD] [varchar](30) NULL,
	[DSC_DRRD] [datetime] NULL,
	[DSC_RPRD] [text] NULL,
	[DSC_STMS] [int] NOT NULL,
	[DSC_NRES] [int] NOT NULL,
	[DSC_UEMS] [varchar](30) NULL,
	[DSC_DEMS] [datetime] NULL,
	[DSC_NRMS] [int] NOT NULL,
	[DSC_URMS] [varchar](30) NULL,
	[DSC_DRMS] [datetime] NULL,
	[DSC_RPMS] [text] NULL,
	[DSC_NVOO] [varchar](35) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAI_NOME] [varchar](35) NULL,
	[DSC_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DSC_DPRV] [datetime] NULL,
	[DSC_PPRV] [numeric](38, 6) NOT NULL,
	[DSC_VPRV] [int] NOT NULL,
	[DSC_STCM] [int] NOT NULL,
	[DSC_UCCM] [varchar](30) NULL,
	[DSC_DCCM] [datetime] NULL,
	[DSC_UCCR] [varchar](30) NULL,
	[DSC_DCCR] [datetime] NULL,
	[DSC_UUCM] [varchar](30) NULL,
	[DSC_DUCM] [datetime] NULL,
	[DSC_UUCR] [varchar](30) NULL,
	[DSC_DUCR] [datetime] NULL,
	[DSC_UACM] [varchar](30) NULL,
	[DSC_DACM] [datetime] NULL,
	[DSC_UACR] [varchar](30) NULL,
	[DSC_DACR] [datetime] NULL,
	[DSC_ESTA] [varchar](3) NULL,
	[DSC_DEFT] [datetime] NULL,
	[DSC_IDCM] [varchar](20) NOT NULL,
 CONSTRAINT [PK_PRO_SDSC] PRIMARY KEY CLUSTERED 
(
	[DSC_EANO] ASC,
	[DSC_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_SDSC] UNIQUE NONCLUSTERED 
(
	[DSC_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_SDSC] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_SDSC] TO [public] AS [dbo]
GRANT INSERT ON [PRO_SDSC] TO [public] AS [dbo]
GRANT SELECT ON [PRO_SDSC] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_SDSC] TO [public] AS [dbo]
/****** Object:  Table [PRO_SDSD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_SDSD](
	[DSC_EANO] [int] NOT NULL,
	[DSC_NPRO] [int] NOT NULL,
	[DSD_NUME] [int] NOT NULL,
	[DSD_NDGA] [varchar](24) NULL,
	[DSD_NRMH] [varchar](30) NOT NULL,
	[DSD_ESTA] [varchar](3) NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
	[DSD_LOED] [varchar](30) NOT NULL,
	[DSD_DTED] [datetime] NOT NULL,
	[DSD_EEED] [varchar](60) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](35) NULL,
	[DSD_TIPO] [varchar](2) NOT NULL,
	[PAE_CODI] [varchar](8) NOT NULL,
	[PAE_NOME] [varchar](35) NULL,
	[PAE_CODI1] [varchar](8) NOT NULL,
	[PAE_NOME1] [varchar](35) NULL,
	[PAE_CODI2] [varchar](8) NOT NULL,
	[PAE_NOME2] [varchar](35) NULL,
	[DSD_TCTU] [bit] NOT NULL,
	[DSD_TMEX] [bit] NOT NULL,
	[DSD_EADC] [varchar](3) NOT NULL,
	[DSD_IDOS] [varchar](50) NULL,
	[DSD_NOOS] [varchar](75) NULL,
	[DSD_IDNS] [varchar](50) NULL,
	[DSD_NONS] [varchar](75) NOT NULL,
	[DSD_IDED] [varchar](50) NULL,
	[DSD_NOMD] [varchar](75) NULL,
	[DSD_IDEN] [varchar](50) NULL,
	[DSD_IDEC] [varchar](50) NOT NULL,
	[DSD_DMER] [varchar](150) NOT NULL,
	[DSD_MRNR] [varchar](25) NOT NULL,
	[TEM_CODI] [varchar](2) NOT NULL,
	[TEM_NOME] [varchar](35) NOT NULL,
	[DSD_PESO] [numeric](38, 6) NOT NULL,
	[DSD_VOLS] [int] NOT NULL,
	[DSD_TCAR] [varchar](3) NOT NULL,
	[LME_CODI] [varchar](17) NOT NULL,
	[LME_NOME] [varchar](70) NULL,
	[PAE_CODI3] [varchar](8) NOT NULL,
	[PAE_NOME3] [varchar](35) NULL,
	[DSD_CAPO] [bit] NOT NULL,
	[DSD_STAT] [int] NOT NULL,
	[DSD_ANUL] [bit] NOT NULL,
	[DSD_DNOW] [datetime] NOT NULL,
	[DSD_ORIG] [int] NOT NULL,
	[EXA_CHVE] [int] NULL,
	[DSD_VALO] [numeric](38, 6) NOT NULL,
	[DSD_NDAU] [varchar](22) NULL,
	[DSD_DTEN] [datetime] NULL,
	[DSD_TDEP] [int] NULL,
	[DSD_ASAI] [bit] NOT NULL,
	[DSD_DEPO] [varchar](50) NULL,
	[DSD_DTSA] [datetime] NULL,
	[DSD_AUX0] [varchar](1000) NULL,
	[DSD_DERR] [text] NULL,
	[DSD_NDGI] [varchar](50) NULL,
	[DSD_JUST] [varchar](250) NULL,
	[DSD_IDNN] [int] IDENTITY(1,1) NOT NULL,
	[DSD_PDEP] [bit] NOT NULL,
	[DSD_ALTD] [int] NOT NULL,
	[DSD_IDCR] [varchar](20) NOT NULL,
	[DSD_CODR] [varchar](20) NULL,
	[DSD_NEAD] [varchar](70) NULL,
	[DSD_CEAD] [varchar](20) NULL,
	[DSD_PES2] [numeric](38, 6) NOT NULL,
	[DSD_VOL2] [int] NOT NULL,
	[DSD_MOTI] [varchar](300) NULL,
	[DSD_MOOS] [varchar](100) NULL,
	[DSD_MORD] [varchar](100) NULL,
	[DSD_ENVI] [bit] NOT NULL,
	[DSD_IDFC] [int] NULL,
	[DSD_PSIM] [bit] NOT NULL,
	[DSD_CPER] [bit] NOT NULL,
	[DSD_AFRQ] [int] NULL,
	[DSD_STRD] [int] NOT NULL,
	[DSD_DERD] [datetime] NULL,
	[DSD_STMS] [int] NOT NULL,
	[DSD_DEMS] [datetime] NULL,
	[DSD_EFRQ] [bit] NOT NULL,
	[DSD_SIRD] [int] NOT NULL,
	[DSD_DIRD] [datetime] NULL,
	[DSD_RIRD] [int] NULL,
	[DSD_EIRD] [text] NULL,
	[DSD_ADRD] [datetime] NULL,
	[DSD_ATRD] [varchar](30) NULL,
	[DSD_DTRD] [varchar](4) NULL,
	[DSD_DNRD] [varchar](30) NULL,
	[DSD_CTRD] [varchar](10) NULL,
	[DSD_SIMS] [int] NOT NULL,
	[DSD_DIMS] [datetime] NULL,
	[DSD_RIMS] [int] NULL,
	[DSD_EIMS] [text] NULL,
	[DSD_IDOR] [int] NULL,
	[DSD_MAWB] [varchar](30) NULL,
	[DSD_NDSC] [varchar](24) NULL,
	[DSD_CPOS] [varchar](17) NULL,
	[DSD_LOOS] [varchar](35) NULL,
	[DSD_NDPR] [varchar](70) NULL,
	[APA_CODI] [varchar](22) NULL,
	[DSD_CPAU] [varchar](22) NULL,
	[TXM_CODI] [varchar](5) NULL,
	[TXM_DESC] [varchar](150) NULL,
	[DSD_PTXT] [varchar](512) NULL,
 CONSTRAINT [PK_PRO_SDSD] PRIMARY KEY CLUSTERED 
(
	[DSC_EANO] ASC,
	[DSC_NPRO] ASC,
	[DSD_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_PRO_SDSD_DSD_IDNN] UNIQUE NONCLUSTERED 
(
	[DSD_IDNN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_SDSD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_SDSD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_SDSD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_SDSD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_SDSD] TO [public] AS [dbo]
/****** Object:  Table [PRO_SSDD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_SSDD](
	[DSC_EANO] [int] NOT NULL,
	[DSC_NPRO] [int] NOT NULL,
	[DSD_NUME] [int] NOT NULL,
	[SDD_NUME] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
	[SDD_NDOC] [varchar](30) NOT NULL,
	[SDD_DDOC] [datetime] NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[EAD_NOME] [varchar](35) NOT NULL,
	[SDD_SDOC] [varchar](1) NOT NULL,
	[SDD_ORIG] [int] NOT NULL,
 CONSTRAINT [PK_PRO_SSDD] PRIMARY KEY CLUSTERED 
(
	[DSC_EANO] ASC,
	[DSC_NPRO] ASC,
	[DSD_NUME] ASC,
	[SDD_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_SSDD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_SSDD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_SSDD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_SSDD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_SSDD] TO [public] AS [dbo]
/****** Object:  Table [PRO_T5AD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_T5AD](
	[T5A_CODI] [int] NOT NULL,
	[T5T_CODI] [int] NOT NULL,
	[T5T_EANO] [int] NOT NULL,
	[APA_CODI] [varchar](22) NULL,
	[T5A_DESG] [varchar](150) NULL,
	[T5A_CPAU] [varchar](22) NULL,
	[T5A_MBRT] [numeric](38, 6) NOT NULL,
	[T5A_MLIQ] [numeric](38, 6) NOT NULL,
	[T5A_MLEX] [varchar](120) NULL,
	[T5A_DPRE] [varchar](50) NULL,
	[T5A_UNSQ] [numeric](38, 6) NULL,
	[USU_CODI] [varchar](10) NULL,
	[T5A_MARC] [varchar](20) NULL,
	[T5A_NUME] [varchar](20) NULL,
	[T5A_QUAN] [int] NOT NULL,
	[UME_NATU] [varchar](2) NOT NULL,
	[TEX_UTIN] [text] NULL,
	[TEX_UTID] [text] NULL,
	[TEX_CERT] [text] NULL,
	[T5A_STAD] [bit] NOT NULL,
	[T5A_FORP] [bit] NOT NULL,
	[T5A_FORB] [bit] NOT NULL,
	[T5A_FFAR] [bit] NOT NULL,
	[T5A_OUTR] [bit] NOT NULL,
	[T5A_DOUT] [varchar](50) NULL,
	[T5A_REGA] [varchar](60) NULL,
	[T5A_DOCJ] [varchar](40) NULL,
	[T5A_DOCA] [varchar](40) NULL,
 CONSTRAINT [PK_PRO_T5AD] PRIMARY KEY CLUSTERED 
(
	[T5A_CODI] ASC,
	[T5T_CODI] ASC,
	[T5T_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_T5AD] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_T5AD] TO [public] AS [dbo]
GRANT INSERT ON [PRO_T5AD] TO [public] AS [dbo]
GRANT SELECT ON [PRO_T5AD] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_T5AD] TO [public] AS [dbo]
/****** Object:  Table [PRO_T5CO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_T5CO](
	[T5C_CODI] [int] NOT NULL,
	[T5A_CODI] [int] NOT NULL,
	[T5T_CODI] [int] NOT NULL,
	[T5T_EANO] [int] NOT NULL,
	[T5C_CNUM] [varchar](20) NOT NULL,
 CONSTRAINT [PK_POR_T5CO] PRIMARY KEY CLUSTERED 
(
	[T5C_CODI] ASC,
	[T5A_CODI] ASC,
	[T5T_CODI] ASC,
	[T5T_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_T5CO] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_T5CO] TO [public] AS [dbo]
GRANT INSERT ON [PRO_T5CO] TO [public] AS [dbo]
GRANT SELECT ON [PRO_T5CO] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_T5CO] TO [public] AS [dbo]
/****** Object:  Table [PRO_T5TR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_T5TR](
	[T5T_CODI] [int] NOT NULL,
	[T5T_EANO] [int] NOT NULL,
	[T5T_DATA] [datetime] NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[T5T_STAT] [int] NOT NULL,
	[T5T_NORD] [varchar](15) NULL,
	[T5T_DTNO] [datetime] NULL,
	[T5T_NCON] [int] NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[T5T_LCRG] [varchar](6) NULL,
	[T5T_ADIC] [int] NOT NULL,
	[T5T_TVOL] [int] NOT NULL,
	[T5T_REF7] [varchar](30) NOT NULL,
	[CLI_EXPE] [varchar](18) NULL,
	[FOR_DEST] [varchar](18) NULL,
	[DEC_CODI] [varchar](6) NULL,
	[PAI_EXPE] [varchar](2) NULL,
	[PAI_DEST] [varchar](2) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[T5T_MATR] [varchar](30) NULL,
	[PAI_NACI] [varchar](2) NULL,
	[T5T_CONT] [int] NOT NULL,
	[T5T_MLTO] [numeric](38, 6) NULL,
	[T5T_MBTO] [numeric](38, 6) NULL,
	[T5T_PDNO] [varchar](70) NULL,
	[T5T_PDMO] [varchar](70) NULL,
	[T5T_PDLO] [varchar](35) NULL,
	[T5T_PDCP] [varchar](12) NULL,
	[T5T_PDLP] [varchar](35) NULL,
	[T5T_PDNF] [varchar](18) NULL,
	[PAI_PDPL] [varchar](2) NULL,
	[T5T_PENO] [varchar](70) NULL,
	[T5T_PEMO] [varchar](70) NULL,
	[T5T_PELO] [varchar](35) NULL,
	[T5T_PECP] [varchar](12) NULL,
	[T5T_PELP] [varchar](35) NULL,
	[T5T_PENF] [varchar](18) NULL,
	[PAI_PEPL] [varchar](2) NULL,
	[DUC_PNUM] [int] NULL,
	[DUC_EANO] [int] NULL,
 CONSTRAINT [PK_PRO_T5TR] PRIMARY KEY CLUSTERED 
(
	[T5T_CODI] ASC,
	[T5T_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_T5TR] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_T5TR] TO [public] AS [dbo]
GRANT INSERT ON [PRO_T5TR] TO [public] AS [dbo]
GRANT SELECT ON [PRO_T5TR] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_T5TR] TO [public] AS [dbo]
/****** Object:  Table [PRO_TACO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_TACO](
	[TAC_CODI] [int] NOT NULL,
	[TAD_CODI] [int] NOT NULL,
	[TMA_CODI] [int] NOT NULL,
	[TMA_EANO] [int] NOT NULL,
	[TAC_CNUM] [varchar](20) NOT NULL,
 CONSTRAINT [PK_PRO_TMCO] PRIMARY KEY CLUSTERED 
(
	[TAC_CODI] ASC,
	[TAD_CODI] ASC,
	[TMA_CODI] ASC,
	[TMA_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_TACO] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_TACO] TO [public] AS [dbo]
GRANT INSERT ON [PRO_TACO] TO [public] AS [dbo]
GRANT SELECT ON [PRO_TACO] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_TACO] TO [public] AS [dbo]
/****** Object:  Table [PRO_TADI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_TADI](
	[TAD_CODI] [int] NOT NULL,
	[TMA_CODI] [int] NOT NULL,
	[TMA_EANO] [int] NOT NULL,
	[APA_CODI] [varchar](22) NULL,
	[TAD_DESG] [varchar](150) NULL,
	[TAD_CPAU] [varchar](22) NULL,
	[TAD_MBRT] [numeric](38, 6) NOT NULL,
	[TAD_MLIQ] [numeric](38, 6) NOT NULL,
	[TAD_DSUM] [bit] NOT NULL,
	[TAD_DPRE] [bit] NOT NULL,
	[TAD_DESC] [varchar](60) NULL,
	[TAD_MARC] [varchar](20) NULL,
	[TAD_NUME] [varchar](20) NULL,
	[TAD_QUAN] [int] NOT NULL,
	[UME_NATU] [varchar](2) NOT NULL,
 CONSTRAINT [PK_PRO_TADI] PRIMARY KEY CLUSTERED 
(
	[TAD_CODI] ASC,
	[TMA_CODI] ASC,
	[TMA_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_TADI] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_TADI] TO [public] AS [dbo]
GRANT INSERT ON [PRO_TADI] TO [public] AS [dbo]
GRANT SELECT ON [PRO_TADI] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_TADI] TO [public] AS [dbo]
/****** Object:  Table [PRO_TMAN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_TMAN](
	[TMA_CODI] [int] NOT NULL,
	[TMA_EANO] [int] NOT NULL,
	[TMA_DATA] [datetime] NOT NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[TMA_TIPO] [int] NULL,
	[TMA_STAT] [int] NOT NULL,
	[TMA_NORD] [varchar](15) NULL,
	[TMA_DTNO] [datetime] NULL,
	[TMA_NCON] [int] NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[TMA_LCRG] [varchar](6) NULL,
	[TMA_ADIC] [int] NOT NULL,
	[TMA_TVOL] [int] NOT NULL,
	[TMA_REF7] [varchar](30) NOT NULL,
	[TMA_EXPE] [varchar](18) NULL,
	[TMA_DEST] [varchar](18) NOT NULL,
	[DEC_CODI] [varchar](6) NULL,
	[PAI_EXPE] [varchar](2) NULL,
	[PAI_DEST] [varchar](2) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[TMA_MATR] [varchar](30) NULL,
	[PAI_NACI] [varchar](2) NULL,
	[MTR_TFRO] [varchar](2) NULL,
	[TMA_MTRF] [varchar](30) NULL,
	[PAI_MTRN] [varchar](2) NULL,
	[TMA_CONT] [int] NOT NULL,
	[MTR_C25] [varchar](2) NULL,
	[LME_CODI] [varchar](17) NULL,
	[TMA_MLTO] [numeric](38, 6) NULL,
	[TMA_MBTO] [numeric](38, 6) NULL,
	[ARM_CODI] [varchar](17) NULL,
	[CLI_RPRI] [varchar](18) NULL,
	[EAD_PAS1] [varchar](8) NULL,
	[EAD_PAS2] [varchar](8) NULL,
	[EAD_PAS3] [varchar](8) NULL,
	[EAD_PAS4] [varchar](8) NULL,
	[EAD_DEST] [varchar](8) NULL,
	[EAD_PART] [varchar](8) NULL,
	[TMA_PDNO] [varchar](70) NULL,
	[TMA_PDMO] [varchar](70) NULL,
	[TMA_PDLO] [varchar](35) NULL,
	[TMA_PDCP] [varchar](12) NULL,
	[TMA_PDLP] [varchar](35) NULL,
	[TMA_PDNF] [varchar](18) NULL,
	[PAI_PDPL] [varchar](2) NULL,
	[TMA_PENO] [varchar](70) NULL,
	[TMA_PEMO] [varchar](70) NULL,
	[TMA_PELO] [varchar](35) NULL,
	[TMA_PECP] [varchar](12) NULL,
	[TMA_PELP] [varchar](35) NULL,
	[TMA_PENF] [varchar](18) NULL,
	[PAI_PEPL] [varchar](2) NULL,
 CONSTRAINT [PK_PRO_TMAN] PRIMARY KEY CLUSTERED 
(
	[TMA_CODI] ASC,
	[TMA_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_TMAN] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_TMAN] TO [public] AS [dbo]
GRANT INSERT ON [PRO_TMAN] TO [public] AS [dbo]
GRANT SELECT ON [PRO_TMAN] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_TMAN] TO [public] AS [dbo]
/****** Object:  Table [PRO_TMDO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_TMDO](
	[TMA_EANO] [int] NOT NULL,
	[TMA_CODI] [int] NOT NULL,
	[TAD_CODI] [int] NOT NULL,
	[TMD_CODI] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[TMD_NUME] [varchar](35) NULL,
	[TMD_DINI] [datetime] NULL,
	[TMD_DFIM] [datetime] NULL,
 CONSTRAINT [PK_PRO_TMDO] PRIMARY KEY CLUSTERED 
(
	[TMA_EANO] ASC,
	[TMA_CODI] ASC,
	[TAD_CODI] ASC,
	[TMD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_TMDO] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_TMDO] TO [public] AS [dbo]
GRANT INSERT ON [PRO_TMDO] TO [public] AS [dbo]
GRANT SELECT ON [PRO_TMDO] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_TMDO] TO [public] AS [dbo]
/****** Object:  Table [PRO_TMGT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [PRO_TMGT](
	[TMA_CODI] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[TMA_EANO] [int] NOT NULL,
	[PAI_NOME] [varchar](50) NULL,
 CONSTRAINT [PK_PRO_TMGT] PRIMARY KEY CLUSTERED 
(
	[TMA_CODI] ASC,
	[PAI_CODI] ASC,
	[TMA_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [PRO_TMGT] TO  SCHEMA OWNER 
GRANT DELETE ON [PRO_TMGT] TO [public] AS [dbo]
GRANT INSERT ON [PRO_TMGT] TO [public] AS [dbo]
GRANT SELECT ON [PRO_TMGT] TO [public] AS [dbo]
GRANT UPDATE ON [PRO_TMGT] TO [public] AS [dbo]
/****** Object:  Table [TAB_ADOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ADOC](
	[ADC_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
	[ADC_UIMP] [bit] NOT NULL,
	[ADC_UEXP] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_ADOC] PRIMARY KEY CLUSTERED 
(
	[ADC_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ADOC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ADOC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ADOC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ADOC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ADOC] TO [public] AS [dbo]
/****** Object:  Table [TAB_ADRE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ADRE](
	[ADR_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[ADR_DESC] [varchar](70) NULL,
	[CTE_COD1] [varchar](3) NULL,
	[ADR_VTER] [numeric](38, 6) NULL,
	[FFA_CODI] [int] NULL,
	[CTE_COD2] [varchar](3) NULL,
	[CPE_CODI] [varchar](3) NULL,
	[ADR_TEOR] [numeric](38, 6) NULL,
	[ADR_PESO] [numeric](38, 6) NULL,
	[INF_CODI] [varchar](8) NULL,
	[APA_CODI] [varchar](22) NULL,
 CONSTRAINT [PK_TAB_ADRE] PRIMARY KEY CLUSTERED 
(
	[ADR_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ADRE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ADRE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ADRE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ADRE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ADRE] TO [public] AS [dbo]
/****** Object:  Table [TAB_ADUM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ADUM](
	[ADU_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](35) NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](35) NULL,
	[ADU_TAXA] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_ADUM] PRIMARY KEY CLUSTERED 
(
	[ADU_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_TAB_ADUM] UNIQUE NONCLUSTERED 
(
	[APA_CHVE] ASC,
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ADUM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ADUM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ADUM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ADUM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ADUM] TO [public] AS [dbo]
/****** Object:  Table [TAB_AETR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_AETR](
	[AET_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_COD2] [varchar](6) NULL,
	[AET_ORIG] [int] NULL,
	[RRE_CODI] [int] NULL,
	[RRE_NOME] [varchar](70) NULL,
	[AET_TAXA] [bit] NOT NULL,
	[AET_TXVL] [numeric](38, 6) NOT NULL,
	[AET_IDST] [varchar](20) NOT NULL,
 CONSTRAINT [PK_TAB_AETR] PRIMARY KEY CLUSTERED 
(
	[AET_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_AETR] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_AETR] TO [public] AS [dbo]
GRANT INSERT ON [TAB_AETR] TO [public] AS [dbo]
GRANT SELECT ON [TAB_AETR] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_AETR] TO [public] AS [dbo]
/****** Object:  Table [TAB_AGEN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_AGEN](
	[AGE_CODI] [varchar](18) NOT NULL,
	[AGE_CEAN] [varchar](13) NULL,
	[AGE_INAC] [bit] NOT NULL,
	[AGE_NOME] [varchar](70) NOT NULL,
	[AGE_MORA] [varchar](70) NULL,
	[AGE_LOCA] [varchar](35) NULL,
	[AGE_CPOS] [varchar](12) NULL,
	[AGE_LPOS] [varchar](35) NULL,
	[AGE_TELF] [varchar](10) NULL,
	[AGE_FAX] [varchar](10) NULL,
	[AGE_EMAI] [varchar](50) NULL,
	[AGE_NIF] [varchar](18) NULL,
	[AGE_TIPO] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
 CONSTRAINT [PK_TAB_AGEN] PRIMARY KEY CLUSTERED 
(
	[AGE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_AGEN] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_AGEN] TO [public] AS [dbo]
GRANT INSERT ON [TAB_AGEN] TO [public] AS [dbo]
GRANT SELECT ON [TAB_AGEN] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_AGEN] TO [public] AS [dbo]
/****** Object:  Table [TAB_AIEC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_AIEC](
	[AIE_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[TEM_CODI] [varchar](2) NULL,
	[AIE_TEOR] [numeric](38, 6) NULL,
	[AIE_PLIQ] [numeric](38, 6) NULL,
	[AIE_PBRT] [numeric](38, 6) NULL,
	[AIE_CAPA] [numeric](38, 6) NULL,
	[AIE_TAXA] [numeric](38, 6) NULL,
	[MIE_CODI] [varchar](25) NULL,
	[MIE_DESC] [varchar](35) NULL,
	[UME_CODI] [varchar](3) NULL,
	[UME_NOME] [varchar](35) NULL,
	[TEM_CODI1] [varchar](2) NULL,
	[TEM_NOME] [varchar](35) NULL,
	[AIE_CATE] [varchar](1) NULL,
	[AIE_CPED] [varchar](5) NULL,
	[AIE_TABH] [varchar](6) NULL,
 CONSTRAINT [PK_TAB_AIEC] PRIMARY KEY CLUSTERED 
(
	[AIE_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_AIEC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_AIEC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_AIEC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_AIEC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_AIEC] TO [public] AS [dbo]
/****** Object:  Table [TAB_ALFA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ALFA](
	[ALF_CODI] [varchar](8) NOT NULL,
	[ALF_NOME] [varchar](70) NOT NULL,
	[ALF_TFDA] [int] NULL,
	[ALF_DEPE] [bit] NOT NULL,
	[ALF_ALPR] [varchar](8) NULL,
	[ALF_PRIN] [bit] NOT NULL,
	[ALF_APRI] [varchar](8) NULL,
	[MTR_CODI] [varchar](2) NULL,
	[ALF_CONT] [int] NOT NULL,
	[ALF_TLOC] [varchar](2) NULL,
	[LME_CODI] [varchar](17) NULL,
	[ALF_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[PAE_CODI] [varchar](8) NULL,
 CONSTRAINT [PK_TAB_ALFA] PRIMARY KEY CLUSTERED 
(
	[ALF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_ALFA] UNIQUE NONCLUSTERED 
(
	[ALF_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ALFA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ALFA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ALFA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ALFA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ALFA] TO [public] AS [dbo]
/****** Object:  Table [TAB_ALFD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ALFD](
	[AFD_CODI] [int] NOT NULL,
	[ALF_CODI] [varchar](8) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
 CONSTRAINT [PK_TAB_ALFD] PRIMARY KEY CLUSTERED 
(
	[AFD_CODI] ASC,
	[ALF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ALFD] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ALFD] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ALFD] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ALFD] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ALFD] TO [public] AS [dbo]
/****** Object:  Table [TAB_ALFM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ALFM](
	[ALF_CODI] [varchar](8) NOT NULL,
	[INF_CODI] [varchar](8) NOT NULL,
 CONSTRAINT [PK_TAB_ALFM] PRIMARY KEY CLUSTERED 
(
	[ALF_CODI] ASC,
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ALFM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ALFM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ALFM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ALFM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ALFM] TO [public] AS [dbo]
/****** Object:  Table [TAB_ALFO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ALFO](
	[ALF_CODI] [varchar](8) NOT NULL,
	[UTI_UTIL] [varchar](30) NOT NULL,
 CONSTRAINT [PK_TAB_ALFO] PRIMARY KEY CLUSTERED 
(
	[ALF_CODI] ASC,
	[UTI_UTIL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ALFO] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ALFO] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ALFO] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ALFO] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ALFO] TO [public] AS [dbo]
/****** Object:  Table [TAB_AMEN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_AMEN](
	[AME_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[INF_CODI] [varchar](8) NOT NULL,
	[INF_DESI] [varchar](150) NULL,
	[AME_UIMP] [bit] NOT NULL,
	[AME_UEXP] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_AMEN] PRIMARY KEY CLUSTERED 
(
	[AME_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_AMEN] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_AMEN] TO [public] AS [dbo]
GRANT INSERT ON [TAB_AMEN] TO [public] AS [dbo]
GRANT SELECT ON [TAB_AMEN] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_AMEN] TO [public] AS [dbo]
/****** Object:  Table [TAB_APAU]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_APAU](
	[APA_CHVE] [int] NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[APA_CEAN] [varchar](22) NULL,
	[APA_INAC] [bit] NOT NULL,
	[APA_CPAU] [varchar](22) NULL,
	[APA_DESG] [varchar](150) NULL,
	[APA_DCOM] [varchar](150) NULL,
	[APA_EUR1] [bit] NOT NULL,
	[APA_ATR] [bit] NOT NULL,
	[APA_AGRX] [bit] NOT NULL,
	[APA_LIMP] [bit] NOT NULL,
	[APA_CORI] [bit] NOT NULL,
	[APA_G156] [bit] NOT NULL,
	[USU_CODI] [varchar](10) NULL,
	[APA_TXCO] [bit] NOT NULL,
	[APA_TRIB] [int] NULL,
	[UME_CODI] [varchar](3) NULL,
	[APA_OBSR] [text] NULL,
	[APA_TPT] [numeric](38, 6) NULL,
	[APA_TPMN] [numeric](38, 6) NULL,
	[APA_TPMX] [numeric](38, 6) NULL,
	[APA_EFTA] [numeric](38, 6) NULL,
	[APA_EFMN] [numeric](38, 6) NULL,
	[APA_EFMX] [numeric](38, 6) NULL,
	[APA_SPG] [numeric](38, 6) NULL,
	[APA_SPMN] [numeric](38, 6) NULL,
	[APA_SPMX] [numeric](38, 6) NULL,
	[APS_CODI] [int] NULL,
	[APO_CODI] [int] NULL,
	[APA_TIVA] [numeric](38, 6) NULL,
	[APA_CIEC] [int] NULL,
	[APA_INDI] [varchar](2) NULL,
	[APA_ANXC] [bit] NOT NULL,
	[APA_ANXD] [bit] NOT NULL,
	[APA_TXIA] [numeric](38, 6) NOT NULL,
	[APA_DPUT] [bit] NOT NULL,
	[APA_ATAR] [varchar](10) NULL,
	[APA_AIVA] [int] NULL,
	[APA_CS50] [bit] NOT NULL,
	[APA_AIC1] [varchar](4) NULL,
	[APA_AIC2] [varchar](4) NULL,
	[APA_AIC3] [varchar](4) NULL,
	[APA_FLUX] [int] NOT NULL,
	[APA_UCRI] [varchar](30) NULL,
	[APA_DCRI] [datetime] NULL,
	[APA_UALT] [varchar](30) NULL,
	[APA_DALT] [datetime] NULL,
	[APA_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[APA_EDAR] [bit] NOT NULL,
	[APA_CCUS] [varchar](9) NULL,
	[APA_AIC4] [varchar](4) NULL,
	[APA_AIC5] [varchar](4) NULL,
	[APA_TMER] [varchar](3) NULL,
	[APA_RTRC] [int] NULL,
 CONSTRAINT [PK_TAB_APAU] PRIMARY KEY CLUSTERED 
(
	[APA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_APAU] UNIQUE NONCLUSTERED 
(
	[APA_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_APAU] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_APAU] TO [public] AS [dbo]
GRANT INSERT ON [TAB_APAU] TO [public] AS [dbo]
GRANT SELECT ON [TAB_APAU] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_APAU] TO [public] AS [dbo]
/****** Object:  Table [TAB_APEF]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_APEF](
	[APE_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NULL,
	[APE_EFTA] [numeric](38, 6) NULL,
	[APE_EFMN] [numeric](38, 6) NULL,
	[APE_EFMX] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_APEF] PRIMARY KEY CLUSTERED 
(
	[APE_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_APEF] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_APEF] TO [public] AS [dbo]
GRANT INSERT ON [TAB_APEF] TO [public] AS [dbo]
GRANT SELECT ON [TAB_APEF] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_APEF] TO [public] AS [dbo]
/****** Object:  Table [TAB_APOI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [TAB_APOI](
	[APO_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[RRE_CODI] [int] NULL,
	[APO_OIMP] [numeric](38, 6) NULL,
	[APO_VALO] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_APOI] PRIMARY KEY CLUSTERED 
(
	[APO_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [TAB_APOI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_APOI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_APOI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_APOI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_APOI] TO [public] AS [dbo]
/****** Object:  Table [TAB_APSP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_APSP](
	[APS_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NULL,
	[APS_SPG] [numeric](38, 6) NULL,
	[APS_SPMN] [numeric](38, 6) NULL,
	[APS_SPMX] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_APSP] PRIMARY KEY CLUSTERED 
(
	[APS_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_APSP] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_APSP] TO [public] AS [dbo]
GRANT INSERT ON [TAB_APSP] TO [public] AS [dbo]
GRANT SELECT ON [TAB_APSP] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_APSP] TO [public] AS [dbo]
/****** Object:  Table [TAB_APTF]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_APTF](
	[APT_CODI] [int] NOT NULL,
	[APA_CHVE] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NULL,
	[APT_TFT] [numeric](38, 6) NULL,
	[APT_DATA] [datetime] NULL,
	[APT_INCR] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_APTF] PRIMARY KEY CLUSTERED 
(
	[APT_CODI] ASC,
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_APTF] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_APTF] TO [public] AS [dbo]
GRANT INSERT ON [TAB_APTF] TO [public] AS [dbo]
GRANT SELECT ON [TAB_APTF] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_APTF] TO [public] AS [dbo]
/****** Object:  Table [TAB_ARMZ]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_ARMZ](
	[ARM_CODI] [varchar](17) NOT NULL,
	[ARM_NOME] [varchar](70) NULL,
	[TAR_CODI] [varchar](1) NULL,
	[EAD_CODI] [varchar](8) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[ARM_NAUT] [varchar](35) NULL,
	[ARM_DATA] [datetime] NULL,
	[ARM_EORI] [varchar](17) NULL,
	[ARM_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_ARMZ] PRIMARY KEY CLUSTERED 
(
	[ARM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_ARMZ] UNIQUE NONCLUSTERED 
(
	[ARM_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_ARMZ] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_ARMZ] TO [public] AS [dbo]
GRANT INSERT ON [TAB_ARMZ] TO [public] AS [dbo]
GRANT SELECT ON [TAB_ARMZ] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_ARMZ] TO [public] AS [dbo]
/****** Object:  Table [TAB_CARM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CARM](
	[CLI_CODI] [varchar](18) NOT NULL,
	[CAR_CODI] [int] NOT NULL,
	[CAR_MORA] [varchar](70) NULL,
	[CAR_LOCA] [varchar](35) NULL,
	[CAR_CPOS] [varchar](12) NULL,
	[CAR_LPOS] [varchar](35) NULL,
 CONSTRAINT [PK_TAB_CARM] PRIMARY KEY CLUSTERED 
(
	[CLI_CODI] ASC,
	[CAR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CARM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CARM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CARM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CARM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CARM] TO [public] AS [dbo]
/****** Object:  Table [TAB_CATG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CATG](
	[CAT_CODI] [varchar](2) NOT NULL,
	[CAT_NOME] [varchar](70) NOT NULL,
	[CAT_RP1] [varchar](2) NOT NULL,
	[CAT_RP2] [varchar](2) NOT NULL,
 CONSTRAINT [PK_TAB_CATE] PRIMARY KEY CLUSTERED 
(
	[CAT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CATG] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CATG] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CATG] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CATG] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CATG] TO [public] AS [dbo]
/****** Object:  Table [TAB_CAUC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CAUC](
	[CAU_CODI] [varchar](5) NOT NULL,
	[CAU_NOME] [varchar](30) NULL,
	[CAU_DCTR] [int] NULL,
	[CAU_LIQU] [bit] NOT NULL,
	[CAU_ATRI] [bit] NOT NULL,
	[CAU_UTIL] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_CAUC] PRIMARY KEY CLUSTERED 
(
	[CAU_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CAUC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CAUC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CAUC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CAUC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CAUC] TO [public] AS [dbo]
/****** Object:  Table [TAB_CENT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CENT](
	[CEN_CODI] [varchar](3) NOT NULL,
	[CEN_NOME] [varchar](35) NULL,
	[CEN_FOR1] [bit] NOT NULL,
	[FIN_CODI1] [int] NULL,
	[CEN_FOR2] [bit] NOT NULL,
	[FIN_CODI2] [int] NULL,
	[CEN_FOR3] [bit] NOT NULL,
	[FIN_CODI3] [int] NULL,
	[CEN_FOR4] [bit] NOT NULL,
	[FIN_CODI4] [int] NULL,
	[CEN_FOR5] [bit] NOT NULL,
	[FIN_CODI5] [int] NULL,
	[CEN_USFR] [bit] NOT NULL,
	[CEN_LOCT] [int] NULL,
	[CEN_LOCD] [int] NULL,
	[CEN_VLFR] [bit] NOT NULL,
	[CEN_VLSG] [bit] NOT NULL,
	[CEN_MPAG] [varchar](1) NULL,
	[CEN_PACC] [bit] NOT NULL,
	[CEN_VLAN] [bit] NOT NULL,
	[CEN_FDHL] [bit] NOT NULL,
	[CEN_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_CENT] PRIMARY KEY CLUSTERED 
(
	[CEN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_CENT] UNIQUE NONCLUSTERED 
(
	[CEN_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CENT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CENT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CENT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CENT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CENT] TO [public] AS [dbo]
/****** Object:  Table [TAB_CLAU]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CLAU](
	[CAU_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[CLI_CODI] [varchar](18) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[CAU_NDOC] [varchar](35) NOT NULL,
 CONSTRAINT [PK_TAB_CLAU] PRIMARY KEY CLUSTERED 
(
	[CAU_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_TAB_CLAU] UNIQUE NONCLUSTERED 
(
	[CLI_CODI] ASC,
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CLAU] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CLAU] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CLAU] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CLAU] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CLAU] TO [public] AS [dbo]
/****** Object:  Table [TAB_CLDO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CLDO](
	[CLI_CODI] [varchar](18) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[CLD_UIMP] [bit] NOT NULL,
	[CLD_UEXP] [bit] NOT NULL,
	[CLD_NDOC] [varchar](35) NULL,
	[CLD_DDOC] [datetime] NULL,
 CONSTRAINT [PK_TAB_CLDO] PRIMARY KEY CLUSTERED 
(
	[CLI_CODI] ASC,
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CLDO] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CLDO] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CLDO] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CLDO] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CLDO] TO [public] AS [dbo]
/****** Object:  Table [TAB_CLFA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CLFA](
	[CLI_CODI] [varchar](18) NOT NULL,
	[FOR_CODI] [varchar](18) NOT NULL,
	[APA_CODI] [varchar](22) NOT NULL,
	[CFA_DCOM] [varchar](100) NULL,
 CONSTRAINT [PK_TAB_CLFA] PRIMARY KEY CLUSTERED 
(
	[CLI_CODI] ASC,
	[APA_CODI] ASC,
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CLFA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CLFA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CLFA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CLFA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CLFA] TO [public] AS [dbo]
/****** Object:  Table [TAB_CLFI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CLFI](
	[CFI_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[CLI_CODI] [varchar](18) NOT NULL,
	[CFI_PATH] [varchar](500) NOT NULL,
	[CFI_NOMF] [varchar](100) NOT NULL,
	[CFI_DESC] [varchar](150) NOT NULL,
	[CFI_TIPO] [int] NOT NULL,
	[CFI_DATA] [datetime] NOT NULL,
	[CFI_UTIL] [varchar](30) NOT NULL,
 CONSTRAINT [PK_TAB_CLFI] PRIMARY KEY CLUSTERED 
(
	[CFI_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CLFI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CLFI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CLFI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CLFI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CLFI] TO [public] AS [dbo]
/****** Object:  Table [TAB_CLIE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CLIE](
	[CLI_CODI] [varchar](18) NOT NULL,
	[CLI_CEAN] [varchar](13) NULL,
	[CLI_INAC] [bit] NOT NULL,
	[CLI_DESP] [bit] NOT NULL,
	[CLI_AUTO] [bit] NOT NULL,
	[CLI_NOME] [varchar](70) NOT NULL,
	[CLI_MORA] [varchar](70) NOT NULL,
	[CLI_LOCA] [varchar](35) NULL,
	[CLI_CPOS] [varchar](12) NULL,
	[CLI_LPOS] [varchar](35) NULL,
	[CLI_TELF] [varchar](14) NULL,
	[CLI_TEL2] [varchar](10) NULL,
	[CLI_FAX] [varchar](10) NULL,
	[CLI_EMAI] [varchar](200) NULL,
	[CLI_WEB] [varchar](50) NULL,
	[CLI_NIF] [varchar](18) NOT NULL,
	[CLI_TNIF] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[RES_CODI] [int] NOT NULL,
	[FLE_CODI] [int] NULL,
	[CLI_MDPG] [varchar](1) NULL,
	[CLI_NDHA] [varchar](17) NULL,
	[CLI_DTDH] [datetime] NULL,
	[CLI_NCA1] [varchar](17) NULL,
	[CLI_ANO1] [varchar](4) NULL,
	[CLI_TCA1] [varchar](1) NULL,
	[CLI_INA1] [bit] NOT NULL,
	[CLI_NCA2] [varchar](17) NULL,
	[CLI_ANO2] [varchar](4) NULL,
	[CLI_TCA2] [varchar](1) NULL,
	[CLI_INA2] [bit] NOT NULL,
	[CLI_NCA3] [varchar](17) NULL,
	[CLI_ANO3] [varchar](4) NULL,
	[CLI_TCA3] [varchar](1) NULL,
	[CLI_INA3] [bit] NOT NULL,
	[CLI_NCA4] [varchar](17) NULL,
	[CLI_ANO4] [varchar](4) NULL,
	[CLI_TCA4] [varchar](1) NULL,
	[CLI_INA4] [bit] NOT NULL,
	[CLI_NCA5] [varchar](17) NULL,
	[CLI_ANO5] [varchar](4) NULL,
	[CLI_TCA5] [varchar](1) NULL,
	[CLI_INA5] [bit] NOT NULL,
	[CLI_CCOR] [varchar](18) NULL,
	[CLI_CPOC] [varchar](10) NULL,
	[CLI_ECON] [varchar](18) NULL,
	[CLI_SUCA] [numeric](38, 6) NULL,
	[CLI_ISAL] [bit] NOT NULL,
	[CLI_STAN] [bit] NOT NULL,
	[CLI_CLIE] [bit] NOT NULL,
	[CLI_APEL] [varchar](25) NULL,
	[CLI_FREG] [varchar](25) NULL,
	[CLI_CONC] [varchar](25) NULL,
	[CLI_DIST] [varchar](25) NULL,
	[CLI_NATU] [varchar](25) NULL,
	[CLI_NACI] [varchar](25) NULL,
	[CLI_NPAI] [varchar](70) NULL,
	[CLI_NMAE] [varchar](70) NULL,
	[CLI_ECIV] [int] NULL,
	[CLI_DNAS] [datetime] NULL,
	[CLI_RESI] [varchar](70) NULL,
	[CLI_PROF] [varchar](25) NULL,
	[EJU_CODI] [varchar](8) NULL,
	[CLI_DEST] [int] NULL,
	[CLI_BI] [varchar](9) NULL,
	[CLI_BIEM] [varchar](25) NULL,
	[CLI_BIDT] [datetime] NULL,
	[CLI_PASS] [varchar](9) NULL,
	[CLI_PAEM] [varchar](25) NULL,
	[CLI_PADT] [datetime] NULL,
	[CLI_CCON] [varchar](9) NULL,
	[CLI_CCEM] [varchar](25) NULL,
	[CLI_CCDT] [datetime] NULL,
	[CLI_CMIL] [varchar](9) NULL,
	[CLI_CMEM] [varchar](25) NULL,
	[CLI_CMDT] [datetime] NULL,
	[CLI_INFO] [text] NULL,
	[CLI_CODC] [bit] NOT NULL,
	[CLI_CPAG] [int] NULL,
	[CLI_MPAG] [int] NULL,
	[DIN_CODI] [int] NULL,
	[CLI_SENT] [varchar](18) NULL,
	[CLI_DUCT] [bit] NOT NULL,
	[CLI_LMCR] [bit] NOT NULL,
	[CLI_VCIL] [numeric](38, 6) NULL,
	[CLI_CACC] [bit] NOT NULL,
	[CLI_CEXB] [bit] NOT NULL,
	[CLI_CDAS] [bit] NOT NULL,
	[CLI_AURS] [varchar](25) NULL,
	[CLI_DTRS] [datetime] NULL,
	[DOC_CODI] [varchar](5) NULL,
	[CLI_NAOE] [varchar](41) NULL,
	[CLI_DTOE] [datetime] NULL,
	[DOC_CDOE] [varchar](5) NULL,
	[CLI_FXOE] [int] NOT NULL,
	[COS_CDLS] [varchar](8) NULL,
	[COS_CDPO] [varchar](8) NULL,
	[CLI_VEVD] [numeric](38, 6) NOT NULL,
	[CLI_AIVA] [int] NULL,
	[CLI_INTR] [bit] NOT NULL,
	[CLI_IEEN] [bit] NOT NULL,
	[CLI_IESA] [bit] NOT NULL,
	[CLI_INDI] [int] NOT NULL,
	[CLI_ITFT] [int] NOT NULL,
	[CLI_IVLF] [numeric](38, 6) NOT NULL,
	[DEC_CODI] [varchar](6) NULL,
	[CLI_TDEC] [int] NULL,
	[CLI_DPRO] [bit] NOT NULL,
	[CLI_CTRO] [bit] NOT NULL,
	[CLI_EMA2] [varchar](200) NULL,
	[CLI_UCRI] [varchar](30) NULL,
	[CLI_DCRI] [datetime] NULL,
	[CLI_UALT] [varchar](30) NULL,
	[CLI_DALT] [datetime] NULL,
	[CLI_DPNM] [varchar](50) NULL,
	[CLI_DPCT] [varchar](30) NULL,
	[CLI_DPTL] [varchar](20) NULL,
	[CLI_DPEM] [varchar](200) NULL,
	[CLI_IESE] [bit] NOT NULL,
	[CLI_DFOE] [datetime] NULL,
	[CLI_SYNC] [bit] NOT NULL,
	[CLI_PLET] [bit] NOT NULL,
	[CLI_BIVA] [bit] NOT NULL,
	[CLI_EILC] [bit] NOT NULL,
	[CLI_CGLO] [bit] NOT NULL,
	[CLI_DIBI] [datetime] NULL,
	[CLI_DCON] [bit] NOT NULL,
	[CLI_DCUT] [varchar](30) NULL,
	[CLI_DCDT] [datetime] NULL,
	[CLI_DCOB] [varchar](200) NULL,
	[CLI_DESQ] [bit] NOT NULL,
	[CLI_DETP] [int] NULL,
	[CLI_DEUT] [varchar](30) NULL,
	[CLI_DEDT] [datetime] NULL,
	[CLI_DEOB] [varchar](200) NULL,
	[CLI_FETE] [int] NULL,
	[CLI_FEEP] [varchar](100) NULL,
	[CLI_FEEC] [varchar](100) NULL,
	[CLI_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[CLI_CSNC] [varchar](10) NULL,
	[CLI_IEDA] [bit] NOT NULL,
	[CLI_CNIF] [varchar](17) NULL,
	[ALF_CODI1] [varchar](8) NULL,
	[CLI_CCA1] [varchar](4) NULL,
	[CLI_OCA1] [varchar](35) NULL,
	[ALF_CODI2] [varchar](8) NULL,
	[CLI_CCA2] [varchar](4) NULL,
	[CLI_OCA2] [varchar](35) NULL,
	[ALF_CODI3] [varchar](8) NULL,
	[CLI_CCA3] [varchar](4) NULL,
	[CLI_OCA3] [varchar](35) NULL,
	[ALF_CODI4] [varchar](8) NULL,
	[CLI_CCA4] [varchar](4) NULL,
	[CLI_OCA4] [varchar](35) NULL,
	[ALF_CODI5] [varchar](8) NULL,
	[CLI_CCA5] [varchar](4) NULL,
	[CLI_OCA5] [varchar](35) NULL,
	[DIN_CODI1] [int] NULL,
	[CLI_EAOE] [varchar](4) NULL,
 CONSTRAINT [PK_TAB_CLIE] PRIMARY KEY CLUSTERED 
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_CLIE] UNIQUE NONCLUSTERED 
(
	[CLI_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CLIE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CLIE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CLIE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CLIE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CLIE] TO [public] AS [dbo]
/****** Object:  Table [TAB_COPE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_COPE](
	[COP_CODI] [int] NOT NULL,
	[COP_DESG] [varchar](35) NOT NULL,
 CONSTRAINT [PK_TAB_COPE] PRIMARY KEY CLUSTERED 
(
	[COP_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_COPE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_COPE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_COPE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_COPE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_COPE] TO [public] AS [dbo]
/****** Object:  Table [TAB_CORE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CORE](
	[COR_CODI] [varchar](2) NOT NULL,
	[COR_NOME] [varchar](35) NOT NULL,
 CONSTRAINT [PK_TAB_CORE] PRIMARY KEY CLUSTERED 
(
	[COR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CORE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CORE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CORE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CORE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CORE] TO [public] AS [dbo]
/****** Object:  Table [TAB_COSM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_COSM](
	[COS_CODE] [varchar](8) NOT NULL,
	[COS_POST] [varchar](50) NULL,
	[COS_SCAN] [varchar](3) NULL,
	[COS_FDES] [varchar](100) NULL,
	[COS_RELI] [bit] NOT NULL,
	[COS_HOLD] [bit] NOT NULL,
	[COS_ANAT] [bit] NOT NULL,
	[NDE_CODI] [varchar](3) NULL,
	[NDE_CDPO] [varchar](3) NULL,
	[COS_IDTY] [int] IDENTITY(100001,1) NOT NULL,
 CONSTRAINT [PK_TAB_COSM] PRIMARY KEY CLUSTERED 
(
	[COS_CODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_COSM] UNIQUE NONCLUSTERED 
(
	[COS_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_COSM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_COSM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_COSM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_COSM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_COSM] TO [public] AS [dbo]
/****** Object:  Table [TAB_CPAI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CPAI](
	[PAI_CODI] [varchar](2) NOT NULL,
	[CPA_DATA] [datetime] NOT NULL,
	[CPA_COMP] [numeric](38, 6) NULL,
	[CPA_VEND] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_CPAI] PRIMARY KEY CLUSTERED 
(
	[PAI_CODI] ASC,
	[CPA_DATA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CPAI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CPAI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CPAI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CPAI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CPAI] TO [public] AS [dbo]
/****** Object:  Table [TAB_CPDI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CPDI](
	[CPD_CPAU] [varchar](22) NOT NULL,
	[CPD_DESI] [varchar](150) NOT NULL,
 CONSTRAINT [PK_TAB_CPDI] PRIMARY KEY CLUSTERED 
(
	[CPD_CPAU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CPDI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CPDI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CPDI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CPDI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CPDI] TO [public] AS [dbo]
/****** Object:  Table [TAB_CPES]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CPES](
	[CPE_CODI] [varchar](3) NOT NULL,
	[CPE_DESC] [varchar](35) NULL,
 CONSTRAINT [PK_TAB_CPES] PRIMARY KEY CLUSTERED 
(
	[CPE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CPES] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CPES] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CPES] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CPES] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CPES] TO [public] AS [dbo]
/****** Object:  Table [TAB_CPOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CPOC](
	[CPO_CODI] [int] NOT NULL,
	[CPO_DESG] [varchar](50) NULL,
	[CPO_CONT] [varchar](15) NULL,
	[CPO_CINC] [varchar](15) NULL,
	[CPO_CLFT] [varchar](15) NULL,
	[CPO_CLNC] [varchar](15) NULL,
	[CPO_CRFT] [varchar](15) NULL,
	[CPO_CVFT] [varchar](15) NULL,
	[CPO_CVNC] [varchar](15) NULL,
 CONSTRAINT [PK_TAB_CPOC] PRIMARY KEY CLUSTERED 
(
	[CPO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CPOC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CPOC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CPOC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CPOC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CPOC] TO [public] AS [dbo]
/****** Object:  Table [TAB_CSER]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CSER](
	[CSE_CODI] [varchar](2) NOT NULL,
	[CSE_NOME] [varchar](70) NOT NULL,
 CONSTRAINT [PK_TAB_CSER] PRIMARY KEY CLUSTERED 
(
	[CSE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CSER] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CSER] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CSER] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CSER] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CSER] TO [public] AS [dbo]
/****** Object:  Table [TAB_CTEO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_CTEO](
	[CTE_CODI] [varchar](3) NOT NULL,
	[CTE_DESC] [varchar](35) NULL,
 CONSTRAINT [PK_TAB_CTEO] PRIMARY KEY CLUSTERED 
(
	[CTE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_CTEO] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_CTEO] TO [public] AS [dbo]
GRANT INSERT ON [TAB_CTEO] TO [public] AS [dbo]
GRANT SELECT ON [TAB_CTEO] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_CTEO] TO [public] AS [dbo]
/****** Object:  Table [TAB_DCSR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DCSR](
	[DCS_CODI] [varchar](18) NOT NULL,
	[DSR_NUME] [int] NOT NULL,
	[DSR_NOME] [varchar](70) NOT NULL,
	[DSR_MORA] [varchar](70) NOT NULL,
	[DSR_CPOS] [varchar](12) NOT NULL,
	[DSR_LOCA] [varchar](35) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[DSR_NNIF] [varchar](17) NOT NULL,
 CONSTRAINT [PK_TAB_DCSR] PRIMARY KEY CLUSTERED 
(
	[DCS_CODI] ASC,
	[DSR_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DCSR] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DCSR] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DCSR] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DCSR] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DCSR] TO [public] AS [dbo]
/****** Object:  Table [TAB_DDOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DDOC](
	[DDO_CODI] [int] NOT NULL,
	[DDO_NOME] [varchar](70) NOT NULL,
	[DDO_IMPR] [bit] NOT NULL,
	[DDO_POCC] [varchar](15) NULL,
	[DDO_POCS] [varchar](15) NULL,
	[DDO_CCDO] [bit] NOT NULL,
	[DDO_PCDO] [int] NULL,
	[DDO_CNAV] [bit] NOT NULL,
	[DDO_PNAV] [int] NULL,
	[DDO_UCTE] [bit] NOT NULL,
	[DDO_DGEP] [bit] NOT NULL,
	[DDO_SPCD] [varchar](15) NULL,
	[DDO_SPSC] [varchar](15) NULL,
	[DDO_FCLC] [varchar](4000) NULL,
	[CCO_CODI] [varchar](4) NULL,
	[DDO_CREC] [int] NULL,
	[DDO_FLCE] [varchar](4000) NULL,
	[DDO_FCLD] [varchar](4000) NULL,
 CONSTRAINT [PK_TAB_DDOC] PRIMARY KEY CLUSTERED 
(
	[DDO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DDOC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DDOC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DDOC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DDOC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DDOC] TO [public] AS [dbo]
/****** Object:  Table [TAB_DECL]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DECL](
	[DEC_CODI] [varchar](6) NOT NULL,
	[DEC_CEAN] [varchar](13) NULL,
	[DEC_INAC] [bit] NOT NULL,
	[DEC_NOME] [varchar](70) NOT NULL,
	[DEC_MORA] [varchar](70) NOT NULL,
	[DEC_LOCA] [varchar](35) NULL,
	[DEC_CPOS] [varchar](12) NULL,
	[DEC_LPOS] [varchar](35) NULL,
	[DEC_TELF] [varchar](10) NULL,
	[DEC_FAX] [varchar](10) NULL,
	[DEC_EMAI] [varchar](50) NULL,
	[DEC_NIF] [varchar](18) NOT NULL,
	[DEC_TNIF] [int] NOT NULL,
	[DEC_CEDU] [varchar](18) NULL,
	[DEC_NCA1] [varchar](17) NULL,
	[DEC_ACA1] [varchar](4) NULL,
	[DEC_TCA1] [varchar](1) NULL,
	[DEC_INA1] [bit] NOT NULL,
	[DEC_NCA2] [varchar](17) NULL,
	[DEC_ACA2] [varchar](4) NULL,
	[DEC_TCA2] [varchar](1) NULL,
	[DEC_INA2] [bit] NOT NULL,
	[DEC_NCA3] [varchar](17) NULL,
	[DEC_ACA3] [varchar](4) NULL,
	[DEC_TCA3] [varchar](1) NULL,
	[DEC_INA3] [bit] NOT NULL,
	[DEC_NCA4] [varchar](17) NULL,
	[DEC_ACA4] [varchar](4) NULL,
	[DEC_TCA4] [varchar](1) NULL,
	[DEC_INA4] [bit] NOT NULL,
	[DEC_NCA5] [varchar](17) NULL,
	[DEC_ACA5] [varchar](4) NULL,
	[DEC_TCA5] [varchar](1) NULL,
	[DEC_INA5] [bit] NOT NULL,
	[FLE_CODI] [int] NULL,
	[DEC_MPAG] [varchar](1) NULL,
	[DEC_TFIA] [varchar](17) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[DEC_TIPO] [int] NOT NULL,
	[DEC_NPRO] [int] NULL,
	[DEC_XIEM] [varchar](35) NULL,
	[DEC_XPPE] [varchar](3) NULL,
	[DEC_LWIN] [bit] NOT NULL,
	[DEC_PWIN] [varchar](30) NULL,
	[DEC_CEPO] [varchar](13) NULL,
	[DEC_EMLX] [varchar](50) NULL,
	[DEC_EMPO] [varchar](50) NULL,
	[DEC_AURS] [varchar](25) NULL,
	[DEC_DTRS] [datetime] NULL,
	[DOC_CODI] [varchar](5) NULL,
	[DEC_NAOE] [varchar](41) NULL,
	[DEC_DTOE] [datetime] NULL,
	[DOC_CDOE] [varchar](5) NULL,
	[DEC_FXOE] [int] NOT NULL,
	[DEC_ARSI] [varchar](35) NULL,
	[DEC_DRSI] [datetime] NULL,
	[DOC_CODI1] [varchar](5) NULL,
	[DEC_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[ALF_CODI1] [varchar](8) NULL,
	[DEC_CCA1] [varchar](4) NULL,
	[DEC_OCA1] [varchar](35) NULL,
	[ALF_CODI2] [varchar](8) NULL,
	[DEC_CCA2] [varchar](4) NULL,
	[DEC_OCA2] [varchar](35) NULL,
	[ALF_CODI3] [varchar](8) NULL,
	[DEC_CCA3] [varchar](4) NULL,
	[DEC_OCA3] [varchar](35) NULL,
	[ALF_CODI4] [varchar](8) NULL,
	[DEC_CCA4] [varchar](4) NULL,
	[DEC_OCA4] [varchar](35) NULL,
	[ALF_CODI5] [varchar](8) NULL,
	[DEC_CCA5] [varchar](4) NULL,
	[DEC_OCA5] [varchar](35) NULL,
	[DEC_WSEP] [varchar](250) NULL,
	[DEC_WSUS] [varchar](50) NULL,
	[DEC_WSPW] [varbinary](128) NULL,
	[DEC_WSPC] [varchar](250) NULL,
	[DEC_WSWC] [varbinary](128) NULL,
	[DEC_XNRA] [bit] NOT NULL,
	[DEC_EAOE] [varchar](4) NULL,
	[DOC_CODI2] [varchar](5) NULL,
	[DEC_WSEX] [varchar](250) NULL,
 CONSTRAINT [PK_TAB_DECL] PRIMARY KEY CLUSTERED 
(
	[DEC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_DECL] UNIQUE NONCLUSTERED 
(
	[DEC_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DECL] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DECL] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DECL] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DECL] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DECL] TO [public] AS [dbo]
/****** Object:  Table [TAB_DECR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DECR](
	[DCR_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[DEC_CODI] [varchar](6) NOT NULL,
	[DCR_TIPO] [tinyint] NOT NULL,
	[EAD_CODI] [varchar](8) NULL,
	[DCR_NOME] [varchar](70) NOT NULL,
	[DCR_TELE] [varchar](10) NOT NULL,
	[DCR_EMAI] [varchar](100) NOT NULL,
	[DCR_IDST] [varchar](20) NOT NULL,
 CONSTRAINT [PK_TAB_DECR] PRIMARY KEY CLUSTERED 
(
	[DCR_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_TAB_DECR] UNIQUE NONCLUSTERED 
(
	[DEC_CODI] ASC,
	[DCR_TIPO] ASC,
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DECR] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DECR] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DECR] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DECR] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DECR] TO [public] AS [dbo]
/****** Object:  Table [TAB_DECS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DECS](
	[DCS_CODI] [varchar](18) NOT NULL,
	[DCS_NOME] [varchar](70) NOT NULL,
	[DCS_MORA] [varchar](70) NOT NULL,
	[DCS_CPOS] [varchar](12) NOT NULL,
	[DCS_LOCA] [varchar](35) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[DCS_NNIF] [varchar](17) NOT NULL,
	[DCS_TDEC] [int] NOT NULL,
	[DCS_PNPR] [int] NOT NULL,
	[DCS_INAC] [bit] NOT NULL,
	[DCS_PPEN] [varchar](3) NOT NULL,
	[EAD_CODI] [varchar](8) NULL,
	[LEM_CODI] [varchar](25) NULL,
	[LME_CODI] [varchar](17) NULL,
	[DCS_IESC] [varchar](1) NULL,
	[DCS_AURS] [varchar](25) NULL,
	[DCS_DTRS] [datetime] NULL,
	[DOC_CODI] [varchar](5) NULL,
	[DCS_NAOE] [varchar](41) NULL,
	[DCS_DTOE] [datetime] NULL,
	[DOC_CDOE] [varchar](5) NULL,
 CONSTRAINT [PK_TAB_DECS] PRIMARY KEY CLUSTERED 
(
	[DCS_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DECS] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DECS] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DECS] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DECS] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DECS] TO [public] AS [dbo]
/****** Object:  Table [TAB_DESA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DESA](
	[DES_CODI] [varchar](25) NOT NULL,
	[DES_DESC] [varchar](60) NOT NULL,
 CONSTRAINT [PK_TAB_DESA] PRIMARY KEY CLUSTERED 
(
	[DES_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DESA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DESA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DESA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DESA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DESA] TO [public] AS [dbo]
/****** Object:  Table [TAB_DINE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DINE](
	[DIN_CODI] [int] NOT NULL,
	[DIN_NOME] [varchar](70) NOT NULL,
	[DIN_POCC] [varchar](15) NULL,
	[DIN_POCS] [varchar](15) NULL,
	[DIN_CCDO] [bit] NOT NULL,
	[DIN_PCDO] [int] NULL,
	[DIN_CNAV] [bit] NOT NULL,
	[DIN_PNAV] [int] NULL,
	[DIN_UCTE] [bit] NOT NULL,
	[DIN_AGRA] [numeric](38, 6) NOT NULL,
	[DIN_IMSL] [bit] NOT NULL,
	[DIN_SPCD] [varchar](15) NULL,
	[DIN_SPSC] [varchar](15) NULL,
	[DIN_FCLC] [varchar](4000) NULL,
	[CCO_CODI] [varchar](4) NULL,
	[DIN_FCLE] [varchar](4000) NULL,
	[DIN_ISEN] [bit] NOT NULL,
	[IIV_CODI] [varchar](3) NULL,
	[IIV_MENC] [varchar](100) NULL,
	[DIN_FCLD] [varchar](4000) NULL,
	[DIN_FCLG] [varchar](4000) NULL,
 CONSTRAINT [PK_TAB_DINE] PRIMARY KEY CLUSTERED 
(
	[DIN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DINE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DINE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DINE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DINE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DINE] TO [public] AS [dbo]
/****** Object:  Table [TAB_DOCU]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_DOCU](
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
	[DOC_RSDA] [bit] NOT NULL,
	[DOC_IOBC] [bit] NOT NULL,
	[DOC_TRAN] [bit] NOT NULL,
	[DOC_DESP] [bit] NOT NULL,
	[DOC_EXPT] [bit] NOT NULL,
	[DOC_CA40] [bit] NOT NULL,
	[DOC_TDNU] [int] NULL,
	[DOC_TDDT] [int] NULL,
	[INF_CODI] [varchar](8) NULL,
	[DOC_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[DOC_DTRA] [bit] NOT NULL,
	[DOC_AUTZ] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_DOCU] PRIMARY KEY CLUSTERED 
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_DOCU] UNIQUE NONCLUSTERED 
(
	[DOC_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_DOCU] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_DOCU] TO [public] AS [dbo]
GRANT INSERT ON [TAB_DOCU] TO [public] AS [dbo]
GRANT SELECT ON [TAB_DOCU] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_DOCU] TO [public] AS [dbo]
/****** Object:  Table [TAB_EADD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_EADD](
	[ADD_CODI] [int] NOT NULL,
	[EAD_CODI] [varchar](8) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
 CONSTRAINT [PK_TAB_EADD] PRIMARY KEY CLUSTERED 
(
	[ADD_CODI] ASC,
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_EADD] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_EADD] TO [public] AS [dbo]
GRANT INSERT ON [TAB_EADD] TO [public] AS [dbo]
GRANT SELECT ON [TAB_EADD] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_EADD] TO [public] AS [dbo]
/****** Object:  Table [TAB_EADM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_EADM](
	[EAD_CODI] [varchar](8) NOT NULL,
	[INF_CODI] [varchar](8) NOT NULL,
 CONSTRAINT [PK_TAB_EADM] PRIMARY KEY CLUSTERED 
(
	[EAD_CODI] ASC,
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_EADM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_EADM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_EADM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_EADM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_EADM] TO [public] AS [dbo]
/****** Object:  Table [TAB_EADU]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_EADU](
	[EAD_CODI] [varchar](8) NOT NULL,
	[EAD_NOME] [varchar](35) NOT NULL,
	[EAD_SLAD] [varchar](17) NULL,
	[EAD_EPAR] [bit] NOT NULL,
	[EAD_EPAS] [bit] NOT NULL,
	[EAD_EDES] [bit] NOT NULL,
	[EAD_CMEU] [bit] NOT NULL,
	[MTR_CODI] [varchar](2) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[EAD_CODI1] [varchar](8) NULL,
	[LME_CODI] [varchar](17) NULL,
	[EAD_CONT] [int] NULL,
	[EAD_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_EADU] PRIMARY KEY CLUSTERED 
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_EADU] UNIQUE NONCLUSTERED 
(
	[EAD_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_EADU] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_EADU] TO [public] AS [dbo]
GRANT INSERT ON [TAB_EADU] TO [public] AS [dbo]
GRANT SELECT ON [TAB_EADU] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_EADU] TO [public] AS [dbo]
/****** Object:  Table [TAB_EEMI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_EEMI](
	[EEM_CODI] [int] NOT NULL,
	[EEM_DESC] [varchar](35) NULL,
 CONSTRAINT [PK_TAB_EEMI] PRIMARY KEY CLUSTERED 
(
	[EEM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_EEMI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_EEMI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_EEMI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_EEMI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_EEMI] TO [public] AS [dbo]
/****** Object:  Table [TAB_EJUR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_EJUR](
	[EJU_CODI] [varchar](8) NOT NULL,
	[EJU_NOME] [varchar](70) NOT NULL,
	[EJU_BENI] [int] NOT NULL,
	[EJU_ONUS] [bit] NOT NULL,
	[EJU_LEGI] [varchar](70) NOT NULL,
 CONSTRAINT [PK_TAB_EJUR] PRIMARY KEY CLUSTERED 
(
	[EJU_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_EJUR] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_EJUR] TO [public] AS [dbo]
GRANT INSERT ON [TAB_EJUR] TO [public] AS [dbo]
GRANT SELECT ON [TAB_EJUR] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_EJUR] TO [public] AS [dbo]
/****** Object:  Table [TAB_EMIT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_EMIT](
	[EMT_CODI] [int] NOT NULL,
	[DEC_CODI] [varchar](6) NULL,
	[ALF_CODI] [varchar](8) NULL,
	[EAD_CODI] [varchar](8) NULL,
	[CLI_CODI] [varchar](18) NULL,
	[EMT_NVIA] [int] NULL,
 CONSTRAINT [PK_TAB_EMIT] PRIMARY KEY CLUSTERED 
(
	[EMT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_EMIT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_EMIT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_EMIT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_EMIT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_EMIT] TO [public] AS [dbo]
/****** Object:  Table [TAB_EOFI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_EOFI](
	[EOF_CODI] [varchar](18) NOT NULL,
	[EOF_NOME] [varchar](70) NOT NULL,
 CONSTRAINT [PK_TAB_EOFI] PRIMARY KEY CLUSTERED 
(
	[EOF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_EOFI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_EOFI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_EOFI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_EOFI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_EOFI] TO [public] AS [dbo]
/****** Object:  Table [TAB_FALM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_FALM](
	[FAL_CODI] [int] NOT NULL,
	[FTA_CODI] [varchar](2) NOT NULL,
	[FAL_LIMD] [numeric](38, 6) NULL,
	[FAL_LIMA] [numeric](38, 6) NULL,
	[FAL_VALO] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_FALM] PRIMARY KEY CLUSTERED 
(
	[FAL_CODI] ASC,
	[FTA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_FALM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_FALM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_FALM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_FALM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_FALM] TO [public] AS [dbo]
/****** Object:  Table [TAB_FFAB]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_FFAB](
	[FFA_CODI] [int] NOT NULL,
	[FFA_DESC] [varchar](35) NULL,
 CONSTRAINT [PK_TAB_FFAB] PRIMARY KEY CLUSTERED 
(
	[FFA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_FFAB] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_FFAB] TO [public] AS [dbo]
GRANT INSERT ON [TAB_FFAB] TO [public] AS [dbo]
GRANT SELECT ON [TAB_FFAB] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_FFAB] TO [public] AS [dbo]
/****** Object:  Table [TAB_FINC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_FINC](
	[FIN_CODI] [int] NOT NULL,
	[FIN_DESC] [varchar](70) NOT NULL,
	[FIN_VFOB] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_FINC] PRIMARY KEY CLUSTERED 
(
	[FIN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_FINC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_FINC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_FINC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_FINC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_FINC] TO [public] AS [dbo]
/****** Object:  Table [TAB_FLEG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_FLEG](
	[FLE_CODI] [int] NOT NULL,
	[FLE_NOME] [varchar](70) NOT NULL,
	[FLE_STAT] [int] NOT NULL,
 CONSTRAINT [PK_TAB_FLEG] PRIMARY KEY CLUSTERED 
(
	[FLE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_FLEG] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_FLEG] TO [public] AS [dbo]
GRANT INSERT ON [TAB_FLEG] TO [public] AS [dbo]
GRANT SELECT ON [TAB_FLEG] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_FLEG] TO [public] AS [dbo]
/****** Object:  Table [TAB_FORN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_FORN](
	[FOR_CODI] [varchar](18) NOT NULL,
	[FOR_CEAN] [varchar](13) NULL,
	[FOR_INAC] [bit] NOT NULL,
	[FOR_DESP] [bit] NOT NULL,
	[FOR_NOME] [varchar](70) NULL,
	[FOR_MORA] [varchar](70) NULL,
	[FOR_LOCA] [varchar](35) NULL,
	[FOR_CPOS] [varchar](12) NULL,
	[FOR_LPOS] [varchar](35) NULL,
	[FOR_TELF] [varchar](10) NULL,
	[FOR_FAX] [varchar](10) NULL,
	[FOR_EMAI] [varchar](50) NULL,
	[FOR_WEB] [varchar](50) NULL,
	[FOR_NIF] [varchar](18) NULL,
	[FOR_TNIF] [int] NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[FOR_IROR] [int] NOT NULL,
	[FOR_INFO] [text] NULL,
	[CLI_CODI] [varchar](18) NULL,
	[ALF_CODI] [varchar](8) NULL,
	[TDE_CODI] [varchar](4) NULL,
	[CEN_CODI] [varchar](3) NULL,
	[PAI_CODI1] [varchar](2) NULL,
	[FOR_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_FORN] PRIMARY KEY CLUSTERED 
(
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_FORN] UNIQUE NONCLUSTERED 
(
	[FOR_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_FORN] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_FORN] TO [public] AS [dbo]
GRANT INSERT ON [TAB_FORN] TO [public] AS [dbo]
GRANT SELECT ON [TAB_FORN] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_FORN] TO [public] AS [dbo]
/****** Object:  Table [TAB_FTAC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_FTAC](
	[FTA_CODI] [varchar](2) NOT NULL,
	[FTA_DESC] [varchar](35) NULL,
	[FTA_LIMI] [numeric](38, 6) NOT NULL,
	[FTA_VLIM] [numeric](38, 6) NOT NULL,
	[FTA_VADI] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_FTAC] PRIMARY KEY CLUSTERED 
(
	[FTA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_FTAC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_FTAC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_FTAC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_FTAC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_FTAC] TO [public] AS [dbo]
/****** Object:  Table [TAB_GPAI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_GPAI](
	[GPA_CODI] [varchar](6) NOT NULL,
	[GPA_DESC] [varchar](35) NULL,
 CONSTRAINT [PK_TAB_GPAI] PRIMARY KEY CLUSTERED 
(
	[GPA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_GPAI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_GPAI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_GPAI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_GPAI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_GPAI] TO [public] AS [dbo]
/****** Object:  Table [TAB_HTEC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_HTEC](
	[HTE_CODI] [varchar](20) NOT NULL,
	[HTE_HOMO] [varchar](20) NULL,
	[MAR_CODI] [int] NOT NULL,
	[HTE_MODE] [varchar](35) NULL,
	[CAT_CODI] [varchar](2) NOT NULL,
	[TVE_CODI] [varchar](3) NOT NULL,
	[HTE_NCIL] [int] NULL,
	[HTE_CILI] [int] NULL,
	[HTE_PNFR] [varchar](10) NULL,
	[HTE_PNRT] [varchar](10) NULL,
	[HTE_REBO] [varchar](10) NULL,
	[HTE_PDEL] [varchar](10) NULL,
	[TCO_CODI] [varchar](2) NOT NULL,
	[HTE_NPTO] [int] NULL,
	[HTE_NPDI] [int] NULL,
	[HTE_NPES] [int] NULL,
	[HTE_NPRE] [int] NULL,
	[HTE_NLUG] [int] NOT NULL,
	[HTE_PESO] [int] NULL,
	[HTE_TARA] [int] NULL,
	[TCX_CODI] [varchar](2) NULL,
	[HTE_COMP] [varchar](10) NULL,
	[HTE_LARG] [varchar](10) NULL,
	[HTE_DEEX] [varchar](10) NULL,
	[HTE_NMOT] [varchar](25) NULL,
	[HTE_NQUA] [varchar](25) NULL,
	[HTE_CCXC] [int] NULL,
	[HTE_ACXC] [int] NULL,
	[HTE_NEXM] [int] NULL,
	[HTE_ANTE] [varchar](2) NULL,
	[HTE_ECO2] [int] NULL,
	[HTE_OBSV] [text] NULL,
	[HTE_VISV] [numeric](38, 6) NOT NULL,
	[HTE_TABE] [varchar](1) NULL,
	[HTE_TCO2] [varchar](4) NULL,
	[HTE_AUTO] [int] NULL,
	[HTE_QUAL] [varchar](1) NULL,
	[HTE_EPAR] [varchar](6) NULL,
 CONSTRAINT [PK_TAB_HTEC] PRIMARY KEY CLUSTERED 
(
	[HTE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_HTEC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_HTEC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_HTEC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_HTEC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_HTEC] TO [public] AS [dbo]
/****** Object:  Table [TAB_IATA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_IATA](
	[PAE_CODI] [varchar](8) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[IAT_CODI] [varchar](6) NOT NULL,
 CONSTRAINT [PK_TAB_IATA] PRIMARY KEY CLUSTERED 
(
	[PAE_CODI] ASC,
	[PAI_CODI] ASC,
	[IAT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_IATA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_IATA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_IATA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_IATA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_IATA] TO [public] AS [dbo]
/****** Object:  Table [TAB_INFC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_INFC](
	[INF_CODI] [varchar](8) NOT NULL,
	[INF_DESI] [varchar](150) NULL,
	[INF_GARA] [bit] NOT NULL,
	[INF_EXPT] [bit] NOT NULL,
	[INF_NSTI] [bit] NOT NULL,
	[INF_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[INF_IMPC] [bit] NOT NULL,
	[INF_CANT] [varchar](5) NULL,
 CONSTRAINT [PK_TAB_INFC] PRIMARY KEY CLUSTERED 
(
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_INFC] UNIQUE NONCLUSTERED 
(
	[INF_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_INFC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_INFC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_INFC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_INFC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_INFC] TO [public] AS [dbo]
/****** Object:  Table [TAB_LEMB]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_LEMB](
	[LEM_CODI] [varchar](25) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAE_CODI] [varchar](8) NOT NULL,
	[LEM_CCOD] [varchar](20) NOT NULL,
	[LEM_DESC] [varchar](70) NULL,
	[EAD_CODI] [varchar](8) NULL,
 CONSTRAINT [PK_TAB_LEMB] PRIMARY KEY CLUSTERED 
(
	[LEM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_LEMB] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_LEMB] TO [public] AS [dbo]
GRANT INSERT ON [TAB_LEMB] TO [public] AS [dbo]
GRANT SELECT ON [TAB_LEMB] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_LEMB] TO [public] AS [dbo]
/****** Object:  Table [TAB_LMER]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_LMER](
	[LME_CODI] [varchar](17) NOT NULL,
	[LME_NOME] [varchar](70) NULL,
	[LME_FLUX] [int] NULL,
	[LME_GAEX] [int] NULL,
	[LME_PNRE] [int] NOT NULL,
	[LME_PNRS] [int] NOT NULL,
	[LME_IMPR] [varchar](250) NULL,
	[LME_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
 CONSTRAINT [PK_TAB_LMER] PRIMARY KEY CLUSTERED 
(
	[LME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_LMER] UNIQUE NONCLUSTERED 
(
	[LME_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_LMER] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_LMER] TO [public] AS [dbo]
GRANT INSERT ON [TAB_LMER] TO [public] AS [dbo]
GRANT SELECT ON [TAB_LMER] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_LMER] TO [public] AS [dbo]
/****** Object:  Table [TAB_MARC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MARC](
	[MAR_CODI] [int] NOT NULL,
	[MAR_NOME] [varchar](35) NULL,
 CONSTRAINT [PK_TAB_MARC] PRIMARY KEY CLUSTERED 
(
	[MAR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MARC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MARC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MARC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MARC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MARC] TO [public] AS [dbo]
/****** Object:  Table [TAB_MCDO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MCDO](
	[CLI_CODI] [varchar](18) NOT NULL,
	[MCF_CODI] [int] NOT NULL,
	[DDO_CODI] [int] NOT NULL,
	[MCD_POSI] [int] NOT NULL,
	[MCD_VALO] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_MCDO] PRIMARY KEY CLUSTERED 
(
	[CLI_CODI] ASC,
	[MCF_CODI] ASC,
	[DDO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MCDO] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MCDO] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MCDO] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MCDO] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MCDO] TO [public] AS [dbo]
/****** Object:  Table [TAB_MCFT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MCFT](
	[CLI_CODI] [varchar](18) NOT NULL,
	[MCF_CODI] [int] NOT NULL,
	[MCF_DESC] [varchar](50) NULL,
	[NDE_CODI] [varchar](3) NOT NULL,
	[MCF_VAGR] [numeric](38, 6) NULL,
	[MCF_VDES] [numeric](38, 6) NULL,
	[MCF_VALO] [numeric](38, 6) NULL,
	[MCF_OBSV] [text] NULL,
 CONSTRAINT [PK_TAB_MFC] PRIMARY KEY CLUSTERED 
(
	[CLI_CODI] ASC,
	[MCF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MCFT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MCFT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MCFT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MCFT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MCFT] TO [public] AS [dbo]
/****** Object:  Table [TAB_MCIN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MCIN](
	[CLI_CODI] [varchar](18) NOT NULL,
	[MCF_CODI] [int] NOT NULL,
	[DIN_CODI] [int] NOT NULL,
	[MCI_POSI] [int] NOT NULL,
	[MCI_VALO] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_MCIN] PRIMARY KEY CLUSTERED 
(
	[CLI_CODI] ASC,
	[MCF_CODI] ASC,
	[DIN_CODI] ASC,
	[MCI_POSI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MCIN] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MCIN] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MCIN] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MCIN] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MCIN] TO [public] AS [dbo]
/****** Object:  Table [TAB_MCRE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MCRE](
	[MCR_CODI] [int] NOT NULL,
	[MCR_DESC] [varchar](50) NOT NULL,
 CONSTRAINT [PK_TAB_MCRE] PRIMARY KEY CLUSTERED 
(
	[MCR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MCRE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MCRE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MCRE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MCRE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MCRE] TO [public] AS [dbo]
/****** Object:  Table [TAB_MIAU]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MIAU](
	[MIA_CODI] [varchar](2) NOT NULL,
	[MIA_DESC] [varchar](150) NULL,
	[MIA_OBRI] [bit] NOT NULL,
	[MIA_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_MIAU] PRIMARY KEY CLUSTERED 
(
	[MIA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_MIAU] UNIQUE NONCLUSTERED 
(
	[MIA_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MIAU] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MIAU] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MIAU] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MIAU] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MIAU] TO [public] AS [dbo]
/****** Object:  Table [TAB_MIEC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MIEC](
	[MIE_CODI] [varchar](25) NOT NULL,
	[MIE_DESC] [varchar](35) NULL,
	[MIE_CODE] [varchar](50) NOT NULL,
 CONSTRAINT [PK_TAB_MIEC] PRIMARY KEY CLUSTERED 
(
	[MIE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MIEC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MIEC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MIEC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MIEC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MIEC] TO [public] AS [dbo]
/****** Object:  Table [TAB_MNDO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MNDO](
	[NDE_CODI] [varchar](3) NOT NULL,
	[MNF_CODI] [int] NOT NULL,
	[DDO_CODI] [int] NOT NULL,
	[DDO_NOME] [varchar](70) NOT NULL,
	[MND_VALO] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_MNDO] PRIMARY KEY CLUSTERED 
(
	[NDE_CODI] ASC,
	[MNF_CODI] ASC,
	[DDO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MNDO] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MNDO] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MNDO] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MNDO] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MNDO] TO [public] AS [dbo]
/****** Object:  Table [TAB_MNFT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MNFT](
	[NDE_CODI] [varchar](3) NOT NULL,
	[MNF_CODI] [int] NOT NULL,
	[NMF_DESC] [varchar](50) NULL,
	[MNF_VAGR] [numeric](38, 6) NOT NULL,
	[MNF_VDES] [numeric](38, 6) NOT NULL,
	[MNF_VALO] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_MNFT] PRIMARY KEY CLUSTERED 
(
	[NDE_CODI] ASC,
	[MNF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MNFT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MNFT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MNFT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MNFT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MNFT] TO [public] AS [dbo]
/****** Object:  Table [TAB_MNIN]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MNIN](
	[NDE_CODI] [varchar](3) NOT NULL,
	[MNF_CODI] [int] NOT NULL,
	[DIN_CODI] [int] NOT NULL,
	[DIN_NOME] [varchar](70) NOT NULL,
	[MNI_VALO] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_MNIN] PRIMARY KEY CLUSTERED 
(
	[NDE_CODI] ASC,
	[MNF_CODI] ASC,
	[DIN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MNIN] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MNIN] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MNIN] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MNIN] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MNIN] TO [public] AS [dbo]
/****** Object:  Table [TAB_MTRA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_MTRA](
	[MTR_CODI] [varchar](2) NOT NULL,
	[MTR_NOME] [varchar](35) NULL,
	[MTR_DOP1] [varchar](20) NULL,
	[MTR_VOP1] [numeric](38, 6) NULL,
	[MTR_DOP2] [varchar](20) NULL,
	[MTR_VOP2] [numeric](38, 6) NULL,
	[MTR_DOP3] [varchar](20) NULL,
	[MTR_VOP3] [numeric](38, 6) NULL,
	[MTR_DOP4] [varchar](20) NULL,
	[MTR_VOP4] [numeric](38, 6) NULL,
	[MTR_DOP5] [varchar](20) NULL,
	[MTR_VOP5] [numeric](38, 6) NULL,
	[MTR_PTAX] [bit] NOT NULL,
	[MTR_VPVL] [int] NULL,
	[MTR_DATA] [datetime] NULL,
	[MTR_TIPO] [int] NULL,
	[MTR_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[MTR_OPAU] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_MTRA] PRIMARY KEY CLUSTERED 
(
	[MTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_MTRA] UNIQUE NONCLUSTERED 
(
	[MTR_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_MTRA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MTRA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MTRA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MTRA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MTRA] TO [public] AS [dbo]
/****** Object:  Table [TAB_MTRO]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [TAB_MTRO](
	[MTO_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[MTR_IDTY] [int] NOT NULL,
	[MTO_LMNP] [numeric](38, 6) NOT NULL,
	[MTO_LMXP] [numeric](38, 6) NOT NULL,
	[MTO_LMNV] [numeric](38, 6) NOT NULL,
	[MTO_LMXV] [numeric](38, 6) NOT NULL,
	[MTO_VOPT] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_MTRO] PRIMARY KEY CLUSTERED 
(
	[MTO_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_TAB_MTRO] UNIQUE NONCLUSTERED 
(
	[MTR_IDTY] ASC,
	[MTO_LMNP] ASC,
	[MTO_LMXP] ASC,
	[MTO_LMNV] ASC,
	[MTO_LMXV] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [TAB_MTRO] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_MTRO] TO [public] AS [dbo]
GRANT INSERT ON [TAB_MTRO] TO [public] AS [dbo]
GRANT SELECT ON [TAB_MTRO] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_MTRO] TO [public] AS [dbo]
/****** Object:  Table [TAB_NDES]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_NDES](
	[NDE_CODI] [varchar](3) NOT NULL,
	[NDE_NOME] [varchar](35) NOT NULL,
	[NDE_TIVA] [numeric](38, 6) NOT NULL,
	[NDE_AHON] [numeric](38, 6) NULL,
	[NDE_DHON] [numeric](38, 6) NULL,
	[NDE_IIVA] [varchar](100) NULL,
	[NDE_FORM] [text] NULL,
	[NDE_PREF] [varchar](2) NULL,
	[NDE_RADI] [varchar](3) NULL,
	[NDE_PENV] [varchar](150) NULL,
	[NDE_STCK] [bit] NOT NULL,
	[NDE_CTEN] [bit] NOT NULL,
	[NDE_LMAX] [numeric](38, 6) NULL,
	[NDE_VLKG] [numeric](38, 6) NULL,
	[NDE_FEDI] [bit] NOT NULL,
	[NDE_WDES] [varchar](35) NULL,
	[NDE_OBSV] [text] NULL,
	[NDE_UTTD] [bit] NOT NULL,
	[NDE_AADT] [bit] NOT NULL,
	[NDE_NDAL] [int] NOT NULL,
	[NDE_TLCV] [int] NULL,
	[TDO_DOCU] [varchar](4) NULL,
	[RFC_CODI] [int] NULL,
	[IIV_CODI] [varchar](3) NULL,
	[NDE_CRCO] [bit] NOT NULL,
	[SIN_CODI] [varchar](8) NULL,
	[FUP_CODI] [int] NULL,
	[CCO_CODI] [varchar](4) NULL,
	[CBT_IDEN] [int] NULL,
	[NDE_DRDR] [bit] NOT NULL,
	[NDE_GADT] [bit] NOT NULL,
	[NDE_IDDP] [varchar](18) NULL,
	[NDE_CTXT] [int] NULL,
	[NDE_PART] [bit] NOT NULL,
	[NDE_CODI1] [varchar](3) NULL,
	[NDE_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[NDE_VDAR] [bit] NOT NULL,
	[NDE_CODI2] [varchar](3) NULL,
	[NDE_CODI3] [varchar](3) NULL,
	[NDE_RETO] [bit] NOT NULL,
	[NDE_OSER] [bit] NOT NULL,
	[NDE_VEXI] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_NDES] PRIMARY KEY CLUSTERED 
(
	[NDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_NDES] UNIQUE NONCLUSTERED 
(
	[NDE_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_NDES] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_NDES] TO [public] AS [dbo]
GRANT INSERT ON [TAB_NDES] TO [public] AS [dbo]
GRANT SELECT ON [TAB_NDES] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_NDES] TO [public] AS [dbo]
/****** Object:  Table [TAB_NNC8]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_NNC8](
	[NC8_EANO] [int] NOT NULL,
	[NC8_CODI] [varchar](10) NOT NULL,
	[NC8_DESG] [text] NOT NULL,
	[NC8_USPL] [bit] NOT NULL,
	[NC8_TIVA] [numeric](38, 6) NOT NULL,
	[NC8_TMLQ] [bit] NOT NULL,
	[NC8_PMDU] [numeric](38, 6) NOT NULL,
	[NC8_REFI] [int] NULL,
 CONSTRAINT [PK_TAB_NNC8] PRIMARY KEY CLUSTERED 
(
	[NC8_EANO] ASC,
	[NC8_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_NNC8] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_NNC8] TO [public] AS [dbo]
GRANT INSERT ON [TAB_NNC8] TO [public] AS [dbo]
GRANT SELECT ON [TAB_NNC8] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_NNC8] TO [public] AS [dbo]
/****** Object:  Table [TAB_NTRA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_NTRA](
	[NTR_CODI] [varchar](2) NOT NULL,
	[NTR_NOME] [varchar](70) NOT NULL,
 CONSTRAINT [PK_TAB_NTRA] PRIMARY KEY CLUSTERED 
(
	[NTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_NTRA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_NTRA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_NTRA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_NTRA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_NTRA] TO [public] AS [dbo]
/****** Object:  Table [TAB_NUMD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_NUMD](
	[TDO_DOCU] [varchar](4) NOT NULL,
	[NUM_EANO] [int] NOT NULL,
	[NUM_TDOC] [int] NOT NULL,
	[NUM_NUME] [int] NULL,
	[NUM_DATA] [datetime] NULL,
	[NUM_CVAT] [varchar](30) NULL,
	[NUM_NVAT] [int] NULL,
	[NUM_DVAT] [datetime] NULL,
	[NUM_UVAT] [varchar](30) NULL,
	[NUM_TVAT] [datetime] NULL,
	[NUM_SERI] [varchar](20) NULL,
	[NUM_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_NUMD] PRIMARY KEY CLUSTERED 
(
	[TDO_DOCU] ASC,
	[NUM_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_NUMD] UNIQUE NONCLUSTERED 
(
	[NUM_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_NUMD] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_NUMD] TO [public] AS [dbo]
GRANT INSERT ON [TAB_NUMD] TO [public] AS [dbo]
GRANT SELECT ON [TAB_NUMD] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_NUMD] TO [public] AS [dbo]
/****** Object:  Table [TAB_PAER]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PAER](
	[PAE_CODI] [varchar](8) NOT NULL,
	[PAE_NOME] [varchar](35) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAE_TAXA] [numeric](38, 6) NULL,
	[FTA_CODI] [varchar](2) NULL,
	[PAE_TIPO] [tinyint] NOT NULL,
	[EAD_CODI] [varchar](8) NULL,
 CONSTRAINT [PK_TAB_PAER] PRIMARY KEY CLUSTERED 
(
	[PAE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PAER] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PAER] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PAER] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PAER] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PAER] TO [public] AS [dbo]
/****** Object:  Table [TAB_PAIS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PAIS](
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAI_NOME] [varchar](35) NULL,
	[PAI_PREF] [varchar](3) NOT NULL,
	[PAI_SUFI] [varchar](2) NOT NULL,
	[PAI_OLCA] [int] NULL,
	[PAI_PRE1] [bit] NOT NULL,
	[PAI_C2E1] [varchar](6) NULL,
	[PAI_C4E1] [varchar](6) NULL,
	[PAI_PATR] [bit] NOT NULL,
	[FTA_CODI] [varchar](2) NULL,
	[PAI_IFRE] [numeric](38, 6) NOT NULL,
	[PAI_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[PAI_ZEUR] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PAIS] PRIMARY KEY CLUSTERED 
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_PAIS] UNIQUE NONCLUSTERED 
(
	[PAI_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PAIS] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PAIS] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PAIS] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PAIS] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PAIS] TO [public] AS [dbo]
/****** Object:  Table [TAB_PAPL]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PAPL](
	[PAP_CODI] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[PAP_TAXA] [numeric](38, 6) NOT NULL,
	[PAP_TXIS] [numeric](38, 6) NOT NULL,
	[RRE_CDIS] [int] NOT NULL,
	[PAP_TXRD] [numeric](38, 6) NOT NULL,
	[RRE_CDRD] [int] NOT NULL,
	[PAP_TXIN] [numeric](38, 6) NOT NULL,
	[RRE_CDIN] [int] NOT NULL,
	[PAP_TXNR] [numeric](38, 6) NOT NULL,
	[RRE_CDNR] [int] NOT NULL,
	[PAP_VERS] [varchar](100) NULL,
	[PAP_PAUT] [bit] NOT NULL,
	[PAP_PSRV] [varchar](100) NULL,
	[PAP_PPRT] [int] NULL,
	[PAP_PUSE] [varchar](100) NULL,
	[PAP_PPWD] [varchar](100) NULL,
	[PAP_KNIF] [varchar](100) NULL,
 CONSTRAINT [PK_TAB_PAPL] PRIMARY KEY CLUSTERED 
(
	[PAP_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PAPL] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PAPL] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PAPL] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PAPL] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PAPL] TO [public] AS [dbo]
/****** Object:  Table [TAB_PCBE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PCBE](
	[CBE_IDEN] [int] NOT NULL,
	[CBT_IDEN] [int] NOT NULL,
	[CLI_CODI] [varchar](18) NOT NULL,
	[CBE_AHON] [bit] NOT NULL,
	[CBE_VHON] [numeric](38, 6) NOT NULL,
	[CBE_PHON] [numeric](38, 6) NOT NULL,
	[CBE_PDES] [numeric](38, 6) NOT NULL,
	[CBE_ACAU] [bit] NOT NULL,
	[CBE_VCAU] [numeric](38, 6) NOT NULL,
	[CBE_PCAU] [numeric](38, 6) NOT NULL,
	[CBE_PVIL] [numeric](38, 6) NOT NULL,
	[CBE_UDTL] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PCBE] PRIMARY KEY CLUSTERED 
(
	[CBE_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PCBE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PCBE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PCBE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PCBE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PCBE] TO [public] AS [dbo]
/****** Object:  Table [TAB_PCBI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [TAB_PCBI](
	[CBI_IDEN] [int] NOT NULL,
	[DIN_CODI] [int] NULL,
	[DIN_CODI1] [int] NULL,
	[DIN_CODI2] [int] NULL,
	[CBI_NADF] [int] NOT NULL,
	[CBI_VLAD] [numeric](38, 6) NOT NULL,
	[DIN_CODI3] [int] NULL,
	[CBI_VLCO] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_PCBI] PRIMARY KEY CLUSTERED 
(
	[CBI_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [TAB_PCBI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PCBI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PCBI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PCBI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PCBI] TO [public] AS [dbo]
/****** Object:  Table [TAB_PCBL]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [TAB_PCBL](
	[CBL_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[CBT_IDEN] [int] NOT NULL,
	[CBL_LINF] [numeric](38, 6) NOT NULL,
	[CBL_LSUP] [numeric](38, 6) NOT NULL,
	[CBL_VHON] [numeric](38, 6) NOT NULL,
	[CBL_PHON] [numeric](38, 6) NOT NULL,
	[CBL_VCAU] [numeric](38, 6) NOT NULL,
	[CBL_PCAU] [numeric](38, 6) NOT NULL,
	[CBL_TIPO] [int] NOT NULL,
	[CBL_MHON] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_PCBL] PRIMARY KEY CLUSTERED 
(
	[CBL_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [TAB_PCBL] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PCBL] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PCBL] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PCBL] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PCBL] TO [public] AS [dbo]
/****** Object:  Table [TAB_PCBT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PCBT](
	[CBT_IDEN] [int] NOT NULL,
	[CBI_IDEN] [int] NOT NULL,
	[CBT_DESC] [varchar](100) NOT NULL,
	[CBT_VREF] [int] NOT NULL,
	[CBT_VRFP] [int] NOT NULL,
 CONSTRAINT [PK_TAB_PCBT] PRIMARY KEY CLUSTERED 
(
	[CBT_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PCBT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PCBT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PCBT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PCBT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PCBT] TO [public] AS [dbo]
/****** Object:  Table [TAB_PCBX]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [TAB_PCBX](
	[CBX_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[CBE_IDEN] [int] NOT NULL,
	[CBX_LINF] [numeric](38, 6) NOT NULL,
	[CBX_LSUP] [numeric](38, 6) NOT NULL,
	[CBX_VHON] [numeric](38, 6) NOT NULL,
	[CBX_PDES] [numeric](38, 6) NOT NULL,
	[CBX_PHON] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_PCBX] PRIMARY KEY CLUSTERED 
(
	[CBX_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [TAB_PCBX] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PCBX] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PCBX] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PCBX] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PCBX] TO [public] AS [dbo]
/****** Object:  Table [TAB_PDCA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PDCA](
	[DCA_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[PDE_CODI] [int] NOT NULL,
	[DCA_EMAI] [varchar](500) NOT NULL,
	[DCA_ECDI] [bit] NOT NULL,
	[DCA_ECFI] [bit] NOT NULL,
	[DCA_ECAI] [bit] NOT NULL,
	[DCA_ECDE] [bit] NOT NULL,
	[DCA_ECFE] [bit] NOT NULL,
	[DCA_ECAE] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PDCA] PRIMARY KEY CLUSTERED 
(
	[DCA_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PDCA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PDCA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PDCA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PDCA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PDCA] TO [public] AS [dbo]
/****** Object:  Table [TAB_PDDC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PDDC](
	[PDE_CODI] [int] NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
 CONSTRAINT [PK_TAB_PDDC] PRIMARY KEY CLUSTERED 
(
	[PDE_CODI] ASC,
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PDDC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PDDC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PDDC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PDDC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PDDC] TO [public] AS [dbo]
/****** Object:  Table [TAB_PDER]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PDER](
	[DER_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[PDE_CODI] [int] NOT NULL,
	[DER_MENS] [varchar](20) NOT NULL,
	[DER_ACTI] [bit] NOT NULL,
	[DER_EASS] [varchar](250) NULL,
	[DER_ETXT] [varchar](max) NULL,
 CONSTRAINT [PK_TAB_PDER] PRIMARY KEY CLUSTERED 
(
	[DER_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PDER] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PDER] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PDER] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PDER] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PDER] TO [public] AS [dbo]
/****** Object:  Table [TAB_PDES]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PDES](
	[PDE_CODI] [int] NOT NULL,
	[PDE_CIMP] [bit] NOT NULL,
	[PDE_CEXP] [bit] NOT NULL,
	[PDE_LFCT] [int] NOT NULL,
	[PDE_CONT] [bit] NOT NULL,
	[PDE_LIMP] [bit] NOT NULL,
	[PDE_LEXP] [bit] NOT NULL,
	[PDE_IEDI] [int] NULL,
	[PDE_VSIM] [numeric](38, 6) NOT NULL,
	[RRE_CDIM] [int] NOT NULL,
	[PDE_VSEX] [numeric](38, 6) NOT NULL,
	[RRE_CDEX] [int] NOT NULL,
	[PDE_TPOS] [numeric](38, 6) NULL,
	[RRE_CDPT] [int] NULL,
	[PDE_TALF] [numeric](38, 6) NULL,
	[RRE_CDAL] [int] NULL,
	[PDE_VIMP] [numeric](38, 6) NULL,
	[RRE_CDVI] [int] NULL,
	[PDE_MDV1] [numeric](38, 6) NULL,
	[PDE_EPEN] [varchar](150) NOT NULL,
	[PDE_EPRE] [varchar](150) NOT NULL,
	[PDE_EPBK] [varchar](150) NOT NULL,
	[PDE_EPPE] [varchar](3) NOT NULL,
	[PDE_XPEN] [varchar](150) NOT NULL,
	[PDE_XPRE] [varchar](150) NOT NULL,
	[PDE_XPBK] [varchar](150) NOT NULL,
	[PDE_NPRO] [int] NOT NULL,
	[PDE_RFC7] [varchar](30) NULL,
	[PDE_TPOS1] [numeric](38, 6) NULL,
	[PDE_TALF1] [numeric](38, 6) NULL,
	[PDE_TDOC] [varchar](4) NULL,
	[PDE_NART] [int] NULL,
	[PDE_EPDI] [varchar](150) NOT NULL,
	[PDE_CPES] [bit] NOT NULL,
	[PDE_NPDT] [int] NOT NULL,
	[PDE_VPDT] [int] NOT NULL,
	[PDE_NTDP] [int] NOT NULL,
	[PDE_VTDP] [int] NOT NULL,
	[PDE_BCNR] [int] NOT NULL,
	[PDE_NGLE] [int] NOT NULL,
	[PDE_VGLE] [int] NOT NULL,
	[PDE_PGLE] [int] NOT NULL,
	[PDE_VCFC] [bit] NOT NULL,
	[PDE_VLAD] [bit] NOT NULL,
	[PDE_ADIV] [int] NULL,
	[PDE_VFMN] [numeric](38, 6) NOT NULL,
	[PDE_VFMX] [numeric](38, 6) NOT NULL,
	[PDE_PSFR] [numeric](38, 6) NOT NULL,
	[PDE_XVAL] [numeric](38, 6) NOT NULL,
	[PDE_XPES] [numeric](38, 6) NOT NULL,
	[PDE_NPDP] [int] NOT NULL,
	[PDE_PNTD] [int] NOT NULL,
	[PDE_IDCV] [bit] NOT NULL,
	[PDE_IMAM] [varchar](250) NULL,
	[PDE_IMCM] [text] NULL,
	[PDE_EXAM] [varchar](250) NULL,
	[PDE_EXCM] [text] NULL,
	[PDE_TPDF] [bit] NOT NULL,
	[PDE_CADI] [int] NULL,
	[PDE_ECBO] [bit] NOT NULL,
	[PDE_PNAL] [int] NOT NULL,
	[PDE_PNAP] [int] NOT NULL,
	[PDE_CERM] [varchar](70) NULL,
	[PDE_CEDL] [varchar](70) NULL,
	[PDE_CEDP] [varchar](70) NULL,
	[PDE_CECC] [varchar](70) NULL,
	[PDE_CETX] [varchar](1000) NULL,
	[PDE_CERP] [varchar](50) NULL,
	[PDE_VCPI] [bit] NOT NULL,
	[PDE_DCPI] [int] NULL,
	[PDE_VCPE] [bit] NOT NULL,
	[PDE_DCPE] [int] NULL,
	[PDE_NTRP] [bit] NOT NULL,
	[PDE_OTIR] [bit] NOT NULL,
	[PDE_GTPR] [bit] NOT NULL,
	[PDE_NGLP] [int] NOT NULL,
	[PDE_PRXA] [bit] NOT NULL,
	[PDE_PRXS] [varchar](100) NULL,
	[PDE_PRXP] [int] NULL,
	[PDE_PRXU] [varchar](100) NULL,
	[PDE_PRXW] [varbinary](128) NULL,
	[PDE_ICAU] [bit] NOT NULL,
	[PDE_CSTD] [bit] NOT NULL,
	[PDE_TSAP] [tinyint] NOT NULL,
	[PDE_ECAU] [bit] NOT NULL,
	[PDE_PTEX] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PDES] PRIMARY KEY CLUSTERED 
(
	[PDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PDES] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PDES] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PDES] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PDES] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PDES] TO [public] AS [dbo]
/****** Object:  Table [TAB_PDTP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PDTP](
	[PDE_CODI] [int] NOT NULL,
	[DTP_CODI] [varchar](8) NOT NULL,
	[DTP_INTE] [bit] NOT NULL,
	[DTP_RENA] [bit] NOT NULL,
	[DTP_NOVN] [varchar](500) NULL,
	[DTP_COPY] [bit] NOT NULL,
	[DTP_PDES] [varchar](150) NULL,
	[DTP_DELE] [bit] NOT NULL,
	[DTP_ARQI] [bit] NOT NULL,
	[DTP_DESC] [varchar](150) NULL,
	[DTP_ISER] [bit] NOT NULL,
	[DTP_EMAI] [bit] NOT NULL,
	[DTP_SUBJ] [varchar](150) NULL,
	[DTP_BODY] [text] NULL,
 CONSTRAINT [PK_TAB_PDTP] PRIMARY KEY CLUSTERED 
(
	[PDE_CODI] ASC,
	[DTP_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PDTP] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PDTP] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PDTP] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PDTP] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PDTP] TO [public] AS [dbo]
/****** Object:  Table [TAB_PFCT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PFCT](
	[PFC_CODI] [int] NOT NULL,
	[PFC_CONT] [bit] NOT NULL,
	[PFC_POCW] [varchar](150) NULL,
	[PFC_IMPP] [bit] NOT NULL,
	[PFC_VREC] [numeric](38, 6) NULL,
	[PFC_RFNT] [numeric](38, 6) NULL,
	[PFC_OBSR] [text] NULL,
	[PFC_PDIC] [varchar](150) NOT NULL,
	[PFC_PENV] [varchar](150) NOT NULL,
	[PFC_SRIE] [varchar](2) NULL,
	[PFC_VBHO] [numeric](38, 6) NOT NULL,
	[PFC_PEPA] [varchar](150) NULL,
	[PFC_VDAT] [bit] NOT NULL,
	[PFC_DATV] [datetime] NULL,
	[PFC_UFDV] [bit] NOT NULL,
	[PFC_ISAP] [bit] NOT NULL,
	[PFC_VBGE] [numeric](38, 6) NOT NULL,
	[PFC_PEPD] [varchar](150) NULL,
	[PFC_FTPS] [varchar](100) NULL,
	[PFC_FTPU] [varchar](50) NULL,
	[PFC_FTPP] [varchar](50) NULL,
	[PFC_PNPG] [int] NOT NULL,
	[PFC_BCLZ] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PFCT] PRIMARY KEY CLUSTERED 
(
	[PFC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PFCT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PFCT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PFCT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PFCT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PFCT] TO [public] AS [dbo]
/****** Object:  Table [TAB_PFTA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PFTA](
	[FTA_IDEN] [int] NOT NULL,
	[FTA_ACTI] [bit] NOT NULL,
	[FTA_DUAS] [bit] NOT NULL,
	[FTA_DUVR] [int] NOT NULL,
	[FTA_ETCC] [int] NOT NULL,
	[FTA_ECDS] [int] NOT NULL,
	[FTA_ECEC] [int] NOT NULL,
	[FTA_ECCG] [int] NOT NULL,
	[FTA_ENAD] [int] NOT NULL,
	[FTA_IADT] [varchar](250) NULL,
	[FTA_CKIN] [bit] NOT NULL,
	[FTA_EPTR] [int] NOT NULL,
	[FTA_DDRI] [bit] NOT NULL,
	[FTA_DDBI] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PFTA] PRIMARY KEY CLUSTERED 
(
	[FTA_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PFTA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PFTA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PFTA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PFTA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PFTA] TO [public] AS [dbo]
/****** Object:  Table [TAB_PFTE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PFTE](
	[FTE_IDEN] [int] NOT NULL,
	[FTE_WSTL] [varchar](250) NULL,
	[FTE_IDAT] [varchar](150) NULL,
	[FTE_PWAT] [varchar](50) NULL,
	[FTE_BEAT] [varchar](1000) NULL,
	[FTE_DEAT] [datetime] NULL,
	[FTE_WSSL] [varchar](250) NULL,
	[FTE_EFRO] [varchar](70) NOT NULL,
	[FTE_ESUB] [varchar](250) NOT NULL,
	[FTE_EBOC] [varchar](2000) NULL,
	[FTE_EBOV] [varchar](2000) NULL,
	[FTE_ETIP] [int] NOT NULL,
 CONSTRAINT [PK_TAB_PFTE] PRIMARY KEY CLUSTERED 
(
	[FTE_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PFTE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PFTE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PFTE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PFTE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PFTE] TO [public] AS [dbo]
/****** Object:  Table [TAB_PFTI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PFTI](
	[FTI_IDEN] [int] NOT NULL,
	[FTA_IDEN] [int] NOT NULL,
	[TDO_DOCU] [varchar](4) NOT NULL,
	[FTI_CTIP] [varchar](3) NOT NULL,
	[FTI_DDVU] [bit] NOT NULL,
	[FTI_DIMP] [int] NOT NULL,
	[FTI_IMPR] [varchar](250) NOT NULL,
	[FTI_DESC] [varchar](100) NULL,
	[FTI_SADT] [bit] NOT NULL,
	[FTI_IAUT] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PFTI] PRIMARY KEY CLUSTERED 
(
	[FTI_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PFTI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PFTI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PFTI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PFTI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PFTI] TO [public] AS [dbo]
/****** Object:  Table [TAB_PINT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PINT](
	[PIN_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[PIN_PENV] [varchar](150) NOT NULL,
	[PIN_PDIC] [varchar](150) NOT NULL,
	[PIN_EMAI] [varchar](150) NULL,
	[DEC_CODI] [varchar](6) NULL,
	[PIN_PNLN] [int] NOT NULL,
	[PIN_PPAC] [int] NOT NULL,
	[PIN_URFI] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_PINT] PRIMARY KEY CLUSTERED 
(
	[PIN_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PINT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PINT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PINT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PINT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PINT] TO [public] AS [dbo]
/****** Object:  Table [TAB_PPOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PPOC](
	[PPO_CODI] [int] NOT NULL,
	[PPO_NINT] [varchar](5) NULL,
	[PPO_VERS] [varchar](3) NULL,
	[PPO_CEMP] [varchar](10) NULL,
	[PPO_EANO] [int] NULL,
	[PPO_DREL] [varchar](60) NULL,
	[PPO_PROC] [varchar](4) NULL,
	[PPO_DPRO] [varchar](4) NULL,
	[PPO_DDOC] [varchar](4) NULL,
	[PPO_DDDO] [varchar](4) NULL,
	[PPO_VDIN] [varchar](4) NULL,
	[PPO_DVDI] [varchar](4) NULL,
	[PPO_FACT] [varchar](4) NULL,
	[PPO_DFAC] [varchar](4) NULL,
	[PPO_NDEV] [varchar](4) NULL,
	[PPO_DNDE] [varchar](4) NULL,
	[PPO_NDEB] [varchar](4) NULL,
	[PPO_DDEB] [varchar](4) NULL,
	[PPO_NCRE] [varchar](4) NULL,
	[PPO_DNCR] [varchar](4) NULL,
	[PPO_SERV] [varchar](4) NULL,
	[PPO_DOCU] [varchar](4) NULL,
	[PPO_INER] [varchar](4) NULL,
	[PPO_RUBR] [varchar](4) NULL,
	[PPO_CCDO] [varchar](15) NULL,
	[PPO_CCTE] [varchar](15) NULL,
 CONSTRAINT [PK_TAB_PPOC] PRIMARY KEY CLUSTERED 
(
	[PPO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PPOC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PPOC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PPOC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PPOC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PPOC] TO [public] AS [dbo]
/****** Object:  Table [TAB_PREF]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PREF](
	[PRE_CODI] [varchar](3) NOT NULL,
	[PRE_NOME] [varchar](70) NULL,
	[PRE_TAXA] [int] NOT NULL,
	[RRE_CODI] [int] NOT NULL,
	[PRE_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_PREF] PRIMARY KEY CLUSTERED 
(
	[PRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_PREF] UNIQUE NONCLUSTERED 
(
	[PRE_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PREF] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PREF] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PREF] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PREF] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PREF] TO [public] AS [dbo]
/****** Object:  Table [TAB_PSDD]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PSDD](
	[PDD_IDEN] [int] NOT NULL,
	[PSD_IDEN] [int] NOT NULL,
	[PDD_COMP] [varchar](20) NOT NULL,
	[PDD_IDRP] [varchar](20) NOT NULL,
	[PDD_IDTP] [varchar](20) NOT NULL,
	[PDD_IDTS] [varchar](20) NOT NULL,
	[PDD_NRAP] [varchar](40) NULL,
	[PDD_AEMI] [int] NULL,
	[EAD_CODI] [varchar](8) NULL,
	[PDD_NVPR] [int] NULL,
	[LME_CODI] [varchar](17) NOT NULL,
	[LME_CODI1] [varchar](17) NOT NULL,
	[PDD_IDDL] [varchar](20) NOT NULL,
	[PDD_IDDP] [varchar](20) NOT NULL,
 CONSTRAINT [PK_TAB_PSDD] PRIMARY KEY CLUSTERED 
(
	[PDD_IDEN] ASC,
	[PSD_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PSDD] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PSDD] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PSDD] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PSDD] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PSDD] TO [public] AS [dbo]
/****** Object:  Table [TAB_PSDS]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_PSDS](
	[PSD_IDEN] [int] IDENTITY(1,1) NOT NULL,
	[PSD_IDRP] [varchar](20) NULL,
	[PSD_IDTP] [varchar](20) NULL,
	[PSD_IDTS] [varchar](20) NULL,
	[PSD_NRAP] [varchar](40) NULL,
	[PSD_AEMI] [int] NULL,
	[EAD_CODI] [varchar](8) NULL,
	[PSD_NVPR] [int] NOT NULL,
	[EAD_CODI1] [varchar](8) NULL,
	[PSD_PRNR] [int] NOT NULL,
	[PSD_ERIM] [int] NOT NULL,
	[PSD_EREX] [int] NOT NULL,
	[PSD_WEBS] [varchar](250) NOT NULL,
	[PSD_UTIL] [varchar](50) NOT NULL,
	[PSD_PASS] [varchar](50) NOT NULL,
	[PSD_PDIC] [varchar](250) NOT NULL,
	[PSD_IXML] [bit] NOT NULL,
	[PSD_IDCS] [varchar](20) NULL,
	[PSD_TCAR] [varchar](3) NULL,
	[PSD_EEED] [varchar](60) NULL,
	[PSD_TIPO] [varchar](2) NULL,
	[LME_CODI] [varchar](17) NULL,
	[LME_CODI1] [varchar](17) NULL,
	[PAE_CODI] [varchar](8) NULL,
	[PAE_CODI1] [varchar](8) NULL,
	[PSD_NPDL] [int] NOT NULL,
	[PSD_NPDP] [int] NOT NULL,
	[PSD_IDDL] [varchar](20) NULL,
	[PSD_IDDP] [varchar](20) NULL,
	[PSD_ISTN] [bit] NOT NULL,
	[PSD_PENV] [varchar](250) NOT NULL,
	[PSD_BDEX] [bit] NOT NULL,
	[PSD_NBDE] [varchar](6) NULL,
	[PSD_GAEX] [bit] NOT NULL,
	[PSD_VCP0] [bit] NOT NULL,
	[PSD_DCP0] [int] NULL,
	[PSD_VCP1] [bit] NOT NULL,
	[PSD_DCP1] [int] NULL,
	[LME_CODI2] [varchar](17) NULL,
	[LME_CODI3] [varchar](17) NULL,
	[PSD_PATC] [varchar](250) NULL,
	[PSD_PWDC] [varchar](50) NULL,
	[PSD_WSTR] [varchar](250) NULL,
	[PSD_UTTR] [varchar](50) NULL,
	[PSD_PWTR] [varchar](50) NULL,
	[PSD_IRPP] [varchar](20) NULL,
	[PSD_ITPP] [varchar](20) NULL,
	[PSD_ITSP] [varchar](20) NULL,
	[PSD_NAPP] [varchar](40) NULL,
	[PSD_AEMP] [int] NULL,
	[EAD_CODI2] [varchar](8) NULL,
	[PSD_NPRP] [int] NOT NULL,
	[PSD_NVIL] [varchar](35) NULL,
	[PSD_NVIP] [varchar](35) NULL,
	[PSD_NVEL] [varchar](35) NULL,
	[PSD_NVEP] [varchar](35) NULL,
	[PAI_CODI] [varchar](2) NULL,
	[PAI_CODI1] [varchar](2) NULL,
	[PSD_HPIL] [datetime] NULL,
	[PSD_HPIP] [datetime] NULL,
	[PSD_HPEL] [datetime] NULL,
	[PSD_HPEP] [datetime] NULL,
 CONSTRAINT [PK_TAB_PSDS] PRIMARY KEY CLUSTERED 
(
	[PSD_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_PSDS] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_PSDS] TO [public] AS [dbo]
GRANT INSERT ON [TAB_PSDS] TO [public] AS [dbo]
GRANT SELECT ON [TAB_PSDS] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_PSDS] TO [public] AS [dbo]
/****** Object:  Table [TAB_REST]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_REST](
	[RES_CODI] [int] NOT NULL,
	[RES_NOME] [varchar](35) NOT NULL,
	[RES_DONO] [int] NULL,
	[RES_NUTS] [varchar](9) NULL,
 CONSTRAINT [PK_TAB_REST] PRIMARY KEY CLUSTERED 
(
	[RES_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_REST] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_REST] TO [public] AS [dbo]
GRANT INSERT ON [TAB_REST] TO [public] AS [dbo]
GRANT SELECT ON [TAB_REST] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_REST] TO [public] AS [dbo]
/****** Object:  Table [TAB_RFCT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_RFCT](
	[RFC_CODI] [int] NOT NULL,
	[RFC_NOME] [varchar](70) NOT NULL,
	[RFC_IVA] [numeric](38, 6) NOT NULL,
	[RFC_PVP] [numeric](38, 6) NULL,
	[RFC_CPOC] [varchar](15) NULL,
	[RFC_TIPO] [int] NULL,
	[RFC_VLNC] [numeric](38, 6) NOT NULL,
	[RFC_VLNS] [numeric](38, 6) NOT NULL,
	[IIV_CODI] [varchar](3) NULL,
	[CCO_CODI] [varchar](4) NULL,
 CONSTRAINT [PK_TAB_RFCT] PRIMARY KEY CLUSTERED 
(
	[RFC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_RFCT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_RFCT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_RFCT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_RFCT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_RFCT] TO [public] AS [dbo]
/****** Object:  Table [TAB_RFRE]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_RFRE](
	[RFR_CODI] [int] NOT NULL,
	[PAI_CODI] [varchar](2) NOT NULL,
	[RFR_TAXA] [numeric](18, 0) NULL,
	[RFR_ZONA] [int] NULL,
 CONSTRAINT [PK_TAB_RFRE] PRIMARY KEY CLUSTERED 
(
	[RFR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_RFRE] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_RFRE] TO [public] AS [dbo]
GRANT INSERT ON [TAB_RFRE] TO [public] AS [dbo]
GRANT SELECT ON [TAB_RFRE] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_RFRE] TO [public] AS [dbo]
/****** Object:  Table [TAB_RREC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_RREC](
	[RRE_CODI] [int] NOT NULL,
	[RRE_NOME] [varchar](35) NOT NULL,
	[RRE_DOIN] [int] NOT NULL,
	[RRE_IVA] [bit] NOT NULL,
	[RRE_RPRO] [bit] NOT NULL,
	[RRE_PAGR] [bit] NOT NULL,
	[RRE_IOBS] [bit] NOT NULL,
	[RRE_VERB] [int] NOT NULL,
	[COP_CODI] [int] NULL,
	[RRE_VALO] [numeric](38, 6) NULL,
	[RRE_UVAL] [bit] NOT NULL,
	[RRE_IMPO] [varchar](3) NULL,
	[RRE_TIEC] [bit] NOT NULL,
	[RRE_DUMP] [bit] NOT NULL,
	[RRE_IDTY] [int] IDENTITY(1,1) NOT NULL,
	[RRE_FADT] [numeric](38, 6) NOT NULL,
	[RRE_MADT] [numeric](38, 6) NOT NULL,
	[RRE_DPOT] [bit] NOT NULL,
 CONSTRAINT [PK_TAB_RREC] PRIMARY KEY CLUSTERED 
(
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_RREC] UNIQUE NONCLUSTERED 
(
	[RRE_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_RREC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_RREC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_RREC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_RREC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_RREC] TO [public] AS [dbo]
/****** Object:  Table [TAB_SINC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_SINC](
	[SIN_CODI] [varchar](4) NOT NULL,
	[SIN_CING] [varchar](8) NULL,
	[SIN_DESP] [varchar](60) NOT NULL,
	[SIN_DESI] [varchar](60) NULL,
	[SIN_ANAT] [bit] NOT NULL,
	[NDE_CODI] [varchar](3) NULL,
	[SIN_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_SINC] PRIMARY KEY CLUSTERED 
(
	[SIN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_SINC] UNIQUE NONCLUSTERED 
(
	[SIN_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_SINC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_SINC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_SINC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_SINC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_SINC] TO [public] AS [dbo]
/****** Object:  Table [TAB_TAMB]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TAMB](
	[TAM_CODI] [int] NOT NULL,
	[TAM_ESCA] [int] NOT NULL,
	[TAM_COMN] [int] NOT NULL,
	[TAM_COMX] [int] NOT NULL,
	[TAM_TAXA] [numeric](38, 6) NOT NULL,
	[TAM_ABAT] [numeric](38, 6) NOT NULL,
	[TCO_CODI] [varchar](2) NULL,
 CONSTRAINT [PK_TAB_TAMB] PRIMARY KEY CLUSTERED 
(
	[TAM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TAMB] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TAMB] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TAMB] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TAMB] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TAMB] TO [public] AS [dbo]
/****** Object:  Table [TAB_TARM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TARM](
	[TAR_CODI] [varchar](1) NOT NULL,
	[TAR_DESC] [varchar](35) NULL,
	[TAR_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_TARM] PRIMARY KEY CLUSTERED 
(
	[TAR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_TARM] UNIQUE NONCLUSTERED 
(
	[TAR_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TARM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TARM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TARM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TARM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TARM] TO [public] AS [dbo]
/****** Object:  Table [TAB_TCOM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TCOM](
	[TCO_CODI] [varchar](2) NOT NULL,
	[TCO_NOME] [varchar](35) NOT NULL,
	[TCO_EXCL] [int] NOT NULL,
 CONSTRAINT [PK_TAB_TCOM] PRIMARY KEY CLUSTERED 
(
	[TCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TCOM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TCOM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TCOM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TCOM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TCOM] TO [public] AS [dbo]
/****** Object:  Table [TAB_TCXA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TCXA](
	[TCX_CODI] [varchar](2) NOT NULL,
	[TCX_NOME] [varchar](35) NOT NULL,
 CONSTRAINT [PK_TAB_TCXA] PRIMARY KEY CLUSTERED 
(
	[TCX_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TCXA] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TCXA] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TCXA] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TCXA] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TCXA] TO [public] AS [dbo]
/****** Object:  Table [TAB_TDEC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TDEC](
	[TDE_CODI] [varchar](4) NOT NULL,
	[TDE_NOME] [varchar](35) NOT NULL,
	[TDE_1CAS] [varchar](5) NULL,
	[TDE_2CAS] [varchar](4) NULL,
	[TDE_3CAS] [varchar](4) NULL,
	[TDE_DFFI] [varchar](4) NOT NULL,
	[TDE_NATU] [int] NULL,
	[TDE_PAIS] [int] NULL,
	[TDE_CPVD] [int] NULL,
	[PRE_CODI] [varchar](3) NULL,
	[TDE_REGI] [varchar](4) NULL,
	[TDE_CA01] [bit] NOT NULL,
	[TDE_CA02] [bit] NOT NULL,
	[TDE_CA03] [bit] NOT NULL,
	[TDE_CA04] [bit] NOT NULL,
	[TDE_CA05] [bit] NOT NULL,
	[TDE_CA06] [bit] NOT NULL,
	[TDE_CA07] [bit] NOT NULL,
	[TDE_CA08] [bit] NOT NULL,
	[TDE_CA09] [bit] NOT NULL,
	[TDE_CA10] [bit] NOT NULL,
	[TDE_CA11] [bit] NOT NULL,
	[TDE_CA12] [bit] NOT NULL,
	[TDE_CA13] [bit] NOT NULL,
	[TDE_CA14] [bit] NOT NULL,
	[TDE_CA15] [bit] NOT NULL,
	[TDE_CA16] [bit] NOT NULL,
	[TDE_CA17] [bit] NOT NULL,
	[TDE_CA18] [bit] NOT NULL,
	[TDE_CA19] [bit] NOT NULL,
	[TDE_CA20] [bit] NOT NULL,
	[TDE_CA21] [bit] NOT NULL,
	[TDE_CA22] [bit] NOT NULL,
	[TDE_CA23] [bit] NOT NULL,
	[TDE_CA24] [bit] NOT NULL,
	[TDE_CA25] [bit] NOT NULL,
	[TDE_CA26] [bit] NOT NULL,
	[TDE_CA27] [bit] NOT NULL,
	[TDE_CA28] [bit] NOT NULL,
	[TDE_CA29] [bit] NOT NULL,
	[TDE_CA30] [bit] NOT NULL,
	[TDE_TPCG] [varchar](5) NULL,
	[TDE_DESD] [varchar](3) NULL,
	[TDE_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_TDEC] PRIMARY KEY CLUSTERED 
(
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_TDEC] UNIQUE NONCLUSTERED 
(
	[TDE_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TDEC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TDEC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TDEC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TDEC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TDEC] TO [public] AS [dbo]
/****** Object:  Table [TAB_TDED]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TDED](
	[TDD_CODI] [int] NOT NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[DOC_CODI] [varchar](5) NOT NULL,
	[DOC_NOME] [varchar](70) NULL,
 CONSTRAINT [PK_TAB_TDED] PRIMARY KEY CLUSTERED 
(
	[TDD_CODI] ASC,
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TDED] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TDED] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TDED] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TDED] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TDED] TO [public] AS [dbo]
/****** Object:  Table [TAB_TDEM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TDEM](
	[TDM_CODI] [int] NOT NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[INF_CODI] [varchar](8) NOT NULL,
	[INF_DESI] [varchar](150) NULL,
 CONSTRAINT [PK_TAB_TDEM] PRIMARY KEY CLUSTERED 
(
	[TDM_CODI] ASC,
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TDEM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TDEM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TDEM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TDEM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TDEM] TO [public] AS [dbo]
/****** Object:  Table [TAB_TDEP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TDEP](
	[TDP_CODI] [int] NOT NULL,
	[TDE_CODI] [varchar](4) NOT NULL,
	[TXM_CODI] [varchar](5) NOT NULL,
	[TDP_TEXT] [varchar](3000) NULL,
 CONSTRAINT [PK_TAB_TDEP] PRIMARY KEY CLUSTERED 
(
	[TDP_CODI] ASC,
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TDEP] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TDEP] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TDEP] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TDEP] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TDEP] TO [public] AS [dbo]
/****** Object:  Table [TAB_TDFC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TDFC](
	[TDF_CODI] [varchar](15) NOT NULL,
	[TDF_NOME] [varchar](35) NOT NULL,
	[TDF_CPOC] [varchar](15) NULL,
	[TDF_TLAN] [int] NULL,
	[TDF_DIAR] [int] NULL,
	[TDF_DBCR] [int] NULL,
 CONSTRAINT [PK_TAB_TDFC] PRIMARY KEY CLUSTERED 
(
	[TDF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TDFC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TDFC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TDFC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TDFC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TDFC] TO [public] AS [dbo]
/****** Object:  Table [TAB_TDOC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TDOC](
	[TDO_DOCU] [varchar](4) NOT NULL,
	[TDO_DESC] [varchar](100) NULL,
	[TDO_TDOC] [int] NULL,
	[TDO_TENT] [int] NULL,
	[TDO_VALI] [bit] NOT NULL,
	[TDO_MREC] [bit] NOT NULL,
	[TDO_CONC] [bit] NOT NULL,
	[TDO_TCNT] [int] NULL,
	[TDO_TMOV] [int] NULL,
	[TDO_CPAR] [varchar](20) NULL,
	[TDO_TLAN] [varchar](4) NULL,
	[TDO_DIAR] [varchar](4) NULL,
	[TDO_ISAL] [bit] NOT NULL,
	[TDO_REP1] [varchar](20) NULL,
	[TDO_REP2] [varchar](20) NULL,
	[TDO_REP3] [varchar](20) NULL,
	[TDO_REP4] [varchar](20) NULL,
	[TDO_DRP1] [varchar](50) NULL,
	[TDO_DRP2] [varchar](50) NULL,
	[TDO_DRP3] [varchar](50) NULL,
	[TDO_DRP4] [varchar](50) NULL,
	[TDO_IRP1] [bit] NOT NULL,
	[TDO_IRP2] [bit] NOT NULL,
	[TDO_IRP3] [bit] NOT NULL,
	[TDO_IRP4] [bit] NOT NULL,
	[TDO_VRP1] [int] NULL,
	[TDO_VRP2] [int] NULL,
	[TDO_VRP3] [int] NULL,
	[TDO_VRP4] [int] NULL,
	[TDO_DVI1] [varchar](50) NULL,
	[TDO_DVI2] [varchar](50) NULL,
	[TDO_DVI3] [varchar](50) NULL,
	[TDO_DVI4] [varchar](50) NULL,
	[TDO_DVI5] [varchar](50) NULL,
	[TDO_DVI6] [varchar](50) NULL,
	[TDO_DVI7] [varchar](50) NULL,
	[TDO_DVI8] [varchar](50) NULL,
	[TDO_DVI9] [varchar](50) NULL,
	[TDO_DVED] [varchar](4) NULL,
	[TDO_TDSF] [varchar](2) NULL,
	[TDO_DCON] [bit] NOT NULL,
	[TDO_EXSF] [bit] NOT NULL,
	[TDO_ARP1] [int] NULL,
	[TDO_ARP2] [int] NULL,
	[TDO_ARP3] [int] NULL,
	[TDO_ARP4] [int] NULL,
	[TDO_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_TDOC] PRIMARY KEY CLUSTERED 
(
	[TDO_DOCU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_TDOC] UNIQUE NONCLUSTERED 
(
	[TDO_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TDOC] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TDOC] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TDOC] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TDOC] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TDOC] TO [public] AS [dbo]
/****** Object:  Table [TAB_TEMB]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TEMB](
	[TEM_CODI] [varchar](2) NOT NULL,
	[TEM_NOME] [varchar](35) NOT NULL,
	[TEM_PVOL] [bit] NOT NULL,
	[TEM_PUNI] [bit] NOT NULL,
	[TEM_TVOL] [bit] NOT NULL,
	[TEM_EXPT] [bit] NOT NULL,
	[TEM_NSTI] [bit] NOT NULL,
	[TEM_DEXT] [varchar](30) NULL,
 CONSTRAINT [PK_TAB_TEMB] PRIMARY KEY CLUSTERED 
(
	[TEM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TEMB] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TEMB] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TEMB] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TEMB] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TEMB] TO [public] AS [dbo]
/****** Object:  Table [TAB_TEXT]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TEXT](
	[TEX_CODI] [int] NOT NULL,
	[TEX_NOME] [varchar](70) NULL,
	[TEX_TEXT] [text] NOT NULL,
 CONSTRAINT [PK_TAB_TEXT] PRIMARY KEY CLUSTERED 
(
	[TEX_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TEXT] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TEXT] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TEXT] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TEXT] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TEXT] TO [public] AS [dbo]
/****** Object:  Table [TAB_TIAU]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [TAB_TIAU](
	[TIA_TABE] [int] NOT NULL,
	[TIA_ESCA] [int] NOT NULL,
	[TIA_CCMN] [int] NOT NULL,
	[TIA_CCMX] [int] NOT NULL,
	[TIA_VEUR] [numeric](38, 6) NOT NULL,
	[TIA_ABAT] [numeric](38, 6) NOT NULL,
	[TIA_UNID] [bit] NOT NULL,
	[TIA_RPAR] [bit] NOT NULL,
	[TIA_VMIN] [numeric](38, 6) NOT NULL,
 CONSTRAINT [PK_TAB_TIAU] PRIMARY KEY CLUSTERED 
(
	[TIA_TABE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [TAB_TIAU] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TIAU] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TIAU] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TIAU] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TIAU] TO [public] AS [dbo]
/****** Object:  Table [TAB_TRAM]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TRAM](
	[TRA_CODI] [int] NOT NULL,
	[TRA_ESCA] [int] NOT NULL,
	[TRA_COMN] [int] NOT NULL,
	[TRA_COMX] [int] NOT NULL,
	[TRA_VALO] [numeric](38, 6) NOT NULL,
	[TCO_CODI] [varchar](2) NULL,
 CONSTRAINT [PK_TAB_TRAM] PRIMARY KEY CLUSTERED 
(
	[TRA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TRAM] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TRAM] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TRAM] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TRAM] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TRAM] TO [public] AS [dbo]
/****** Object:  Table [TAB_TRED]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [TAB_TRED](
	[TRE_CODI] [int] NOT NULL,
	[TRE_PRED] [numeric](38, 6) NULL,
 CONSTRAINT [PK_TAB_TRED] PRIMARY KEY CLUSTERED 
(
	[TRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [TAB_TRED] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TRED] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TRED] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TRED] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TRED] TO [public] AS [dbo]
/****** Object:  Table [TAB_TVEI]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TVEI](
	[TVE_CODI] [varchar](3) NOT NULL,
	[TVE_NOME] [varchar](35) NOT NULL,
	[TVE_RP1] [varchar](2) NOT NULL,
	[TVE_RP2] [varchar](2) NOT NULL,
	[TVE_1402] [varchar](35) NOT NULL,
	[TVE_EXCL] [int] NOT NULL,
 CONSTRAINT [PK_TAB_TVEI] PRIMARY KEY CLUSTERED 
(
	[TVE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TVEI] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TVEI] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TVEI] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TVEI] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TVEI] TO [public] AS [dbo]
/****** Object:  Table [TAB_TXML]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_TXML](
	[TXM_CODI] [varchar](5) NOT NULL,
	[TXM_DESC] [varchar](150) NOT NULL,
	[TXM_TEXT] [varchar](3000) NULL,
	[DOC_CODI] [varchar](5) NULL,
	[INF_CODI] [varchar](8) NULL,
	[TXM_TXT2] [varchar](3000) NULL,
	[TXM_TXT3] [varchar](3000) NULL,
	[TXM_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_TXML] PRIMARY KEY CLUSTERED 
(
	[TXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_TXML] UNIQUE NONCLUSTERED 
(
	[TXM_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_TXML] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_TXML] TO [public] AS [dbo]
GRANT INSERT ON [TAB_TXML] TO [public] AS [dbo]
GRANT SELECT ON [TAB_TXML] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_TXML] TO [public] AS [dbo]
/****** Object:  Table [TAB_UMED]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_UMED](
	[UME_CODI] [varchar](3) NOT NULL,
	[UME_NOME] [varchar](35) NOT NULL,
	[UME_DECIM] [varchar](35) NULL,
	[UME_FACT] [numeric](38, 6) NOT NULL,
	[UME_TVOL] [bit] NOT NULL,
	[UME_IMPT] [bit] NOT NULL,
	[UME_EXPT] [bit] NOT NULL,
	[UME_COD2] [varchar](6) NULL,
	[UME_IDTY] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TAB_UMED] PRIMARY KEY CLUSTERED 
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
 CONSTRAINT [UK_TAB_UMED] UNIQUE NONCLUSTERED 
(
	[UME_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_UMED] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_UMED] TO [public] AS [dbo]
GRANT INSERT ON [TAB_UMED] TO [public] AS [dbo]
GRANT SELECT ON [TAB_UMED] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_UMED] TO [public] AS [dbo]
/****** Object:  Table [TAB_USUP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [TAB_USUP](
	[USU_CODI] [varchar](10) NOT NULL,
	[USU_SIGL] [varchar](10) NOT NULL,
 CONSTRAINT [PK_TAB_USUP] PRIMARY KEY CLUSTERED 
(
	[USU_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [TAB_USUP] TO  SCHEMA OWNER 
GRANT DELETE ON [TAB_USUP] TO [public] AS [dbo]
GRANT INSERT ON [TAB_USUP] TO [public] AS [dbo]
GRANT SELECT ON [TAB_USUP] TO [public] AS [dbo]
GRANT UPDATE ON [TAB_USUP] TO [public] AS [dbo]
/****** Object:  Table [tb_ConfiguracoesDAR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_ConfiguracoesDAR](
	[id] [tinyint] IDENTITY(1,1) NOT NULL,
	[assuntoEmailArquivos] [varchar](250) NULL,
	[textoEmailArquivos] [varchar](max) NULL,
	[id_tipoDeclaracaoIM] [int] NULL,
	[id_tipoDeclaracaoEU] [int] NULL,
	[identificacaoMeioTransporte] [varchar](30) NULL,
	[id_paisMeioTransporte] [int] NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[wsEndereco] [varchar](250) NULL,
	[wsUtilizador] [varchar](50) NULL,
	[wsPassword] [varbinary](128) NULL,
	[wsPathCertificado] [varchar](250) NULL,
	[wsPasswordCertificado] [varbinary](128) NULL,
	[proxyAuthentication] [bit] NOT NULL,
	[proxyServer] [varchar](100) NULL,
	[proxyPort] [int] NULL,
	[proxyUser] [varchar](100) NULL,
	[proxyPassword] [varbinary](128) NULL,
	[wsEnderecoDMG] [varchar](250) NULL,
	[wsUtilizadorDMG] [varchar](50) NULL,
	[wsPasswordDMG] [varbinary](128) NULL,
	[baseDadosDMG] [varchar](250) NULL,
	[gestaoCEeVDA] [tinyint] NULL,
	[diasFreeADT] [tinyint] NOT NULL,
 CONSTRAINT [PK_tb_ConfiguracoesDAR] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_ConfiguracoesDAR] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_ConfiguracoesDAR] TO [public] AS [dbo]
GRANT INSERT ON [tb_ConfiguracoesDAR] TO [public] AS [dbo]
GRANT SELECT ON [tb_ConfiguracoesDAR] TO [public] AS [dbo]
GRANT UPDATE ON [tb_ConfiguracoesDAR] TO [public] AS [dbo]
/****** Object:  Table [tb_ConfiguracoesDAREmailsResposta]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_ConfiguracoesDAREmailsResposta](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[mensagem] [varchar](20) NOT NULL,
	[ativo] [bit] NOT NULL,
	[listaRegimesIVA] [varchar](3) NULL,
	[assuntoEmail] [varchar](250) NULL,
	[textoEmail] [varchar](max) NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_ConfiguracoesDAREmailsResposta] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_ConfiguracoesDAREmailsResposta] UNIQUE NONCLUSTERED 
(
	[mensagem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_ConfiguracoesDAREmailsResposta] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_ConfiguracoesDAREmailsResposta] TO [public] AS [dbo]
GRANT INSERT ON [tb_ConfiguracoesDAREmailsResposta] TO [public] AS [dbo]
GRANT SELECT ON [tb_ConfiguracoesDAREmailsResposta] TO [public] AS [dbo]
GRANT UPDATE ON [tb_ConfiguracoesDAREmailsResposta] TO [public] AS [dbo]
/****** Object:  Table [tb_ConfiguracoesDARNotificacoesControlo]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_ConfiguracoesDARNotificacoesControlo](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[enderecoEmail] [varchar](500) NOT NULL,
	[enviaEmailEmCAP] [bit] NOT NULL,
	[enviaEmailEmCD] [bit] NOT NULL,
	[enviaEmailEmCF] [bit] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_ConfiguracoesDARNotificacoesControlo] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_ConfiguracoesDARNotificacoesControlo] UNIQUE NONCLUSTERED 
(
	[enderecoEmail] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_ConfiguracoesDARNotificacoesControlo] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_ConfiguracoesDARNotificacoesControlo] TO [public] AS [dbo]
GRANT INSERT ON [tb_ConfiguracoesDARNotificacoesControlo] TO [public] AS [dbo]
GRANT SELECT ON [tb_ConfiguracoesDARNotificacoesControlo] TO [public] AS [dbo]
GRANT UPDATE ON [tb_ConfiguracoesDARNotificacoesControlo] TO [public] AS [dbo]
/****** Object:  Table [tb_ConfiguracoesDARNumeradores]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [tb_ConfiguracoesDARNumeradores](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[ano] [smallint] NOT NULL,
	[proximoNumero] [int] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_ConfiguracoesDARNumeradores] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_ConfiguracoesDARNumeradores] UNIQUE NONCLUSTERED 
(
	[ano] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [tb_ConfiguracoesDARNumeradores] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_ConfiguracoesDARNumeradores] TO [public] AS [dbo]
GRANT INSERT ON [tb_ConfiguracoesDARNumeradores] TO [public] AS [dbo]
GRANT SELECT ON [tb_ConfiguracoesDARNumeradores] TO [public] AS [dbo]
GRANT UPDATE ON [tb_ConfiguracoesDARNumeradores] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDAR]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDAR](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ano] [smallint] NOT NULL,
	[numero] [int] NOT NULL,
	[data] [datetime] NOT NULL,
	[numeroReferenciaLocal] [varchar](25) NOT NULL,
	[documentoTransporte] [varchar](35) NOT NULL,
	[dataVoo] [datetime] NULL,
	[id_natureza] [int] NOT NULL,
	[regimeIVA] [tinyint] NOT NULL,
	[regimeAdicional] [varchar](3) NOT NULL,
	[status] [tinyint] NOT NULL,
	[dataEnvio] [datetime] NULL,
	[versao] [tinyint] NULL,
	[revisao] [tinyint] NULL,
	[numeroProvisorio] [varchar](20) NULL,
	[estadoOperacao] [varchar](3) NULL,
	[controloDocumental] [bit] NOT NULL,
	[dataControloDocumental] [datetime] NULL,
	[conferenteControloDocumental] [varchar](80) NULL,
	[verificadorControloDocumental] [varchar](80) NULL,
	[fechadoControloDocumental] [bit] NOT NULL,
	[dataFechoControloDocumental] [datetime] NULL,
	[controloFisico] [bit] NOT NULL,
	[dataControloFisico] [datetime] NULL,
	[conferenteControloFisico] [varchar](80) NULL,
	[verificadorControloFisico] [varchar](80) NULL,
	[fechadoControloFisico] [bit] NOT NULL,
	[dataFechoControloFisico] [datetime] NULL,
	[controloAduaneiro] [bit] NOT NULL,
	[dataControloAduaneiro] [datetime] NULL,
	[conferenteControloAduaneiro] [varchar](80) NULL,
	[verificadorControloAduaneiro] [varchar](80) NULL,
	[fechadoControloAduaneiro] [bit] NOT NULL,
	[dataFechoControloAduaneiro] [datetime] NULL,
	[autorizacaoSaida] [bit] NOT NULL,
	[dataAutorizacaoSaida] [datetime] NULL,
	[numeroNRM] [varchar](25) NULL,
	[dataNRM] [datetime] NULL,
	[numeroNRMExportacao] [varchar](25) NULL,
	[tipoDeclaracao] [varchar](1) NOT NULL,
	[numeroNRUR] [varchar](35) NULL,
	[numeroVossaReferencia] [varchar](50) NULL,
	[id_estancia] [int] NOT NULL,
	[totalAdicoes] [smallint] NOT NULL,
	[totalVolumes] [int] NOT NULL,
	[totalMassaBruta] [decimal](18, 6) NOT NULL,
	[id_fornecedor] [int] NULL,
	[nomeFornecedor] [varchar](70) NULL,
	[id_paisFornecedor] [int] NULL,
	[moradaFornecedor] [varchar](70) NULL,
	[localidadeFornecedor] [varchar](35) NULL,
	[codPostalFornecedor] [varchar](20) NULL,
	[locPostalFornecedor] [varchar](35) NULL,
	[id_cliente] [int] NOT NULL,
	[nomeCliente] [varchar](70) NOT NULL,
	[id_paisCliente] [int] NOT NULL,
	[nifCliente] [varchar](18) NOT NULL,
	[moradaCliente] [varchar](70) NOT NULL,
	[localidadeCliente] [varchar](35) NOT NULL,
	[codPostalCliente] [varchar](20) NOT NULL,
	[locPostalCliente] [varchar](35) NOT NULL,
	[tipoContaCliente] [varchar](3) NULL,
	[telefoneCliente] [varchar](15) NULL,
	[emailCliente] [varchar](70) NULL,
	[id_declarante] [int] NOT NULL,
	[nomeDeclarante] [varchar](70) NOT NULL,
	[id_paisDeclarante] [int] NOT NULL,
	[nifDeclarante] [varchar](18) NOT NULL,
	[moradaDeclarante] [varchar](70) NOT NULL,
	[localidadeDeclarante] [varchar](35) NOT NULL,
	[codPostalDeclarante] [varchar](20) NOT NULL,
	[locPostalDeclarante] [varchar](35) NOT NULL,
	[estatutoDeclarante] [tinyint] NULL,
	[nifRepresentante] [varchar](18) NULL,
	[caucao] [varchar](24) NULL,
	[funcaoRegimeIOSS] [varchar](3) NULL,
	[numeroIdentificacaoIVA] [varchar](17) NULL,
	[id_paisMoedaCustosTransporte] [int] NOT NULL,
	[cambioCustosTransporte] [decimal](12, 6) NOT NULL,
	[totalCustosTransporte] [decimal](18, 2) NOT NULL,
	[localizacaoMercadorias] [varchar](1) NOT NULL,
	[qualificador] [varchar](1) NOT NULL,
	[id_estanciaMercadorias] [int] NULL,
	[id_localAutorizado] [int] NULL,
	[id_paisMoedaMontante] [int] NOT NULL,
	[cambioMontante] [decimal](12, 6) NOT NULL,
	[totalMontante] [decimal](18, 2) NOT NULL,
	[totalMontanteEUR] [decimal](18, 2) NOT NULL,
	[totalIVA] [decimal](18, 2) NOT NULL,
	[numeroRequerimento] [varchar](30) NULL,
	[numeroDURetorno] [varchar](30) NULL,
	[numeroT1Retorno] [varchar](30) NULL,
	[payment] [tinyint] NULL,
	[numeroPDDT] [int] NULL,
	[numeroPDDTDEV] [int] NULL,
	[numeroTD] [int] NULL,
	[numeroACTM] [int] NULL,
	[numeroRegistoLiquidacao] [varchar](20) NULL,
	[dataRegistoLiquidacao] [datetime] NULL,
	[dataLimitePagamento] [datetime] NULL,
	[volumesDirty] [int] NOT NULL,
	[volumesClean] [int] NOT NULL,
	[volumesScan] [int] NOT NULL,
	[miniCPA] [varchar](20) NULL,
	[tipoCarga] [varchar](5) NULL,
	[dutyType] [varchar](2) NULL,
	[numeroContaExpedidor] [varchar](10) NULL,
	[numeroContaDestinatario] [varchar](10) NULL,
	[nomeOriginalDestinatario] [varchar](70) NULL,
	[moradaOriginalDestinatario] [varchar](70) NULL,
	[localidadeOriginalDestinatario] [varchar](35) NULL,
	[codPostalOriginalDestinatario] [varchar](12) NULL,
	[locPostalOriginalDestinatario] [varchar](35) NULL,
	[aeroportoOrigem] [varchar](80) NULL,
	[numeroVoo] [varchar](20) NULL,
	[referenciaExterna1] [varchar](50) NULL,
	[referenciaExterna2] [varchar](50) NULL,
	[shipID] [varchar](11) NULL,
	[tracking] [varchar](35) NULL,
	[posicaoAviao] [varchar](13) NULL,
	[nivelServico] [int] NULL,
	[nomeFicheiroUPS] [varchar](100) NULL,
	[condicaoEntregaUPS] [varchar](2) NULL,
	[freteOriginal] [decimal](18, 2) NOT NULL,
	[moedaFreteOriginal] [varchar](3) NULL,
	[gatewayFEDEX] [varchar](6) NULL,
	[locIDFEDEX] [varchar](6) NULL,
	[portesAccFEDEX] [varchar](10) NULL,
	[portesFEDEX] [varchar](13) NULL,
	[despachoAccFEDEX] [varchar](50) NULL,
	[despesasDHL] [decimal](18, 3) NOT NULL,
	[dataDocumentoTransporte] [datetime] NULL,
	[participacao] [bit] NOT NULL,
	[dataParticipacao] [datetime] NULL,
	[numeroContraOrdenacao] [varchar](50) NULL,
	[multa] [decimal](18, 2) NOT NULL,
	[motivoMulta] [varchar](35) NULL,
	[debitarMultaA] [varchar](15) NULL,
	[reembolsoMulta] [varchar](3) NULL,
	[tipoShipment] [tinyint] NOT NULL,
	[volumesPendentesParte] [int] NOT NULL,
	[totalMassaBrutaParte] [decimal](18, 6) NOT NULL,
	[totalCustosTransporteParte] [decimal](18, 2) NOT NULL,
	[totalMontanteParte] [decimal](18, 2) NOT NULL,
	[totalMontanteEURParte] [decimal](18, 2) NOT NULL,
	[totalIVAParte] [decimal](18, 2) NOT NULL,
	[id_conta] [bigint] NULL,
	[origem] [tinyint] NOT NULL,
	[id_declaracaoDAR] [int] NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[id_followUp] [int] NULL,
	[id_utilizadorNomeado] [int] NULL,
	[libertoADT] [bit] NOT NULL,
	[dataADT] [datetime] NULL,
	[id_utilizadorADT] [int] NULL,
	[diasDescontoADT] [smallint] NOT NULL,
	[numeroSequencia] [int] NULL,
	[id_tipoDocumentoConta] [int] NULL,
	[exportado] [tinyint] NOT NULL,
	[acao] [tinyint] NOT NULL,
	[envioEntregue] [bit] NOT NULL,
	[statusIVA] [tinyint] NOT NULL,
	[bloqueado] [bit] NOT NULL,
	[taxaIVAMaxima] [decimal](8, 2) NOT NULL,
	[beneficiarioIVACliente] [bit] NOT NULL,
	[tipoCaucao] [tinyint] NULL,
	[dataEntradaDT] [datetime] NULL,
	[numeroGL] [int] NULL,
	[posicaoArmazem] [varchar](15) NULL,
	[flatFileCaucao] [bit] NOT NULL,
	[id_condicaoEntrega] [int] NULL,
	[id_meioTransporte] [int] NULL,
	[totalOptativas] [decimal](18, 2) NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDAR] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_DeclaracoesDAR] UNIQUE NONCLUSTERED 
(
	[ano] ASC,
	[numero] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDAR] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDAR] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDAR] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDAR] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDAR] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARAdicoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARAdicoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[numeroAdicao] [smallint] NOT NULL,
	[id_artigo] [int] NOT NULL,
	[codigoPautal] [varchar](6) NOT NULL,
	[codigoNC] [varchar](2) NULL,
	[codigoTARIC] [varchar](2) NULL,
	[adicionalTARIC1] [varchar](4) NULL,
	[adicionalTARIC2] [varchar](4) NULL,
	[adicionalTARIC3] [varchar](4) NULL,
	[adicionalNacional1] [varchar](4) NULL,
	[adicionalNacional2] [varchar](4) NULL,
	[adicionalNacional3] [varchar](4) NULL,
	[designacao] [varchar](260) NOT NULL,
	[numeroNRUR] [varchar](35) NULL,
	[metodoPagamento] [varchar](1) NULL,
	[id_paisOrigem] [int] NULL,
	[regimeAdicional] [varchar](3) NULL,
	[unidades] [decimal](18, 6) NOT NULL,
	[massaBruta] [decimal](18, 6) NOT NULL,
	[volumes] [int] NOT NULL,
	[id_paisMoedaMontante] [int] NOT NULL,
	[cambioMontante] [decimal](12, 6) NOT NULL,
	[montante] [decimal](18, 2) NOT NULL,
	[montanteEUR] [decimal](18, 2) NOT NULL,
	[baseTributacaoIVA] [decimal](18, 2) NOT NULL,
	[taxaIVA] [decimal](8, 2) NOT NULL,
	[valorIVA] [decimal](18, 2) NOT NULL,
	[id_paisMoedaCustosTransporte] [int] NOT NULL,
	[cambioCustosTransporte] [decimal](12, 6) NOT NULL,
	[custosTransporte] [decimal](18, 2) NOT NULL,
	[custosTransporteEUR] [decimal](18, 2) NOT NULL,
	[id_fornecedor] [int] NULL,
	[nomeFornecedor] [varchar](70) NULL,
	[id_paisFornecedor] [int] NULL,
	[moradaFornecedor] [varchar](70) NULL,
	[localidadeFornecedor] [varchar](35) NULL,
	[codPostalFornecedor] [varchar](20) NULL,
	[locPostalFornecedor] [varchar](35) NULL,
	[codigoBarrasCTT] [varchar](30) NULL,
	[numeroObjetoCTT] [varchar](20) NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[triggerOff] [bit] NOT NULL,
	[optativas] [decimal](18, 2) NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARAdicoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_DeclaracoesDARAdicoes] UNIQUE NONCLUSTERED 
(
	[id_declaracaoDAR] ASC,
	[numeroAdicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARAdicoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARAdicoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARAdicoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARAdicoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARAdicoes] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARAdicoesDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARAdicoesDocumentos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [bigint] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARAdicoesDocumentos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARAdicoesDocumentos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARAdicoesDocumentos] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARAdicoesDocumentos] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARAdicoesDocumentos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARAdicoesDocumentos] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARAdicoesMencoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARAdicoesMencoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [bigint] NOT NULL,
	[id_mencao] [int] NOT NULL,
	[texto] [varchar](512) NULL,
	[origem] [tinyint] NOT NULL,
	[id_adicaoDocumento] [bigint] NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARAdicoesMencoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARAdicoesMencoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARAdicoesMencoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARAdicoesMencoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARAdicoesMencoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARAdicoesMencoes] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARAdicoesPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARAdicoesPrecedentes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [bigint] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARAdicoesPrecedentes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARAdicoesPrecedentes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARAdicoesPrecedentes] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARAdicoesPrecedentes] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARAdicoesPrecedentes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARAdicoesPrecedentes] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARArquivos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARArquivos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[descricao] [varchar](150) NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[nomeFicheiro] [varchar](100) NOT NULL,
	[ficheiro] [varbinary](max) NOT NULL,
	[id_utilizadorArquivo] [int] NOT NULL,
	[dataArquivo] [datetime] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARArquivos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARArquivos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARArquivos] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARArquivos] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARArquivos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARArquivos] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARContactos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARContactos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[descricao] [varchar](200) NOT NULL,
	[id_utilizadorContacto] [int] NOT NULL,
	[dataContacto] [datetime] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARContactos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARContactos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARContactos] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARContactos] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARContactos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARContactos] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARDocumentos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARDocumentos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARDocumentos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARDocumentos] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARDocumentos] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARDocumentos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARDocumentos] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARFollowUps]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [tb_DeclaracoesDARFollowUps](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[id_followUp] [int] NOT NULL,
	[id_utilizadorFollowUp] [int] NOT NULL,
	[dataFollowUp] [datetime] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARFollowUps] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [tb_DeclaracoesDARFollowUps] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARFollowUps] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARFollowUps] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARFollowUps] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARFollowUps] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARIncidencias]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARIncidencias](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[id_statusIncidencia] [int] NOT NULL,
	[dataInicio] [datetime] NOT NULL,
	[dataFim] [datetime] NOT NULL,
	[observacoes] [varchar](500) NULL,
	[id_utilizadorCriacao] [int] NOT NULL,
	[dataCriacao] [datetime] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[releaseHold] [varchar](1) NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARIncidencias] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARIncidencias] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARIncidencias] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARIncidencias] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARIncidencias] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARIncidencias] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARManifestos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARManifestos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[tipoManifesto] [tinyint] NOT NULL,
	[documentoTransporte] [varchar](35) NULL,
	[massaBruta] [decimal](18, 3) NOT NULL,
	[descricao] [varchar](150) NULL,
	[id_pais] [int] NULL,
	[valor] [decimal](18, 3) NOT NULL,
	[id_paisMoeda] [int] NULL,
	[totalFatura] [decimal](18, 3) NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[triggerOff] [bit] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARManifestos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARManifestos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARManifestos] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARManifestos] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARManifestos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARManifestos] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARMencoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARMencoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[id_mencao] [int] NOT NULL,
	[texto] [varchar](512) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARMencoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARMencoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARMencoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARMencoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARMencoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARMencoes] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARMensagens]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARMensagens](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[fluxo] [tinyint] NOT NULL,
	[mensagem] [varchar](20) NOT NULL,
	[id_utilizadorMensagem] [int] NOT NULL,
	[dataMensagem] [datetime] NOT NULL,
	[pedido] [xml] NOT NULL,
	[resposta] [xml] NOT NULL,
	[sucesso] [bit] NOT NULL,
	[estadoOperacao] [varchar](3) NULL,
	[exportado] [bit] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARMensagens] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARMensagens] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARMensagens] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARMensagens] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARMensagens] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARMensagens] TO [public] AS [dbo]
/****** Object:  Table [tb_DeclaracoesDARPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_DeclaracoesDARPrecedentes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoDAR] [int] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[dataContramarca] [datetime] NULL,
 CONSTRAINT [PK_tb_DeclaracoesDARPrecedentes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_DeclaracoesDARPrecedentes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_DeclaracoesDARPrecedentes] TO [public] AS [dbo]
GRANT INSERT ON [tb_DeclaracoesDARPrecedentes] TO [public] AS [dbo]
GRANT SELECT ON [tb_DeclaracoesDARPrecedentes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_DeclaracoesDARPrecedentes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAdicoesAutorizacoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesAdicoesAutorizacoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](35) NOT NULL,
	[titular] [varchar](17) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAdicoesAutorizacoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_EXP_DeclaracoesAdicoesAutorizacoes] UNIQUE NONCLUSTERED 
(
	[id_adicao] ASC,
	[id_documento] ASC,
	[numero] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAdicoesAutorizacoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAdicoesAutorizacoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAdicoesAutorizacoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAdicoesAutorizacoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAdicoesAutorizacoes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAdicoesContentores]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [tb_EXP_DeclaracoesAdicoesContentores](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_contentor] [int] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAdicoesContentores] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_EXP_DeclaracoesAdicoesContentores] UNIQUE NONCLUSTERED 
(
	[id_adicao] ASC,
	[id_contentor] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAdicoesContentores] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAdicoesContentores] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAdicoesContentores] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAdicoesContentores] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAdicoesContentores] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAdicoesImposicoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesAdicoesImposicoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_rubricaReceita] [int] NOT NULL,
	[imposicao] [varchar](3) NOT NULL,
	[montante] [decimal](18, 2) NOT NULL,
	[metodoPagamento] [varchar](1) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAdicoesImposicoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAdicoesImposicoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAdicoesImposicoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAdicoesImposicoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAdicoesImposicoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAdicoesImposicoes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAdicoesImposicoesTaxas]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_imposicao] [bigint] NOT NULL,
	[tipoCalculo] [tinyint] NOT NULL,
	[taxaValor] [decimal](18, 3) NOT NULL,
	[id_unidadeMedida] [int] NULL,
	[quantidade] [decimal](18, 6) NOT NULL,
	[valor] [decimal](18, 2) NOT NULL,
	[montante] [decimal](18, 2) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAdicoesImposicoesTaxas] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAdicoesIntervenientes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesAdicoesIntervenientes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[funcao] [varchar](3) NOT NULL,
	[nif] [varchar](17) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAdicoesIntervenientes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_EXP_DeclaracoesAdicoesIntervenientes] UNIQUE NONCLUSTERED 
(
	[id_adicao] ASC,
	[funcao] ASC,
	[nif] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAdicoesIntervenientes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAdicoesIntervenientes] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAdicoesIntervenientes] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAdicoesIntervenientes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAdicoesIntervenientes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAdicoesPedidos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesAdicoesPedidos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_pedido] [int] NOT NULL,
	[numero] [varchar](512) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAdicoesPedidos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAdicoesPedidos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAdicoesPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[numeroAdicao] [int] NULL,
	[id_unidadeMedidaVolumes] [int] NULL,
	[volumes] [int] NULL,
	[id_unidadeMedidaQualificador] [int] NULL,
	[quantidade] [decimal](18, 6) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAdicoesPrecedentes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAdicoesPrecedentes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesAutorizacoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesAutorizacoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](35) NOT NULL,
	[titular] [varchar](17) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesAutorizacoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_EXP_DeclaracoesAutorizacoes] UNIQUE NONCLUSTERED 
(
	[id_declaracaoEXP] ASC,
	[id_documento] ASC,
	[numero] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesAutorizacoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesAutorizacoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesAutorizacoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesAutorizacoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesAutorizacoes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesContentoresSelos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesContentoresSelos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_contentor] [int] NOT NULL,
	[numeroSelo] [varchar](20) NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesContentoresSelos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_EXP_DeclaracoesContentoresSelos] UNIQUE NONCLUSTERED 
(
	[id_contentor] ASC,
	[numeroSelo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesContentoresSelos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesContentoresSelos] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesContentoresSelos] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesContentoresSelos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesContentoresSelos] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesDocumentos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NULL,
	[dataValidade] [datetime] NULL,
	[entidadeEmissora] [varchar](70) NULL,
	[numeroAdicao] [int] NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesDocumentos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesDocumentos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesDocumentos] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesDocumentos] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesDocumentos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesDocumentos] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesIncidencias]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesIncidencias](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[id_statusIncidencia] [int] NOT NULL,
	[dataInicio] [datetime] NOT NULL,
	[dataFim] [datetime] NOT NULL,
	[observacoes] [varchar](500) NULL,
	[id_utilizadorCriacao] [int] NOT NULL,
	[dataCriacao] [datetime] NOT NULL,
	[releaseHold] [varchar](1) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesIncidencias] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesIncidencias] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesIncidencias] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesIncidencias] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesIncidencias] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesIncidencias] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesIntervenientes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesIntervenientes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[funcao] [varchar](3) NOT NULL,
	[nif] [varchar](17) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesIntervenientes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_EXP_DeclaracoesIntervenientes] UNIQUE NONCLUSTERED 
(
	[id_declaracaoEXP] ASC,
	[funcao] ASC,
	[nif] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesIntervenientes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesIntervenientes] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesIntervenientes] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesIntervenientes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesIntervenientes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesLocaisTransformacao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesLocaisTransformacao](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[tipo] [varchar](1) NOT NULL,
	[qualificador] [varchar](1) NOT NULL,
	[id_localAutorizado] [int] NULL,
	[morada] [varchar](70) NULL,
	[localidade] [varchar](35) NULL,
	[codigoPostal] [varchar](17) NULL,
	[id_pais] [int] NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[texto] [varchar](512) NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesLocaisTransformacao] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesLocaisTransformacao] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesMeiosTransportePartida]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesMeiosTransportePartida](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[id_meioTransporte] [int] NOT NULL,
	[identificacao] [varchar](35) NOT NULL,
	[id_pais] [int] NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesMeiosTransportePartida] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesMeiosTransportePartida] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesMeiosTransportePartida] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesMeiosTransportePartida] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesMeiosTransportePartida] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesMeiosTransportePartida] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesMensagens]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesMensagens](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[fluxo] [tinyint] NOT NULL,
	[mensagem] [varchar](20) NOT NULL,
	[id_utilizadorMensagem] [int] NOT NULL,
	[dataMensagem] [datetime] NOT NULL,
	[pedido] [xml] NOT NULL,
	[resposta] [xml] NOT NULL,
	[sucesso] [bit] NOT NULL,
	[estadoOperacao] [varchar](3) NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[nomeFicheiro] [varchar](100) NOT NULL,
	[ficheiro] [varbinary](max) NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesMensagens] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesMensagens] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesMensagens] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesMensagens] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesMensagens] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesMensagens] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesPrecedentes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesPrecedentes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesPrecedentes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesPrecedentes] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesPrecedentes] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesPrecedentes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesPrecedentes] TO [public] AS [dbo]
/****** Object:  Table [tb_EXP_DeclaracoesProdutosTransformados]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_EXP_DeclaracoesProdutosTransformados](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoEXP] [bigint] NOT NULL,
	[id_artigo] [int] NOT NULL,
	[codigoPautal] [varchar](22) NOT NULL,
	[designacao] [varchar](512) NOT NULL,
	[descricao] [varchar](512) NOT NULL,
	[taxaRendimento] [varchar](512) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[id_meioIdentificacao] [int] NOT NULL,
 CONSTRAINT [PK_tb_EXP_DeclaracoesProdutosTransformados] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_EXP_DeclaracoesProdutosTransformados] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_EXP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
GRANT INSERT ON [tb_EXP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
GRANT SELECT ON [tb_EXP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
GRANT UPDATE ON [tb_EXP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
/****** Object:  Table [tb_FAC_DocContasArquivos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_FAC_DocContasArquivos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_docConta] [bigint] NOT NULL,
	[descricao] [varchar](150) NOT NULL,
	[anexarEmail] [bit] NOT NULL,
	[nomeFicheiro] [varchar](100) NOT NULL,
	[ficheiro] [varbinary](max) NOT NULL,
	[id_utilizadorArquivo] [int] NOT NULL,
	[dataArquivo] [datetime] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_FAC_DocContasArquivos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_FAC_DocContasArquivos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_FAC_DocContasArquivos] TO [public] AS [dbo]
GRANT INSERT ON [tb_FAC_DocContasArquivos] TO [public] AS [dbo]
GRANT SELECT ON [tb_FAC_DocContasArquivos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_FAC_DocContasArquivos] TO [public] AS [dbo]
/****** Object:  Table [tb_HistoricoDMG]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_HistoricoDMG](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[ano] [smallint] NOT NULL,
	[mes] [tinyint] NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[id_utilizadorSubmissao] [int] NOT NULL,
	[dataSubmissao] [datetime] NOT NULL,
	[pedido] [xml] NOT NULL,
	[resposta] [xml] NOT NULL,
	[idDMG] [bigint] NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[estadoDMG] [varchar](50) NULL,
	[sucesso] [bit] NOT NULL,
	[ficheiroComprovativo] [varbinary](max) NULL,
	[ficheiroPagamento] [varbinary](max) NULL,
 CONSTRAINT [PK_tb_HistoricoDMG] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_HistoricoDMG] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_HistoricoDMG] TO [public] AS [dbo]
GRANT INSERT ON [tb_HistoricoDMG] TO [public] AS [dbo]
GRANT SELECT ON [tb_HistoricoDMG] TO [public] AS [dbo]
GRANT UPDATE ON [tb_HistoricoDMG] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesAcrescimosDeducoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesAcrescimosDeducoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[codigo] [varchar](2) NOT NULL,
	[montante] [decimal](18, 2) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesAcrescimosDeducoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_IMP_DeclaracoesAcrescimosDeducoes] UNIQUE NONCLUSTERED 
(
	[id_declaracaoIMP] ASC,
	[tipo] ASC,
	[codigo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesAcrescimosDeducoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesAcrescimosDeducoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesAcrescimosDeducoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesAcrescimosDeducoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesAcrescimosDeducoes] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[codigo] [varchar](2) NOT NULL,
	[montante] [decimal](18, 2) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] UNIQUE NONCLUSTERED 
(
	[id_adicao] ASC,
	[tipo] ASC,
	[codigo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesAdicoesEntrepostos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_armazem] [int] NOT NULL,
	[id_tipoArmazem] [int] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numeroReferencia] [varchar](35) NOT NULL,
	[numeroEORI] [varchar](17) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesAdicoesEntrepostos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesAdicoesEntrepostos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesAdicoesEntrepostos] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesAdicoesEntrepostos] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesAdicoesEntrepostos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesAdicoesEntrepostos] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesAdicoesPedidos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesAdicoesPedidos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_pedido] [int] NOT NULL,
	[numero] [varchar](512) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[id_veiculo] [int] NULL,
	[id_mercadoriaIEC] [int] NULL,
	[id_chassi] [bigint] NULL,
	[nomeFicheiro] [varchar](100) NULL,
	[ficheiro] [varbinary](max) NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesAdicoesPedidos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesAdicoesPedidos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesAdicoesPedidos] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesAdicoesPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[id_unidadeMedidaVolumes] [int] NULL,
	[volumes] [int] NULL,
	[id_unidadeMedidaQualificador] [int] NULL,
	[quantidade] [decimal](18, 6) NOT NULL,
	[numeroAdicao] [int] NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesAdicoesPrecedentes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesAdicoesPrecedentes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesAdicoesPrecedentes] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesAdicoesReferenciasFiscais]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesAdicoesReferenciasFiscais](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_adicao] [int] NOT NULL,
	[funcao] [varchar](3) NOT NULL,
	[nif] [varchar](17) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesAdicoesReferenciasFiscais] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_IMP_DeclaracoesAdicoesReferenciasFiscais] UNIQUE NONCLUSTERED 
(
	[id_adicao] ASC,
	[funcao] ASC,
	[nif] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesAdicoesReferenciasFiscais] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesAdicoesReferenciasFiscais] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesAdicoesReferenciasFiscais] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesAdicoesReferenciasFiscais] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesAdicoesReferenciasFiscais] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesCondicoesEconomicas]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesCondicoesEconomicas](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[codigo] [tinyint] NOT NULL,
	[texto] [varchar](512) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesCondicoesEconomicas] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesCondicoesEconomicas] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesCondicoesEconomicas] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesCondicoesEconomicas] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesCondicoesEconomicas] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesCondicoesEconomicas] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesDocumentos](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[tipo] [tinyint] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NULL,
	[qualificador] [varchar](2) NULL,
	[dataValidade] [datetime] NULL,
	[id_paisMoeda] [int] NULL,
	[montante] [decimal](18, 2) NOT NULL,
	[entidadeEmissora] [varchar](70) NULL,
	[id_unidadeMedida] [int] NULL,
	[quantidade] [decimal](18, 6) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
	[nomeFicheiro] [varchar](100) NULL,
	[ficheiro] [varbinary](max) NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesDocumentos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesDocumentos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesDocumentos] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesDocumentos] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesDocumentos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesDocumentos] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesEstancias]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [tb_IMP_DeclaracoesEstancias](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[id_estancia] [int] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesEstancias] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_IMP_DeclaracoesEstancias] UNIQUE NONCLUSTERED 
(
	[id_declaracaoIMP] ASC,
	[id_estancia] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesEstancias] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesEstancias] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesEstancias] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesEstancias] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesEstancias] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesIntervenientes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesIntervenientes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[funcao] [varchar](3) NOT NULL,
	[nif] [varchar](17) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesIntervenientes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_IMP_DeclaracoesIntervenientes] UNIQUE NONCLUSTERED 
(
	[id_declaracaoIMP] ASC,
	[funcao] ASC,
	[nif] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesIntervenientes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesIntervenientes] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesIntervenientes] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesIntervenientes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesIntervenientes] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesLocaisTransformacao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesLocaisTransformacao](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[tipo] [varchar](1) NOT NULL,
	[qualificador] [varchar](1) NOT NULL,
	[id_localAutorizado] [int] NULL,
	[morada] [varchar](70) NULL,
	[localidade] [varchar](35) NULL,
	[codigoPostal] [varchar](17) NULL,
	[id_pais] [int] NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesLocaisTransformacao] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesLocaisTransformacao] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesLocaisTransformacao] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesMeiosIdentificacao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesMeiosIdentificacao](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[id_meioIdentificacao] [int] NOT NULL,
	[descricao] [varchar](512) NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesMeiosIdentificacao] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesMeiosIdentificacao] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesMeiosIdentificacao] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesMeiosIdentificacao] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesMeiosIdentificacao] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesMeiosIdentificacao] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesPrecedentes](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[id_documento] [int] NOT NULL,
	[numero] [varchar](70) NOT NULL,
	[qualificador] [varchar](2) NULL,
	[dataContramarca] [datetime] NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesPrecedentes] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesPrecedentes] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesPrecedentes] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesPrecedentes] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesPrecedentes] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesPrecedentes] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesProdutosTransformados]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesProdutosTransformados](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[id_artigo] [int] NOT NULL,
	[codigoPautal] [varchar](22) NOT NULL,
	[designacao] [varchar](512) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesProdutosTransformados] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesProdutosTransformados] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesProdutosTransformados] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesProprietarios]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesProprietarios](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[id_cliente] [int] NULL,
	[nome] [varchar](70) NOT NULL,
	[morada] [varchar](70) NOT NULL,
	[localidade] [varchar](35) NOT NULL,
	[codigoPostal] [varchar](17) NOT NULL,
	[id_pais] [int] NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesProprietarios] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesProprietarios] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesProprietarios] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesProprietarios] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesProprietarios] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesProprietarios] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesReferenciasFiscais]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesReferenciasFiscais](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[funcao] [varchar](3) NOT NULL,
	[nif] [varchar](17) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesReferenciasFiscais] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_IMP_DeclaracoesReferenciasFiscais] UNIQUE NONCLUSTERED 
(
	[id_declaracaoIMP] ASC,
	[funcao] ASC,
	[nif] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesReferenciasFiscais] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesReferenciasFiscais] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesReferenciasFiscais] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesReferenciasFiscais] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesReferenciasFiscais] TO [public] AS [dbo]
/****** Object:  Table [tb_IMP_DeclaracoesTaxasRendimento]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_IMP_DeclaracoesTaxasRendimento](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NOT NULL,
	[taxaRendimento] [varchar](512) NOT NULL,
	[origem] [tinyint] NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_IMP_DeclaracoesTaxasRendimento] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_IMP_DeclaracoesTaxasRendimento] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_IMP_DeclaracoesTaxasRendimento] TO [public] AS [dbo]
GRANT INSERT ON [tb_IMP_DeclaracoesTaxasRendimento] TO [public] AS [dbo]
GRANT SELECT ON [tb_IMP_DeclaracoesTaxasRendimento] TO [public] AS [dbo]
GRANT UPDATE ON [tb_IMP_DeclaracoesTaxasRendimento] TO [public] AS [dbo]
/****** Object:  Table [tb_TBL_Desdobramentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_TBL_Desdobramentos](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[tipoDeclaracao] [varchar](2) NOT NULL,
	[regime] [varchar](4) NOT NULL,
	[desdobramento1] [varchar](3) NOT NULL,
	[desdobramento2] [varchar](3) NULL,
	[desdobramento3] [varchar](3) NULL,
	[desdobramento4] [varchar](3) NULL,
	[desdobramento5] [varchar](3) NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_TBL_Desdobramentos] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_TBL_Desdobramentos] UNIQUE NONCLUSTERED 
(
	[tipoDeclaracao] ASC,
	[regime] ASC,
	[desdobramento1] ASC,
	[desdobramento2] ASC,
	[desdobramento3] ASC,
	[desdobramento4] ASC,
	[desdobramento5] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_TBL_Desdobramentos] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_TBL_Desdobramentos] TO [public] AS [dbo]
GRANT INSERT ON [tb_TBL_Desdobramentos] TO [public] AS [dbo]
GRANT SELECT ON [tb_TBL_Desdobramentos] TO [public] AS [dbo]
GRANT UPDATE ON [tb_TBL_Desdobramentos] TO [public] AS [dbo]
/****** Object:  Table [tb_TBL_HonorariosIMP]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [tb_TBL_HonorariosIMP](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[valorMercadoria] [decimal](18, 2) NOT NULL,
	[valorHonorarios] [decimal](18, 2) NOT NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_TBL_HonorariosIMP] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_tb_TBL_HonorariosIMP] UNIQUE NONCLUSTERED 
(
	[valorMercadoria] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER AUTHORIZATION ON [tb_TBL_HonorariosIMP] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_TBL_HonorariosIMP] TO [public] AS [dbo]
GRANT INSERT ON [tb_TBL_HonorariosIMP] TO [public] AS [dbo]
GRANT SELECT ON [tb_TBL_HonorariosIMP] TO [public] AS [dbo]
GRANT UPDATE ON [tb_TBL_HonorariosIMP] TO [public] AS [dbo]
/****** Object:  Table [tb_TBL_LinhasOGMA]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [tb_TBL_LinhasOGMA](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[id_declaracaoIMP] [bigint] NULL,
	[id_declaracaoEXP] [bigint] NULL,
	[numeroLinha] [int] NOT NULL,
	[dataProcesso] [datetime] NOT NULL,
	[numeroProcesso] [varchar](100) NOT NULL,
	[idBILote] [int] NULL,
	[artigo] [varchar](40) NULL,
	[quantidade] [decimal](18, 3) NOT NULL,
	[unidadeMedidaQtd] [varchar](3) NOT NULL,
	[valorUnitario] [decimal](18, 3) NOT NULL,
	[numeroSerie] [varchar](80) NULL,
	[observacoes] [varchar](100) NOT NULL,
	[numeroOrdem] [varchar](22) NULL,
	[dataOrdem] [datetime] NULL,
	[numeroVolumes] [int] NOT NULL,
	[guia] [varchar](20) NULL,
	[numeroAdPrec] [int] NULL,
	[codigoPautalPrec] [varchar](22) NULL,
	[pesoUnitario] [decimal](18, 3) NOT NULL,
	[unidadeMedidaPeso] [varchar](12) NOT NULL,
	[tipoProcesso] [varchar](2) NOT NULL,
	[expedidor] [varchar](200) NULL,
	[designacaoMercadoria] [varchar](100) NULL,
	[id_artigo] [int] NULL,
	[montante] [decimal](28, 3) NOT NULL,
	[massaLiquida] [decimal](28, 6) NOT NULL,
	[massaBruta] [decimal](28, 6) NOT NULL,
	[unidades] [decimal](28, 6) NOT NULL,
	[id_paisOrigem] [int] NULL,
	[id_preferencia] [int] NULL,
	[id_unidadeMedida] [int] NULL,
	[volumes] [int] NOT NULL,
	[numeroAdicao] [int] NULL,
	[id_utilizadorControlo] [int] NOT NULL,
	[dataControlo] [datetime] NOT NULL,
 CONSTRAINT [PK_tb_TBL_LinhasOGMA] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
ALTER AUTHORIZATION ON [tb_TBL_LinhasOGMA] TO  SCHEMA OWNER 
GRANT DELETE ON [tb_TBL_LinhasOGMA] TO [public] AS [dbo]
GRANT INSERT ON [tb_TBL_LinhasOGMA] TO [public] AS [dbo]
GRANT SELECT ON [tb_TBL_LinhasOGMA] TO [public] AS [dbo]
GRANT UPDATE ON [tb_TBL_LinhasOGMA] TO [public] AS [dbo]
/****** Object:  View [VW_Consultas_Faturacao_RelacaoProcessosFEDEX]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Consultas_Faturacao_RelacaoProcessosFEDEX] AS
	SELECT cdo.CDO_IDTY, (CASE duc.DUC_DUNO WHEN 2 THEN 'IMP-CAU' ELSE 'DUI2' END) AS DUC_CNTX, cdo.CDO_TDOC, cdo.CDO_DTEM, cdo.CDO_DTAB, cdo.CDO_STAT, cdo.ALF_CODI, cdo.CLI_DESP, cdo.CLI_CCOR, cdo.CDO_NPRO, cdo.NDE_CODI, cdo.CDO_CPRT, 
		cdo.CDO_NORD, cdo.CDO_DTAC, cdo.CDO_VREF, ISNULL(cdo.CDO_TTDC, 0) AS CDO_TTDC, ISNULL(cdo.CDO_TTIN, 0) AS CDO_TTIN, ISNULL(cdo.CDO_TTHO, 0) AS CDO_TTHO,
		duc.PAI_DLIV, duc.DUC_DNOM, duc.DUC_DMOR, NULL AS DUC_MOR2, NULL AS DUC_MOR3, duc.DUC_DLOC, duc.DUC_DLPO, duc.DUC_DCPO, (CASE ISNULL(duc.DUC_DTEL, ISNULL(duc.DUC_TXT1, '')) WHEN '' THEN NULL ELSE '(+351)' END) AS DUC_TLIN, ISNULL(duc.DUC_DTEL, ISNULL(duc.DUC_TXT1, '')) AS DUC_DTEL, duc.DUC_DEMA, 
		clc.PAI_CODI, clc.CLI_NOME, clc.CLI_MORA, NULL AS CLI_MOR2, NULL AS CLI_MOR3, clc.CLI_LOCA, clc.CLI_LPOS, clc.CLI_CPOS, (CASE ISNULL(clc.CLI_TELF, ISNULL(duc.DUC_TXT1, '')) WHEN '' THEN NULL ELSE '(+351)' END) AS CLI_TLIN, ISNULL(clc.CLI_TELF, ISNULL(duc.DUC_TXT1, '')) AS CLI_TELF, clc.CLI_EMAI, 
		(CASE duc.DUC_DNIF WHEN '999999990' THEN 'N' ELSE 'Y' END) AS DUC_RNIF, 
		duc.DUC_DNIF, duc.DUC_REF1, 
		(CASE duc.DUC_PAYM WHEN 0 THEN 'Sender' WHEN 1 THEN 'Recipient' WHEN 2 THEN 'Outro' ELSE NULL END) AS DUC_PAYM, 	
		ISNULL((SELECT SUM(cdd.DCD_VTOT)
				FROM FAC_DCDO AS cdd WITH(NOLOCK) 
					INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON cdd.DDO_CODI = ddo.DDO_CODI
				WHERE cdd.CDO_EANO = cdo.CDO_EANO AND cdd.CDO_TDOC = cdo.CDO_TDOC AND cdd.CDO_IDEN = cdo.CDO_IDEN AND ISNULL(ddo.DDO_CREC, 0) <> 3), 0) AS CDO_DIRE, 
		(CASE cld.CLI_BIVA 
			WHEN 1 THEN 0 
			ELSE ISNULL((SELECT SUM(cdd.DCD_VTOT)
						FROM FAC_DCDO AS cdd WITH(NOLOCK) 
							INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON cdd.DDO_CODI = ddo.DDO_CODI
						WHERE cdd.CDO_EANO = cdo.CDO_EANO AND cdd.CDO_TDOC = cdo.CDO_TDOC AND cdd.CDO_IDEN = cdo.CDO_IDEN AND ISNULL(ddo.DDO_CREC, 0) = 3), 0) 
		END) AS CDO_VIVA,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI = 13), 0) AS CDO_EADM,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI = 8), 0) AS CDO_MLTC,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI = 21), 0) AS CDO_MANU,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI NOT IN (8, 13, 21)), 0) AS CDO_OTIN
	FROM FAC_CDOC AS cdo WITH(NOLOCK) 
		INNER JOIN TAB_CLIE AS cld WITH(NOLOCK) ON cdo.CLI_DESP = cld.CLI_CODI
		INNER JOIN TAB_CLIE AS clc WITH(NOLOCK) ON cdo.CLI_CCOR = clc.CLI_CODI
		INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON cdo.CDO_IMEX = 0 AND cdo.CDO_PANO = duc.DUC_EANO AND cdo.CDO_NPRO = duc.DUC_PNUM
	WHERE cdo.CDO_STAT <> 3 AND cdo.id_declaracaoDAR IS NULL
	UNION ALL
	SELECT cdo.CDO_IDTY, 'DAR' AS DUC_CNTX, cdo.CDO_TDOC, cdo.CDO_DTEM, cdo.CDO_DTAB, cdo.CDO_STAT, cdo.ALF_CODI, cdo.CLI_DESP, cdo.CLI_CCOR, cdo.CDO_NPRO, cdo.NDE_CODI, cdo.CDO_CPRT, 
		cdo.CDO_NORD, cdo.CDO_DTAC, cdo.CDO_VREF, ISNULL(cdo.CDO_TTDC, 0) AS CDO_TTDC, ISNULL(cdo.CDO_TTIN, 0) AS CDO_TTIN, ISNULL(cdo.CDO_TTHO, 0) AS CDO_TTHO,
		pcl.PAI_CODI, dar.nomeCliente, dar.moradaCliente, NULL AS DUC_MOR2, NULL AS DUC_MOR3, dar.localidadeCliente, dar.locPostalCliente, dar.codPostalCliente, (CASE ISNULL(dar.telefoneCliente, '') WHEN '' THEN NULL ELSE '(+351)' END) AS DUC_TLIN, dar.telefoneCliente, dar.emailCliente,  
		clc.PAI_CODI, clc.CLI_NOME, clc.CLI_MORA, NULL AS CLI_MOR2, NULL AS CLI_MOR3, clc.CLI_LOCA, clc.CLI_LPOS, clc.CLI_CPOS, (CASE ISNULL(clc.CLI_TELF, '') WHEN '' THEN NULL ELSE '(+351)' END) AS CLI_TLIN, clc.CLI_TELF, clc.CLI_EMAI, 
		(CASE dar.nifCliente WHEN '999999990' THEN 'N' ELSE 'Y' END) AS DUC_RNIF, 
		dar.nifCliente, dar.despachoAccFEDEX, 
		(CASE dar.payment WHEN 0 THEN 'Sender' WHEN 1 THEN 'Recipient' WHEN 2 THEN 'Outro' ELSE NULL END) AS DUC_PAYM, 
		ISNULL((SELECT SUM(cdd.DCD_VTOT)
				FROM FAC_DCDO AS cdd WITH(NOLOCK) 
					INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON cdd.DDO_CODI = ddo.DDO_CODI
				WHERE cdd.CDO_EANO = cdo.CDO_EANO AND cdd.CDO_TDOC = cdo.CDO_TDOC AND cdd.CDO_IDEN = cdo.CDO_IDEN AND ISNULL(ddo.DDO_CREC, 0) <> 3), 0) AS CDO_DIRE, 
		(CASE cld.CLI_BIVA 
			WHEN 1 THEN 0 
			ELSE ISNULL((SELECT SUM(cdd.DCD_VTOT)
						FROM FAC_DCDO AS cdd WITH(NOLOCK) 
							INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON cdd.DDO_CODI = ddo.DDO_CODI
						WHERE cdd.CDO_EANO = cdo.CDO_EANO AND cdd.CDO_TDOC = cdo.CDO_TDOC AND cdd.CDO_IDEN = cdo.CDO_IDEN AND ISNULL(ddo.DDO_CREC, 0) = 3), 0) 
		END) AS CDO_VIVA,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI = 13), 0) AS CDO_EADM,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI = 8), 0) AS CDO_MLTC,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI = 21), 0) AS CDO_MANU,
		ISNULL((SELECT SUM(cdi.ICD_VTOT)
				FROM FAC_ICDO AS cdi WITH(NOLOCK) 
					INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON cdi.DIN_CODI = din.DIN_CODI
				WHERE cdi.CDO_EANO = cdo.CDO_EANO AND cdi.CDO_TDOC = cdo.CDO_TDOC AND cdi.CDO_IDEN = cdo.CDO_IDEN AND din.DIN_CODI NOT IN (8, 13, 21)), 0) AS CDO_OTIN
	FROM FAC_CDOC AS cdo WITH(NOLOCK) 
		INNER JOIN TAB_CLIE AS cld WITH(NOLOCK) ON cdo.CLI_DESP = cld.CLI_CODI
		INNER JOIN TAB_CLIE AS clc WITH(NOLOCK) ON cdo.CLI_CCOR = clc.CLI_CODI
		INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON cdo.id_declaracaoDAR = dar.id
		INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
	WHERE cdo.CDO_STAT <> 3


ALTER AUTHORIZATION ON [VW_Consultas_Faturacao_RelacaoProcessosFEDEX] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Consultas_Faturacao_RelacaoProcessosFEDEX] TO [public] AS [dbo]
/****** Object:  View [VW_Contas_ReportDadosDespesasDocumentadas]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Contas_ReportDadosDespesasDocumentadas] AS
	SELECT CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DDO_CODI, DCD_DESC, DCD_VTOT
	FROM FAC_DCDO WITH(NOLOCK) 

ALTER AUTHORIZATION ON [VW_Contas_ReportDadosDespesasDocumentadas] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Contas_ReportDadosDespesasDocumentadas] TO [public] AS [dbo]
/****** Object:  View [VW_Contas_ReportDadosDespesasInerentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Contas_ReportDadosDespesasInerentes] AS
	SELECT CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, DIN_CODI, ICD_DESC, ICD_VTOT, ICD_ISEN, IIV_CODI, IIV_MENC
	FROM FAC_ICDO WITH(NOLOCK) 

ALTER AUTHORIZATION ON [VW_Contas_ReportDadosDespesasInerentes] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Contas_ReportDadosDespesasInerentes] TO [public] AS [dbo]
/****** Object:  View [VW_Contas_ReportDadosGerais]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Contas_ReportDadosGerais] AS
	SELECT t.CDO_EANO, t.CDO_TDOC, t.CDO_IDEN, t.NDE_CODI, t.CDO_NPRO, t.CDO_PANO, t.DEC_CODI, t.ALF_CODI, t.CDO_NORD, t.CDO_DTAC, t.CDO_STAT, t.CDO_CNUM, t.CDO_DTEM, t.CDO_DTAB, 
		t.CDO_DTIN, t.CDO_DTFI, t.CLI_DESP, t.CLI_CCOR, t.CLI_ENDC, t.CDO_TTDC, t.CDO_TTIN, t.CDO_TTHO, t.CDO_TTRF, t.CDO_BIVA, t.CDO_IVA, t.CDO_TXIV, t.CDO_RTFO, t.CDO_TTPR, 
		t.IIV_CODI, t.CDO_ISIV, t.CDO_QUNT, t.CDO_QUAL, t.CDO_DESC, t.CDO_PBRT, t.CDO_PLIQ, t.CDO_VADU, t.CDO_MARC, t.CDO_NFIA, t.CDO_CTMR, t.CDO_VREF, t.MTR_CODI, t.CDO_MTRA, 
		t.PAI_MTRA, t.CDO_DTEN, t.CDO_DTSA, t.CDO_PROC, t.CDO_IMPR, t.CDO_DEST, t.CDO_ARQU, t.CDO_TONE, t.CDO_OPER, t.CDO_NREC, t.CDO_DTRE, t.CDO_RGPR, t.CDO_OBSR, t.CDO_IN04, 
		t.CDO_REGL, t.CDO_DTRL, t.EXM_OPER, t.CDO_IMEX, t.CDO_ORNR, t.CDO_ORDT, t.CDO_CTIP, t.CDO_CPRT, t.CDO_CNOM, t.CDO_CMOR, t.CDO_CLOC, t.CDO_CCPO, t.CDO_CLPO, t.CDO_CPAI, 
		t.CDO_CEAN, t.FOR_CODI, t.FOR_NOME, t.CDO_CPAG, t.CDO_MBEN, t.CDO_MBRF, t.CDO_IDTY, t.CDO_ATCU, t.id_declaracaoDAR, t.CDO_SERI, t.CDO_INVN, td.TDO_DESC, td.TDO_DVI1, 
		td.TDO_DVI2, td.TDO_DVI3, td.TDO_DVI4, td.TDO_DVI5, td.TDO_DVI6, td.TDO_DVI7, td.TDO_DVI8, td.TDO_DVI9, n.NDE_NOME, n.NDE_IIVA, n.NDE_WDES, l.DEC_NOME, l.DEC_MORA, 
		l.DEC_LOCA, l.DEC_CPOS, l.DEC_LPOS, l.DEC_NIF, l.DEC_CEDU, f.ALF_NOME, cd.CLI_CODI, cd.CLI_CEAN, cd.CLI_NOME, cd.CLI_MORA, cd.CLI_LOCA, cd.CLI_CPOS, cd.CLI_LPOS, 
		cd.CLI_NIF, cd.CLI_CODC, cd.CLI_CPOC, cc.CLI_CODI as CLI_CODI_1, cc.CLI_CEAN as CLI_CEAN_1, cc.CLI_NOME as CLI_NOME_1, cc.CLI_MORA as CLI_MORA_1, cc.CLI_LOCA as CLI_LOCA_1, 
		cc.CLI_CPOS as CLI_CPOS_1, cc.CLI_LPOS as CLI_LPOS_1, cc.CLI_TELF as CLI_TELF_1, cc.CLI_EMAI as CLI_EMAI_1, cc.CLI_NIF as CLI_NIF_1, cc.CLI_TNIF as CLI_TNIF_1, 
		cc.CLI_CODC as CLI_CODC_1, cc.CLI_CPAG as CLI_CPAG_1, cc.CLI_LMCR as CLI_LMCR_1, cc.CLI_VCIL as CLI_VCIL_1, cc.CLI_CPOC as CLI_CPOC_1, cc.PAI_CODI as PAI_CODI_1, 
		ce.CLI_CODI as CLI_CODI_2, ce.CLI_NOME as CLI_NOME_2, ce.CLI_MORA as CLI_MORA_2, ce.CLI_LOCA as CLI_LOCA_2, ce.CLI_CPOS as CLI_CPOS_2, ce.CLI_LPOS as CLI_LPOS_2, 
		ce.CLI_NIF as CLI_NIF_2, d.DUC_ENOM, d.TDE_1CAS, d.TDE_2CAS, d.DUC_ADI5, d.DUC_ARTI, d.PAI_P15A, d.CEN_CO20, d.DUC_DE20, d.PAI_MO22, d.DUC_MT22, d.DUC_DTAS, d.DUC_WCAN, 
		d.DUC_WCAI, d.DUC_WCAF, a.APA_CP33, a.PAI_CO34, a.DUA_MB35, a.DUA_ML38, a.PRE_CO36, a.DUA_RG37, a.DUA_R37B, a.DUA_DDAT, 
		(SELECT dbo.FNT_Extenso_ValorPorExtenso(t.CDO_TTPR, 'euros', 'cêntimos')) as TOTAL_EXT,
		ISNULL((SELECT TOP 1 SUM(DDC_VALO) - SUM(DDC_VALO / (1 + (DDC_TIVA / 100))) FROM FAC_DDCD WITH(NOLOCK) WHERE DDC_IVA = 1 and CDO_EANO = t.CDO_EANO 
			and CDO_TDOC = t.CDO_TDOC and CDO_IDEN = t.CDO_IDEN GROUP BY DDC_TIVA), 0) as IVA_DOCUMENTADAS,
		ISNULL((SELECT SUM(DDC_VALO) - SUM(DDC_VALO / (1 + (DDC_TIVA / 100))) FROM FAC_DDCD WITH(NOLOCK) WHERE DDC_TIVA IS NOT NULL and DDC_VALO IS NOT NULL 
			and CDO_EANO = t.CDO_EANO and CDO_TDOC = t.CDO_TDOC and CDO_IDEN = t.CDO_IDEN), 0) as IVA_DOCU, t.CDO_IVAA as IVA_LIQU,
		(CASE t.CDO_IMEX WHEN 1 THEN (SELECT EXM_NRIN FROM PRO_EXML WITH(NOLOCK) WHERE EXM_EANO = t.CDO_PANO and EXM_NRII = t.CDO_NPRO and DEC_CODI = t.EXM_OPER) 
			ELSE NULL END) as NUMREFINTERNA,
		(CASE t.CDO_IMEX WHEN 1 THEN (SELECT EXM_NRLO FROM PRO_EXML WITH(NOLOCK) WHERE EXM_EANO = t.CDO_PANO and EXM_NRII = t.CDO_NPRO and DEC_CODI = t.EXM_OPER) 
			ELSE NULL END) as NUMREFLOCAL, 
		(SELECT PAI_NOME FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = d.PAI_ELIV) as DU_PAISEXPEDIDOR,		
		(SELECT dbo.FNT_CalculaLstDocsAdicoesDUImportacao(d.DUC_PNUM, d.DUC_EANO, 1)) as DU_LISTADOCUMENTOS,
		dbo.FNT_Facturacao_ObtemExpressaoImpressao(t.CDO_HASH, t.CDO_CNUM) as CDO_EXPR, dbo.FNT_Facturacao_ObtemDadosQRCode(0, t.CDO_IDTY) AS CDO_QRCD
	FROM FAC_CDOC as t WITH(NOLOCK) INNER JOIN TAB_TDOC as td WITH(NOLOCK) ON t.CDO_TDOC = td.TDO_DOCU
		INNER JOIN TAB_NDES as n WITH(NOLOCK) ON t.NDE_CODI = n.NDE_CODI
		LEFT OUTER JOIN TAB_DECL as l WITH(NOLOCK) ON t.DEC_CODI = l.DEC_CODI
		LEFT OUTER JOIN TAB_ALFA as f WITH(NOLOCK) ON t.ALF_CODI = f.ALF_CODI
		INNER JOIN TAB_CLIE as cd WITH(NOLOCK) ON t.CLI_DESP = cd.CLI_CODI
		INNER JOIN TAB_CLIE as cc WITH(NOLOCK) ON t.CLI_CCOR = cc.CLI_CODI
		INNER JOIN TAB_CLIE as ce WITH(NOLOCK) ON t.CLI_ENDC = ce.CLI_CODI
		LEFT OUTER JOIN PRO_DUCG as d WITH(NOLOCK) ON t.CDO_NPRO = d.DUC_PNUM and t.CDO_PANO = d.DUC_EANO and t.CDO_IMEX = 0 and t.id_declaracaoDAR IS NULL
		LEFT OUTER JOIN PRO_DUAD as a WITH(NOLOCK) ON t.CDO_NPRO = a.DUC_PNUM and t.CDO_PANO = a.DUC_EANO and t.CDO_IMEX = 0 and a.DUA_CODI = 1 and t.id_declaracaoDAR IS NULL

ALTER AUTHORIZATION ON [VW_Contas_ReportDadosGerais] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Contas_ReportDadosGerais] TO [public] AS [dbo]
/****** Object:  View [VW_Contas_ReportDadosGestaoDocumental]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Contas_ReportDadosGestaoDocumental] AS
	SELECT CDO_EANO, CDO_TDOC, CDO_IDEN, CDD_LINH, CDD_TDOC, CDD_NDOC, CDD_DTEN, CDD_ENVI, CDD_RECE, CDD_DTRE
	FROM FAC_CDDO WITH(NOLOCK) 

ALTER AUTHORIZATION ON [VW_Contas_ReportDadosGestaoDocumental] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Contas_ReportDadosGestaoDocumental] TO [public] AS [dbo]
/****** Object:  View [vw_DeclaracoesDAR_ReportAdicoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_DeclaracoesDAR_ReportAdicoes] AS
	SELECT dad.id, dad.id_declaracaoDAR, dad.numeroAdicao, dad.codigoPautal, dad.codigoNC, dad.codigoTARIC, dad.adicionalTARIC1, dad.adicionalTARIC2, dad.adicionalTARIC3, dad.designacao, 
		dad.metodoPagamento, dad.unidades, dad.massaBruta, dad.volumes, dad.cambioMontante, dad.montante, dad.montanteEUR, dad.baseTributacaoIVA, dad.taxaIVA, dad.valorIVA, 
		dad.cambioCustosTransporte, dad.custosTransporte, dad.custosTransporteEUR
	FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK)

ALTER AUTHORIZATION ON [vw_DeclaracoesDAR_ReportAdicoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_DeclaracoesDAR_ReportAdicoes] TO [public] AS [dbo]
/****** Object:  View [vw_DeclaracoesDAR_ReportDadosGerais]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_DeclaracoesDAR_ReportDadosGerais] AS
	SELECT dar.id, dar.ano, dar.numero, dar.data, dar.numeroReferenciaLocal, dar.documentoTransporte, dar.dataVoo, dar.numeroNRM, est.ALF_CODI AS codEstanciaA, est.ALF_NOME AS nomeEstanciaA, 
		dar.totalAdicoes, dar.totalVolumes, dar.totalMassaBruta, dar.nomeFornecedor, pfo.PAI_CODI AS codPaisFornecedor, pfo.PAI_NOME AS nomePaisFornecedor, dar.moradaFornecedor, 
		dar.localidadeFornecedor, dar.codPostalFornecedor, dar.locPostalFornecedor, cli.CLI_CODI AS codCliente, cli.CLI_INFO AS alertaCliente, cli.CLI_NDHA AS numDocHabilitacaoCliente, 
		cli.CLI_DTDH AS dataDocHabilitacaoCliente, cli.CLI_SENT AS codCliServicoCliente, dar.nomeCliente, pcl.PAI_CODI AS codPaisCliente, pcl.PAI_NOME AS nomePaisCliente, dar.nifCliente, 
		dar.tipoContaCliente, dar.telefoneCliente, dar.emailCliente, pmc.PAI_CODI AS codPaisMoedaCustos, pmc.PAI_NOME AS nomePaisMoedaCustos, pmc.PAI_PREF AS moedaPaisMoedaCustos, 
		dar.totalCustosTransporte, pmo.PAI_CODI AS codPaisMoedaMontante, pmo.PAI_NOME AS nomePaisMoedaMontante, pmo.PAI_PREF AS moedaPaisMoedaMontante, dar.cambioMontante, dar.totalMontante, 
		dar.totalMontanteEUR, dar.totalIVA, dar.numeroDURetorno, dar.numeroT1Retorno, dar.payment, dar.numeroPDDT, dar.numeroPDDTDEV, dar.numeroTD, dar.volumesDirty, dar.volumesClean, 
		dar.volumesScan, dar.miniCPA, dar.tipoCarga, dar.numeroContaExpedidor, dar.numeroContaDestinatario, dar.nomeOriginalDestinatario, dar.moradaOriginalDestinatario, 
		dar.localidadeOriginalDestinatario, dar.codPostalOriginalDestinatario, dar.locPostalOriginalDestinatario, dar.aeroportoOrigem, dar.numeroVoo, dar.posicaoAviao, 
		dar.nomeFicheiroUPS, dar.condicaoEntregaUPS, dar.numeroSequencia, dar.dataEntradaDT, 
		cnt.CDO_CNUM AS numeroConta, 
		(SELECT TOP 1 descricao FROM tb_DeclaracoesDARManifestos WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id) AS descricaoManifesto,
		(SELECT TOP 1 numero FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id) AS numeroDocPrecedente, 
		dbo.FNT_Extenso_ValorPorExtenso(dar.totalIVA, 'euros', 'cêntimos') AS totalIVAExtenso
	FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_ALFA AS est WITH(NOLOCK) ON dar.id_estancia = est.ALF_IDTY
		LEFT OUTER JOIN TAB_PAIS AS pfo WITH(NOLOCK) ON dar.id_paisFornecedor = pfo.PAI_IDTY
		INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
		INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
		INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmo.PAI_IDTY
		INNER JOIN TAB_PAIS AS pmc WITH(NOLOCK) ON dar.id_paisMoedaCustosTransporte = pmc.PAI_IDTY
		LEFT OUTER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON dar.id_conta = cnt.CDO_IDTY

ALTER AUTHORIZATION ON [vw_DeclaracoesDAR_ReportDadosGerais] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_DeclaracoesDAR_ReportDadosGerais] TO [public] AS [dbo]
/****** Object:  View [vw_DeclaracoesDAR_ReportDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_DeclaracoesDAR_ReportDocumentos] AS
	SELECT ddo.id, ddo.id_declaracaoDAR, doc.DOC_CODI, doc.DOC_NOME, ddo.numero, ddo.tipo
	FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY

ALTER AUTHORIZATION ON [vw_DeclaracoesDAR_ReportDocumentos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_DeclaracoesDAR_ReportDocumentos] TO [public] AS [dbo]
/****** Object:  View [vw_DeclaracoesDAR_ReportManifestos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_DeclaracoesDAR_ReportManifestos] AS
	SELECT dma.id, dma.id_declaracaoDAR, dma.tipoManifesto, dma.documentoTransporte, dma.massaBruta, dma.descricao
	FROM tb_DeclaracoesDARManifestos AS dma WITH(NOLOCK)

ALTER AUTHORIZATION ON [vw_DeclaracoesDAR_ReportManifestos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_DeclaracoesDAR_ReportManifestos] TO [public] AS [dbo]
/****** Object:  View [VW_DUS_CAUC]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_DUS_CAUC] AS
	SELECT d.DUC_PNUM, d.DUC_EANO, d.DUC_DST8, d.DUC_NORD, d.DUC_NDAT, d.DUC_VLRC,
	d.DEC_CO14, d.NDE_CODI, d.ALF_CODI, f.FLE_STAT
	FROM PRO_DUCG d, TAB_FLEG f
	WHERE d.DUC_TIPO = 1 AND (SELECT TOP 1 a.FLE_CODI FROM PRO_DUAD a
	WHERE a.DUC_PNUM = d.DUC_PNUM AND a.DUC_EANO = d.DUC_EANO) = f.FLE_CODI AND f.FLE_STAT < 3



ALTER AUTHORIZATION ON [VW_DUS_CAUC] TO  SCHEMA OWNER 
GRANT DELETE ON [VW_DUS_CAUC] TO [public] AS [dbo]
GRANT INSERT ON [VW_DUS_CAUC] TO [public] AS [dbo]
GRANT SELECT ON [VW_DUS_CAUC] TO [public] AS [dbo]
GRANT UPDATE ON [VW_DUS_CAUC] TO [public] AS [dbo]
/****** Object:  View [VW_EntradasAEX_ReportDadosGerais]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_EntradasAEX_ReportDadosGerais] AS
	SELECT dg.EDG_EANO, dg.LME_CODI, dg.EDG_NUME, dg.EDG_DATA, dg.EDG_TVOL, dg.EDG_TPBR, dg.EDG_TMCU, dg.EDG_TVAL, dg.EDG_PTRN, dg.EDG_TRNP, dg.EDG_REFI, dg.EDG_SVOL, dg.EDG_SPBR, dg.CLI_CODI, dg.EDG_ENOM, 
		dg.EDG_EMOR, dg.EDG_ELOC, dg.EDG_ECPO, dg.EDG_ELPO, dg.EDG_ENIF, dg.PAI_CODI, dg.FOR_CODI, dg.EDG_DNOM, dg.EDG_DMOR, dg.EDG_DLOC, dg.PAI_CODI1, dg.EDG_OBSE, dg.EDG_ORIG, dg.EDG_UCRI, dg.EDG_DCRI, 
		dg.EDG_UALT, dg.EDG_DALT, dg.EDG_NEXT, lm.LME_NOME, cl.CLI_CEAN, pe.PAI_NOME, pe.PAI_PREF, pe.PAI_SUFI, fo.FOR_CEAN, pd.PAI_NOME AS PAI_NOME_1, pd.PAI_PREF AS PAI_PREF_1, pd.PAI_SUFI AS PAI_SUFI_1, 
		(SELECT TOP 1 SDG_VOLS FROM AEX_SADG WITH(NOLOCK) WHERE EDG_EANO = dg.EDG_EANO and LME_CODI = dg.LME_CODI and EDG_NUME = dg.EDG_NUME ORDER BY EDG_NUME DESC) as SDG_VOLS,
		(SELECT TOP 1 SDG_PBRT FROM AEX_SADG WITH(NOLOCK) WHERE EDG_EANO = dg.EDG_EANO and LME_CODI = dg.LME_CODI and EDG_NUME = dg.EDG_NUME ORDER BY EDG_NUME DESC) as SDG_PBRT,
		(SELECT TOP 1 SDG_DATA FROM AEX_SADG WITH(NOLOCK) WHERE EDG_EANO = dg.EDG_EANO and LME_CODI = dg.LME_CODI and EDG_NUME = dg.EDG_NUME ORDER BY EDG_NUME DESC) as SDG_DATA
	FROM AEX_ENDG as dg WITH(NOLOCK) INNER JOIN TAB_LMER as lm WITH(NOLOCK) ON dg.LME_CODI = lm.LME_CODI
		LEFT OUTER JOIN TAB_CLIE as cl WITH(NOLOCK) ON dg.CLI_CODI = cl.CLI_CODI
		INNER JOIN TAB_PAIS as pe WITH(NOLOCK) ON dg.PAI_CODI = pe.PAI_CODI
		LEFT OUTER JOIN TAB_FORN as fo WITH(NOLOCK) ON dg.FOR_CODI = fo.FOR_CODI
		INNER JOIN TAB_PAIS as pd WITH(NOLOCK) ON dg.PAI_CODI1 = pd.PAI_CODI

ALTER AUTHORIZATION ON [VW_EntradasAEX_ReportDadosGerais] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_EntradasAEX_ReportDadosGerais] TO [public] AS [dbo]
/****** Object:  View [VW_EntradasAEX_ReportDadosMercadorias]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_EntradasAEX_ReportDadosMercadorias] AS
	SELECT ln.EDG_EANO, ln.LME_CODI, ln.EDG_NUME, ln.ELN_NLIN, ln.ELN_VOLS, ln.ELN_PART, ln.TEM_CODI, ln.ELN_MARC, ln.APA_CODI, ln.ELN_DMER, ln.ELN_PLIQ, ln.ELN_PBRT, ln.ELN_VALO, ln.ELN_LOCA, ln.ELN_EADU, 
		ln.ELN_ALTU, ln.ELN_COMP, ln.ELN_LARG, ln.ELN_UCRI, ln.ELN_DCRI, ln.ELN_UALT, ln.ELN_DALT, te.TEM_NOME, ap.APA_CEAN, ap.APA_CPAU
	FROM AEX_ENLN as ln WITH(NOLOCK) INNER JOIN TAB_TEMB as te WITH(NOLOCK) ON ln.TEM_CODI = te.TEM_CODI
		LEFT OUTER JOIN TAB_APAU as ap WITH(NOLOCK) ON ln.APA_CODI = ap.APA_CODI

ALTER AUTHORIZATION ON [VW_EntradasAEX_ReportDadosMercadorias] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_EntradasAEX_ReportDadosMercadorias] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAdicoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAdicoes] AS
	SELECT EXA_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CO33, APA_CP33, APA_DESG, PAI_CODI, PAI_NOME, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, EXA_VALO, EXA_VEST, EXA_IRES, TDE_REGI, 
		EXA_ATAR, EXA_ATA1, EXA_ATA2, EXA_ATA3, EXA_ATA4, EXA_ATA5, EXA_AIC1, EXA_AIC2, EXA_AIC3, EXA_AIC4, EXA_AIC5, EXA_CCUS, NTR_CODI, EXA_NRUR, EXA_MPAG, CLI_CODI, CLI_NOME, CLI_MORA, 
		CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_NIF, PAI_CODI1, PAI_CODI2, RES_CODI, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, FOR_NIF, PAI_CODI3, PAI_CODI4, EXA_AJUS, CLI_TNIF,
		NULL AS CAL_LISTADOCS, NULL AS CAL_LISTAMENC, NULL AS CAL_LISTAVEIC
	FROM PRO_EXAD WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAdicoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAdicoes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAdicoesAutorizacoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAdicoesAutorizacoes] AS
	SELECT dau.id, dau.id_adicao, doc.DOC_CODI, doc.DOC_NOME, dau.numero, dau.titular
	FROM tb_EXP_DeclaracoesAdicoesAutorizacoes AS dau WITH(NOLOCK) 
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dau.id_documento = doc.DOC_IDTY		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAdicoesAutorizacoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAdicoesAutorizacoes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAdicoesDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAdicoesDocumentos] AS
	SELECT EXD_CHVE, EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EEM_DESC, PAI_CODI, PAI_MOED, PAI_NOME, EXD_MONT, EXD_QNTD, UME_CODI, UME_NOME, EXA_LINH, EXD_TIPO, EXD_NADI
	FROM PRO_EXDA WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAdicoesDocumentos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAdicoesDocumentos] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAdicoesIntervenientes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAdicoesIntervenientes] AS
	SELECT id, id_adicao, funcao, nif
	FROM tb_EXP_DeclaracoesAdicoesIntervenientes WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAdicoesIntervenientes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAdicoesIntervenientes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAdicoesMarcasEVolumes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAdicoesMarcasEVolumes] AS
	SELECT EXM_CHVE, EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART
	FROM PRO_EXMV WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAdicoesMarcasEVolumes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAdicoesMarcasEVolumes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAdicoesPedidos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAdicoesPedidos] AS
	SELECT dpe.id, dpe.id_adicao, ped.TXM_CODI, ped.TXM_DESC, dpe.numero
	FROM tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) 
		INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.id_pedido = ped.TXM_IDTY		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAdicoesPedidos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAdicoesPedidos] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAdicoesPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAdicoesPrecedentes] AS
	SELECT dap.id, dap.id_adicao, doc.DOC_CODI, doc.DOC_NOME, dap.numero, dap.numeroAdicao, umv.UME_CODI AS UME_CODV, umv.UME_NOME AS UME_NOMV, dap.volumes, umq.UME_CODI AS UME_CODQ, 
		umq.UME_NOME AS UME_NOMQ, dap.quantidade
	FROM tb_EXP_DeclaracoesAdicoesPrecedentes AS dap WITH(NOLOCK) 
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dap.id_documento = doc.DOC_IDTY
		LEFT OUTER JOIN TAB_UMED AS umv WITH(NOLOCK) ON dap.id_unidadeMedidaVolumes = umv.UME_IDTY
		LEFT OUTER JOIN TAB_UMED AS umq WITH(NOLOCK) ON dap.id_unidadeMedidaQualificador = umq.UME_IDTY

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAdicoesPrecedentes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAdicoesPrecedentes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportAutorizacoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportAutorizacoes] AS
	SELECT dau.id, dau.id_declaracaoEXP, doc.DOC_CODI, doc.DOC_NOME, dau.numero, dau.titular
	FROM tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) 		
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dau.id_documento = doc.DOC_IDTY

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportAutorizacoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportAutorizacoes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportCertificados]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportCertificados] AS
	SELECT EXC_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_FNIF, EXC_NFAC, EXC_DFAC, EXC_DCOM, EXC_PLIQ, EXC_PBRT, EXC_VALO
	FROM PRO_EXCE WITH(NOLOCK) 

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportCertificados] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportCertificados] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportCertificadosVolumes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportCertificadosVolumes] AS
	SELECT EXD_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXD_QTDE, TEM_CODI, TEM_NOME
	FROM PRO_EXCD WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportCertificadosVolumes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportCertificadosVolumes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportContentores]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportContentores] AS
	SELECT EXC_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_CONT
	FROM PRO_EXCT WITH(NOLOCK) 

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportContentores] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportContentores] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportDadosGerais]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportDadosGerais] AS
	SELECT ddg.EXM_EANO, ddg.EXM_CODI, ddg.DEC_CODI, ddg.EXM_TPRO, ddg.NDE_CODI, ddg.NDE_NOME, ddg.DEC_NOME, ddg.EXM_DATA, ddg.EXM_NRIN, ddg.EXM_NRLO, ddg.EXM_STAT, ddg.EXM_CNUM, ddg.EXM_ESTO, 
		ddg.EXM_NDGA, ddg.EXM_DDGA, ddg.EAD_CODA, ddg.EAD_NOMA, ddg.TDE_COD1, ddg.TDE_NOM1, ddg.CLI_COD2, ddg.CLI_NOM2, ddg.CLI_MOR2, ddg.CLI_LOC2, ddg.CLI_CPO2, ddg.CLI_LPO2, ddg.CLI_NIF2, 
		ddg.CLI_PAI2, ddg.EXM_TP2A, ddg.EXM_TAD5, ddg.EXM_TVL6, ddg.FOR_COD8, ddg.FOR_NOM8, ddg.FOR_MOR8, ddg.FOR_LOC8, ddg.FOR_CPO8, ddg.FOR_LPO8, ddg.FOR_NIF8, ddg.FOR_PAI8, ddg.DEC_CO14, 
		ddg.DEC_NO14, ddg.EXM_TP14, ddg.EXM_P15A, ddg.EXM_P17A, ddg.EXM_CT19, ddg.MTR_CO18, ddg.MTR_NO18, ddg.EXM_MT18, ddg.MTR_CO21, ddg.MTR_NO21, ddg.EXM_MT21, ddg.PAI_CO21, ddg.PAI_NO21, 
		ddg.MTR_CO25, ddg.MTR_CO26, ddg.CEN_CO20, ddg.CEN_NO20, ddg.EXM_LG20, ddg.NTR_CO24, ddg.NTR_NO24, ddg.PAI_CO22, ddg.PAI_MO22, ddg.EXM_MT22, ddg.EXM_TX23, ddg.EXM_TFRT, ddg.EXM_TSEG, 
		ddg.EXM_TMLQ, ddg.EXM_TMBR, ddg.EXM_TREM, ddg.EXM_VEUR, ddg.EXM_VATT, ddg.EAD_CO29, ddg.EAD_NO29, ddg.EAD_C29A, ddg.EAD_N29A, ddg.EAD_CO30, ddg.EAD_NO30, ddg.LEM_CO30, ddg.LEM_NO30, 
		ddg.LME_CO30, ddg.LME_NO30, ddg.EXM_MR30, ddg.EXM_CP30, ddg.EXM_LP30, ddg.ARM_CO49, ddg.ARM_NO49, ddg.TAR_CO49, ddg.TAR_DE49, ddg.EXM_NRII, ddg.EXM_NVRF, ddg.EXM_CPRT, ddg.EXM_NPRO, 
		ddg.EXM_INCE, ddg.EXM_NCMR, ddg.EXM_DTMP, ddg.EXM_CRTD, ddg.EXM_CRTF, ddg.EXM_CRTA, ddg.EXM_ASAI, ddg.EXM_DTAS, ddg.EXM_IDTY, ddg.EXM_SEGU, ddg.EXM_DGEN, ddg.EXM_DCMP, ddg.CLI_CODI1, 
		ddg.CLI_NOME1, ddg.CLI_MORA1, ddg.CLI_LOCA1, ddg.CLI_CPOS1, ddg.CLI_LPOS1, ddg.CLI_NIF1, ddg.PAI_CODI1, ddg.EAD_CODI, ddg.PAI_CODI, ddg.PAE_CODI1, ddg.EXM_TXTC, ddg.PAI_CODI2, 
		ddg.PAI_CODI3, ddg.PAI_CODI4, ddg.EXM_TLOC, ddg.EXM_QUAL, ddg.PAI_CODI5, ddg.EXM_IADI, ddg.EXM_NAUT, ddg.EXM_ONIF, ddg.EAD_CODI1, ddg.EXM_PRZA, ddg.EXM_ATVP, ddg.EXM_INFA, ddg.EXM_ANXB, 
		ddg.EXM_DTCS, ddg.EXM_REGI, ddg.EXM_DCEN, ddg.EXM_MTIT, ddg.EXM_MTFT, ddg.CLI_TNIF1, 
		dcl.DEC_MORA, dcl.DEC_LOCA, dcl.DEC_CPOS, dcl.DEC_LPOS, dcl.DEC_NIF, dcl.DEC_CEDU, pcl.PAI_NOME, pfo.PAI_NOME AS PAI_NOME_3
	FROM PRO_EXML AS ddg WITH(NOLOCK)		
		INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ddg.DEC_CO14 = dcl.DEC_CODI
		LEFT OUTER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON ddg.CLI_PAI2 = pcl.PAI_CODI
		LEFT OUTER JOIN TAB_PAIS AS pfo WITH(NOLOCK) ON ddg.FOR_PAI8 = pfo.PAI_CODI
	WHERE ddg.EXM_CNTX = 1	

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportDadosGerais] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportDadosGerais] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportDocumentos] AS
	SELECT ddo.id, ddo.id_declaracaoEXP, ddo.tipo, doc.DOC_CODI, doc.DOC_NOME, ddo.numero, ddo.dataValidade, ddo.entidadeEmissora, ddo.numeroAdicao
	FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportDocumentos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportDocumentos] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportIntervenientes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportIntervenientes] AS
	SELECT id, id_declaracaoEXP, funcao, nif
	FROM tb_EXP_DeclaracoesIntervenientes WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportIntervenientes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportIntervenientes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportLocaisTransformacao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportLocaisTransformacao] AS
	SELECT dlt.id, dlt.id_declaracaoEXP, dlt.tipo, dlt.qualificador, lme.LME_CODI, lme.LME_NOME, dlt.morada, dlt.localidade, dlt.codigoPostal, pai.PAI_CODI, pai.PAI_NOME, dlt.texto
	FROM tb_EXP_DeclaracoesLocaisTransformacao AS dlt WITH(NOLOCK) 		
		LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dlt.id_localAutorizado = lme.LME_IDTY
		LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dlt.id_pais = pai.PAI_IDTY

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportLocaisTransformacao] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportLocaisTransformacao] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportMeiosTransportePartida]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportMeiosTransportePartida] AS
	SELECT dmt.id, dmt.id_declaracaoEXP, mtr.MTR_CODI, mtr.MTR_NOME, dmt.identificacao, pai.PAI_CODI, pai.PAI_NOME
	FROM tb_EXP_DeclaracoesMeiosTransportePartida AS dmt WITH(NOLOCK) 
		INNER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dmt.id_meioTransporte = mtr.MTR_IDTY
		LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dmt.id_pais = pai.PAI_CODI

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportMeiosTransportePartida] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportMeiosTransportePartida] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportPaisesRota]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportPaisesRota] AS
	SELECT EXP_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, PAI_CODI, PAI_NOME
	FROM PRO_EXPI WITH(NOLOCK) 

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportPaisesRota] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportPaisesRota] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportPedidos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportPedidos] AS
	SELECT EXP_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC
	FROM PRO_EXPA WITH(NOLOCK) 

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportPedidos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportPedidos] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportPrecedentes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportPrecedentes] AS
	SELECT dpr.id, dpr.id_declaracaoEXP, doc.DOC_CODI, doc.DOC_NOME, dpr.numero
	FROM tb_EXP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportPrecedentes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportPrecedentes] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_ReportProdutosTransformados]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_ReportProdutosTransformados] AS
	SELECT dpt.id, dpt.id_declaracaoEXP, dpt.codigoPautal, dpt.designacao, mid.MIA_CODI, dpt.descricao, dpt.taxaRendimento
	FROM tb_EXP_DeclaracoesProdutosTransformados AS dpt WITH(NOLOCK) 
		INNER JOIN TAB_MIAU AS mid WITH(NOLOCK) ON dpt.id_meioIdentificacao = mid.MIA_IDTY

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_ReportProdutosTransformados] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_ReportProdutosTransformados] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_WSPendentesResposta]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_WSPendentesResposta] AS
	SELECT dex.EXM_IDTY, dex.EXM_EANO, dex.EXM_CODI, dex.DEC_CODI, dex.EXM_DATA, dex.EXM_NRLO, dex.EXM_STAT, dex.EXM_ESTO, dex.EXM_NDGA, dex.EXM_DDGA, dex.EAD_CODA, dex.EAD_NOMA, dex.CLI_COD2, 
		dex.CLI_NOM2, dex.EXM_UCRI, dex.EXM_NRII, dex.EXM_CPRT, 
		(CASE 
			WHEN (dex.EXM_STAT = 1 OR (dex.EXM_STAT = 2 AND dex.EXM_ASAI = 0 AND ISNULL(dex.EXM_ESTO, '') <> 'SNA')) THEN 0			
			WHEN (dex.EXM_STAT = 2 AND dex.EXM_ASAI = 1 AND DATEDIFF(DAY, dex.EXM_DTAS, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <= 60) THEN 1
			ELSE -1
		END) AS EXM_TPEN
	FROM PRO_EXML AS dex WITH(NOLOCK) 
		INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dex.NDE_CODI = nat.NDE_CODI	
		INNER JOIN TAB_PDES AS pde WITH(NOLOCK)	ON 1 = 1
	WHERE ((dex.EXM_STAT = 1 OR (dex.EXM_STAT = 2 AND dex.EXM_ASAI = 0 AND ISNULL(dex.EXM_ESTO, '') <> 'SNA')) -- p/ mensagens PT528C, PT556C, PT504C, PT509C, ..., PT582C 				
			OR (dex.EXM_STAT = 2 AND dex.EXM_ASAI = 1 AND DATEDIFF(DAY, dex.EXM_DTAS, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <= 60) -- p/ restantes mensagens pós CC429A
		) AND dex.EXM_CNTX = 1 AND ISNULL(dex.EXM_TAD5, 0) > 0 AND ISNULL(dex.EXM_TVL6, 0) > 0 AND nat.NDE_FEDI = 1 	
		AND (CASE WHEN ISNULL(pde.PDE_CADI, 0) IN (1, 2) THEN ISNULL(dex.EXM_VCLE, 0) ELSE ISNULL(dex.EXM_TVL6, 0) END) = ISNULL(dex.EXM_TVL6, 0) --FEDEX/TNT, UPS			
		AND NOT EXISTS(SELECT EXA_CHVE FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = dex.EXM_EANO AND EXM_CODI = dex.EXM_CODI AND EXM_COPE = dex.DEC_CODI AND APA_CP33 = '9999999999')
		AND ISNULL(dex.EXM_MT22, 0) = (SELECT SUM(EXA_VALO) FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = dex.EXM_EANO AND EXM_CODI = dex.EXM_CODI AND EXM_COPE = dex.DEC_CODI)
		AND NOT EXISTS(SELECT id FROM tb_EXP_DeclaracoesDocumentos WITH(NOLOCK)WHERE id_declaracaoEXP = dex.EXM_IDTY AND tipo IN (0, 1) AND ISNULL(numero, '') = '')		
		AND NOT EXISTS(SELECT ado.EXD_CHVE FROM PRO_EXAD AS exa WITH(NOLOCK) INNER JOIN PRO_EXDA AS ado WITH(NOLOCK) ON exa.EXA_CHVE = ado.EXA_CHVE WHERE exa.EXM_EANO = dex.EXM_EANO AND exa.EXM_CODI = dex.EXM_CODI AND exa.EXM_COPE = dex.DEC_CODI AND ado.EXD_TIPO IN (0, 1) AND ISNULL(ado.EXD_NREF, '') = '')
		AND (CASE pde.PDE_PTEX WHEN 1 THEN (SELECT COUNT(*) FROM PRO_EXAD AS exa WITH(NOLOCK) INNER JOIN PRO_EXDA AS ado WITH(NOLOCK) ON exa.EXA_CHVE = ado.EXA_CHVE WHERE exa.EXM_EANO = dex.EXM_EANO AND exa.EXM_CODI = dex.EXM_CODI AND exa.EXM_COPE = dex.DEC_CODI AND exa.EXA_LINH = 1 AND ado.DOC_CODI IN ('N315', 'N380', 'N325', 'N203', 'N395', 'N381', '9E06')) ELSE (SELECT COUNT(*) FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoEXP = dex.EXM_IDTY AND doc.DOC_CODI IN ('N315', 'N380', 'N325', 'N203', 'N395', 'N381', '9E06')) END) > 0
		AND ((dex.EXM_CT19 = 0) OR ((dex.EXM_CT19 = 1) AND (EXISTS(SELECT EXC_CHVE FROM PRO_EXCT WITH(NOLOCK) WHERE EXM_EANO = dex.EXM_EANO AND EXM_CODI = dex.EXM_CODI AND EXM_COPE = dex.DEC_CODI)) AND (NOT EXISTS(SELECT exa.EXA_CHVE FROM PRO_EXAD AS exa WITH(NOLOCK) LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesContentores AS aco WITH(NOLOCK) ON exa.EXA_CHVE = aco.id_adicao WHERE exa.EXM_EANO = dex.EXM_EANO AND exa.EXM_CODI = dex.EXM_CODI AND exa.EXM_COPE = dex.DEC_CODI AND aco.id IS NULL))))

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_WSPendentesResposta] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_WSPendentesResposta] TO [public] AS [dbo]
/****** Object:  View [vw_EXP_Declaracoes_WSPendentesSubmissao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_EXP_Declaracoes_WSPendentesSubmissao] AS
	SELECT dex.EXM_IDTY, dex.EXM_EANO, dex.EXM_CODI, dex.DEC_CODI, dex.EXM_TPRO, dex.NDE_CODI, dex.NDE_NOME, dex.EXM_DATA, dex.EXM_NRLO, dex.EXM_ESTO, dex.EAD_CODA, dex.EAD_NOMA, dex.TDE_COD1, 
		dex.TDE_NOM1, dex.CLI_COD2, dex.CLI_NOM2, dex.FOR_COD8, dex.FOR_NOM8, dex.EXM_NRII, dex.EXM_CPRT, dex.EXM_ANXB, dex.EXM_REGI 
	FROM PRO_EXML AS dex WITH(NOLOCK) 
		INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dex.NDE_CODI = nat.NDE_CODI	
		INNER JOIN TAB_PDES AS pde WITH(NOLOCK)	ON 1 = 1	
	WHERE dex.EXM_CNTX = 1 AND dex.EXM_STAT = 0 AND ISNULL(dex.EXM_ESTO, '') <> 'RE' AND ISNULL(dex.EXM_TAD5, 0) > 0 AND ISNULL(dex.EXM_TVL6, 0) > 0 AND nat.NDE_FEDI = 1			
		AND (CASE WHEN (dex.EXM_TPRO <> 'D') AND (ISNULL(pde.PDE_CADI, 0) IN (1, 2, 3)) THEN dex.EXM_VSCA ELSE ISNULL(dex.EXM_TVL6, 0) END) = ISNULL(dex.EXM_TVL6, 0) --FEDEX/TNT, UPS, DHL
		AND (CASE WHEN (dex.EXM_TPRO = 'D') AND (ISNULL(pde.PDE_CADI, 0) IN (1, 2, 3)) THEN ISNULL(dex.EXM_VDIR, 0) ELSE ISNULL(dex.EXM_TVL6, 0) END) > 0 --FEDEX/TNT, UPS, DHL
		AND NOT EXISTS(SELECT EXA_CHVE FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = dex.EXM_EANO AND EXM_CODI = dex.EXM_CODI AND EXM_COPE = dex.DEC_CODI AND APA_CP33 = '9999999999')
		AND ISNULL(dex.EXM_MT22, 0) = (SELECT SUM(EXA_VALO) FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = dex.EXM_EANO AND EXM_CODI = dex.EXM_CODI AND EXM_COPE = dex.DEC_CODI)
		AND NOT EXISTS(SELECT id FROM tb_EXP_DeclaracoesDocumentos WITH(NOLOCK)WHERE id_declaracaoEXP = dex.EXM_IDTY AND tipo IN (0, 1) AND ISNULL(numero, '') = '')
		AND NOT EXISTS(SELECT ado.EXD_CHVE FROM PRO_EXAD AS exa WITH(NOLOCK) INNER JOIN PRO_EXDA AS ado WITH(NOLOCK) ON exa.EXA_CHVE = ado.EXA_CHVE WHERE exa.EXM_EANO = dex.EXM_EANO AND exa.EXM_CODI = dex.EXM_CODI AND exa.EXM_COPE = dex.DEC_CODI AND ado.EXD_TIPO IN (0, 1) AND ISNULL(ado.EXD_NREF, '') = '')
		AND (CASE pde.PDE_PTEX WHEN 1 THEN (SELECT COUNT(*) FROM PRO_EXAD AS exa WITH(NOLOCK) INNER JOIN PRO_EXDA AS ado WITH(NOLOCK) ON exa.EXA_CHVE = ado.EXA_CHVE WHERE exa.EXM_EANO = dex.EXM_EANO AND exa.EXM_CODI = dex.EXM_CODI AND exa.EXM_COPE = dex.DEC_CODI AND exa.EXA_LINH = 1 AND ado.DOC_CODI IN ('N315', 'N380', 'N325', 'N203', 'N395', 'N381', '9E06')) ELSE (SELECT COUNT(*) FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoEXP = dex.EXM_IDTY AND doc.DOC_CODI IN ('N315', 'N380', 'N325', 'N203', 'N395', 'N381', '9E06')) END) > 0
		AND ((dex.EXM_CT19 = 0) OR ((dex.EXM_CT19 = 1) AND (EXISTS(SELECT EXC_CHVE FROM PRO_EXCT WITH(NOLOCK) WHERE EXM_EANO = dex.EXM_EANO AND EXM_CODI = dex.EXM_CODI AND EXM_COPE = dex.DEC_CODI)) AND (NOT EXISTS(SELECT exa.EXA_CHVE FROM PRO_EXAD AS exa WITH(NOLOCK) LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesContentores AS aco WITH(NOLOCK) ON exa.EXA_CHVE = aco.id_adicao WHERE exa.EXM_EANO = dex.EXM_EANO AND exa.EXM_CODI = dex.EXM_CODI AND exa.EXM_COPE = dex.DEC_CODI AND aco.id IS NULL))))

ALTER AUTHORIZATION ON [vw_EXP_Declaracoes_WSPendentesSubmissao] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_EXP_Declaracoes_WSPendentesSubmissao] TO [public] AS [dbo]
/****** Object:  View [VW_Exportacao_DataCenterDeclaracoesParaSupervisao]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Exportacao_DataCenterDeclaracoesParaSupervisao] AS	
	SELECT de.EXM_DTCR, de.EXM_DTVO, de.EXM_DATA, de.EXM_NRII, de.EXM_CPRT, de.EXM_EANO, de.EXM_CODI, de.DEC_CODI, de.NDE_CODI, de.EXM_NVRF, de.CLI_COD2, de.CLI_NOM2, de.EXM_DTAL,
		(CASE de.EXM_TPRO WHEN 'A' THEN 'Declaração Completa' WHEN 'B' THEN 'Declaração Incompleta'
			WHEN 'C' THEN 'Declaração Simplificada' WHEN 'D' THEN 'Declaração Completa sem apres. mercadoria'
			WHEN 'E' THEN 'Declaração Incompleta sem apres. mercadoria' WHEN 'F' THEN 'Declaração Simplificada sem apres. mercadoria'
			WHEN 'X' THEN 'Declaração Complementar (código B)' WHEN 'Y' THEN 'Declaração Complementar (código C)'
			WHEN 'Z' THEN 'Dec. Complementar nº 1, alínea c, artº 76 do CAC' ELSE NULL END) as TPR_DESC,
		de.EXM_NDGA, de.EXM_PIUP, CAST((CONVERT(varchar(10), de.EXM_DPUP, 105) + ' ' + CONVERT(varchar(12), de.EXM_HPUP, 114)) as datetime) as EXM_DPUP,
		(SELECT TOP 1 ef.UTI_UTIL FROM PRO_EXFW AS ef WITH (NOLOCK) INNER JOIN GIDWIN..FAP_FWUP AS fu WITH (NOLOCK) ON ef.FUP_CODI = fu.FUP_CODI
			WHERE fu.FUP_VUTI = 1 and ef.EXM_EANO = de.EXM_EANO and ef.EXM_CODI = de.EXM_CODI and ef.EXM_COPE = de.DEC_CODI ORDER BY ef.EFW_DATA desc) as UTI_UTIL,
		(CASE WHEN (de.EXM_STAT in (1, 3, 4, 5, 7)) or (de.EXM_STAT = 2 and de.EXM_EMMA = 0) THEN 'ENV' WHEN (de.EXM_STAT = 6) or (de.EXM_STAT = 2 and de.EXM_EMMA = 1) THEN 'MA' ELSE NULL END) as EXM_ENVI,
		(CASE de.EXM_ESTO WHEN 'AP' THEN 'Operação Efectuada' WHEN 'RE' THEN 'Operação Rejeitada'
			WHEN 'AJ' THEN 'Operação Pendente' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'CS' THEN 'Certificação de Saída'
			WHEN 'CD' THEN 'Controlo Documental' WHEN 'CFS' THEN 'Controlo Físico de Saída' WHEN 'CFP' THEN 'Controlo Físico Parcial'
			WHEN 'CF' THEN 'Controlo Físico' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' ELSE NULL END) as EST_DESC,
		de.EXM_ARGW, de.EXM_ASAI, de.EXM_FACI, de.FUP_CODI, de.EXM_DDDM, fw.FUP_DESC,		
		(SELECT TOP 1 EXF_DATA FROM PRO_EXFI WITH (NOLOCK) WHERE EXF_TMSG = 'FATURA' and EXM_EANO = de.EXM_EANO and EXM_CODI = de.EXM_CODI and DEC_CODI = de.DEC_CODI) as EXF_DTFT
	FROM PRO_EXML AS de WITH (NOLOCK) INNER JOIN GIDWIN..FAP_FWUP AS fw WITH (NOLOCK) ON de.FUP_CODI = fw.FUP_CODI
	WHERE de.EXM_ASAI = 0 and ISNULL(de.SIN_CODI, '') not in ('A13', 'A99', 'AHS') and fw.FUP_EFIM = 0

ALTER AUTHORIZATION ON [VW_Exportacao_DataCenterDeclaracoesParaSupervisao] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Exportacao_DataCenterDeclaracoesParaSupervisao] TO [public] AS [dbo]
/****** Object:  View [VW_Exportacao_DataCenterDeclaracoesParaWorkload]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Exportacao_DataCenterDeclaracoesParaWorkload] AS	
	SELECT de.EXM_NRII, de.EXM_CPRT, de.EXM_EANO, de.EXM_CODI, de.DEC_CODI, de.NDE_CODI, de.EXM_NVRF, de.CLI_COD2, de.CLI_NOM2,
		de.EXM_HVLV, de.EXM_DTAL, de.EXM_PIUP, CAST((CONVERT(varchar(10), de.EXM_DPUP, 105) + ' ' + CONVERT(varchar(12), de.EXM_HPUP, 114)) as datetime) as EXM_DPUP,
		de.EXM_ARGW, de.EXM_FACI, de.FUP_CODI, de.EXM_DDDM, fw.FUP_DESC, fw.FUP_CSEG, fw.GRU_CODI, 
		(CASE de.EXM_TPRO WHEN 'A' THEN 'Declaração Completa' WHEN 'B' THEN 'Declaração Incompleta'
			WHEN 'C' THEN 'Declaração Simplificada' WHEN 'D' THEN 'Declaração Completa sem apres. mercadoria'
			WHEN 'E' THEN 'Declaração Incompleta sem apres. mercadoria' WHEN 'F' THEN 'Declaração Simplificada sem apres. mercadoria'
			WHEN 'X' THEN 'Declaração Complementar (código B)' WHEN 'Y' THEN 'Declaração Complementar (código C)'
			WHEN 'Z' THEN 'Dec. Complementar nº 1, alínea c, artº 76 do CAC' ELSE NULL END) as TPR_DESC,
		(CASE WHEN (de.EXM_STAT in (1, 3, 4, 5, 7)) or (de.EXM_STAT = 2 and de.EXM_EMMA = 0) THEN 'ENV' WHEN (de.EXM_STAT = 6) or (de.EXM_STAT = 2 and de.EXM_EMMA = 1) THEN 'MA' ELSE NULL END) as EXM_ENVI,
		(CASE de.EXM_ESTO WHEN 'AP' THEN 'Operação Efectuada' WHEN 'RE' THEN 'Operação Rejeitada'
			WHEN 'AJ' THEN 'Operação Pendente' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'CS' THEN 'Certificação de Saída'
			WHEN 'CD' THEN 'Controlo Documental' WHEN 'CFS' THEN 'Controlo Físico de Saída' WHEN 'CFP' THEN 'Controlo Físico Parcial'
			WHEN 'CF' THEN 'Controlo Físico' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' ELSE NULL END) as EST_DESC,
		(CASE WHEN EXISTS(SELECT EXF_IDEN FROM PRO_EXFI WITH (NOLOCK) WHERE EXF_TMSG = 'FATURA' and EXM_EANO = de.EXM_EANO and EXM_CODI = de.EXM_CODI and DEC_CODI = de.DEC_CODI) THEN CAST(1 as bit) ELSE CAST(0 as bit) END) as EXM_TDFT,
		(SELECT TOP 1 EXF_LINK FROM PRO_EXFI WITH (NOLOCK) WHERE EXF_TMSG = 'FATURA' and EXM_EANO = de.EXM_EANO and EXM_CODI = de.EXM_CODI and DEC_CODI = de.DEC_CODI) as EXF_LKFT,
		(SELECT TOP 1 EXF_LINK FROM PRO_EXFI WITH (NOLOCK) WHERE EXF_TMSG = 'DOCTRANS' and EXM_EANO = de.EXM_EANO and EXM_CODI = de.EXM_CODI and DEC_CODI = de.DEC_CODI) as EXF_LKDT,		
		(SELECT TOP 1 EXF_DATA FROM PRO_EXFI WITH (NOLOCK) WHERE EXF_TMSG = 'FATURA' and EXM_EANO = de.EXM_EANO and EXM_CODI = de.EXM_CODI and DEC_CODI = de.DEC_CODI) as EXF_DTFT, 
		(SELECT MAX(EFW_CODI) FROM PRO_EXFW WITH (NOLOCK) WHERE EXM_EANO = de.EXM_EANO and EXM_CODI = de.EXM_CODI and EXM_COPE = de.DEC_CODI) as EFW_CODI
	FROM PRO_EXML AS de WITH (NOLOCK) INNER JOIN GIDWIN..FAP_FWUP AS fw WITH (NOLOCK) ON de.FUP_CODI = fw.FUP_CODI		
	WHERE de.EXM_ASAI = 0 and ISNULL(de.SIN_CODI, '') not in ('A13', 'A99', 'AHS') and fw.FUP_EFIM = 0 and fw.FUP_VUTI = 1

ALTER AUTHORIZATION ON [VW_Exportacao_DataCenterDeclaracoesParaWorkload] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Exportacao_DataCenterDeclaracoesParaWorkload] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoes] AS
	SELECT adi.DUC_EANO, adi.DUC_PNUM, adi.DUA_CODI, adi.APA_CO33, adi.DUA_TIVA, adi.PAI_CO34, adi.DUA_MB35, adi.PRE_CO36, adi.RRE_PREF, adi.DUA_RG37, adi.DUA_R37B, adi.DUA_ML38, adi.DUA_CO39, 
		adi.DUA_US41, adi.USU_CO41, adi.DUA_VA42, adi.DUA_VFRE, adi.DUA_VSEG, adi.DUA_VTRA, adi.DUA_VDIR, adi.DUA_VOPT, adi.DUA_DESG, adi.DUA_VEST, adi.DUA_AJUS, adi.DUA_DNUM, adi.DUA_DDAT, 
		adi.DUA_VATO, adi.DUA_BTRI, adi.DUA_TXCO, adi.DUA_TXVL, adi.DUA_MTRI, adi.DUA_IVAV, adi.DUA_BTIV, adi.RRE_CODI, adi.DUA_VIVA, adi.DUA_VAEU, adi.APA_CP33, adi.PAI_NOME, adi.PRE_NOME, 
		adi.USU_NOME, adi.RRE_NOME, adi.DUA_IMPO, adi.DUA_ATAR, adi.DUA_AIVA, adi.DUA_R37C, adi.DUA_IDEN, adi.DUA_2TAR, adi.DUA_3TAR, adi.DUA_MAVA, adi.RRE_NOME1, adi.DUA_IMPI, adi.DUA_1TAR, 
		adi.DUA_ABTI, adi.DUA_4TAR, adi.DUA_5TAR, adi.APA_CCUS, adi.NTR_CODI, adi.DUA_NRUR, adi.DUA_TMER, adi.DUA_IAVA, adi.FOR_CODI, adi.FOR_NOME, adi.FOR_MORA, adi.FOR_LOCA, adi.FOR_CPOS, 
		adi.FOR_LPOS, adi.FOR_NIF, adi.PAI_CODI, adi.PAI_CODI1, adi.PAI_CODI2, adi.RES_CODI, adi.FOR_CODI1, adi.FOR_NOME1, adi.FOR_MORA1, adi.FOR_LOCA1, adi.FOR_CPOS1, adi.FOR_LPOS1, adi.FOR_NIF1, 
		adi.PAI_CODI3, adi.CLI_CODI, adi.CLI_NOME, adi.CLI_MORA, adi.CLI_LOCA, adi.CLI_CPOS, adi.CLI_LPOS, adi.CLI_NIF, adi.PAI_CODI4, adi.DUA_ACRE, adi.DUA_DEDU, adi.DUA_MIVI, adi.DUA_QTDD, 
		adi.PAI_CODI5, 
		dbo.FNT_Extenso_ValorPorExtenso(ROUND(DUA_VATO, 2), 'euros', 'cêntimos') AS EXT_DUA_VATO, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 DOC_CODI AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 0 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 ISNULL(DDO_NUME, '') AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 0 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_NUMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 ISNULL(CONVERT(varchar(10), DDO_DINI, 105), '') AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 0 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_DATS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 ISNULL(DDO_EEMI, '') AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 0 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_EEMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 DOC_CODI AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 1 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DTR_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 ISNULL(DDO_NUME, '') AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 1 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DTR_NUMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 DOC_CODI AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 2 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DRA_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 ISNULL(DDO_NUME, '') AS field1Value FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 2 ORDER BY DDO_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DRA_NUMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 ped.TXM_CODI AS field1Value FROM tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dap.id_pedido = ped.TXM_IDTY WHERE dap.id_adicao = adi.DUA_IDEN ORDER BY dap.id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS PED_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 ISNULL(numero, '') AS field1Value FROM tb_IMP_DeclaracoesAdicoesPedidos WITH(NOLOCK) WHERE id_adicao = adi.DUA_IDEN ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS PED_NUMS,
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 3 ISNULL(funcao, '') AS field1Value FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais WITH(NOLOCK) WHERE id_adicao = adi.DUA_IDEN ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS RFI_FUNS,
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 3 ISNULL(nif, '') AS field1Value FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais WITH(NOLOCK) WHERE id_adicao = adi.DUA_IDEN ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS RFI_NIFS
	FROM PRO_DUAD AS adi WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoes] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesAcrescimosDeducoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesAcrescimosDeducoes] AS
	SELECT id, id_adicao, tipo, codigo, montante
	FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesAcrescimosDeducoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesAcrescimosDeducoes] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesContentores]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesContentores] AS
	SELECT DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO
	FROM PRO_DCON WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesContentores] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesContentores] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesDocumentos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesDocumentos] AS
	SELECT DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, PAI_CODI, DDO_MONT, DDO_NINV, DDO_TIPO, DDO_EEMI, UME_CODI, DDO_QTDE
	FROM PRO_DDOC WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesDocumentos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesDocumentos] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesEntrepostos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesEntrepostos] AS
	SELECT dae.id, dae.id_adicao, arm.ARM_CODI, arm.ARM_NOME, tar.TAR_CODI, tar.TAR_DESC, doc.DOC_CODI, doc.DOC_NOME, dae.numeroReferencia, dae.numeroEORI
	FROM tb_IMP_DeclaracoesAdicoesEntrepostos AS dae WITH(NOLOCK) 
		INNER JOIN TAB_ARMZ AS arm WITH(NOLOCK) ON dae.id_armazem = arm.ARM_CODI
		INNER JOIN TAB_TARM AS tar WITH(NOLOCK) ON dae.id_tipoArmazem = tar.TAR_IDTY
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dae.id_documento = doc.DOC_IDTY

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesEntrepostos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesEntrepostos] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesImposicoes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesImposicoes] AS
	SELECT DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, DUO_IMPO, DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT, ALF_CODI, DUO_CCAC, 
		DUO_CORF, DUO_CNRD, DUO_QTDE
	FROM PRO_DUOI WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesImposicoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesImposicoes] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesMarcasEVolumes]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesMarcasEVolumes] AS
	SELECT DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_LOPT
	FROM PRO_DU31 WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesMarcasEVolumes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesMarcasEVolumes] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesVeiculos]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesVeiculos] AS
	SELECT DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, DBT_VLIA, DBT_MARC, DBT_MODE, HTE_CODI, DBT_HOMO, 
		DBT_TABE, DBT_TCO2, DBT_AUTN, DBT_DIMT
	FROM PRO_DUBT WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesVeiculos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesVeiculos] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportAdicoesVeiculosChassis]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportAdicoesVeiculosChassis] AS
	SELECT DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS, DVC_DMAT, DVC_DCHA
	FROM PRO_DUVE WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportAdicoesVeiculosChassis] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportAdicoesVeiculosChassis] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportDadosGerais]    Script Date: 04-11-2025 10:22:20 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportDadosGerais] AS
	SELECT duc.DUC_PNUM, duc.DUC_EANO, duc.DUC_DATA, duc.NDE_CODI, duc.DUC_CPRT, duc.DUC_STAT, duc.DUC_DENV, duc.DUC_NORD, duc.DUC_NDAT, duc.DUC_CNTN, duc.DUC_NPRO, duc.TDE_CODI, duc.ALF_CODI, 
		duc.DUC_ADI5, duc.DUC_TVL6, duc.DUC_REF7, duc.DUC_EXP2, duc.DUC_DST8, duc.DEC_CO14, duc.PAI_PA15, duc.PAI_PA17, duc.PAI_P17B, duc.MTR_PT18, duc.DUC_MT18, duc.DUC_OP18, duc.DUC_CT18, 
		duc.MTR_FT21, duc.PAI_PA21, duc.DUC_CT19, duc.CEN_CO20, duc.DUC_DE20, duc.NTR_CO24, duc.DUC_LC27, duc.LME_CO30, duc.DUC_LC30, duc.PAI_PR22, duc.DUC_MT22, duc.DUC_TX23, duc.DUC_FRET, 
		duc.PAI_FRET, duc.DUC_TXFR, duc.DUC_SEGU, duc.PAI_SEGU, duc.DUC_TXSE, duc.DUC_MLQT, duc.DUC_MBRT, duc.DUC_VTRN, duc.PAI_VTRN, duc.DUC_TXVT, duc.DUC_VEUR, duc.DUC_DIRT, duc.DUC_TFDA, 
		duc.DUC_ENOM, duc.DUC_EMOR, duc.DUC_ELOC, duc.DUC_ECPO, duc.DUC_ELPO, duc.DUC_ENIF, duc.PAI_ELIV, duc.DUC_DNOM, duc.DUC_DMOR, duc.DUC_DLOC, duc.DUC_DCPO, duc.DUC_DLPO, duc.DUC_DNIF, 
		duc.PAI_DLIV, duc.DUC_HIST, duc.DUC_VLRC, duc.DUC_VLRE, duc.DUC_VATT, duc.DUC_UCRI, duc.DUC_DTCR, duc.DUC_UALT, duc.DUC_DTAL, duc.NDE_NOME, duc.TDE_NOME, duc.ALF_NOME, duc.PAI_NO15, 
		duc.PAI_NO17, duc.PAI_MO22, duc.PAI_MOFT, duc.PAI_MOSG, duc.PAI_MOVT, duc.DEC_NOME, duc.DEC_CENI, duc.MTR_NO18, duc.MTR_NO21, duc.DUC_NREQ, duc.DUC_NDUR, duc.DUC_T1RE, duc.DUC_DDTE, 
		duc.DUC_DTVO, duc.DUC_PAYM, duc.DUC_NPDT, duc.DUC_NPDD, duc.DUC_NTDP, duc.DUC_PARM, duc.DUC_NVRF, duc.DUC_TREM, duc.DUC_CIEX, duc.DUC_CIDE, duc.DUC_AERO, duc.DUC_PPFC, duc.DUC_NVOO, 
		duc.DUC_MCPA, duc.DUC_NSEQ, duc.DUC_REF1, duc.DUC_REF2, duc.DUC_SHIP, duc.DUC_TRAC, duc.DUC_DTYP, duc.DUC_POSA, duc.DUC_TPCG, duc.DUC_FUPS, duc.DUC_VDIR, duc.DUC_VCLE, duc.DUC_D2NO, 
		duc.DUC_D2MO, duc.DUC_D2LO, duc.DUC_D2CP, duc.DUC_D2LP, duc.DUC_ASAI, duc.DUC_TPDS, duc.DUC_TPDC, duc.TDE_1CAS, duc.TDE_2CAS, duc.DUC_DTAS, duc.DUC_GTWY, duc.DUC_DELG, duc.CLI_CODI, 
		duc.CLI_NOME, duc.DUC_VERS, duc.DUC_REVI, duc.DUC_ESTO, duc.DUC_CAUC, duc.DUC_TLOC, duc.ALF_CODI1, duc.ALF_NOME1, duc.DUC_LAMO, duc.DUC_LALO, duc.DUC_LACP, duc.ARM_CODI, duc.ARM_NOME, 
		duc.TAR_CODI, duc.TAR_DESC, duc.DUC_NRLO, duc.NTR_NOME, duc.DUC_VSCA, duc.DUC_CRTD, duc.DUC_CRTF, duc.DUC_CRTA, duc.DUC_VFRC, duc.DUC_MFRC, duc.DUC_NVSR, duc.DUC_DDDT, duc.DUC_NACT, 
		duc.DUC_VDES, duc.DUC_DTEL, duc.DUC_DEMA, duc.DUC_IDTY, duc.DUC_DCEN, duc.DUC_ANXB, duc.DUC_DGEN, duc.FOR_CODI, duc.FOR_NOME, duc.FOR_MORA, duc.FOR_LOCA, duc.FOR_CPOS, duc.FOR_LPOS, 
		duc.FOR_NIF, duc.PAI_CODI, duc.CLI_CODI1, duc.CLI_NOME1, duc.CLI_MORA, duc.CLI_LOCA, duc.CLI_CPOS, duc.CLI_LPOS, duc.CLI_NIF AS CLI_NIF1, duc.PAI_CODI1, duc.DEC_NIF, duc.ALF_CODI2, 
		duc.DUC_CCAC, duc.DUC_CORF, duc.ALF_CODI3, duc.ALF_CODI4, duc.PAI_CODI2, duc.PAE_CODI, duc.MTR_CODI, duc.MTR_TIPO, duc.DUC_CONT, duc.DUC_QUAL, duc.DUC_IADI, duc.DUC_ONIF, duc.DOC_CODI, 
		duc.DUC_NRAU, duc.DUC_EORI, duc.DUC_REGI, 
		dcl.DEC_MORA, dcl.DEC_LOCA, dcl.DEC_CPOS, dcl.DEC_LPOS, dcl.DEC_WSUS,
		cli.CLI_TELF, cli.CLI_EMAI, cli.CLI_NIF, cli.CLI_NDHA, cli.CLI_DTDH, cli.CLI_INFO, cli.CLI_CODC, cli.CLI_SENT, cli.CLI_CGLO,
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 doc.DOC_CODI AS field1Value FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 0 ORDER BY ddo.id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 ISNULL(numero, '') AS field1Value FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK) WHERE id_declaracaoIMP = duc.DUC_IDTY AND tipo = 0 ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_NUMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 ISNULL(CONVERT(varchar(10), dataValidade, 105), '') AS field1Value FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK) WHERE id_declaracaoIMP = duc.DUC_IDTY AND tipo = 0 ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_DATS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 4 ISNULL(entidadeEmissora, '') AS field1Value FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK) WHERE id_declaracaoIMP = duc.DUC_IDTY AND tipo = 0 ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DSU_EEMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 doc.DOC_CODI AS field1Value FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 1 ORDER BY ddo.id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DTR_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 ISNULL(numero, '') AS field1Value FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK) WHERE id_declaracaoIMP = duc.DUC_IDTY AND tipo = 1 ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DTR_NUMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 doc.DOC_CODI AS field1Value FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 2 ORDER BY ddo.id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DRA_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 ISNULL(numero, '') AS field1Value FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK) WHERE id_declaracaoIMP = duc.DUC_IDTY AND tipo = 2 ORDER BY id FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS DRA_NUMS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 TXM_CODI AS field1Value FROM PRO_DUPD WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM ORDER BY DPD_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS PED_CODS, 
		dbo.fn_Geral_ConverteTabelaXMLParaLista((SELECT TOP 2 ISNULL(DPD_DESC, '') AS field1Value FROM PRO_DUPD WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM ORDER BY DPD_CODI FOR XML PATH('record'), ROOT('table'), TYPE), NULL, (CHAR(13) + CHAR(10))) AS PED_NUMS		
	FROM PRO_DUCG AS duc WITH(NOLOCK)
		INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI
		INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
	WHERE duc.DUC_DUNO = 2	

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportDadosGerais] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportDadosGerais] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportDocumentos]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportDocumentos] AS
	SELECT ddo.id, ddo.id_declaracaoIMP, ddo.tipo, doc.DOC_CODI, doc.DOC_NOME, ddo.numero, ddo.dataValidade, ddo.montante
	FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportDocumentos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportDocumentos] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportLiquidacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportLiquidacao] AS
	SELECT DUC_EANO, DUC_PNUM, RRE_CODI, RRE_NOME, DUL_MONT
	FROM PRO_DULR WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportLiquidacao] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportLiquidacao] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportManifestos]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportManifestos] AS
	SELECT DUC_EANO, DUC_PNUM, DUO_CODI, PAI_CODI, DUO_DESC, APA_CPAU, DUO_VALO, DUO_MOED, DUO_TFAC, DUO_CPA2, DUO_PES2, DUO_TIPO
	FROM PRO_DUOD WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportManifestos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportManifestos] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportPedidos]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportPedidos] AS
	SELECT DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC
	FROM PRO_DUPD WITH(NOLOCK) 		

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportPedidos] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportPedidos] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_ReportPrecedentes]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_ReportPrecedentes] AS
	SELECT dpr.id, dpr.id_declaracaoIMP, doc.DOC_CODI, doc.DOC_NOME, dpr.numero, dpr.dataContramarca
	FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 
		INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_ReportPrecedentes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_ReportPrecedentes] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_WSPendentesResposta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_WSPendentesResposta] AS
	SELECT dim.DUC_IDTY, dim.DUC_PNUM, dim.DUC_EANO, dim.DUC_DATA, dim.DUC_CPRT, dim.DUC_STAT, dim.DUC_NORD, dim.DUC_NDAT, dim.ALF_CODI, dim.DUC_DST8, dim.DUC_DNOM, 
		dim.DUC_UCRI, dim.ALF_NOME, dim.DUC_ESTO, dim.DUC_NRLO, 
		(CASE 
			WHEN (dim.DUC_STAT = 1 OR (dim.DUC_STAT = 2 AND dim.DUC_ASAI = 0 AND ISNULL(dim.DUC_ESTO, '') <> 'SNA')) THEN 0			
			WHEN (dim.DUC_STAT = 2 AND dim.DUC_ASAI = 1 AND DATEDIFF(DAY, dim.DUC_DTAS, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <= 60) THEN 1
			ELSE -1
		END) AS DUC_TPEN
	FROM PRO_DUCG AS dim WITH(NOLOCK) 
		INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dim.DEC_CO14 = dcl.DEC_CODI
		INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dim.NDE_CODI = nat.NDE_CODI	
		INNER JOIN TAB_PDES AS pde WITH(NOLOCK)	ON 1 = 1
	WHERE dim.DUC_DUNO = 2 AND dim.DUC_ADI5 > 0 AND nat.NDE_FEDI = 1 AND ISNULL(dcl.DEC_WSEP, '') <> ''
		AND ((dim.DUC_STAT = 1 OR (dim.DUC_STAT = 2 AND dim.DUC_ASAI = 0 AND ISNULL(dim.DUC_ESTO, '') <> 'SNA')) -- p/ mensagens CC428A, CC456A, CC426A, ..., CC451A ou CC429A					
			OR (dim.DUC_STAT = 2 AND dim.DUC_ASAI = 1 AND DATEDIFF(DAY, dim.DUC_DTAS, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <= 60)) -- p/ restantes mensagens pós CC429A		
		AND (CASE WHEN ISNULL(pde.PDE_CADI, 0) IN (1, 2) THEN ISNULL(dim.DUC_VCLE, 0) ELSE ISNULL(dim.DUC_TVL6, 0) END) = ISNULL(dim.DUC_TVL6, 0) --FEDEX/TNT, UPS			
		AND NOT EXISTS(SELECT 1 FROM dbo.fn_IMP_ObtemErrosSubmissaoWS(dim.DUC_IDTY))

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_WSPendentesResposta] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_WSPendentesResposta] TO [public] AS [dbo]
/****** Object:  View [vw_IMP_Declaracoes_WSPendentesSubmissao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_IMP_Declaracoes_WSPendentesSubmissao] AS
	SELECT dim.DUC_IDTY, dim.DUC_PNUM, dim.DUC_EANO, dim.DUC_DATA, dim.NDE_CODI, dim.DUC_CPRT, dim.TDE_CODI, dim.ALF_CODI, dim.DUC_EXP2, dim.DUC_DST8, dim.DUC_ENOM, 
		dim.DUC_DNOM, ISNULL(dim.DUC_VLRC, 0) AS DUC_VLRC, dim.NDE_NOME, dim.TDE_NOME, dim.ALF_NOME, dim.TDE_2CAS, dim.DUC_ESTO, dim.DUC_NRLO, dim.DUC_ANXB, dim.DUC_REGI 
	FROM PRO_DUCG AS dim WITH(NOLOCK) 
		INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dim.DEC_CO14 = dcl.DEC_CODI
		INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dim.NDE_CODI = nat.NDE_CODI	
		INNER JOIN TAB_PDES AS pde WITH(NOLOCK)	ON 1 = 1	
	WHERE dim.DUC_DUNO = 2 AND dim.DUC_STAT = 0 AND dim.DUC_ADI5 > 0 AND nat.NDE_FEDI = 1 AND ISNULL(dcl.DEC_WSEP, '') <> '' AND ISNULL(dim.DUC_ESTO, '') <> 'RE' 		
		AND (CASE WHEN (ISNULL(dim.TDE_2CAS, '') <> 'D') AND (ISNULL(pde.PDE_CADI, 0) IN (1, 2, 3)) THEN dim.DUC_VSCA ELSE ISNULL(dim.DUC_TVL6, 0) END) = ISNULL(dim.DUC_TVL6, 0) --FEDEX/TNT, UPS, DHL
		AND (CASE WHEN (ISNULL(dim.TDE_2CAS, '') = 'D') AND (ISNULL(pde.PDE_CADI, 0) IN (1, 2, 3)) THEN dim.DUC_VDIR ELSE ISNULL(dim.DUC_TVL6, 0) END) > 0 --FEDEX/TNT, UPS, DHL						
		AND NOT EXISTS(SELECT 1 FROM dbo.fn_IMP_ObtemErrosSubmissaoWS(dim.DUC_IDTY)) 

ALTER AUTHORIZATION ON [vw_IMP_Declaracoes_WSPendentesSubmissao] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_IMP_Declaracoes_WSPendentesSubmissao] TO [public] AS [dbo]
/****** Object:  View [VW_Importacao_GestaoADT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Importacao_GestaoADT] AS		
	SELECT (CASE duc.DUC_DUNO WHEN 2 THEN 'IMP-CAU' ELSE 'DUI2' END) AS DUC_CNTX, duc.DUC_IDTY, duc.DUC_EANO, duc.DUC_PNUM, duc.NDE_CODI, nat.NDE_NOME, duc.DUC_CPRT, duc.DUC_DST8, duc.DUC_DNOM, 
		duc.DUC_TVL6, duc.DUC_MBRT, duc.DUC_TREM, duc.DUC_NVRF, (CASE WHEN duc.ALF_CODI = 'PT000015' THEN duc.DUC_NACT ELSE duc.DUC_NPDD END) AS DUC_NACT, duc.DUC_MCPA, duc.DUC_CNTN, 
		duc.TDO_DOCU, duc.DUC_LADT, duc.DUC_DELG, duc.LME_CO30, duc.DUC_LC30, 
		(CASE duc.DUC_ACAO WHEN 1 THEN CAST(1 AS bit) ELSE CAST(0 AS BIT) END) AS DUC_FAUT, 
		nat.NDE_GADT, nat.NDE_CRCO, 
		cli.CLI_CGLO, (CASE WHEN cli.CLI_CODC = 1 THEN 'COD' WHEN cli.CLI_CACC = 1 THEN 'ACC' WHEN cli.CLI_CEXB = 1 THEN 'EXB' WHEN cli.CLI_CDAS = 1 THEN 'DAS' ELSE NULL END) AS CLI_TIPO, 
		dua.DUA_DDAT, 
		(SELECT TOP 1 CAST(CONVERT(varchar(10), DUI_DINI, 105) + ' ' + CONVERT(varchar(12), DUI_HINI, 114) AS datetime) 
			FROM PRO_DUIN WITH(NOLOCK)
			WHERE DUC_PNUM = duc.DUC_PNUM and DUC_EANO = duc.DUC_EANO and (SIN_CODI in ('A00', 'A13', 'ND') or DUI_REHO = 0) ORDER BY DUI_CODI desc) AS DUI_DINI,
		(CASE WHEN EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_IDCV = 0) THEN NULL WHEN duc.DUC_DTYP in ('A5' , 'A6', 'DA') THEN 'ACC' WHEN duc.DUC_DTYP in ('CA', 'EC') THEN 'COD' WHEN duc.DUC_DTYP in ('D5', 'D6', 'LD') THEN 'EXB' ELSE NULL END) as CDO_CTIP	
	FROM PRO_DUCG as duc WITH(NOLOCK) 
		INNER JOIN TAB_NDES as nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI	
		LEFT OUTER JOIN TAB_CLIE as cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
		INNER JOIN PRO_DUAD as dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO and duc.DUC_PNUM = dua.DUC_PNUM and dua.DUA_CODI = 1
	WHERE duc.DUC_LADT = 0 AND EXISTS(SELECT DUI_CODI FROM PRO_DUIN WITH(NOLOCK) WHERE DUC_PNUM = duc.DUC_PNUM and DUC_EANO = duc.DUC_EANO and (SIN_CODI in ('A00', 'A13', 'ND') or DUI_REHO = 0))
		AND (nat.NDE_GADT = 1 OR (nat.NDE_GADT = 0 AND nat.NDE_CRCO = 1 AND (cli.CLI_CGLO = 1 OR (cli.CLI_CGLO = 0 AND duc.DUC_CNTN IS NOT NULL))))
	UNION ALL
	SELECT 'DAR', dar.id, dar.ano, dar.numero, nat.NDE_CODI, nat.NDE_NOME, dar.documentoTransporte, cli.CLI_CODI, dar.nomeCliente, 
		dar.totalVolumes, dar.totalMassaBruta, dar.totalMassaBruta, dar.numeroVossaReferencia, (CASE WHEN alf.ALF_CODI = 'PT000015' THEN dar.numeroACTM ELSE dar.numeroPDDTDEV END), dar.miniCPA, cnt.CDO_CNUM, 
		tdo.TDO_DOCU, dar.libertoADT, dar.locIDFEDEX, lme.LME_CODI, lme.LME_NOME, 
		(CASE dar.acao WHEN 1 THEN CAST(1 AS bit) ELSE CAST(0 AS BIT) END), 
		nat.NDE_GADT, nat.NDE_CRCO, 
		cli.CLI_CGLO, (CASE WHEN cli.CLI_CODC = 1 THEN 'COD' WHEN cli.CLI_CACC = 1 THEN 'ACC' WHEN cli.CLI_CEXB = 1 THEN 'EXB' WHEN cli.CLI_CDAS = 1 THEN 'DAS' ELSE NULL END), 
		(SELECT TOP 1 dataContramarca FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id), 
		(SELECT TOP 1 din.dataInicio
			FROM tb_DeclaracoesDARIncidencias AS din WITH(NOLOCK) 
				LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON din.id_statusIncidencia = inc.SIN_IDTY 
				LEFT OUTER JOIN TAB_COSM AS cco WITH(NOLOCK) ON din.id_statusIncidencia = cco.COS_IDTY
			WHERE din.id_declaracaoDAR = dar.id AND (inc.SIN_CODI IN ('A00', 'A13', 'ND') OR cco.COS_CODE IN ('A00', 'A13', 'ND') OR din.releaseHold = 'R') 
			ORDER BY din.id DESC), 
		(CASE WHEN EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_IDCV = 0) THEN NULL WHEN dar.dutyType IN ('A5' , 'A6', 'DA') THEN 'ACC' WHEN dar.dutyType in ('CA', 'EC') THEN 'COD' WHEN dar.dutyType in ('D5', 'D6', 'LD') THEN 'EXB' ELSE NULL END)
	FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
		INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
		INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
		INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
		LEFT OUTER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON dar.id_conta = cnt.CDO_IDTY
		LEFT OUTER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dar.id_tipoDocumentoConta = tdo.TDO_IDTY
		LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dar.id_localAutorizado = lme.LME_IDTY
	WHERE dar.libertoADT = 0 
		AND EXISTS(SELECT din.id
					FROM tb_DeclaracoesDARIncidencias AS din WITH(NOLOCK) 
						LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON din.id_statusIncidencia = inc.SIN_IDTY 
						LEFT OUTER JOIN TAB_COSM AS cco WITH(NOLOCK) ON din.id_statusIncidencia = cco.COS_IDTY
					WHERE din.id_declaracaoDAR = dar.id AND (inc.SIN_CODI IN ('A00', 'A13', 'ND') OR cco.COS_CODE IN ('A00', 'A13', 'ND') OR din.releaseHold = 'R'))		
		AND (nat.NDE_GADT = 1 OR (nat.NDE_GADT = 0 AND nat.NDE_CRCO = 1 AND (cli.CLI_CGLO = 1 OR (cli.CLI_CGLO = 0 AND cnt.CDO_CNUM IS NOT NULL))))

ALTER AUTHORIZATION ON [VW_Importacao_GestaoADT] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Importacao_GestaoADT] TO [public] AS [dbo]
/****** Object:  View [VW_MAP_HONO]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_MAP_HONO] AS
	select m.MVC_TDOC, m.MVC_NDOC, m.MVC_EANO, m.MVC_ENTI, m.MVC_DATA, m.MVC_TMOV, m.MVC_CTXT, m.MVC_NDES, t.CLI_NOME, 
		(isnull(c.CDO_TTIN, 0) + isnull(c.CDO_TTHO, 0)) as VAL_HONO
	from FAC_MVCC as m INNER JOIN TAB_CLIE as t ON m.MVC_ENTI = t.CLI_CODI
		INNER JOIN FAC_CDOC as c ON m.MVC_TDOC = c.CDO_TDOC and m.MVC_NDOC = c.CDO_CNUM and m.MVC_EANO = c.CDO_EANO
	where m.MVC_CTXT = 0
	UNION ALL
	select m.MVC_TDOC, m.MVC_NDOC, m.MVC_EANO, m.MVC_ENTI, m.MVC_DATA, m.MVC_TMOV, m.MVC_CTXT, m.MVC_NDES, t.CLI_NOME, 
		(isnull(sum(round(isnull(v.DVD_QUAN, 0) * isnull(v.DVD_VALO, 0), 2)), 0)) as VAL_HONO
	from FAC_MVCC as m INNER JOIN TAB_CLIE as t ON m.MVC_ENTI = t.CLI_CODI
		INNER JOIN FAC_DVDT as v ON m.MVC_TDOC = v.DVE_TDOC and m.MVC_NDOC = v.DVE_NDOC and m.MVC_EANO = v.DVE_EANO
	where m.MVC_CTXT = 1 and v.DVD_LHON = 1
	group by m.MVC_TDOC, m.MVC_NDOC, m.MVC_EANO, m.MVC_ENTI, m.MVC_DATA, m.MVC_TMOV, m.MVC_CTXT, m.MVC_NDES, t.CLI_NOME

ALTER AUTHORIZATION ON [VW_MAP_HONO] TO  SCHEMA OWNER 
GRANT DELETE ON [VW_MAP_HONO] TO [public] AS [dbo]
GRANT INSERT ON [VW_MAP_HONO] TO [public] AS [dbo]
GRANT SELECT ON [VW_MAP_HONO] TO [public] AS [dbo]
GRANT UPDATE ON [VW_MAP_HONO] TO [public] AS [dbo]
/****** Object:  View [VW_MAPA_RECAPITULATIVO]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_MAPA_RECAPITULATIVO] AS
	select m.MVC_EANO, m.MVC_ENTI, c.CLI_NOME, c.CLI_NIF, 
		(round(sum((case m.MVC_TMOV when 1 then (-1) * ((round(isnull(d.DVD_QUAN, 0) * isnull(d.DVD_VALO, 0), 2)) * (1 + d.DVD_IVA / 100))
		else ((round(isnull(d.DVD_QUAN, 0) * isnull(d.DVD_VALO, 0), 2)) * (1 + d.DVD_IVA / 100)) end)), 2)) as TOTAL
	from FAC_MVCC as m INNER JOIN TAB_TDOC as t ON m.MVC_TDOC = t.TDO_DOCU
		INNER JOIN TAB_CLIE as c ON MVC_ENTI = c.CLI_CODI
		INNER JOIN FAC_DVDT as d ON m.MVC_TDOC = d.DVE_TDOC and m.MVC_NDOC = d.DVE_NDOC and m.MVC_EANO = d.DVE_EANO
	where m.MVC_CTXT = 1 and m.MVC_TENT = 0 and t.TDO_MREC = 1 and d.DVD_LHON = 1
	group by m.MVC_EANO, m.MVC_ENTI, c.CLI_NOME, c.CLI_NIF
	UNION ALL
	select m.MVC_EANO, m.MVC_ENTI, c.CLI_NOME, c.CLI_NIF, sum((case m.MVC_TMOV when 1 then (-1) * ((isnull(d.CDO_TTIN, 0) + isnull(d.CDO_TTHO, 0) + isnull(CDO_IVA, 0)))
		else ((isnull(d.CDO_TTIN, 0) + isnull(d.CDO_TTHO, 0) + isnull(CDO_IVA, 0))) end))
	from FAC_MVCC as m INNER JOIN TAB_TDOC as t ON m.MVC_TDOC = t.TDO_DOCU
		INNER JOIN TAB_CLIE as c ON MVC_ENTI = c.CLI_CODI
		INNER JOIN FAC_CDOC as d ON m.MVC_TDOC = d.CDO_TDOC and m.MVC_NDOC = d.CDO_CNUM and m.MVC_EANO = d.CDO_EANO
	where m.MVC_CTXT = 0 and m.MVC_TENT = 0 and t.TDO_MREC = 1
	group by m.MVC_EANO, m.MVC_ENTI, c.CLI_NOME, c.CLI_NIF

ALTER AUTHORIZATION ON [VW_MAPA_RECAPITULATIVO] TO  SCHEMA OWNER 
GRANT DELETE ON [VW_MAPA_RECAPITULATIVO] TO [public] AS [dbo]
GRANT INSERT ON [VW_MAPA_RECAPITULATIVO] TO [public] AS [dbo]
GRANT SELECT ON [VW_MAPA_RECAPITULATIVO] TO [public] AS [dbo]
GRANT UPDATE ON [VW_MAPA_RECAPITULATIVO] TO [public] AS [dbo]
/****** Object:  View [VW_SDSViaAerea_EnvioManifestoDadosAWBPendentes]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_SDSViaAerea_EnvioManifestoDadosAWBPendentes] AS	
	SELECT sd.DSC_EANO, sd.DSC_NPRO, sd.DSD_NUME, sd.DSD_ESTA, sd.DSD_NDGA, sd.DSD_ANUL, sd.DSD_DNOW, sc.DSC_UDEM, sd.DSD_NRMH, sd.DOC_CODI, sd.DSD_LOED, sd.DSD_DTED, sd.DSD_EEED, sd.PAI_CODI, 
		sd.DSD_TIPO, pd.PAI_CODI AS PAI_CODI1, sd.PAE_CODI, sd.PAE_NOME, pe.PAI_CODI AS PAI_CODI2, pe.EAD_CODI, sd.PAE_CODI1, po.PAI_CODI AS PAI_CODI3, sd.PAE_CODI2, sd.PAE_NOME2, sd.DSD_EADC, 
		sd.DSD_IDOS, sd.DSD_NOOS, sd.DSD_IDNS, sd.DSD_NONS, sd.DSD_IDED, sd.DSD_NOMD, sd.DSD_IDEN, sd.DSD_IDEC, sd.DSD_DMER, sd.DSD_MRNR, sd.TEM_CODI, sd.DSD_VOLS, sd.DSD_PESO, sd.DSD_VALO, 
		sd.DSD_TCAR, sd.LME_CODI, p1.PAI_CODI as PAI_CODI4, sd.PAE_CODI3, sd.PAE_NOME3, sd.DSD_CAPO, sd.DSD_TCTU, sd.DSD_TMEX, sd.DSD_NDGI, sd.DSD_DEPO, sd.DSD_JUST, sd.DSD_IDCR, sd.DSD_CODR, 
		sd.DSD_NEAD, sd.DSD_CEAD, sd.DSD_MOOS, sd.DSD_MORD, sd.DSD_NDAU, sd.DSD_DTEN, sd.DSD_ORIG, sd.DSD_AFRQ, sd.DSD_MAWB, sd.DSD_IDOR, sd.DSD_IDNN, sd.DSD_NDSC, sd.DSD_CPOS, sd.DSD_LOOS, 
		sd.DSD_NDPR, sd.APA_CODI, sd.DSD_CPAU, sd.TXM_CODI, sd.DSD_PTXT, sc.DSC_DTVO, 
		(CASE 
			WHEN (sd.DSD_STAT IN (0, 3) AND ISNULL(sd.DSD_ESTA, '') = '' AND ISNULL(sd.DSD_NDGA, '') = '' AND ISNULL(sd.DSD_NDGI, '') = '' AND sd.DSD_PDEP = 0) THEN 1 
			WHEN (ISNULL(sd.DSD_ESTA, '') <> '' AND (ISNULL(sd.DSD_NDGA, '') <> '' OR ISNULL(sd.DSD_NDGI, '') <> '') AND sd.DSD_ANUL = 0 AND sd.DSD_DNOW > sc.DSC_UDEM) THEN 2 
			WHEN (ISNULL(sd.DSD_ESTA, '') <> '' AND (ISNULL(sd.DSD_NDGA, '') <> '' OR ISNULL(sd.DSD_NDGI, '') <> '') AND sd.DSD_ANUL = 1 AND sd.DSD_DNOW > sc.DSC_UDEM) THEN 3 
			ELSE 0 
		END) AS DSD_ESTI
	FROM PRO_SDSD AS sd WITH(NOLOCK) 
		INNER JOIN PRO_SDSC AS sc WITH(NOLOCK) ON sd.DSC_EANO = sc.DSC_EANO AND sd.DSC_NPRO = sc.DSC_NPRO 
		INNER JOIN TAB_PAER AS pd WITH(NOLOCK) ON sd.PAE_CODI = pd.PAE_CODI 
		INNER JOIN TAB_PAER AS pe WITH(NOLOCK) ON sd.PAE_CODI1 = pe.PAE_CODI 
		INNER JOIN TAB_PAER AS po WITH(NOLOCK) ON sd.PAE_CODI2 = po.PAE_CODI 
		INNER JOIN TAB_PAER AS p1 WITH(NOLOCK) ON sd.PAE_CODI3 = p1.PAE_CODI 
	WHERE sd.DSD_ENVI = 1 AND sd.DSD_EFRQ = 0 
		AND ((sd.DSD_STAT IN (0, 3) AND ISNULL(sd.DSD_ESTA, '') = '' AND ISNULL(sd.DSD_NDGA, '') = '' AND ISNULL(sd.DSD_NDGI, '') = '' AND sd.DSD_PDEP = 0 AND sd.DSD_DNOW > ISNULL(sc.DSC_UDEM, DATEADD(d, -1, sd.DSD_DNOW))) 
			OR (ISNULL(sd.DSD_ESTA, '') <> '' AND (ISNULL(sd.DSD_NDGA, '') <> '' OR ISNULL(sd.DSD_NDGI, '') <> '') AND sd.DSD_ANUL = 0 AND sd.DSD_DNOW > sc.DSC_UDEM) 
			OR (ISNULL(sd.DSD_ESTA, '') <> '' AND (ISNULL(sd.DSD_NDGA, '') <> '' OR ISNULL(sd.DSD_NDGI, '') <> '') AND sd.DSD_ANUL = 1 AND sd.DSD_DNOW > sc.DSC_UDEM))

ALTER AUTHORIZATION ON [VW_SDSViaAerea_EnvioManifestoDadosAWBPendentes] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_SDSViaAerea_EnvioManifestoDadosAWBPendentes] TO [public] AS [dbo]
/****** Object:  View [VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes] AS
	SELECT dsd.DSC_EANO, dsd.DSC_NPRO, dsd.DSD_NUME, dsd.DSD_IDNN, dsd.DOC_CODI, dsd.DSD_NRMH, dsd.DSD_DMER, dsd.DSD_PESO, dsd.DSD_VOLS, dsd.TEM_CODI, dsd.DSD_MRNR, dsd.DSD_TCAR, dsd.LME_CODI, 
		dsd.DSD_CPER, dsd.DSD_CAPO, dsd.PAE_CODI, dsd.EXA_CHVE, dsd.DSD_NDPR, 
		(CASE 
			WHEN ((dsd.DSD_STRD > 0) AND (dsd.DSD_SIRD > 0) AND (dsd.DSD_RIRD IN (1, 3)) AND (dsd.DSD_DNOW > dsd.DSD_DERD) AND ((dsd.DSD_JUST like '%Volume%') OR (dsd.DSD_JUST like '%Peso%'))) THEN 1 
			WHEN ((dsd.DSD_STRD > 0) AND (dsd.DSD_SIRD > 0) AND (dsd.DSD_RIRD IN (1, 3)) AND (dsd.DSD_DNOW > dsd.DSD_DERD) AND (dsd.DSD_ANUL = 1)) THEN 2
			ELSE 0 
		END) AS DSD_ESTI,
		dsc.DSC_TIPO, dsc.EAD_CODI, dsc.DSC_DTVO, pad.PAI_CODI 
	FROM PRO_SDSD AS dsd WITH(NOLOCK) 
		INNER JOIN PRO_SDSC AS dsc WITH(NOLOCK) ON dsd.DSC_EANO = dsc.DSC_EANO AND dsd.DSC_NPRO = dsc.DSC_NPRO 		
		INNER JOIN TAB_PAER AS pad WITH(NOLOCK) ON dsd.PAE_CODI = pad.PAE_CODI 
	WHERE dsc.DSC_TIPO = 0 AND dsd.DSD_EADC <> 'C' AND dsd.DSD_TIPO <> 'TR' AND dsd.DSD_DEPO = dsc.DSC_IDDP AND dsd.DSD_ENVI = 1 
		AND (((dsd.DSD_STRD = 0) AND (dsd.DSD_ANUL = 0)) OR ((dsd.DSD_STRD > 0) AND (dsd.DSD_SIRD > 0) AND (dsd.DSD_RIRD = 2))
			OR ((dsd.DSD_STRD > 0) AND (dsd.DSD_SIRD > 0) AND (dsd.DSD_RIRD IN (1, 3)) AND (dsd.DSD_DNOW > dsd.DSD_DERD) AND ((dsd.DSD_JUST like '%Volume%') OR (dsd.DSD_JUST like '%Peso%')))
			OR ((dsd.DSD_STRD > 0) AND (dsd.DSD_SIRD > 0) AND (dsd.DSD_RIRD IN (1, 3)) AND (dsd.DSD_DNOW > dsd.DSD_DERD) AND (dsd.DSD_ANUL = 1)))

ALTER AUTHORIZATION ON [VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes] TO [public] AS [dbo]
/****** Object:  View [VW_SDSViaAerea_HistorioIntegracaoWSDetalhado]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_SDSViaAerea_HistorioIntegracaoWSDetalhado] AS
	SELECT DSI_CODI, DSI_MSGI, DSI_STAT, DSI_TMSG, DSI_RDES, DSI_NCTM, DSI_RESG, DSC_EANO, DSC_NPRO, 
		XML_MSGR.MSG_DATA.value('(*:CustomsDocument/*:Number)[1]', 'varchar(30)') AS DSI_NAWB,
		XML_MSGR.MSG_DATA.value('(*:ActionResult/*:Result)[1]', 'varchar(50)') AS DSI_ARSL
	FROM HST_SDSI AS dsi CROSS APPLY DSI_MSGD.nodes('*:AirCustomsResponse/*:Cargos/*:Cargo') as XML_MSGR(MSG_DATA)
	UNION
	SELECT DSI_CODI, DSI_MSGI, DSI_STAT, DSI_TMSG, DSI_RDES, DSI_NCTM, DSI_RESG, DSC_EANO, DSC_NPRO,  
		NULL AS DSI_NAWB,
		NULL AS DSI_ARSL
	FROM HST_SDSI AS dsi CROSS APPLY DSI_MSGD.nodes('*:AirCustomsResponse') as XML_MSGR(MSG_DATA)
	WHERE ISNULL(XML_MSGR.MSG_DATA.value('(*:Cargos/*:Cargo/*:CustomsDocument/*:Number)[1]', 'varchar(30)'), '') = ''
	UNION
	SELECT DSI_CODI, DSI_MSGI, DSI_STAT, DSI_TMSG, DSI_RDES, DSI_NCTM, DSI_RESG, DSC_EANO, DSC_NPRO, 
		XML_MSGR.MSG_DATA.value('(*:CustomsDocument/*:Number)[1]', 'varchar(30)') AS DSI_NAWB,
		(CASE WHEN DSI_TMSG = 2 THEN XML_MSGR.MSG_DATA.value('(*:Authorization/*:AuthorizationType)[1]', 'varchar(50)') ELSE XML_MSGR.MSG_DATA.value('(*:Control/*:Type)[1]', 'varchar(50)') END) AS DSI_ARSL
	FROM HST_SDSI AS dsi CROSS APPLY DSI_MSGD.nodes('*:AirCustomsNotification/*:Cargos/*:Cargo') as XML_MSGR(MSG_DATA)

ALTER AUTHORIZATION ON [VW_SDSViaAerea_HistorioIntegracaoWSDetalhado] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_SDSViaAerea_HistorioIntegracaoWSDetalhado] TO [public] AS [dbo]
/****** Object:  View [VW_SDSViaAerea_MovimentoSaidaDadosAWB]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_SDSViaAerea_MovimentoSaidaDadosAWB] AS
	SELECT dsd.DSC_EANO, dsd.DSC_NPRO, dsd.DSD_NUME, dsd.DSD_IDNN, dsd.DSD_NRMH, dsd.DOC_CODI, dsd.DOC_NOME, dsd.DSD_DMER, dsd.DSD_PESO, dsd.DSD_VOLS, dsd.TEM_CODI, dsd.DSD_MRNR, dsd.DSD_TCAR, 
		dsd.DSD_NDGA, dsd.DSD_NDGI, dsd.DSD_DTRD, dsd.DSD_DNRD, dsd.DSD_NDPR, dsc.DSC_TIPO, dsc.EAD_CODI, dsc.EAD_NOME, dsc.DSC_NCMF, dsc.DSC_NCMV, dsc.DSC_NVOO, dsc.DSC_DPRV, dsc.DSC_DEFT, 
		DATEDIFF(day, dsc.DSC_DTVO, GETDATE()) AS DSC_NDIA, 
		MIN(dui.SIN_CODI) AS SIN_CODI, 
		MIN(CAST(CONVERT(varchar(10), dui.DUI_DINI, 105) + ' ' + CONVERT(varchar(12), dui.DUI_HINI, 114) AS datetime)) AS DUI_DINI
	FROM PRO_SDSD AS dsd WITH(NOLOCK)
		INNER JOIN PRO_SDSC AS dsc WITH(NOLOCK) ON dsd.DSC_EANO = dsc.DSC_EANO AND dsd.DSC_NPRO = dsc.DSC_NPRO 
		INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dsd.DSD_NRMH = duc.DUC_CPRT AND CAST(CONVERT(varchar(10), dsc.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime)
		LEFT OUTER JOIN PRO_DUIN AS dui WITH(NOLOCK) ON duc.DUC_EANO = dui.DUC_EANO AND duc.DUC_PNUM = dui.DUC_PNUM AND (dui.SIN_CODI IN ('A00', 'A13') OR dui.DUI_REHO = 0)
	WHERE dsd.DSD_STRD > 0 AND dsd.DSD_STMS = 0 AND dsc.DSC_TIPO = 0 AND dsc.DSC_STRD > 1
		AND (SELECT COUNT(*) 
			FROM PRO_SDSD AS dsd1 WITH(NOLOCK)
				INNER JOIN PRO_SDSC AS dsc1 WITH(NOLOCK) ON dsd1.DSC_EANO = dsc1.DSC_EANO AND dsd1.DSC_NPRO = dsc1.DSC_NPRO 
				INNER JOIN PRO_DUCG AS duc1 WITH(NOLOCK) ON dsd1.DSD_NRMH = duc1.DUC_CPRT AND CAST(CONVERT(varchar(10), dsc1.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), duc1.DUC_DTVO, 105) AS datetime)
				LEFT OUTER JOIN PRO_DUIN AS dui1 WITH(NOLOCK) ON duc1.DUC_EANO = dui1.DUC_EANO AND duc1.DUC_PNUM = dui1.DUC_PNUM AND (dui1.SIN_CODI IN ('A00', 'A13') OR dui1.DUI_REHO = 0)
			WHERE dsd1.DSD_STRD > 0 AND dsd1.DSD_STMS = 0 AND dsd1.DSD_SIRD = 0 AND dsd1.DSC_EANO = dsd.DSC_EANO AND dsd1.DSC_NPRO = dsd.DSC_NPRO) = 0
	GROUP BY dsd.DSC_EANO, dsd.DSC_NPRO, dsd.DSD_NUME, dsd.DSD_IDNN, dsd.DSD_NRMH, dsd.DOC_CODI, dsd.DOC_NOME, dsd.DSD_DMER, dsd.DSD_PESO, dsd.DSD_VOLS, dsd.TEM_CODI, dsd.DSD_MRNR, dsd.DSD_TCAR, 
		dsd.DSD_NDGA, dsd.DSD_NDGI, dsd.DSD_DTRD, dsd.DSD_DNRD, dsd.DSD_NDPR, dsc.DSC_TIPO, dsc.EAD_CODI, dsc.EAD_NOME, dsc.DSC_NCMF, dsc.DSC_NCMV, dsc.DSC_NVOO, dsc.DSC_DPRV, dsc.DSC_DEFT, dsc.DSC_DTVO

ALTER AUTHORIZATION ON [VW_SDSViaAerea_MovimentoSaidaDadosAWB] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_SDSViaAerea_MovimentoSaidaDadosAWB] TO [public] AS [dbo]
/****** Object:  View [vw_TBL_Caucoes]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [vw_TBL_Caucoes] AS		
	SELECT 0 AS CAU_TIPO, DEC_IDTY AS CAU_ENTI, DEC_CODI AS CAU_ENTC, 1 AS CAU_IDTY, (ISNULL(RIGHT(DEC_ACA1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(DEC_NCA1))) + DEC_NCA1) AS CAU_CAUC, 
		DEC_INA1 AS CAU_INAC, DEC_ACA1 AS CAU_EANO, DEC_NCA1 AS CAU_NUME, DEC_TCA1 AS CAU_TIPC, ALF_CODI1 AS CAU_ALFA, DEC_CCA1 AS CAU_CACE, DEC_OCA1 AS CAU_OREF
	FROM TAB_DECL WITH(NOLOCK)
	WHERE ISNULL(DEC_NCA1, '') <> ''
	UNION
	SELECT 0 AS CAU_TIPO, DEC_IDTY AS CAU_ENTI, DEC_CODI AS CAU_ENTC, 2 AS CAU_IDTY, (ISNULL(RIGHT(DEC_ACA2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(DEC_NCA2))) + DEC_NCA2) AS CAU_CAUC, 
		DEC_INA2 AS CAU_INAC, DEC_ACA2 AS CAU_EANO, DEC_NCA2 AS CAU_NUME, DEC_TCA2 AS CAU_TIPC, ALF_CODI2 AS CAU_ALFA, DEC_CCA2 AS CAU_CACE, DEC_OCA2 AS CAU_OREF
	FROM TAB_DECL WITH(NOLOCK)
	WHERE ISNULL(DEC_NCA2, '') <> ''
	UNION
	SELECT 0 AS CAU_TIPO, DEC_IDTY AS CAU_ENTI, DEC_CODI AS CAU_ENTC, 3 AS CAU_IDTY, (ISNULL(RIGHT(DEC_ACA3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(DEC_NCA3))) + DEC_NCA3) AS CAU_CAUC, 
		DEC_INA3 AS CAU_INAC, DEC_ACA3 AS CAU_EANO, DEC_NCA3 AS CAU_NUME, DEC_TCA3 AS CAU_TIPC, ALF_CODI3 AS CAU_ALFA, DEC_CCA3 AS CAU_CACE, DEC_OCA3 AS CAU_OREF
	FROM TAB_DECL WITH(NOLOCK)
	WHERE ISNULL(DEC_NCA3, '') <> ''
	UNION
	SELECT 0 AS CAU_TIPO, DEC_IDTY AS CAU_ENTI, DEC_CODI AS CAU_ENTC, 4 AS CAU_IDTY, (ISNULL(RIGHT(DEC_ACA4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(DEC_NCA4))) + DEC_NCA4) AS CAU_CAUC, 
		DEC_INA4 AS CAU_INAC, DEC_ACA4 AS CAU_EANO, DEC_NCA4 AS CAU_NUME, DEC_TCA4 AS CAU_TIPC, ALF_CODI4 AS CAU_ALFA, DEC_CCA4 AS CAU_CACE, DEC_OCA4 AS CAU_OREF
	FROM TAB_DECL WITH(NOLOCK)
	WHERE ISNULL(DEC_NCA4, '') <> ''
	UNION
	SELECT 0 AS CAU_TIPO, DEC_IDTY AS CAU_ENTI, DEC_CODI AS CAU_ENTC, 5 AS CAU_IDTY, (ISNULL(RIGHT(DEC_ACA5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(DEC_NCA5))) + DEC_NCA5) AS CAU_CAUC, 
		DEC_INA5 AS CAU_INAC, DEC_ACA5 AS CAU_EANO, DEC_NCA5 AS CAU_NUME, DEC_TCA5 AS CAU_TIPC, ALF_CODI5 AS CAU_ALFA, DEC_CCA5 AS CAU_CACE, DEC_OCA5 AS CAU_OREF
	FROM TAB_DECL WITH(NOLOCK)
	WHERE ISNULL(DEC_NCA5, '') <> ''
	UNION
	SELECT 1 AS CAU_TIPO, CLI_IDTY AS CAU_ENTI, CLI_CODI AS CAU_ENTC, 1 AS CAU_IDTY, (ISNULL(RIGHT(CLI_ANO1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(CLI_NCA1))) + CLI_NCA1) AS CAU_CAUC, 
		CLI_INA1 AS CAU_INAC, CLI_ANO1 AS CAU_EANO, CLI_NCA1 AS CAU_NUME, CLI_TCA1 AS CAU_TIPC, ALF_CODI1 AS CAU_ALFA, CLI_CCA1 AS CAU_CACE, CLI_OCA1 AS CAU_OREF
	FROM TAB_CLIE WITH(NOLOCK)
	WHERE ISNULL(CLI_NCA1, '') <> ''
	UNION
	SELECT 1 AS CAU_TIPO, CLI_IDTY AS CAU_ENTI, CLI_CODI AS CAU_ENTC, 2 AS CAU_IDTY, (ISNULL(RIGHT(CLI_ANO2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(CLI_NCA2))) + CLI_NCA2) AS CAU_CAUC, 
		CLI_INA2 AS CAU_INAC, CLI_ANO2 AS CAU_EANO, CLI_NCA2 AS CAU_NUME, CLI_TCA2 AS CAU_TIPC, ALF_CODI2 AS CAU_ALFA, CLI_CCA2 AS CAU_CACE, CLI_OCA2 AS CAU_OREF
	FROM TAB_CLIE WITH(NOLOCK)
	WHERE ISNULL(CLI_NCA2, '') <> ''
	UNION
	SELECT 1 AS CAU_TIPO, CLI_IDTY AS CAU_ENTI, CLI_CODI AS CAU_ENTC, 3 AS CAU_IDTY, (ISNULL(RIGHT(CLI_ANO3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(CLI_NCA3))) + CLI_NCA3) AS CAU_CAUC, 
		CLI_INA3 AS CAU_INAC, CLI_ANO3 AS CAU_EANO, CLI_NCA3 AS CAU_NUME, CLI_TCA3 AS CAU_TIPC, ALF_CODI3 AS CAU_ALFA, CLI_CCA3 AS CAU_CACE, CLI_OCA3 AS CAU_OREF
	FROM TAB_CLIE WITH(NOLOCK)
	WHERE ISNULL(CLI_NCA3, '') <> ''
	UNION
	SELECT 1 AS CAU_TIPO, CLI_IDTY AS CAU_ENTI, CLI_CODI AS CAU_ENTC, 4 AS CAU_IDTY, (ISNULL(RIGHT(CLI_ANO4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(CLI_NCA4))) + CLI_NCA4) AS CAU_CAUC, 
		CLI_INA4 AS CAU_INAC, CLI_ANO4 AS CAU_EANO, CLI_NCA4 AS CAU_NUME, CLI_TCA4 AS CAU_TIPC, ALF_CODI4 AS CAU_ALFA, CLI_CCA4 AS CAU_CACE, CLI_OCA4 AS CAU_OREF
	FROM TAB_CLIE WITH(NOLOCK)
	WHERE ISNULL(CLI_NCA4, '') <> ''
	UNION
	SELECT 1 AS CAU_TIPO, CLI_IDTY AS CAU_ENTI, CLI_CODI AS CAU_ENTC, 5 AS CAU_IDTY, (ISNULL(RIGHT(CLI_ANO5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(CLI_NCA5))) + CLI_NCA5) AS CAU_CAUC, 
		CLI_INA5 AS CAU_INAC, CLI_ANO5 AS CAU_EANO, CLI_NCA5 AS CAU_NUME, CLI_TCA5 AS CAU_TIPC, ALF_CODI5 AS CAU_ALFA, CLI_CCA5 AS CAU_CACE, CLI_OCA5 AS CAU_OREF
	FROM TAB_CLIE WITH(NOLOCK)
	WHERE ISNULL(CLI_NCA5, '') <> ''

ALTER AUTHORIZATION ON [vw_TBL_Caucoes] TO  SCHEMA OWNER 
GRANT SELECT ON [vw_TBL_Caucoes] TO [public] AS [dbo]
/****** Object:  View [VW_Vendas_ReportDadosGerais]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Vendas_ReportDadosGerais] AS
	SELECT d.DVE_TDOC, d.DVE_NDOC, d.DVE_EANO, d.DVE_DATA, d.CLI_CODI, d.DVE_CNOM, d.DVE_CMOR, d.DVE_CLOC, d.DVE_CCPO, d.DVE_CLPO, d.DVE_CNIF, d.PAI_CLIV, d.NDE_CODI, d.DVE_NPRO, d.DVE_OBSV, 
		d.DVE_UTIC, d.DVE_DTCR, d.DVE_UTIA, d.DVE_DTAL, d.DVE_IN01, d.DVE_IN02, d.DVE_IN03, d.DVE_IN04, d.DVE_VI01, d.DVE_VI02, d.DVE_VI03, d.DVE_VI04, d.DVE_ANUL, d.DVE_VLIQ, d.DVE_VIVA, 
		d.DVE_VTOT, d.DVE_IMPR, d.DVE_STAT, d.DVE_DIPS, d.DVE_DFPS, d.DVE_NDOR, d.DVE_PANO, d.DVE_IMEX, d.MCR_CODI, d.DVE_MCRE, d.DVE_NEXT, d.DVE_IDTY, d.DVE_ATCU, d.DEC_CODI, d.DVE_IDAR, 
		d.DVE_SERI, d.DVE_INVN, t.TDO_DESC, t.TDO_DVI1, t.TDO_DVI2, t.TDO_DVI3, t.TDO_DVI4, t.TDO_DVI5, t.TDO_DVI6, t.TDO_DVI7, t.TDO_DVI8, t.TDO_DVI9, c.CLI_CEAN, c.CLI_TELF, c.CLI_EMAI, 
		c.CLI_CODC, c.CLI_CPAG, c.CLI_LMCR, c.CLI_VCIL, c.CLI_CPOC, n.NDE_NOME, n.NDE_IIVA, 
		(ISNULL((SELECT TOP 1 DVD_IVA FROM FAC_DVDT WITH(NOLOCK) WHERE DVD_IVA <> 0 and DVE_TDOC = d.DVE_TDOC and DVE_EANO = d.DVE_EANO and DVE_NDOC = d.DVE_NDOC), (SELECT TOP 1 PAP_TXNR FROM TAB_PAPL WITH(NOLOCK)))) AS IVA_NORM,
		dbo.FNT_Facturacao_ObtemExpressaoImpressao(d.DVE_HASH, d.DVE_NDOC) AS DVE_EXPR, dbo.FNT_Facturacao_ObtemDadosQRCode(1, d.DVE_IDTY) AS DVE_QRCD
	FROM FAC_DVEN AS d WITH(NOLOCK) INNER JOIN TAB_TDOC AS t WITH(NOLOCK) ON d.DVE_TDOC = t.TDO_DOCU
		INNER JOIN TAB_CLIE AS c WITH(NOLOCK) ON d.CLI_CODI = c.CLI_CODI
		LEFT OUTER JOIN TAB_NDES AS n WITH(NOLOCK) ON d.NDE_CODI = n.NDE_CODI

ALTER AUTHORIZATION ON [VW_Vendas_ReportDadosGerais] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Vendas_ReportDadosGerais] TO [public] AS [dbo]
/****** Object:  View [VW_Vendas_ReportDadosLinhas]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE VIEW [VW_Vendas_ReportDadosLinhas] AS
	SELECT DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_FORN, DVD_LHON, IIV_CODI, IIV_MENC
	FROM FAC_DVDT WITH(NOLOCK) 

ALTER AUTHORIZATION ON [VW_Vendas_ReportDadosLinhas] TO  SCHEMA OWNER 
GRANT SELECT ON [VW_Vendas_ReportDadosLinhas] TO [public] AS [dbo]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_AGE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_AGE_CODI] ON [AEX_ENDG]
(
	[AGE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_CLI_CODI] ON [AEX_ENDG]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_AEX_ENDG_EDG_DATA]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_EDG_DATA] ON [AEX_ENDG]
(
	[EDG_DATA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_EDG_EANO_EDG_REFI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_EDG_EANO_EDG_REFI] ON [AEX_ENDG]
(
	[EDG_EANO] ASC,
	[EDG_REFI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_EXM_EANO_EXM_CODI_DEC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_EXM_EANO_EXM_CODI_DEC_CODI] ON [AEX_ENDG]
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[DEC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_FOR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_FOR_CODI] ON [AEX_ENDG]
(
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_LME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_LME_CODI] ON [AEX_ENDG]
(
	[LME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_PAI_CODI] ON [AEX_ENDG]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENDG_PAI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENDG_PAI_CODI1] ON [AEX_ENDG]
(
	[PAI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENLN_APA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENLN_APA_CODI] ON [AEX_ENLN]
(
	[APA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENLN_EDG_EANO_LME_CODI_EDG_NUME]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENLN_EDG_EANO_LME_CODI_EDG_NUME] ON [AEX_ENLN]
(
	[EDG_EANO] ASC,
	[LME_CODI] ASC,
	[EDG_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_ENLN_TEM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_ENLN_TEM_CODI] ON [AEX_ENLN]
(
	[TEM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_AEX_SADG_EDG_EANO_LME_CODI_EDG_NUME]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_SADG_EDG_EANO_LME_CODI_EDG_NUME] ON [AEX_SADG]
(
	[EDG_EANO] ASC,
	[LME_CODI] ASC,
	[EDG_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_AEX_SADG_SDG_DATA]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_AEX_SADG_SDG_DATA] ON [AEX_SADG]
(
	[SDG_DATA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_FAC_CDOC_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_CDOC_CCO_CODI] ON [FAC_CDOC]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_FAC_CDOC_CDO_CNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_CDOC_CDO_CNUM] ON [FAC_CDOC]
(
	[CDO_CNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_FAC_CDOC_CDO_DTAB]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_CDOC_CDO_DTAB] ON [FAC_CDOC]
(
	[CDO_DTAB] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_FAC_CDOC_CDO_IMEX_CDO_NPRO_CDO_PANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_CDOC_CDO_IMEX_CDO_NPRO_CDO_PANO] ON [FAC_CDOC]
(
	[CDO_IMEX] ASC,
	[CDO_NPRO] ASC,
	[CDO_PANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_FAC_CDOC_CLI_CCOR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_CDOC_CLI_CCOR] ON [FAC_CDOC]
(
	[CLI_CCOR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_FAC_CDOC_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_CDOC_id_declaracaoDAR] ON [FAC_CDOC]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_FAC_DCDO_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_DCDO_CCO_CODI] ON [FAC_DCDO]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_FAC_DVDT_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_DVDT_CCO_CODI] ON [FAC_DVDT]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_FAC_DVEN_DVE_IDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_DVEN_DVE_IDAR] ON [FAC_DVEN]
(
	[DVE_IDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_FAC_DVEN_DVE_IMEX_DVE_PANO_DVE_NPRO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_DVEN_DVE_IMEX_DVE_PANO_DVE_NPRO] ON [FAC_DVEN]
(
	[DVE_IMEX] ASC,
	[DVE_PANO] ASC,
	[DVE_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_FAC_ICDO_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_ICDO_CCO_CODI] ON [FAC_ICDO]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_FAC_MVCC_MVC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_MVCC_MVC_EANO] ON [FAC_MVCC]
(
	[MVC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_FAC_MVCC_MVC_EANO_MVC_NPRO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_MVCC_MVC_EANO_MVC_NPRO] ON [FAC_MVCC]
(
	[MVC_EANO] ASC,
	[MVC_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_FAC_MVCC_MVC_ENTI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_MVCC_MVC_ENTI] ON [FAC_MVCC]
(
	[MVC_ENTI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_FAC_MVCC_MVC_NDES]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_FAC_MVCC_MVC_NDES] ON [FAC_MVCC]
(
	[MVC_NDES] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_HST_SDSI_DSC_EANO_DSC_NPRO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_HST_SDSI_DSC_EANO_DSC_NPRO] ON [HST_SDSI]
(
	[DSC_EANO] ASC,
	[DSC_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_HST_SDSI_DSI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_HST_SDSI_DSI_CODI] ON [HST_SDSI]
(
	[DSI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCC_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCC_CLI_CODI] ON [INT_LNCC]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCC_DEC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCC_DEC_CODI] ON [INT_LNCC]
(
	[DEC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCC_FOR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCC_FOR_CODI] ON [INT_LNCC]
(
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCC_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCC_PAI_CODI] ON [INT_LNCC]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCC_PAI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCC_PAI_CODI1] ON [INT_LNCC]
(
	[PAI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCD_CEN_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_CEN_CODI] ON [INT_LNCD]
(
	[CEN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_INT_LNCD_LNC_EANO_LNC_NUME]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_LNC_EANO_LNC_NUME] ON [INT_LNCD]
(
	[LNC_EANO] ASC,
	[LNC_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCD_LNC_EANO_NC8_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_LNC_EANO_NC8_CODI] ON [INT_LNCD]
(
	[LNC_EANO] ASC,
	[NC8_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCD_MTR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_MTR_CODI] ON [INT_LNCD]
(
	[MTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCD_NTR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_NTR_CODI] ON [INT_LNCD]
(
	[NTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCD_PAE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_PAE_CODI] ON [INT_LNCD]
(
	[PAE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCD_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_PAI_CODI] ON [INT_LNCD]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_INT_LNCD_PAI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_PAI_CODI1] ON [INT_LNCD]
(
	[PAI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_INT_LNCD_RES_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_INT_LNCD_RES_CODI] ON [INT_LNCD]
(
	[RES_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_CCCA_CCC_IORI_MCA_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_CCCA_CCC_IORI_MCA_IDEN] ON [PRO_CCCA]
(
	[CCC_IORI] ASC,
	[MCA_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_CCCA_CCC_TENT_CCC_ENTI_CCC_NCAU_CCC_CANO_CCC_CTIP_ALF_ORIG]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_CCCA_CCC_TENT_CCC_ENTI_CCC_NCAU_CCC_CANO_CCC_CTIP_ALF_ORIG] ON [PRO_CCCA]
(
	[CCC_TENT] ASC,
	[CCC_ENTI] ASC,
	[CCC_NCAU] ASC,
	[CCC_CANO] ASC,
	[CCC_CTIP] ASC,
	[ALF_ORIG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_CCCA_CCC_TENT_CCC_NCAU_CCC_CANO_CCC_CTIP_ALF_ORIG]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_CCCA_CCC_TENT_CCC_NCAU_CCC_CANO_CCC_CTIP_ALF_ORIG] ON [PRO_CCCA]
(
	[CCC_TENT] ASC,
	[CCC_NCAU] ASC,
	[CCC_CANO] ASC,
	[CCC_CTIP] ASC,
	[ALF_ORIG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_CCCA_DUC_PNUM_DUC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_CCCA_DUC_PNUM_DUC_EANO] ON [PRO_CCCA]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_CCCA_DUC_PNUM_DUC_EANO_DUC_TIPO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_CCCA_DUC_PNUM_DUC_EANO_DUC_TIPO] ON [PRO_CCCA]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[DUC_TIPO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DCON_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DCON_DUC_EANO_DUC_PNUM] ON [PRO_DCON]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DCON_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DCON_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DCON]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DDOC_CEN_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DDOC_CEN_CODI] ON [PRO_DDOC]
(
	[CEN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DDOC_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DDOC_DOC_CODI] ON [PRO_DDOC]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DDOC_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DDOC_DUC_EANO_DUC_PNUM] ON [PRO_DDOC]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DDOC_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DDOC_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DDOC]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DDOC_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DDOC_PAI_CODI] ON [PRO_DDOC]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DSSA_DSD_IDNN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DSSA_DSD_IDNN] ON [PRO_DSSA]
(
	[DSD_IDNN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DSSD_DSS_EANO_DCS_CODI_DSS_NPRO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DSSD_DSS_EANO_DCS_CODI_DSS_NPRO] ON [PRO_DSSD]
(
	[DSS_EANO] ASC,
	[DCS_CODI] ASC,
	[DSS_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DU31_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DU31_DUC_EANO_DUC_PNUM] ON [PRO_DU31]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DU31_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DU31_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DU31]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DU31_DVC_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DU31_DVC_IDEN] ON [PRO_DU31]
(
	[DVC_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DU31_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DU31_UME_CODI] ON [PRO_DU31]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_AGE_CO50]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_AGE_CO50] ON [PRO_DUAD]
(
	[AGE_CO50] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_ALF_CO53]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_ALF_CO53] ON [PRO_DUAD]
(
	[ALF_CO53] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_ALF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_ALF_CODI] ON [PRO_DUAD]
(
	[ALF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_ALF_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_ALF_CODI1] ON [PRO_DUAD]
(
	[ALF_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_APA_CO33]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_APA_CO33] ON [PRO_DUAD]
(
	[APA_CO33] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_ARM_CO49]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_ARM_CO49] ON [PRO_DUAD]
(
	[ARM_CO49] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_CLI_CODI] ON [PRO_DUAD]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_DOC_CODI] ON [PRO_DUAD]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUAD_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_DUA_CODI] ON [PRO_DUAD]
(
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_DUA_DNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_DUA_DNUM] ON [PRO_DUAD]
(
	[DUA_DNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUAD_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_DUC_EANO_DUC_PNUM] ON [PRO_DUAD]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_EAD_CODI] ON [PRO_DUAD]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUAD_FLE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_FLE_CODI] ON [PRO_DUAD]
(
	[FLE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_FOR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_FOR_CODI] ON [PRO_DUAD]
(
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_FOR_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_FOR_CODI1] ON [PRO_DUAD]
(
	[FOR_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUAD_id_desdobramento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_id_desdobramento] ON [PRO_DUAD]
(
	[id_desdobramento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_MTR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_MTR_CODI] ON [PRO_DUAD]
(
	[MTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_NTR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_NTR_CODI] ON [PRO_DUAD]
(
	[NTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PAI_CO34]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PAI_CO34] ON [PRO_DUAD]
(
	[PAI_CO34] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PAI_CODI] ON [PRO_DUAD]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PAI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PAI_CODI1] ON [PRO_DUAD]
(
	[PAI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PAI_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PAI_CODI2] ON [PRO_DUAD]
(
	[PAI_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PAI_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PAI_CODI3] ON [PRO_DUAD]
(
	[PAI_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PAI_CODI4]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PAI_CODI4] ON [PRO_DUAD]
(
	[PAI_CODI4] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PAI_CODI5]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PAI_CODI5] ON [PRO_DUAD]
(
	[PAI_CODI5] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_PRE_CO36]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_PRE_CO36] ON [PRO_DUAD]
(
	[PRE_CO36] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUAD_RES_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_RES_CODI] ON [PRO_DUAD]
(
	[RES_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUAD_RRE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_RRE_CODI] ON [PRO_DUAD]
(
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_UME_CODI] ON [PRO_DUAD]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUAD_USU_CO41]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUAD_USU_CO41] ON [PRO_DUAD]
(
	[USU_CO41] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUBT_CAT_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUBT_CAT_CODI] ON [PRO_DUBT]
(
	[CAT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUBT_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUBT_DUC_EANO_DUC_PNUM] ON [PRO_DUBT]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUBT_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUBT_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DUBT]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUBT_HTE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUBT_HTE_CODI] ON [PRO_DUBT]
(
	[HTE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUBT_TCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUBT_TCO_CODI] ON [PRO_DUBT]
(
	[TCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUBT_TVE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUBT_TVE_CODI] ON [PRO_DUBT]
(
	[TVE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUBT_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUBT_UME_CODI] ON [PRO_DUBT]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_ALF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_ALF_CODI] ON [PRO_DUCG]
(
	[ALF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_ALF_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_ALF_CODI2] ON [PRO_DUCG]
(
	[ALF_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_ALF_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_ALF_CODI3] ON [PRO_DUCG]
(
	[ALF_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_ALF_CODI4]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_ALF_CODI4] ON [PRO_DUCG]
(
	[ALF_CODI4] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_CEN_CO20]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_CEN_CO20] ON [PRO_DUCG]
(
	[CEN_CO20] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_CLI_CODI] ON [PRO_DUCG]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_CLI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_CLI_CODI1] ON [PRO_DUCG]
(
	[CLI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DEC_CEDE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DEC_CEDE] ON [PRO_DUCG]
(
	[DEC_CEDE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DEC_CO14]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DEC_CO14] ON [PRO_DUCG]
(
	[DEC_CO14] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DES_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DES_CODI] ON [PRO_DUCG]
(
	[DES_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DOC_CODI] ON [PRO_DUCG]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUCG_DUC_CNTN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_CNTN] ON [PRO_DUCG]
(
	[DUC_CNTN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DUC_CPRT]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_CPRT] ON [PRO_DUCG]
(
	[DUC_CPRT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUCG_DUC_DATA]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_DATA] ON [PRO_DUCG]
(
	[DUC_DATA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DUC_DST8]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_DST8] ON [PRO_DUCG]
(
	[DUC_DST8] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUCG_DUC_DTVO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_DTVO] ON [PRO_DUCG]
(
	[DUC_DTVO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DUC_EANO_DUC_CPRT]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_EANO_DUC_CPRT] ON [PRO_DUCG]
(
	[DUC_EANO] ASC,
	[DUC_CPRT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DUC_EANO_DUC_TIPO_DUC_EXP2_DUC_DST8]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_EANO_DUC_TIPO_DUC_EXP2_DUC_DST8] ON [PRO_DUCG]
(
	[DUC_EANO] ASC,
	[DUC_TIPO] ASC,
	[DUC_EXP2] ASC,
	[DUC_DST8] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DUC_EXP2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_EXP2] ON [PRO_DUCG]
(
	[DUC_EXP2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUCG_DUC_TIPO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_TIPO] ON [PRO_DUCG]
(
	[DUC_TIPO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_DUC_TIPO_DUC_DST8]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_DUC_TIPO_DUC_DST8] ON [PRO_DUCG]
(
	[DUC_TIPO] ASC,
	[DUC_DST8] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_EAD_CO29]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_EAD_CO29] ON [PRO_DUCG]
(
	[EAD_CO29] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_FOR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_FOR_CODI] ON [PRO_DUCG]
(
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_LME_CO27]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_LME_CO27] ON [PRO_DUCG]
(
	[LME_CO27] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_LME_CO30]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_LME_CO30] ON [PRO_DUCG]
(
	[LME_CO30] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_LME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_LME_CODI] ON [PRO_DUCG]
(
	[LME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_MTR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_MTR_CODI] ON [PRO_DUCG]
(
	[MTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_MTR_FT21]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_MTR_FT21] ON [PRO_DUCG]
(
	[MTR_FT21] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_MTR_PT18]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_MTR_PT18] ON [PRO_DUCG]
(
	[MTR_PT18] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_NDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_NDE_CODI] ON [PRO_DUCG]
(
	[NDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_NDE_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_NDE_CODI1] ON [PRO_DUCG]
(
	[NDE_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_NST_CODI_NST_EANO_CLI_OPER]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_NST_CODI_NST_EANO_CLI_OPER] ON [PRO_DUCG]
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_NTR_CO24]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_NTR_CO24] ON [PRO_DUCG]
(
	[NTR_CO24] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAE_CODI] ON [PRO_DUCG]
(
	[PAE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_CLIV]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_CLIV] ON [PRO_DUCG]
(
	[PAI_CLIV] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_CODI] ON [PRO_DUCG]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_CODI1] ON [PRO_DUCG]
(
	[PAI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_CODI2] ON [PRO_DUCG]
(
	[PAI_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_CODI3] ON [PRO_DUCG]
(
	[PAI_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_DLIV]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_DLIV] ON [PRO_DUCG]
(
	[PAI_DLIV] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_ELIV]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_ELIV] ON [PRO_DUCG]
(
	[PAI_ELIV] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_FRET]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_FRET] ON [PRO_DUCG]
(
	[PAI_FRET] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUCG_PAI_P15B]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_P15B] ON [PRO_DUCG]
(
	[PAI_P15B] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUCG_PAI_P17B]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_P17B] ON [PRO_DUCG]
(
	[PAI_P17B] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_PA10]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_PA10] ON [PRO_DUCG]
(
	[PAI_PA10] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_PA11]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_PA11] ON [PRO_DUCG]
(
	[PAI_PA11] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_PA16]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_PA16] ON [PRO_DUCG]
(
	[PAI_PA16] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_PA17]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_PA17] ON [PRO_DUCG]
(
	[PAI_PA17] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_PA18]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_PA18] ON [PRO_DUCG]
(
	[PAI_PA18] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_PA21]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_PA21] ON [PRO_DUCG]
(
	[PAI_PA21] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_PR22]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_PR22] ON [PRO_DUCG]
(
	[PAI_PR22] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_SEGU]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_SEGU] ON [PRO_DUCG]
(
	[PAI_SEGU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_PAI_VTRN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_PAI_VTRN] ON [PRO_DUCG]
(
	[PAI_VTRN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_TDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_TDE_CODI] ON [PRO_DUCG]
(
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_TDO_DOCU]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_TDO_DOCU] ON [PRO_DUCG]
(
	[TDO_DOCU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUCG_TDO_DOCU1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCG_TDO_DOCU1] ON [PRO_DUCG]
(
	[TDO_DOCU1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUCN_DUC_PNUM_DUC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUCN_DUC_PNUM_DUC_EANO] ON [PRO_DUCN]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUDA_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUDA_DUC_EANO_DUC_PNUM] ON [PRO_DUDA]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUDA_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUDA_EAD_CODI] ON [PRO_DUDA]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUDD_DUC_PNUM_DUC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUDD_DUC_PNUM_DUC_EANO] ON [PRO_DUDD]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUET_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUET_DUC_EANO_DUC_PNUM] ON [PRO_DUET]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUET_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUET_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DUET]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUET_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUET_UME_CODI] ON [PRO_DUET]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUFI_DUC_PNUM_DUC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUFI_DUC_PNUM_DUC_EANO] ON [PRO_DUFI]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUFW_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUFW_DUC_EANO_DUC_PNUM] ON [PRO_DUFW]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUIN_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUIN_DUC_EANO_DUC_PNUM] ON [PRO_DUIN]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUIN_SIN_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUIN_SIN_CODI] ON [PRO_DUIN]
(
	[SIN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUIT_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUIT_DUC_EANO_DUC_PNUM] ON [PRO_DUIT]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUIT_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUIT_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DUIT]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUIT_DUC_EANO_DUC_PNUM_DUA_CODI_DMI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUIT_DUC_EANO_DUC_PNUM_DUA_CODI_DMI_CODI] ON [PRO_DUIT]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DMI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUIT_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUIT_UME_CODI] ON [PRO_DUIT]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DULO_DUC_PNUM_DUC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DULO_DUC_PNUM_DUC_EANO] ON [PRO_DULO]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DULO_RRE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DULO_RRE_CODI] ON [PRO_DULO]
(
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DULR_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DULR_DUC_EANO_DUC_PNUM] ON [PRO_DULR]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DULR_RRE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DULR_RRE_CODI] ON [PRO_DULR]
(
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUMI_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUMI_DUC_EANO_DUC_PNUM] ON [PRO_DUMI]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUMI_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUMI_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DUMI]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUOD_APA_CPAU]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOD_APA_CPAU] ON [PRO_DUOD]
(
	[APA_CPAU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUOD_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOD_DUC_EANO_DUC_PNUM] ON [PRO_DUOD]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUOD_DUO_CPA2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOD_DUO_CPA2] ON [PRO_DUOD]
(
	[DUO_CPA2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUOD_DUO_MOED]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOD_DUO_MOED] ON [PRO_DUOD]
(
	[DUO_MOED] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUOD_DUO_TIPO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOD_DUO_TIPO] ON [PRO_DUOD]
(
	[DUO_TIPO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUOD_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOD_PAI_CODI] ON [PRO_DUOD]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUOD_PAI_IDTY]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOD_PAI_IDTY] ON [PRO_DUOD]
(
	[PAI_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUOI_ALF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOI_ALF_CODI] ON [PRO_DUOI]
(
	[ALF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUOI_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOI_DUC_EANO_DUC_PNUM] ON [PRO_DUOI]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUOI_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOI_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DUOI]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUOI_RRE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOI_RRE_CODI] ON [PRO_DUOI]
(
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUOI_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUOI_UME_CODI] ON [PRO_DUOI]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUPD_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUPD_DUC_EANO_DUC_PNUM] ON [PRO_DUPD]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DUPD_TXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUPD_TXM_CODI] ON [PRO_DUPD]
(
	[TXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DURA_DOC_COD2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DURA_DOC_COD2] ON [PRO_DURA]
(
	[DOC_COD2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DURA_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DURA_DOC_CODI] ON [PRO_DURA]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DURA_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DURA_DUC_EANO_DUC_PNUM] ON [PRO_DURA]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DURA_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DURA_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DURA]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DURA_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DURA_EAD_CODI] ON [PRO_DURA]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DURP_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DURP_DUC_EANO_DUC_PNUM] ON [PRO_DURP]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_DURP_TDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DURP_TDE_CODI] ON [PRO_DURP]
(
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUVE_DUC_EANO_DUC_PNUM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUVE_DUC_EANO_DUC_PNUM] ON [PRO_DUVE]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUVE_DUC_EANO_DUC_PNUM_DUA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUVE_DUC_EANO_DUC_PNUM_DUA_CODI] ON [PRO_DUVE]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_DUVE_DUC_EANO_DUC_PNUM_DUA_CODI_DBT_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_DUVE_DUC_EANO_DUC_PNUM_DUA_CODI_DBT_CODI] ON [PRO_DUVE]
(
	[DUC_EANO] ASC,
	[DUC_PNUM] ASC,
	[DUA_CODI] ASC,
	[DBT_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_APA_CO33]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_APA_CO33] ON [PRO_EXAD]
(
	[APA_CO33] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_CLI_CODI] ON [PRO_EXAD]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_EXA_CHVE_EXM_EANO_EXM_COPE_EXM_CODI_EXA_LINH]    Script Date: 04-11-2025 10:22:21 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_PRO_EXAD_EXA_CHVE_EXM_EANO_EXM_COPE_EXM_CODI_EXA_LINH] ON [PRO_EXAD]
(
	[EXA_CHVE] ASC,
	[EXM_EANO] ASC,
	[EXM_COPE] ASC,
	[EXM_CODI] ASC,
	[EXA_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_EXM_EANO__EXM_COPE_EXM_CODI_EXA_LINH]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_EXM_EANO__EXM_COPE_EXM_CODI_EXA_LINH] ON [PRO_EXAD]
(
	[EXM_EANO] ASC,
	[EXM_COPE] ASC,
	[EXM_CODI] ASC,
	[EXA_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_EXM_EANO_EXM_COPE_EXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_EXM_EANO_EXM_COPE_EXM_CODI] ON [PRO_EXAD]
(
	[EXM_EANO] ASC,
	[EXM_COPE] ASC,
	[EXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_FOR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_FOR_CODI] ON [PRO_EXAD]
(
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_GPA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_GPA_CODI] ON [PRO_EXAD]
(
	[GPA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXAD_id_desdobramento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_id_desdobramento] ON [PRO_EXAD]
(
	[id_desdobramento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_NTR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_NTR_CODI] ON [PRO_EXAD]
(
	[NTR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_PAI_CODI] ON [PRO_EXAD]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_PAI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_PAI_CODI1] ON [PRO_EXAD]
(
	[PAI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_PAI_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_PAI_CODI2] ON [PRO_EXAD]
(
	[PAI_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_PAI_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_PAI_CODI3] ON [PRO_EXAD]
(
	[PAI_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_PAI_CODI4]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_PAI_CODI4] ON [PRO_EXAD]
(
	[PAI_CODI4] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXAD_RES_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_RES_CODI] ON [PRO_EXAD]
(
	[RES_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXAD_USU_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXAD_USU_CODI] ON [PRO_EXAD]
(
	[USU_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXCD_EXM_EANO_EXM_CODI_EXM_COPE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXCD_EXM_EANO_EXM_CODI_EXM_COPE] ON [PRO_EXCD]
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[EXM_COPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXCD_EXM_EANO_EXM_CODI_EXM_COPE_EXC_LINH]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXCD_EXM_EANO_EXM_CODI_EXM_COPE_EXC_LINH] ON [PRO_EXCD]
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[EXM_COPE] ASC,
	[EXC_LINH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXCD_TEM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXCD_TEM_CODI] ON [PRO_EXCD]
(
	[TEM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXCE_EXM_EANO_EXM_COPE_EXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXCE_EXM_EANO_EXM_COPE_EXM_CODI] ON [PRO_EXCE]
(
	[EXM_EANO] ASC,
	[EXM_COPE] ASC,
	[EXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXCE_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXCE_UME_CODI] ON [PRO_EXCE]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXCT_EXM_EANO_EXM_COPE_EXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXCT_EXM_EANO_EXM_COPE_EXM_CODI] ON [PRO_EXCT]
(
	[EXM_EANO] ASC,
	[EXM_COPE] ASC,
	[EXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXDA_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXDA_DOC_CODI] ON [PRO_EXDA]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXDA_EXA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXDA_EXA_CHVE] ON [PRO_EXDA]
(
	[EXA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXDA_EXM_EANO_EXM_CODI_EXM_COPE_EXA_LINH_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXDA_EXM_EANO_EXM_CODI_EXM_COPE_EXA_LINH_DOC_CODI] ON [PRO_EXDA]
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[EXM_COPE] ASC,
	[EXA_LINH] ASC,
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXFI_EXM_EANO_DEC_CODI_EXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXFI_EXM_EANO_DEC_CODI_EXM_CODI] ON [PRO_EXFI]
(
	[EXM_EANO] ASC,
	[DEC_CODI] ASC,
	[EXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXFI_EXM_EANO_DEC_CODI_EXM_CODI_EXF_TMSG]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXFI_EXM_EANO_DEC_CODI_EXM_CODI_EXF_TMSG] ON [PRO_EXFI]
(
	[EXM_EANO] ASC,
	[DEC_CODI] ASC,
	[EXM_CODI] ASC,
	[EXF_TMSG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXFW_EXM_EANO_EXM_CODI_EXM_COPE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXFW_EXM_EANO_EXM_CODI_EXM_COPE] ON [PRO_EXFW]
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[EXM_COPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXIC_EXA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXIC_EXA_CHVE] ON [PRO_EXIC]
(
	[EXA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXME_EXA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXME_EXA_CHVE] ON [PRO_EXME]
(
	[EXA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXME_EXA_CHVE_INF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXME_EXA_CHVE_INF_CODI] ON [PRO_EXME]
(
	[EXA_CHVE] ASC,
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXME_INF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXME_INF_CODI] ON [PRO_EXME]
(
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_AGE_CO50]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_AGE_CO50] ON [PRO_EXML]
(
	[AGE_CO50] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_ARM_CO49]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_ARM_CO49] ON [PRO_EXML]
(
	[ARM_CO49] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_CEN_CO20]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_CEN_CO20] ON [PRO_EXML]
(
	[CEN_CO20] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_CLI_COD2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_CLI_COD2] ON [PRO_EXML]
(
	[CLI_COD2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_CLI_CODI] ON [PRO_EXML]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_CLI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_CLI_CODI1] ON [PRO_EXML]
(
	[CLI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_DEC_CO14]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_DEC_CO14] ON [PRO_EXML]
(
	[DEC_CO14] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EAD_C17C]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EAD_C17C] ON [PRO_EXML]
(
	[EAD_C17C] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EAD_C29A]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EAD_C29A] ON [PRO_EXML]
(
	[EAD_C29A] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EAD_CO29]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EAD_CO29] ON [PRO_EXML]
(
	[EAD_CO29] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EAD_CO30]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EAD_CO30] ON [PRO_EXML]
(
	[EAD_CO30] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EAD_CODA]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EAD_CODA] ON [PRO_EXML]
(
	[EAD_CODA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EAD_CODI] ON [PRO_EXML]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EAD_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EAD_CODI1] ON [PRO_EXML]
(
	[EAD_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXML_EXM_CNTX]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_CNTX] ON [PRO_EXML]
(
	[EXM_CNTX] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EXM_CPRT]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_CPRT] ON [PRO_EXML]
(
	[EXM_CPRT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXML_EXM_DATA]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_DATA] ON [PRO_EXML]
(
	[EXM_DATA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EXM_EANO_DEC_CODI_EXM_NRII]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_EANO_DEC_CODI_EXM_NRII] ON [PRO_EXML]
(
	[EXM_EANO] ASC,
	[DEC_CODI] ASC,
	[EXM_NRII] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXML_EXM_EANO_EXM_ASAI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_EANO_EXM_ASAI] ON [PRO_EXML]
(
	[EXM_EANO] ASC,
	[EXM_ASAI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EXM_EANO_EXM_CPRT]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_EANO_EXM_CPRT] ON [PRO_EXML]
(
	[EXM_EANO] ASC,
	[EXM_CPRT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXML_EXM_NRII]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_NRII] ON [PRO_EXML]
(
	[EXM_NRII] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EXM_P15A]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_P15A] ON [PRO_EXML]
(
	[EXM_P15A] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_EXM_P17A]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_EXM_P17A] ON [PRO_EXML]
(
	[EXM_P17A] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_FOR_COD8]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_FOR_COD8] ON [PRO_EXML]
(
	[FOR_COD8] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_LEM_C30A]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_LEM_C30A] ON [PRO_EXML]
(
	[LEM_C30A] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_LEM_CO30]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_LEM_CO30] ON [PRO_EXML]
(
	[LEM_CO30] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_LME_CO30]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_LME_CO30] ON [PRO_EXML]
(
	[LME_CO30] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_MTR_CO18]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_MTR_CO18] ON [PRO_EXML]
(
	[MTR_CO18] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_MTR_CO21]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_MTR_CO21] ON [PRO_EXML]
(
	[MTR_CO21] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_MTR_CO25]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_MTR_CO25] ON [PRO_EXML]
(
	[MTR_CO25] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_MTR_CO26]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_MTR_CO26] ON [PRO_EXML]
(
	[MTR_CO26] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_NDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_NDE_CODI] ON [PRO_EXML]
(
	[NDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_NST_CODI_NST_EANO_CLI_OPER]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_NST_CODI_NST_EANO_CLI_OPER] ON [PRO_EXML]
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_NTR_CO24]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_NTR_CO24] ON [PRO_EXML]
(
	[NTR_CO24] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAE_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAE_CODI1] ON [PRO_EXML]
(
	[PAE_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CO21]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CO21] ON [PRO_EXML]
(
	[PAI_CO21] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CO22]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CO22] ON [PRO_EXML]
(
	[PAI_CO22] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CODI] ON [PRO_EXML]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CODI1] ON [PRO_EXML]
(
	[PAI_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CODI2] ON [PRO_EXML]
(
	[PAI_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CODI3] ON [PRO_EXML]
(
	[PAI_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CODI4]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CODI4] ON [PRO_EXML]
(
	[PAI_CODI4] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_PAI_CODI5]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_PAI_CODI5] ON [PRO_EXML]
(
	[PAI_CODI5] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_SIN_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_SIN_CODI] ON [PRO_EXML]
(
	[SIN_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXML_TDE_COD1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXML_TDE_COD1] ON [PRO_EXML]
(
	[TDE_COD1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_EXMV_EXA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXMV_EXA_CHVE] ON [PRO_EXMV]
(
	[EXA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXMV_EXM_EANO_EXM_CODI_EXM_COPE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXMV_EXM_EANO_EXM_CODI_EXM_COPE] ON [PRO_EXMV]
(
	[EXM_EANO] ASC,
	[EXM_CODI] ASC,
	[EXM_COPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXPA_EXM_EANO_EXM_COPE_EXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXPA_EXM_EANO_EXM_COPE_EXM_CODI] ON [PRO_EXPA]
(
	[EXM_EANO] ASC,
	[EXM_COPE] ASC,
	[EXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXPA_TXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXPA_TXM_CODI] ON [PRO_EXPA]
(
	[TXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXPI_EXM_EANO_EXM_COPE_EXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXPI_EXM_EANO_EXM_COPE_EXM_CODI] ON [PRO_EXPI]
(
	[EXM_EANO] ASC,
	[EXM_COPE] ASC,
	[EXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_EXPI_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_EXPI_PAI_CODI] ON [PRO_EXPI]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_GSSL_NST_CODI_NST_EANO_CLI_OPER]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_GSSL_NST_CODI_NST_EANO_CLI_OPER] ON [PRO_GSSL]
(
	[NST_CODI] ASC,
	[NST_EANO] ASC,
	[CLI_OPER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_GSSL_SSL_NSEL]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_GSSL_SSL_NSEL] ON [PRO_GSSL]
(
	[SSL_NSEL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_MCAU_DUC_PNUM_DUC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_MCAU_DUC_PNUM_DUC_EANO] ON [PRO_MCAU]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_MCAU_DUC_PNUM_DUC_EANO_DUC_TIPO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_MCAU_DUC_PNUM_DUC_EANO_DUC_TIPO] ON [PRO_MCAU]
(
	[DUC_PNUM] ASC,
	[DUC_EANO] ASC,
	[DUC_TIPO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_MCAU_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_MCAU_id_declaracaoDAR] ON [PRO_MCAU]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_MCAU_MCA_TENT_MCA_ENTI_MCA_NCAU_ALF_ORIG]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_MCAU_MCA_TENT_MCA_ENTI_MCA_NCAU_ALF_ORIG] ON [PRO_MCAU]
(
	[MCA_TENT] ASC,
	[MCA_ENTI] ASC,
	[MCA_NCAU] ASC,
	[ALF_ORIG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_MCAU_MCA_TENT_MCA_NCAU_ALF_ORIG]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_MCAU_MCA_TENT_MCA_NCAU_ALF_ORIG] ON [PRO_MCAU]
(
	[MCA_TENT] ASC,
	[MCA_NCAU] ASC,
	[ALF_ORIG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_SDSC_DSC_EANO_DSC_TIPO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSC_DSC_EANO_DSC_TIPO] ON [PRO_SDSC]
(
	[DSC_EANO] ASC,
	[DSC_TIPO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSC_DSC_EANO_DSC_TIPO_DSC_DTVO_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSC_DSC_EANO_DSC_TIPO_DSC_DTVO_EAD_CODI] ON [PRO_SDSC]
(
	[DSC_EANO] ASC,
	[DSC_TIPO] ASC,
	[DSC_DTVO] ASC,
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSC_DSC_TIPO_DSC_IXML_DSC_DTVO_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSC_DSC_TIPO_DSC_IXML_DSC_DTVO_EAD_CODI] ON [PRO_SDSC]
(
	[DSC_TIPO] ASC,
	[DSC_IXML] ASC,
	[DSC_DTVO] ASC,
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSC_DSC_TIPO_DSC_NCMF_DSC_NCMV]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSC_DSC_TIPO_DSC_NCMF_DSC_NCMV] ON [PRO_SDSC]
(
	[DSC_TIPO] ASC,
	[DSC_NCMF] ASC,
	[DSC_NCMV] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSC_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSC_EAD_CODI] ON [PRO_SDSC]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSC_EAD_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSC_EAD_CODI1] ON [PRO_SDSC]
(
	[EAD_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSC_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSC_PAI_CODI] ON [PRO_SDSC]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_APA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_APA_CODI] ON [PRO_SDSD]
(
	[APA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_DOC_CODI] ON [PRO_SDSD]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_SDSD_DSC_EANO_DSC_NPRO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_DSC_EANO_DSC_NPRO] ON [PRO_SDSD]
(
	[DSC_EANO] ASC,
	[DSC_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_DSD_NRMH_DSC_EANO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_DSD_NRMH_DSC_EANO] ON [PRO_SDSD]
(
	[DSD_NRMH] ASC,
	[DSC_EANO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_PRO_SDSD_EXA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_EXA_CHVE] ON [PRO_SDSD]
(
	[EXA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_LME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_LME_CODI] ON [PRO_SDSD]
(
	[LME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_PAE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_PAE_CODI] ON [PRO_SDSD]
(
	[PAE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_PAE_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_PAE_CODI1] ON [PRO_SDSD]
(
	[PAE_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_PAE_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_PAE_CODI2] ON [PRO_SDSD]
(
	[PAE_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_PAE_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_PAE_CODI3] ON [PRO_SDSD]
(
	[PAE_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_PAI_CODI] ON [PRO_SDSD]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_TEM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_TEM_CODI] ON [PRO_SDSD]
(
	[TEM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SDSD_TXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SDSD_TXM_CODI] ON [PRO_SDSD]
(
	[TXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SSDD_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SSDD_DOC_CODI] ON [PRO_SSDD]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_SSDD_DSC_EANO_DSC_NPRO]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SSDD_DSC_EANO_DSC_NPRO] ON [PRO_SSDD]
(
	[DSC_EANO] ASC,
	[DSC_NPRO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_PRO_SSDD_DSC_EANO_DSC_NPRO_DSD_NUME]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SSDD_DSC_EANO_DSC_NPRO_DSD_NUME] ON [PRO_SSDD]
(
	[DSC_EANO] ASC,
	[DSC_NPRO] ASC,
	[DSD_NUME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_PRO_SSDD_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_PRO_SSDD_EAD_CODI] ON [PRO_SSDD]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_TAB_ADUM_APA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ADUM_APA_CHVE] ON [TAB_ADUM]
(
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_ADUM_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ADUM_PAI_CODI] ON [TAB_ADUM]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_ADUM_RRE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ADUM_RRE_CODI] ON [TAB_ADUM]
(
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_AETR_APA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_AETR_APA_CHVE] ON [TAB_AETR]
(
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_TAB_AETR_RRE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_AETR_RRE_CODI] ON [TAB_AETR]
(
	[RRE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_AETR_UME_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_AETR_UME_CODI] ON [TAB_AETR]
(
	[UME_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_ALFA_PAE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ALFA_PAE_CODI] ON [TAB_ALFA]
(
	[PAE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_ALFM_ALF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ALFM_ALF_CODI] ON [TAB_ALFM]
(
	[ALF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_ALFM_INF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ALFM_INF_CODI] ON [TAB_ALFM]
(
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_TAB_AMEN_APA_CHVE]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_AMEN_APA_CHVE] ON [TAB_AMEN]
(
	[APA_CHVE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_AMEN_INF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_AMEN_INF_CODI] ON [TAB_AMEN]
(
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_APAU_APA_DESG]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_APAU_APA_DESG] ON [TAB_APAU]
(
	[APA_DESG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_ARMZ_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ARMZ_DOC_CODI] ON [TAB_ARMZ]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_ARMZ_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_ARMZ_EAD_CODI] ON [TAB_ARMZ]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLAU_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLAU_CLI_CODI] ON [TAB_CLAU]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLAU_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLAU_DOC_CODI] ON [TAB_CLAU]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLDO_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLDO_CLI_CODI] ON [TAB_CLDO]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLDO_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLDO_DOC_CODI] ON [TAB_CLDO]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLFA_APA_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLFA_APA_CODI] ON [TAB_CLFA]
(
	[APA_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLFA_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLFA_CLI_CODI] ON [TAB_CLFA]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLFA_FOR_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLFA_FOR_CODI] ON [TAB_CLFA]
(
	[FOR_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLFI_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLFI_CLI_CODI] ON [TAB_CLFI]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLIE_ALF_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_ALF_CODI1] ON [TAB_CLIE]
(
	[ALF_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLIE_ALF_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_ALF_CODI2] ON [TAB_CLIE]
(
	[ALF_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLIE_ALF_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_ALF_CODI3] ON [TAB_CLIE]
(
	[ALF_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLIE_ALF_CODI4]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_ALF_CODI4] ON [TAB_CLIE]
(
	[ALF_CODI4] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLIE_ALF_CODI5]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_ALF_CODI5] ON [TAB_CLIE]
(
	[ALF_CODI5] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLIE_CLI_NIF]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_CLI_NIF] ON [TAB_CLIE]
(
	[CLI_NIF] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_CLIE_DEC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_DEC_CODI] ON [TAB_CLIE]
(
	[DEC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_TAB_CLIE_DIN_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_CLIE_DIN_CODI1] ON [TAB_CLIE]
(
	[DIN_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DDOC_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DDOC_CCO_CODI] ON [TAB_DDOC]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECL_ALF_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECL_ALF_CODI1] ON [TAB_DECL]
(
	[ALF_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECL_ALF_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECL_ALF_CODI2] ON [TAB_DECL]
(
	[ALF_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECL_ALF_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECL_ALF_CODI3] ON [TAB_DECL]
(
	[ALF_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECL_ALF_CODI4]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECL_ALF_CODI4] ON [TAB_DECL]
(
	[ALF_CODI4] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECL_ALF_CODI5]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECL_ALF_CODI5] ON [TAB_DECL]
(
	[ALF_CODI5] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECL_DOC_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECL_DOC_CODI2] ON [TAB_DECL]
(
	[DOC_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECR_DEC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECR_DEC_CODI] ON [TAB_DECR]
(
	[DEC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DECR_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DECR_EAD_CODI] ON [TAB_DECR]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DINE_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DINE_CCO_CODI] ON [TAB_DINE]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_DOCU_INF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_DOCU_INF_CODI] ON [TAB_DOCU]
(
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_EADM_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_EADM_EAD_CODI] ON [TAB_EADM]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_EADM_INF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_EADM_INF_CODI] ON [TAB_EADM]
(
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_FORN_FOR_NOME]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_FORN_FOR_NOME] ON [TAB_FORN]
(
	[FOR_NOME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_LEMB_EAD_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_LEMB_EAD_CODI] ON [TAB_LEMB]
(
	[EAD_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_LMER_PAI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_LMER_PAI_CODI] ON [TAB_LMER]
(
	[PAI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_MTRO_MTR_IDTY]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_MTRO_MTR_IDTY] ON [TAB_MTRO]
(
	[MTR_IDTY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_NDES_CBT_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_NDES_CBT_IDEN] ON [TAB_NDES]
(
	[CBT_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_NDES_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_NDES_CCO_CODI] ON [TAB_NDES]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_NDES_NDE_CODI1]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_NDES_NDE_CODI1] ON [TAB_NDES]
(
	[NDE_CODI1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_NDES_NDE_CODI2]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_NDES_NDE_CODI2] ON [TAB_NDES]
(
	[NDE_CODI2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_NDES_NDE_CODI3]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_NDES_NDE_CODI3] ON [TAB_NDES]
(
	[NDE_CODI3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PCBE_CBT_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PCBE_CBT_IDEN] ON [TAB_PCBE]
(
	[CBT_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_PCBE_CLI_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PCBE_CLI_CODI] ON [TAB_PCBE]
(
	[CLI_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PCBL_CBT_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PCBL_CBT_IDEN] ON [TAB_PCBL]
(
	[CBT_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PCBT_CBI_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PCBT_CBI_IDEN] ON [TAB_PCBT]
(
	[CBI_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PCBX_CBE_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PCBX_CBE_IDEN] ON [TAB_PCBX]
(
	[CBE_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PDCA_PDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PDCA_PDE_CODI] ON [TAB_PDCA]
(
	[PDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PDER_PDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PDER_PDE_CODI] ON [TAB_PDER]
(
	[PDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PDTP_PDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PDTP_PDE_CODI] ON [TAB_PDTP]
(
	[PDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PFTI_FTA_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PFTI_FTA_IDEN] ON [TAB_PFTI]
(
	[FTA_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_TAB_PSDD_PSD_IDEN]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_PSDD_PSD_IDEN] ON [TAB_PSDD]
(
	[PSD_IDEN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_RFCT_CCO_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_RFCT_CCO_CODI] ON [TAB_RFCT]
(
	[CCO_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_TDED_DOC_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_TDED_DOC_CODI] ON [TAB_TDED]
(
	[DOC_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_TDED_TDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_TDED_TDE_CODI] ON [TAB_TDED]
(
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_TDEM_INF_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_TDEM_INF_CODI] ON [TAB_TDEM]
(
	[INF_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_TDEM_TDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_TDEM_TDE_CODI] ON [TAB_TDEM]
(
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_TDEP_TDE_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_TDEP_TDE_CODI] ON [TAB_TDEP]
(
	[TDE_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_TAB_TDEP_TXM_CODI]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_TAB_TDEP_TXM_CODI] ON [TAB_TDEP]
(
	[TXM_CODI] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_ConfiguracoesDAR_id_paisMeioTransporte]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_ConfiguracoesDAR_id_paisMeioTransporte] ON [tb_ConfiguracoesDAR]
(
	[id_paisMeioTransporte] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_ConfiguracoesDAR_id_tipoDeclaracaoEU]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_ConfiguracoesDAR_id_tipoDeclaracaoEU] ON [tb_ConfiguracoesDAR]
(
	[id_tipoDeclaracaoEU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_ConfiguracoesDAR_id_tipoDeclaracaoIM]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_ConfiguracoesDAR_id_tipoDeclaracaoIM] ON [tb_ConfiguracoesDAR]
(
	[id_tipoDeclaracaoIM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_ConfiguracoesDAR_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_ConfiguracoesDAR_id_utilizadorControlo] ON [tb_ConfiguracoesDAR]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_ConfiguracoesDAREmailsResposta_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_ConfiguracoesDAREmailsResposta_id_utilizadorControlo] ON [tb_ConfiguracoesDAREmailsResposta]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_ConfiguracoesDARNotificacoesControlo_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_ConfiguracoesDARNotificacoesControlo_id_utilizadorControlo] ON [tb_ConfiguracoesDARNotificacoesControlo]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_ConfiguracoesDARNumeradores_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_ConfiguracoesDARNumeradores_id_utilizadorControlo] ON [tb_ConfiguracoesDARNumeradores]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_ano]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_ano] ON [tb_DeclaracoesDAR]
(
	[ano] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_data]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_data] ON [tb_DeclaracoesDAR]
(
	[data] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_dataVoo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_dataVoo] ON [tb_DeclaracoesDAR]
(
	[dataVoo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_tb_DeclaracoesDAR_documentoTransporte]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_documentoTransporte] ON [tb_DeclaracoesDAR]
(
	[documentoTransporte] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_cliente]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_cliente] ON [tb_DeclaracoesDAR]
(
	[id_cliente] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_condicaoEntrega]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_condicaoEntrega] ON [tb_DeclaracoesDAR]
(
	[id_condicaoEntrega] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_conta]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_conta] ON [tb_DeclaracoesDAR]
(
	[id_conta] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_declaracaoDAR] ON [tb_DeclaracoesDAR]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_declarante]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_declarante] ON [tb_DeclaracoesDAR]
(
	[id_declarante] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_estancia]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_estancia] ON [tb_DeclaracoesDAR]
(
	[id_estancia] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_estanciaMercadorias]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_estanciaMercadorias] ON [tb_DeclaracoesDAR]
(
	[id_estanciaMercadorias] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_followUp]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_followUp] ON [tb_DeclaracoesDAR]
(
	[id_followUp] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_fornecedor]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_fornecedor] ON [tb_DeclaracoesDAR]
(
	[id_fornecedor] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_localAutorizado]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_localAutorizado] ON [tb_DeclaracoesDAR]
(
	[id_localAutorizado] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_meioTransporte]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_meioTransporte] ON [tb_DeclaracoesDAR]
(
	[id_meioTransporte] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_natureza]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_natureza] ON [tb_DeclaracoesDAR]
(
	[id_natureza] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_paisCliente]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_paisCliente] ON [tb_DeclaracoesDAR]
(
	[id_paisCliente] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_paisDeclarante]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_paisDeclarante] ON [tb_DeclaracoesDAR]
(
	[id_paisDeclarante] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_paisFornecedor]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_paisFornecedor] ON [tb_DeclaracoesDAR]
(
	[id_paisFornecedor] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_paisMoedaCustosTransporte]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_paisMoedaCustosTransporte] ON [tb_DeclaracoesDAR]
(
	[id_paisMoedaCustosTransporte] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_paisMoedaMontante]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_paisMoedaMontante] ON [tb_DeclaracoesDAR]
(
	[id_paisMoedaMontante] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_tipoDocumentoConta]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_tipoDocumentoConta] ON [tb_DeclaracoesDAR]
(
	[id_tipoDocumentoConta] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_utilizadorADT]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_utilizadorADT] ON [tb_DeclaracoesDAR]
(
	[id_utilizadorADT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_utilizadorControlo] ON [tb_DeclaracoesDAR]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_id_utilizadorNomeado]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_id_utilizadorNomeado] ON [tb_DeclaracoesDAR]
(
	[id_utilizadorNomeado] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDAR_status]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDAR_status] ON [tb_DeclaracoesDAR]
(
	[status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_artigo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_artigo] ON [tb_DeclaracoesDARAdicoes]
(
	[id_artigo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_declaracaoDAR] ON [tb_DeclaracoesDARAdicoes]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_fornecedor]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_fornecedor] ON [tb_DeclaracoesDARAdicoes]
(
	[id_fornecedor] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_paisFornecedor]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_paisFornecedor] ON [tb_DeclaracoesDARAdicoes]
(
	[id_paisFornecedor] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_paisMoedaCustosTransporte]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_paisMoedaCustosTransporte] ON [tb_DeclaracoesDARAdicoes]
(
	[id_paisMoedaCustosTransporte] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_paisMoedaMontante]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_paisMoedaMontante] ON [tb_DeclaracoesDARAdicoes]
(
	[id_paisMoedaMontante] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_paisOrigem]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_paisOrigem] ON [tb_DeclaracoesDARAdicoes]
(
	[id_paisOrigem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoes_id_utilizadorControlo] ON [tb_DeclaracoesDARAdicoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesDocumentos_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesDocumentos_id_adicao] ON [tb_DeclaracoesDARAdicoesDocumentos]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesDocumentos_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesDocumentos_id_documento] ON [tb_DeclaracoesDARAdicoesDocumentos]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesDocumentos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesDocumentos_id_utilizadorControlo] ON [tb_DeclaracoesDARAdicoesDocumentos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesMencoes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesMencoes_id_adicao] ON [tb_DeclaracoesDARAdicoesMencoes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesMencoes_id_adicaoDocumento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesMencoes_id_adicaoDocumento] ON [tb_DeclaracoesDARAdicoesMencoes]
(
	[id_adicaoDocumento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesMencoes_id_mencao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesMencoes_id_mencao] ON [tb_DeclaracoesDARAdicoesMencoes]
(
	[id_mencao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesMencoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesMencoes_id_utilizadorControlo] ON [tb_DeclaracoesDARAdicoesMencoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesPrecedentes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesPrecedentes_id_adicao] ON [tb_DeclaracoesDARAdicoesPrecedentes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesPrecedentes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesPrecedentes_id_documento] ON [tb_DeclaracoesDARAdicoesPrecedentes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARAdicoesPrecedentes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARAdicoesPrecedentes_id_utilizadorControlo] ON [tb_DeclaracoesDARAdicoesPrecedentes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARArquivos_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARArquivos_id_declaracaoDAR] ON [tb_DeclaracoesDARArquivos]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARArquivos_id_utilizadorArquivo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARArquivos_id_utilizadorArquivo] ON [tb_DeclaracoesDARArquivos]
(
	[id_utilizadorArquivo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARArquivos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARArquivos_id_utilizadorControlo] ON [tb_DeclaracoesDARArquivos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARContactos_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARContactos_id_declaracaoDAR] ON [tb_DeclaracoesDARContactos]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARContactos_id_utilizadorContacto]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARContactos_id_utilizadorContacto] ON [tb_DeclaracoesDARContactos]
(
	[id_utilizadorContacto] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARContactos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARContactos_id_utilizadorControlo] ON [tb_DeclaracoesDARContactos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARDocumentos_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARDocumentos_id_declaracaoDAR] ON [tb_DeclaracoesDARDocumentos]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARDocumentos_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARDocumentos_id_documento] ON [tb_DeclaracoesDARDocumentos]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARDocumentos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARDocumentos_id_utilizadorControlo] ON [tb_DeclaracoesDARDocumentos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARFollowUps_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARFollowUps_id_declaracaoDAR] ON [tb_DeclaracoesDARFollowUps]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARFollowUps_id_followUp]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARFollowUps_id_followUp] ON [tb_DeclaracoesDARFollowUps]
(
	[id_followUp] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARFollowUps_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARFollowUps_id_utilizadorControlo] ON [tb_DeclaracoesDARFollowUps]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARFollowUps_id_utilizadorFollowUp]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARFollowUps_id_utilizadorFollowUp] ON [tb_DeclaracoesDARFollowUps]
(
	[id_utilizadorFollowUp] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARIncidencias_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARIncidencias_id_declaracaoDAR] ON [tb_DeclaracoesDARIncidencias]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARIncidencias_id_statusIncidencia]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARIncidencias_id_statusIncidencia] ON [tb_DeclaracoesDARIncidencias]
(
	[id_statusIncidencia] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARIncidencias_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARIncidencias_id_utilizadorControlo] ON [tb_DeclaracoesDARIncidencias]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARIncidencias_id_utilizadorCriacao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARIncidencias_id_utilizadorCriacao] ON [tb_DeclaracoesDARIncidencias]
(
	[id_utilizadorCriacao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_tb_DeclaracoesDARManifestos_documentoTransporte]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARManifestos_documentoTransporte] ON [tb_DeclaracoesDARManifestos]
(
	[documentoTransporte] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARManifestos_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARManifestos_id_declaracaoDAR] ON [tb_DeclaracoesDARManifestos]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARManifestos_id_pais]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARManifestos_id_pais] ON [tb_DeclaracoesDARManifestos]
(
	[id_pais] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARManifestos_id_paisMoeda]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARManifestos_id_paisMoeda] ON [tb_DeclaracoesDARManifestos]
(
	[id_paisMoeda] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARManifestos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARManifestos_id_utilizadorControlo] ON [tb_DeclaracoesDARManifestos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARManifestos_tipoManifesto]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARManifestos_tipoManifesto] ON [tb_DeclaracoesDARManifestos]
(
	[tipoManifesto] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARMencoes_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARMencoes_id_declaracaoDAR] ON [tb_DeclaracoesDARMencoes]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARMencoes_id_mencao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARMencoes_id_mencao] ON [tb_DeclaracoesDARMencoes]
(
	[id_mencao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARMencoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARMencoes_id_utilizadorControlo] ON [tb_DeclaracoesDARMencoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARMensagens_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARMensagens_id_declaracaoDAR] ON [tb_DeclaracoesDARMensagens]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARMensagens_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARMensagens_id_utilizadorControlo] ON [tb_DeclaracoesDARMensagens]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARMensagens_id_utilizadorMensagem]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARMensagens_id_utilizadorMensagem] ON [tb_DeclaracoesDARMensagens]
(
	[id_utilizadorMensagem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARPrecedentes_id_declaracaoDAR]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARPrecedentes_id_declaracaoDAR] ON [tb_DeclaracoesDARPrecedentes]
(
	[id_declaracaoDAR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARPrecedentes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARPrecedentes_id_documento] ON [tb_DeclaracoesDARPrecedentes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_DeclaracoesDARPrecedentes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_DeclaracoesDARPrecedentes_id_utilizadorControlo] ON [tb_DeclaracoesDARPrecedentes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesAutorizacoes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesAutorizacoes_id_adicao] ON [tb_EXP_DeclaracoesAdicoesAutorizacoes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesAutorizacoes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesAutorizacoes_id_documento] ON [tb_EXP_DeclaracoesAdicoesAutorizacoes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesAutorizacoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesAutorizacoes_id_utilizadorControlo] ON [tb_EXP_DeclaracoesAdicoesAutorizacoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesContentores_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesContentores_id_adicao] ON [tb_EXP_DeclaracoesAdicoesContentores]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesContentores_id_contentor]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesContentores_id_contentor] ON [tb_EXP_DeclaracoesAdicoesContentores]
(
	[id_contentor] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesContentores_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesContentores_id_utilizadorControlo] ON [tb_EXP_DeclaracoesAdicoesContentores]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesImposicoes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesImposicoes_id_adicao] ON [tb_EXP_DeclaracoesAdicoesImposicoes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesImposicoes_id_rubricaReceita]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesImposicoes_id_rubricaReceita] ON [tb_EXP_DeclaracoesAdicoesImposicoes]
(
	[id_rubricaReceita] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesImposicoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesImposicoes_id_utilizadorControlo] ON [tb_EXP_DeclaracoesAdicoesImposicoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_id_imposicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_id_imposicao] ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas]
(
	[id_imposicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_id_unidadeMedida]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_id_unidadeMedida] ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas]
(
	[id_unidadeMedida] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_id_utilizadorControlo] ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesIntervenientes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesIntervenientes_id_adicao] ON [tb_EXP_DeclaracoesAdicoesIntervenientes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesIntervenientes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesIntervenientes_id_utilizadorControlo] ON [tb_EXP_DeclaracoesAdicoesIntervenientes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPedidos_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPedidos_id_adicao] ON [tb_EXP_DeclaracoesAdicoesPedidos]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPedidos_id_pedido]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPedidos_id_pedido] ON [tb_EXP_DeclaracoesAdicoesPedidos]
(
	[id_pedido] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPedidos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPedidos_id_utilizadorControlo] ON [tb_EXP_DeclaracoesAdicoesPedidos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_adicao] ON [tb_EXP_DeclaracoesAdicoesPrecedentes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_documento] ON [tb_EXP_DeclaracoesAdicoesPrecedentes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaQualificador]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaQualificador] ON [tb_EXP_DeclaracoesAdicoesPrecedentes]
(
	[id_unidadeMedidaQualificador] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaVolumes]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaVolumes] ON [tb_EXP_DeclaracoesAdicoesPrecedentes]
(
	[id_unidadeMedidaVolumes] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAdicoesPrecedentesid_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAdicoesPrecedentesid_utilizadorControlo] ON [tb_EXP_DeclaracoesAdicoesPrecedentes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAutorizacoes_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAutorizacoes_id_declaracaoEXP] ON [tb_EXP_DeclaracoesAutorizacoes]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAutorizacoes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAutorizacoes_id_documento] ON [tb_EXP_DeclaracoesAutorizacoes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesAutorizacoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesAutorizacoes_id_utilizadorControlo] ON [tb_EXP_DeclaracoesAutorizacoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesContentoresSelos_id_contentor]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesContentoresSelos_id_contentor] ON [tb_EXP_DeclaracoesContentoresSelos]
(
	[id_contentor] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesContentoresSelos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesContentoresSelos_id_utilizadorControlo] ON [tb_EXP_DeclaracoesContentoresSelos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesDocumentos_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesDocumentos_id_declaracaoEXP] ON [tb_EXP_DeclaracoesDocumentos]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesDocumentos_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesDocumentos_id_documento] ON [tb_EXP_DeclaracoesDocumentos]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesDocumentos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesDocumentos_id_utilizadorControlo] ON [tb_EXP_DeclaracoesDocumentos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesIncidencias_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesIncidencias_id_declaracaoEXP] ON [tb_EXP_DeclaracoesIncidencias]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesIncidencias_id_statusIncidencia]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesIncidencias_id_statusIncidencia] ON [tb_EXP_DeclaracoesIncidencias]
(
	[id_statusIncidencia] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesIncidencias_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesIncidencias_id_utilizadorControlo] ON [tb_EXP_DeclaracoesIncidencias]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesIncidencias_id_utilizadorCriacao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesIncidencias_id_utilizadorCriacao] ON [tb_EXP_DeclaracoesIncidencias]
(
	[id_utilizadorCriacao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesIntervenientes_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesIntervenientes_id_declaracaoEXP] ON [tb_EXP_DeclaracoesIntervenientes]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesIntervenientes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesIntervenientes_id_utilizadorControlo] ON [tb_EXP_DeclaracoesIntervenientes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_declaracaoEXP] ON [tb_EXP_DeclaracoesLocaisTransformacao]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_localAutorizado]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_localAutorizado] ON [tb_EXP_DeclaracoesLocaisTransformacao]
(
	[id_localAutorizado] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_pais]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_pais] ON [tb_EXP_DeclaracoesLocaisTransformacao]
(
	[id_pais] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesLocaisTransformacao_id_utilizadorControlo] ON [tb_EXP_DeclaracoesLocaisTransformacao]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_declaracaoEXP] ON [tb_EXP_DeclaracoesMeiosTransportePartida]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_meioTransporte]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_meioTransporte] ON [tb_EXP_DeclaracoesMeiosTransportePartida]
(
	[id_meioTransporte] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_pais]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_pais] ON [tb_EXP_DeclaracoesMeiosTransportePartida]
(
	[id_pais] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesMeiosTransportePartida_id_utilizadorControlo] ON [tb_EXP_DeclaracoesMeiosTransportePartida]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesMensagens_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesMensagens_id_declaracaoEXP] ON [tb_EXP_DeclaracoesMensagens]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesMensagens_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesMensagens_id_utilizadorControlo] ON [tb_EXP_DeclaracoesMensagens]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesMensagens_id_utilizadorMensagem]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesMensagens_id_utilizadorMensagem] ON [tb_EXP_DeclaracoesMensagens]
(
	[id_utilizadorMensagem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesPrecedentes_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesPrecedentes_id_declaracaoEXP] ON [tb_EXP_DeclaracoesPrecedentes]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesPrecedentes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesPrecedentes_id_documento] ON [tb_EXP_DeclaracoesPrecedentes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesPrecedentes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesPrecedentes_id_utilizadorControlo] ON [tb_EXP_DeclaracoesPrecedentes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesProdutosTransformados_id_artigo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesProdutosTransformados_id_artigo] ON [tb_EXP_DeclaracoesProdutosTransformados]
(
	[id_artigo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesProdutosTransformados_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesProdutosTransformados_id_declaracaoEXP] ON [tb_EXP_DeclaracoesProdutosTransformados]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesProdutosTransformados_id_meioIdentificacao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesProdutosTransformados_id_meioIdentificacao] ON [tb_EXP_DeclaracoesProdutosTransformados]
(
	[id_meioIdentificacao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_EXP_DeclaracoesProdutosTransformados_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_EXP_DeclaracoesProdutosTransformados_id_utilizadorControlo] ON [tb_EXP_DeclaracoesProdutosTransformados]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_FAC_DocContasArquivos_id_docConta]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_FAC_DocContasArquivos_id_docConta] ON [tb_FAC_DocContasArquivos]
(
	[id_docConta] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_FAC_DocContasArquivos_id_utilizadorArquivo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_FAC_DocContasArquivos_id_utilizadorArquivo] ON [tb_FAC_DocContasArquivos]
(
	[id_utilizadorArquivo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_FAC_DocContasArquivos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_FAC_DocContasArquivos_id_utilizadorControlo] ON [tb_FAC_DocContasArquivos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_HistoricoDMG_ano]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_HistoricoDMG_ano] ON [tb_HistoricoDMG]
(
	[ano] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_HistoricoDMG_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_HistoricoDMG_id_utilizadorControlo] ON [tb_HistoricoDMG]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_HistoricoDMG_id_utilizadorSubmissao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_HistoricoDMG_id_utilizadorSubmissao] ON [tb_HistoricoDMG]
(
	[id_utilizadorSubmissao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAcrescimosDeducoes_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAcrescimosDeducoes_id_declaracaoIMP] ON [tb_IMP_DeclaracoesAcrescimosDeducoes]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAcrescimosDeducoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAcrescimosDeducoes_id_utilizadorControlo] ON [tb_IMP_DeclaracoesAcrescimosDeducoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_id_adicao] ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_id_utilizadorControlo] ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_adicao] ON [tb_IMP_DeclaracoesAdicoesEntrepostos]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_armazem]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_armazem] ON [tb_IMP_DeclaracoesAdicoesEntrepostos]
(
	[id_armazem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_documento] ON [tb_IMP_DeclaracoesAdicoesEntrepostos]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_tipoArmazem]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_tipoArmazem] ON [tb_IMP_DeclaracoesAdicoesEntrepostos]
(
	[id_tipoArmazem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesEntrepostos_id_utilizadorControlo] ON [tb_IMP_DeclaracoesAdicoesEntrepostos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_adicao] ON [tb_IMP_DeclaracoesAdicoesPedidos]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_chassi]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_chassi] ON [tb_IMP_DeclaracoesAdicoesPedidos]
(
	[id_chassi] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_mercadoriaIEC]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_mercadoriaIEC] ON [tb_IMP_DeclaracoesAdicoesPedidos]
(
	[id_mercadoriaIEC] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_pedido]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_pedido] ON [tb_IMP_DeclaracoesAdicoesPedidos]
(
	[id_pedido] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_utilizadorControlo] ON [tb_IMP_DeclaracoesAdicoesPedidos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_veiculo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPedidos_id_veiculo] ON [tb_IMP_DeclaracoesAdicoesPedidos]
(
	[id_veiculo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_adicao] ON [tb_IMP_DeclaracoesAdicoesPrecedentes]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_documento] ON [tb_IMP_DeclaracoesAdicoesPrecedentes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaQualificador]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaQualificador] ON [tb_IMP_DeclaracoesAdicoesPrecedentes]
(
	[id_unidadeMedidaQualificador] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaVolumes]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_unidadeMedidaVolumes] ON [tb_IMP_DeclaracoesAdicoesPrecedentes]
(
	[id_unidadeMedidaVolumes] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesPrecedentes_id_utilizadorControlo] ON [tb_IMP_DeclaracoesAdicoesPrecedentes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesReferenciasFiscais_id_adicao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesReferenciasFiscais_id_adicao] ON [tb_IMP_DeclaracoesAdicoesReferenciasFiscais]
(
	[id_adicao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesAdicoesReferenciasFiscais_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesAdicoesReferenciasFiscais_id_utilizadorControlo] ON [tb_IMP_DeclaracoesAdicoesReferenciasFiscais]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesCondicoesEconomicas_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesCondicoesEconomicas_id_declaracaoIMP] ON [tb_IMP_DeclaracoesCondicoesEconomicas]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesCondicoesEconomicas_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesCondicoesEconomicas_id_utilizadorControlo] ON [tb_IMP_DeclaracoesCondicoesEconomicas]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesDocumentos_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesDocumentos_id_declaracaoIMP] ON [tb_IMP_DeclaracoesDocumentos]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesDocumentos_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesDocumentos_id_documento] ON [tb_IMP_DeclaracoesDocumentos]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesDocumentos_id_paisMoeda]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesDocumentos_id_paisMoeda] ON [tb_IMP_DeclaracoesDocumentos]
(
	[id_paisMoeda] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesDocumentos_id_unidadeMedida]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesDocumentos_id_unidadeMedida] ON [tb_IMP_DeclaracoesDocumentos]
(
	[id_unidadeMedida] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesDocumentos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesDocumentos_id_utilizadorControlo] ON [tb_IMP_DeclaracoesDocumentos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesEstancias_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesEstancias_id_declaracaoIMP] ON [tb_IMP_DeclaracoesEstancias]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesEstancias_id_estancia]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesEstancias_id_estancia] ON [tb_IMP_DeclaracoesEstancias]
(
	[id_estancia] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesEstancias_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesEstancias_id_utilizadorControlo] ON [tb_IMP_DeclaracoesEstancias]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesIntervenientes_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesIntervenientes_id_declaracaoIMP] ON [tb_IMP_DeclaracoesIntervenientes]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesIntervenientes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesIntervenientes_id_utilizadorControlo] ON [tb_IMP_DeclaracoesIntervenientes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_declaracaoIMP] ON [tb_IMP_DeclaracoesLocaisTransformacao]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_localAutorizado]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_localAutorizado] ON [tb_IMP_DeclaracoesLocaisTransformacao]
(
	[id_localAutorizado] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_pais]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_pais] ON [tb_IMP_DeclaracoesLocaisTransformacao]
(
	[id_pais] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesLocaisTransformacao_id_utilizadorControlo] ON [tb_IMP_DeclaracoesLocaisTransformacao]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesMeiosIdentificacao_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesMeiosIdentificacao_id_declaracaoIMP] ON [tb_IMP_DeclaracoesMeiosIdentificacao]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesMeiosIdentificacao_id_meioIdentificacao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesMeiosIdentificacao_id_meioIdentificacao] ON [tb_IMP_DeclaracoesMeiosIdentificacao]
(
	[id_meioIdentificacao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesMeiosIdentificacao_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesMeiosIdentificacao_id_utilizadorControlo] ON [tb_IMP_DeclaracoesMeiosIdentificacao]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesPrecedentes_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesPrecedentes_id_declaracaoIMP] ON [tb_IMP_DeclaracoesPrecedentes]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesPrecedentes_id_documento]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesPrecedentes_id_documento] ON [tb_IMP_DeclaracoesPrecedentes]
(
	[id_documento] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesPrecedentes_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesPrecedentes_id_utilizadorControlo] ON [tb_IMP_DeclaracoesPrecedentes]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesProdutosTransformados_id_artigo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesProdutosTransformados_id_artigo] ON [tb_IMP_DeclaracoesProdutosTransformados]
(
	[id_artigo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesProdutosTransformados_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesProdutosTransformados_id_declaracaoIMP] ON [tb_IMP_DeclaracoesProdutosTransformados]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesProdutosTransformados_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesProdutosTransformados_id_utilizadorControlo] ON [tb_IMP_DeclaracoesProdutosTransformados]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesProprietarios_id_cliente]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesProprietarios_id_cliente] ON [tb_IMP_DeclaracoesProprietarios]
(
	[id_cliente] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesProprietarios_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesProprietarios_id_declaracaoIMP] ON [tb_IMP_DeclaracoesProprietarios]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesProprietarios_id_pais]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesProprietarios_id_pais] ON [tb_IMP_DeclaracoesProprietarios]
(
	[id_pais] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesProprietarios_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesProprietarios_id_utilizadorControlo] ON [tb_IMP_DeclaracoesProprietarios]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesReferenciasFiscais_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesReferenciasFiscais_id_declaracaoIMP] ON [tb_IMP_DeclaracoesReferenciasFiscais]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesReferenciasFiscais_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesReferenciasFiscais_id_utilizadorControlo] ON [tb_IMP_DeclaracoesReferenciasFiscais]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesTaxasRendimento_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesTaxasRendimento_id_declaracaoIMP] ON [tb_IMP_DeclaracoesTaxasRendimento]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_IMP_DeclaracoesTaxasRendimento_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_IMP_DeclaracoesTaxasRendimento_id_utilizadorControlo] ON [tb_IMP_DeclaracoesTaxasRendimento]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_Desdobramentos_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_Desdobramentos_id_utilizadorControlo] ON [tb_TBL_Desdobramentos]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_tb_TBL_Desdobramentos_regime]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_Desdobramentos_regime] ON [tb_TBL_Desdobramentos]
(
	[regime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_tb_TBL_Desdobramentos_TipoDeclaracao]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_Desdobramentos_TipoDeclaracao] ON [tb_TBL_Desdobramentos]
(
	[tipoDeclaracao] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
SET ANSI_PADDING ON

/****** Object:  Index [IX_tb_TBL_Desdobramentos_tipoDeclaracao_regime]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_Desdobramentos_tipoDeclaracao_regime] ON [tb_TBL_Desdobramentos]
(
	[tipoDeclaracao] ASC,
	[regime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_HonorariosIMP_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_HonorariosIMP_id_utilizadorControlo] ON [tb_TBL_HonorariosIMP]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_LinhasOGMA_id_artigo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_LinhasOGMA_id_artigo] ON [tb_TBL_LinhasOGMA]
(
	[id_artigo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_LinhasOGMA_id_declaracaoEXP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_LinhasOGMA_id_declaracaoEXP] ON [tb_TBL_LinhasOGMA]
(
	[id_declaracaoEXP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_LinhasOGMA_id_declaracaoIMP]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_LinhasOGMA_id_declaracaoIMP] ON [tb_TBL_LinhasOGMA]
(
	[id_declaracaoIMP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_LinhasOGMA_id_paisOrigem]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_LinhasOGMA_id_paisOrigem] ON [tb_TBL_LinhasOGMA]
(
	[id_paisOrigem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_LinhasOGMA_id_preferencia]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_LinhasOGMA_id_preferencia] ON [tb_TBL_LinhasOGMA]
(
	[id_preferencia] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_LinhasOGMA_id_unidadeMedida]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_LinhasOGMA_id_unidadeMedida] ON [tb_TBL_LinhasOGMA]
(
	[id_unidadeMedida] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
/****** Object:  Index [IX_tb_TBL_LinhasOGMA_id_utilizadorControlo]    Script Date: 04-11-2025 10:22:21 ******/
CREATE NONCLUSTERED INDEX [IX_tb_TBL_LinhasOGMA_id_utilizadorControlo] ON [tb_TBL_LinhasOGMA]
(
	[id_utilizadorControlo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_TVOL]  DEFAULT ((0)) FOR [EDG_TVOL]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_TPBR]  DEFAULT ((0)) FOR [EDG_TPBR]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_TMCU]  DEFAULT ((0)) FOR [EDG_TMCU]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_TVAL]  DEFAULT ((0)) FOR [EDG_TVAL]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_SVOL]  DEFAULT ((0)) FOR [EDG_SVOL]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_SPBR]  DEFAULT ((0)) FOR [EDG_SPBR]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_ORIG]  DEFAULT ((0)) FOR [EDG_ORIG]
ALTER TABLE [AEX_ENDG] ADD  CONSTRAINT [DF_AEX_ENDG_EDG_EXPO]  DEFAULT ((0)) FOR [EDG_EXPO]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_VOLS]  DEFAULT ((0)) FOR [ELN_VOLS]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_PART]  DEFAULT ((0)) FOR [ELN_PART]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_PLIQ]  DEFAULT ((0)) FOR [ELN_PLIQ]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_PBRT]  DEFAULT ((0)) FOR [ELN_PBRT]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_VALO]  DEFAULT ((0)) FOR [ELN_VALO]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_ALTU]  DEFAULT ((0)) FOR [ELN_ALTU]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_COMP]  DEFAULT ((0)) FOR [ELN_COMP]
ALTER TABLE [AEX_ENLN] ADD  CONSTRAINT [DF_AEX_ENLN_ELN_LARG]  DEFAULT ((0)) FOR [ELN_LARG]
ALTER TABLE [AEX_SADG] ADD  CONSTRAINT [DF_AEX_SADG_SDG_VOLS]  DEFAULT ((0)) FOR [SDG_VOLS]
ALTER TABLE [AEX_SADG] ADD  CONSTRAINT [DF_AEX_SADG_SDG_PBRT]  DEFAULT ((0)) FOR [SDG_PBRT]
ALTER TABLE [AEX_SADG] ADD  CONSTRAINT [DF_AEX_SADG_SDG_ASAI]  DEFAULT ((0)) FOR [SDG_ASAI]
ALTER TABLE [AEX_SADG] ADD  CONSTRAINT [DF_AEX_SADG_SDG_ANUL]  DEFAULT ((0)) FOR [SDG_ANUL]
ALTER TABLE [AEX_SADG] ADD  CONSTRAINT [DF_AEX_SADG_SDG_ORIG]  DEFAULT ((0)) FOR [SDG_ORIG]
ALTER TABLE [FAC_CDDO] ADD  CONSTRAINT [DF_FAC_CDDO_CDD_ENVI]  DEFAULT (0) FOR [CDD_ENVI]
ALTER TABLE [FAC_CDDO] ADD  CONSTRAINT [DF_FAC_CDDO_CDD_RECE]  DEFAULT (0) FOR [CDD_RECE]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_TCDO]  DEFAULT ((0)) FOR [CDO_TCNT]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_ANUL]  DEFAULT ((0)) FOR [CDO_ANUL]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_INCC]  DEFAULT ((0)) FOR [CDO_IMPR]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_IN01]  DEFAULT ((0)) FOR [CDO_IN01]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_IN02]  DEFAULT ((0)) FOR [CDO_IN02]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_IN03]  DEFAULT ((0)) FOR [CDO_IN03]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_IN04]  DEFAULT ((0)) FOR [CDO_IN04]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_VI01]  DEFAULT ((0)) FOR [CDO_VI01]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_VI02]  DEFAULT ((0)) FOR [CDO_VI02]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_VI03]  DEFAULT ((0)) FOR [CDO_VI03]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_DVE_VI04]  DEFAULT ((0)) FOR [CDO_VI04]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_CPRO]  DEFAULT ((0)) FOR [CDO_CPRO]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_CFED]  DEFAULT ((0)) FOR [CDO_CFED]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_DPOC]  DEFAULT ((0)) FOR [CDO_DPOC]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_IPOC]  DEFAULT ((0)) FOR [CDO_IPOC]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_PALT]  DEFAULT ((0)) FOR [CDO_PALT]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_OKIM]  DEFAULT ((0)) FOR [CDO_OKPI]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_IMEX]  DEFAULT ((0)) FOR [CDO_IMEX]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_PAGO]  DEFAULT ((0)) FOR [CDO_PAGO]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_2ENV]  DEFAULT ((0)) FOR [CDO_2ENV]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_IVAA]  DEFAULT ((0)) FOR [CDO_IVAA]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_ORIG]  DEFAULT ((0)) FOR [CDO_ORIG]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_PENH]  DEFAULT ((0)) FOR [CDO_PENH]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_EADC]  DEFAULT ((0)) FOR [CDO_EADC]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_ATCU]  DEFAULT ((0)) FOR [CDO_ATCU]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_PMRP]  DEFAULT ((1)) FOR [CDO_PMRP]
ALTER TABLE [FAC_CDOC] ADD  CONSTRAINT [DF_FAC_CDOC_CDO_ESAF]  DEFAULT ((0)) FOR [CDO_ESAF]
ALTER TABLE [FAC_DCDO] ADD  CONSTRAINT [DF_FAC_DCDO_DCD_DNOW]  DEFAULT (getdate()) FOR [DCD_DNOW]
ALTER TABLE [FAC_DCDO] ADD  CONSTRAINT [DF_FAC_DCDO_DCD_VFCX]  DEFAULT ((0)) FOR [DCD_VFCX]
ALTER TABLE [FAC_DCDO] ADD  CONSTRAINT [DF_FAC_DCDO_DVD_PMRP]  DEFAULT ((1)) FOR [DCD_PMRP]
ALTER TABLE [FAC_DDCD] ADD  CONSTRAINT [DF_FAC_DDCO_DDC_IVA]  DEFAULT ((0)) FOR [DDC_IVA]
ALTER TABLE [FAC_DICD] ADD  CONSTRAINT [DF_FAC_DICD_DIC_IVA]  DEFAULT (0) FOR [DIC_IVA]
ALTER TABLE [FAC_DVDT] ADD  CONSTRAINT [DF_FAC_DVDT_DVD_LHON]  DEFAULT (0) FOR [DVD_LHON]
ALTER TABLE [FAC_DVDT] ADD  CONSTRAINT [DF_FAC_DVDT_DVD_PMRP]  DEFAULT ((1)) FOR [DVD_PMRP]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_TDOC]  DEFAULT ((0)) FOR [DVE_TDOC]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_IN01]  DEFAULT ((0)) FOR [DVE_IN01]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_IN02]  DEFAULT ((0)) FOR [DVE_IN02]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_IN03]  DEFAULT ((0)) FOR [DVE_IN03]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_IN04]  DEFAULT ((0)) FOR [DVE_IN04]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_VI01]  DEFAULT ((0)) FOR [DVE_VI01]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_VI02]  DEFAULT ((0)) FOR [DVE_VI02]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_VI03]  DEFAULT ((0)) FOR [DVE_VI03]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_VI04]  DEFAULT ((0)) FOR [DVE_VI04]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_ANUL]  DEFAULT ((0)) FOR [DVE_ANUL]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_VLIQ]  DEFAULT ((0)) FOR [DVE_VLIQ]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_VIVA]  DEFAULT ((0)) FOR [DVE_VIVA]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_VTOT]  DEFAULT ((0)) FOR [DVE_VTOT]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_IMPR]  DEFAULT ((0)) FOR [DVE_IMPR]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_STAT]  DEFAULT ((0)) FOR [DVE_STAT]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_IMEX]  DEFAULT ((0)) FOR [DVE_IMEX]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_ATCU]  DEFAULT ((0)) FOR [DVE_ATCU]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_SERI]  DEFAULT ((1)) FOR [DVE_SERI]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_PMRP]  DEFAULT ((1)) FOR [DVE_PMRP]
ALTER TABLE [FAC_DVEN] ADD  CONSTRAINT [DF_FAC_DVEN_DVE_ESAF]  DEFAULT ((0)) FOR [DVE_ESAF]
ALTER TABLE [FAC_FCDT] ADD  CONSTRAINT [DF_FAC_FCDT_FCD_VTOT]  DEFAULT (0) FOR [FCD_VTOT]
ALTER TABLE [FAC_FCDT] ADD  CONSTRAINT [DF_FAC_FCDT_FCD_SINA]  DEFAULT (0) FOR [FCD_SINA]
ALTER TABLE [FAC_FCDT] ADD  CONSTRAINT [DF_FAC_FCDT_FCD_SLIS]  DEFAULT (0) FOR [FCD_SLIS]
ALTER TABLE [FAC_FCDT] ADD  CONSTRAINT [DF_FAC_FCDT_FCD_LPRO]  DEFAULT (0) FOR [FCD_LPRO]
ALTER TABLE [FAC_FCDT] ADD  CONSTRAINT [DF_FAC_FCDT_FCD_ENVI]  DEFAULT (0) FOR [FCD_ENVI]
ALTER TABLE [FAC_FCXA] ADD  CONSTRAINT [DF_FAC_FCXA_FCX_STAT]  DEFAULT (0) FOR [FCX_STAT]
ALTER TABLE [FAC_ICDO] ADD  CONSTRAINT [DF_FAC_ICDO_ICD_ISEN]  DEFAULT ((0)) FOR [ICD_ISEN]
ALTER TABLE [FAC_ICDO] ADD  CONSTRAINT [DF_FAC_ICDO_ICD_PMRP]  DEFAULT ((1)) FOR [ICD_PMRP]
ALTER TABLE [FAC_LCCT] ADD  CONSTRAINT [DF_FAC_LCCT_LCC_VTOT]  DEFAULT (0) FOR [LCC_VTOT]
ALTER TABLE [FAC_LCCT] ADD  CONSTRAINT [DF_FAC_LCCT_LCC_ANUL]  DEFAULT (0) FOR [LCC_ANUL]
ALTER TABLE [FAC_LCCT] ADD  CONSTRAINT [DF_FAC_LCCT_LCC_IMPR]  DEFAULT (0) FOR [LCC_IMPR]
ALTER TABLE [FAC_LCCT] ADD  CONSTRAINT [DF_FAC_LCCT_LCC_CONF]  DEFAULT ((0)) FOR [LCC_CONF]
ALTER TABLE [FAC_LCCT] ADD  CONSTRAINT [DF_FAC_LCCT_REC_SERI]  DEFAULT ((1)) FOR [LCC_SERI]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_ENTI]  DEFAULT (0) FOR [MVC_TENT]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_NPRO]  DEFAULT (0) FOR [MVC_NPRO]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VTOT]  DEFAULT (0) FOR [MVC_VTOT]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VDEB]  DEFAULT (0) FOR [MVC_VDEB]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VIVA]  DEFAULT (0) FOR [MVC_VIVA]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VI01]  DEFAULT (0) FOR [MVC_VI01]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VI02]  DEFAULT (0) FOR [MVC_VI02]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VI03]  DEFAULT (0) FOR [MVC_VI03]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VI04]  DEFAULT (0) FOR [MVC_VI04]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_IN01]  DEFAULT (0) FOR [MVC_IN01]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_IN02]  DEFAULT (0) FOR [MVC_IN02]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_IN03]  DEFAULT (0) FOR [MVC_IN03]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_IN04]  DEFAULT (0) FOR [MVC_IN04]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_RECA]  DEFAULT (0) FOR [MVC_RECA]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_IMPR]  DEFAULT (0) FOR [MVC_IMPR]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_STAT]  DEFAULT (0) FOR [MVC_STAT]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_GPOC]  DEFAULT (0) FOR [MVC_GPOC]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_MVC_VRTF]  DEFAULT ((0)) FOR [MVC_VRTF]
ALTER TABLE [FAC_MVCC] ADD  CONSTRAINT [DF_FAC_MVCC_LCC_SERI]  DEFAULT ((1)) FOR [MVC_SERI]
ALTER TABLE [FAC_RECC] ADD  CONSTRAINT [DF_FAC_RECC_REC_VLIQ]  DEFAULT (0) FOR [REC_VLIQ]
ALTER TABLE [FAC_RECC] ADD  CONSTRAINT [DF_FAC_RECC_REC_VDES]  DEFAULT (0) FOR [REC_VDES]
ALTER TABLE [FAC_RECC] ADD  CONSTRAINT [DF_FAC_RECC_REC_VTOT]  DEFAULT (0) FOR [REC_VTOT]
ALTER TABLE [FAC_RECC] ADD  CONSTRAINT [DF_FAC_RECC_REC_ATCU]  DEFAULT ((0)) FOR [REC_ATCU]
ALTER TABLE [FAC_RECC] ADD  CONSTRAINT [DF_FAC_RECC_DVE_SERI]  DEFAULT ((1)) FOR [REC_SERI]
ALTER TABLE [FAC_RECD] ADD  CONSTRAINT [DF_FAC_RECD_REC_PGTD]  DEFAULT (0) FOR [REC_PGTD]
ALTER TABLE [FAC_RECD] ADD  CONSTRAINT [DF_FAC_RECD_REC_VRTF]  DEFAULT ((0)) FOR [REC_VRTF]
ALTER TABLE [HST_SDSI] ADD  CONSTRAINT [DF_HST_SDSI_DSI_STAT]  DEFAULT ((0)) FOR [DSI_STAT]
ALTER TABLE [HST_SDSI] ADD  CONSTRAINT [DF_HST_SDSI_DSI_RDES]  DEFAULT ((1)) FOR [DSI_RDES]
ALTER TABLE [IMP_DUI2] ADD  CONSTRAINT [DF_IMP_DUI2_DU2_DTIN]  DEFAULT (getdate()) FOR [DU2_DTIN]
ALTER TABLE [IMP_DUI2] ADD  CONSTRAINT [DF_IMP_DUI2_DU2_CT19]  DEFAULT ((0)) FOR [DU2_CT19]
ALTER TABLE [IMP_DUI2] ADD  CONSTRAINT [DF_IMP_DUI2_DU2_MT22]  DEFAULT ((0)) FOR [DU2_MT22]
ALTER TABLE [IMP_DUI2] ADD  CONSTRAINT [DF_IMP_DUI2_DU2_MBRT]  DEFAULT ((0)) FOR [DU2_MBRT]
ALTER TABLE [IMP_DUI2] ADD  CONSTRAINT [DF_IMP_DUI2_DU2_MLQT]  DEFAULT ((0)) FOR [DU2_MLQT]
ALTER TABLE [IMP_DUI2] ADD  CONSTRAINT [DF_IMP_DUI2_DU2_US41]  DEFAULT ((0)) FOR [DU2_US41]
ALTER TABLE [IMP_DUI2] ADD  CONSTRAINT [DF_IMP_DUI2_DU2_SINT]  DEFAULT ((0)) FOR [DU2_SINT]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_STAT]  DEFAULT ((0)) FOR [LNC_STAT]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_TFAC]  DEFAULT ((0)) FOR [LNC_TFAC]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_CAMB]  DEFAULT ((1)) FOR [LNC_CAMB]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_TFRE]  DEFAULT ((0)) FOR [LNC_TFRE]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_CMBF]  DEFAULT ((1)) FOR [LNC_CMBF]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_TDES]  DEFAULT ((0)) FOR [LNC_TDES]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_TMLQ]  DEFAULT ((0)) FOR [LNC_TMLQ]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_TAPE]  DEFAULT ((0)) FOR [LNC_TUNS]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_VEST]  DEFAULT ((0)) FOR [LNC_VEST]
ALTER TABLE [INT_LNCC] ADD  CONSTRAINT [DF_INT_LNCC_LNC_IVCB]  DEFAULT ((1)) FOR [LNC_IVCB]
ALTER TABLE [INT_LNCD] ADD  CONSTRAINT [DF_INT_LNCD_LND_TIVA]  DEFAULT ((0)) FOR [LND_TIVA]
ALTER TABLE [INT_LNCD] ADD  CONSTRAINT [DF_INT_LNCD_LND_VALO]  DEFAULT ((0)) FOR [LND_VALO]
ALTER TABLE [INT_LNCD] ADD  CONSTRAINT [DF_INT_LNCD_LND_MLIQ]  DEFAULT ((0)) FOR [LND_MLIQ]
ALTER TABLE [INT_LNCD] ADD  CONSTRAINT [DF_INT_LNCD_LND_QUNS]  DEFAULT ((0)) FOR [LND_QUNS]
ALTER TABLE [INT_LNCD] ADD  CONSTRAINT [DF_INT_LNCD_LND_VEST]  DEFAULT ((0)) FOR [LND_VEST]
ALTER TABLE [INT_LNCD] ADD  CONSTRAINT [DF_INT_LNCD_LND_ORIG]  DEFAULT ((0)) FOR [LND_ORIG]
ALTER TABLE [PRO_AEUR] ADD  CONSTRAINT [DF_PRO_AEUR_DEC_CODI]  DEFAULT (0) FOR [DEC_CODI]
ALTER TABLE [PRO_CCCA] ADD  CONSTRAINT [DF_PRO_CCCA_CCC_PROV]  DEFAULT ((0)) FOR [CCC_PROV]
ALTER TABLE [PRO_CCCA] ADD  CONSTRAINT [DF_PRO_CCCA_CCC_LIQD]  DEFAULT ((0)) FOR [CCC_LIQD]
ALTER TABLE [PRO_DAVE] ADD  CONSTRAINT [DF_PRO_DAVE_DAV_EMPC]  DEFAULT ((0)) FOR [DAV_EMPC]
ALTER TABLE [PRO_DAVE] ADD  CONSTRAINT [DF_PRO_DAVE_DAV_PVPR]  DEFAULT ((0)) FOR [DAV_PVPR]
ALTER TABLE [PRO_DAVE] ADD  CONSTRAINT [DF_PRO_DAVE_DAV_ISVR]  DEFAULT ((0)) FOR [DAV_ISVR]
ALTER TABLE [PRO_DAVE] ADD  CONSTRAINT [DF_PRO_DAVE_DAV_VAVL]  DEFAULT ((0)) FOR [DAV_VAVL]
ALTER TABLE [PRO_DAVE] ADD  CONSTRAINT [DF_PRO_DAVE_DAV_EXCL]  DEFAULT ((0)) FOR [DAV_EXCL]
ALTER TABLE [PRO_DCON] ADD  CONSTRAINT [DF_PRO_DCON_DCO_PMRP]  DEFAULT ((1)) FOR [DCO_PMRP]
ALTER TABLE [PRO_DDOC] ADD  CONSTRAINT [DF_PRO_DDOC_DDO_AUTO]  DEFAULT ((0)) FOR [DDO_AUTO]
ALTER TABLE [PRO_DDOC] ADD  CONSTRAINT [DF_PRO_DDOC_DDO_TIPO]  DEFAULT ((0)) FOR [DDO_TIPO]
ALTER TABLE [PRO_DDOC] ADD  CONSTRAINT [DF_PRO_DDOC_DDO_QTDE]  DEFAULT ((0)) FOR [DDO_QTDE]
ALTER TABLE [PRO_DDOC] ADD  CONSTRAINT [DF_PRO_DDOC_DDO_DEST]  DEFAULT ((0)) FOR [DDO_DEST]
ALTER TABLE [PRO_DESS] ADD  CONSTRAINT [DF_PRO_DESS_DSS_STAT]  DEFAULT ((0)) FOR [DSS_STAT]
ALTER TABLE [PRO_DESS] ADD  CONSTRAINT [DF_PRO_DESS_DSS_VERS]  DEFAULT ((1)) FOR [DSS_VERS]
ALTER TABLE [PRO_DESS] ADD  CONSTRAINT [DF_PRO_DESS_DSS_NADI]  DEFAULT ((0)) FOR [DSS_NADI]
ALTER TABLE [PRO_DESS] ADD  CONSTRAINT [DF_PRO_DESS_DSS_TVOL]  DEFAULT ((0)) FOR [DSS_TVOL]
ALTER TABLE [PRO_DESS] ADD  CONSTRAINT [DF_PRO_DESS_DSS_MBRT]  DEFAULT ((0)) FOR [DSS_MBRT]
ALTER TABLE [PRO_DESS] ADD  CONSTRAINT [DF_PRO_DESS_DSS_MCNT]  DEFAULT ((0)) FOR [DSS_MCNT]
ALTER TABLE [PRO_DSAD] ADD  CONSTRAINT [DF_PRO_DSAD_DAD_AUTO]  DEFAULT ((0)) FOR [DAD_AUTO]
ALTER TABLE [PRO_DSAM] ADD  CONSTRAINT [DF_PRO_DSAM_DAM_NVOL]  DEFAULT ((0)) FOR [DAM_NVOL]
ALTER TABLE [PRO_DSAM] ADD  CONSTRAINT [DF_PRO_DSAM_DAM_NPCS]  DEFAULT ((0)) FOR [DAM_NPCS]
ALTER TABLE [PRO_DSAM] ADD  CONSTRAINT [DF_PRO_DSAM_DAM_PART]  DEFAULT ((0)) FOR [DAM_PART]
ALTER TABLE [PRO_DSAM] ADD  CONSTRAINT [DF_PRO_DSAM_DAM_AUTO]  DEFAULT ((0)) FOR [DAM_AUTO]
ALTER TABLE [PRO_DSAM] ADD  CONSTRAINT [DF_PRO_DSAM_DAM_TIPO]  DEFAULT ((0)) FOR [DAM_TIPO]
ALTER TABLE [PRO_DSAS] ADD  CONSTRAINT [DF_PRO_DSAS_DAS_AUTO]  DEFAULT ((0)) FOR [DAS_AUTO]
ALTER TABLE [PRO_DSIM] ADD  CONSTRAINT [DF_PRO_DSIM_DSI_STAT]  DEFAULT (0) FOR [DSI_STAT]
ALTER TABLE [PRO_DSSA] ADD  CONSTRAINT [DF_PRO_DSSA_DSA_MBRT]  DEFAULT ((0)) FOR [DSA_MBRT]
ALTER TABLE [PRO_DU31] ADD  CONSTRAINT [DF_PRO_DA31_D31_CASP]  DEFAULT ((0)) FOR [D31_CASP]
ALTER TABLE [PRO_DU31] ADD  CONSTRAINT [DF_PRO_DA31_D31_CASR]  DEFAULT ((0)) FOR [D31_CASR]
ALTER TABLE [PRO_DU31] ADD  CONSTRAINT [DF_PRO_DA31_D31_CASC]  DEFAULT ((0)) FOR [D31_CASC]
ALTER TABLE [PRO_DU31] ADD  CONSTRAINT [DF_PRO_DU31_D31_TTVL]  DEFAULT ((0)) FOR [D31_TTVL]
ALTER TABLE [PRO_DU31] ADD  CONSTRAINT [DF_PRO_DU31_D31_AUTO]  DEFAULT ((0)) FOR [D31_AUTO]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_TAB_DUAD_DUA_CLQC]  DEFAULT ((0)) FOR [DUA_LCMB]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_TXCO]  DEFAULT ((0)) FOR [DUA_TXCO]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_CS50]  DEFAULT ((0)) FOR [DUA_CS50]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_BMAN]  DEFAULT ((0)) FOR [DUA_BMAN]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VIRT]  DEFAULT ((0)) FOR [DUA_VIRT]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VTXC]  DEFAULT ((0)) FOR [DUA_VTXC]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VVTV]  DEFAULT ((0)) FOR [DUA_VVTV]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VMTD]  DEFAULT ((0)) FOR [DUA_VMTD]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VMGD]  DEFAULT ((0)) FOR [DUA_VMGD]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VBTR]  DEFAULT ((0)) FOR [DUA_VBTR]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VTIV]  DEFAULT ((0)) FOR [DUA_VTIV]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VVIV]  DEFAULT ((0)) FOR [DUA_VVIV]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VMGI]  DEFAULT ((0)) FOR [DUA_VMGI]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_ABTI]  DEFAULT ((0)) FOR [DUA_ABTI]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_VQTD]  DEFAULT ((0)) FOR [DUA_VQTD]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_TIVO]  DEFAULT ((0)) FOR [DUA_TIVO]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_ACRE]  DEFAULT ((0)) FOR [DUA_ACRE]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_DEDU]  DEFAULT ((0)) FOR [DUA_DEDU]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_MIVI]  DEFAULT ((0)) FOR [DUA_MIVI]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_QTDD]  DEFAULT ((0)) FOR [DUA_QTDD]
ALTER TABLE [PRO_DUAD] ADD  CONSTRAINT [DF_PRO_DUAD_DUA_PMRP]  DEFAULT ((1)) FOR [DUA_PMRP]
ALTER TABLE [PRO_DUBT] ADD  CONSTRAINT [DF_PRO_DUBT_DBT_QTDE]  DEFAULT ((0)) FOR [DBT_QTDE]
ALTER TABLE [PRO_DUBT] ADD  CONSTRAINT [DF_PRO_DUBT_DBT_AUTO]  DEFAULT ((0)) FOR [DBT_AUTO]
ALTER TABLE [PRO_DUBT] ADD  CONSTRAINT [DF_PRO_DUBT_DBT_VLIA]  DEFAULT ((0)) FOR [DBT_VLIA]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_STAT]  DEFAULT ((0)) FOR [DUC_STAT]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_UFOB]  DEFAULT ((0)) FOR [DUC_UFOB]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VFIS]  DEFAULT ((0)) FOR [DUC_VFIS]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PART]  DEFAULT ((0)) FOR [DUC_PART]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_STBY]  DEFAULT ((0)) FOR [DUC_STBY]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PRIO]  DEFAULT ((0)) FOR [DUC_PRIO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_EPRE]  DEFAULT ((0)) FOR [DUC_EPRE]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_CPRO]  DEFAULT ((0)) FOR [DUC_CPRO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_BUPS]  DEFAULT ((0)) FOR [DUC_BUPS]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_BFFC_1]  DEFAULT ((0)) FOR [DUC_BFFC]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_RIUP]  DEFAULT ((0)) FOR [DUC_RIUP]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VLRP]  DEFAULT ((0)) FOR [DUC_VLRP]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VLIL]  DEFAULT ((0)) FOR [DUC_VLIL]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_ASAI]  DEFAULT ((0)) FOR [DUC_ASAI]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PREC]  DEFAULT ((0)) FOR [DUC_PREC]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_NRVW]  DEFAULT ((0)) FOR [DUC_NRVW]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PRVW]  DEFAULT ((0)) FOR [DUC_PRVW]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PALT]  DEFAULT ((0)) FOR [DUC_PALT]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_RTFW]  DEFAULT ((0)) FOR [DUC_RTFW]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_FCHW]  DEFAULT ((0)) FOR [DUC_FCHW]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PRFW]  DEFAULT ((0)) FOR [DUC_PRFW]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_NRFW]  DEFAULT ((1)) FOR [DUC_NRFW]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TMSF]  DEFAULT ((0)) FOR [DUC_TMSF]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PDVU]  DEFAULT ((0)) FOR [DUC_PDVU]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VERS]  DEFAULT ((0)) FOR [DUC_VERS]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_REVI]  DEFAULT ((0)) FOR [DUC_REVI]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_CGLB]  DEFAULT ((1)) FOR [DUC_CGLB]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_DUNO]  DEFAULT ((0)) FOR [DUC_DUNO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VBAT]  DEFAULT ((1)) FOR [DUC_VBAT]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VSCA]  DEFAULT ((0)) FOR [DUC_VSCA]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_CRTD]  DEFAULT ((0)) FOR [DUC_CRTD]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_CRTF]  DEFAULT ((0)) FOR [DUC_CRTF]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_CRTA]  DEFAULT ((0)) FOR [DUC_CRTA]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VMUL]  DEFAULT ((0)) FOR [DUC_VMUL]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VFRC]  DEFAULT ((0)) FOR [DUC_VFRC]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_IMSR]  DEFAULT ((0)) FOR [DUC_IMSR]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_EMSR]  DEFAULT ((0)) FOR [DUC_EMSR]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_RTDT]  DEFAULT ((0)) FOR [DUC_RTDT]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_COBR]  DEFAULT ((0)) FOR [DUC_COBR]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_BLOQ]  DEFAULT ((0)) FOR [DUC_BLOQ]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_BIVA]  DEFAULT ((0)) FOR [DUC_BIVA]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VDES]  DEFAULT ((0)) FOR [DUC_VDES]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_EXPO]  DEFAULT ((0)) FOR [DUC_EXPO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_LADT]  DEFAULT ((0)) FOR [DUC_LADT]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_DDSC]  DEFAULT ((0)) FOR [DUC_DDSC]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TSHI]  DEFAULT ((0)) FOR [DUC_TSHI]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_VPRS]  DEFAULT ((0)) FOR [DUC_VPRS]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TMOO]  DEFAULT ((0)) FOR [DUC_TMOO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TFRO]  DEFAULT ((0)) FOR [DUC_TFRO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TSEO]  DEFAULT ((0)) FOR [DUC_TSEO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TMLO]  DEFAULT ((0)) FOR [DUC_TMLO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TMBO]  DEFAULT ((0)) FOR [DUC_TMBO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TVEO]  DEFAULT ((0)) FOR [DUC_TVEO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TVAO]  DEFAULT ((0)) FOR [DUC_TVAO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TOPO]  DEFAULT ((0)) FOR [DUC_TOPO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_TLRO]  DEFAULT ((0)) FOR [DUC_TLRO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_ACAO]  DEFAULT ((0)) FOR [DUC_ACAO]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_DCEN]  DEFAULT ((0)) FOR [DUC_DCEN]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_ANXB]  DEFAULT ('H1') FOR [DUC_ANXB]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_SERV]  DEFAULT ((0)) FOR [DUC_SERV]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_PMRP]  DEFAULT ((1)) FOR [DUC_PMRP]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_APPR]  DEFAULT ((0)) FOR [DUC_APPR]
ALTER TABLE [PRO_DUCG] ADD  CONSTRAINT [DF_PRO_DUCG_DUC_ACMD]  DEFAULT ((0)) FOR [DUC_ACMD]
ALTER TABLE [PRO_DUDD] ADD  CONSTRAINT [DF_PRO_DUDD_DDD_VALO]  DEFAULT ((0)) FOR [DDD_VALO]
ALTER TABLE [PRO_DUET] ADD  CONSTRAINT [DF_PRO_DUET_DET_TIPO]  DEFAULT ((1)) FOR [DET_TIPO]
ALTER TABLE [PRO_DUET] ADD  CONSTRAINT [DF_PRO_DUET_DET_QTDE]  DEFAULT ((0)) FOR [DET_QTDE]
ALTER TABLE [PRO_DUET] ADD  CONSTRAINT [DF_PRO_DUET_DET_AUTO]  DEFAULT ((0)) FOR [DET_AUTO]
ALTER TABLE [PRO_DUET] ADD  CONSTRAINT [DF_PRO_DUET_DET_TAXA]  DEFAULT ((0)) FOR [DET_TAXA]
ALTER TABLE [PRO_DUET] ADD  CONSTRAINT [DF_PRO_DUET_DET_TXVL]  DEFAULT ((0)) FOR [DET_TXVL]
ALTER TABLE [PRO_DUFI] ADD  CONSTRAINT [DF_PRO_DUFI_DUF_ENVI]  DEFAULT (0) FOR [DUF_ENVI]
ALTER TABLE [PRO_DUFI] ADD  CONSTRAINT [DF_PRO_DUFI_DUF_ISER]  DEFAULT ((0)) FOR [DUF_ISER]
ALTER TABLE [PRO_DUFI] ADD  CONSTRAINT [DF_PRO_DUFI_DUF_ORIG]  DEFAULT ((0)) FOR [DUF_ORIG]
ALTER TABLE [PRO_DUFI] ADD  CONSTRAINT [DF_PRO_DUFI_DUF_PMRP]  DEFAULT ((1)) FOR [DUF_PMRP]
ALTER TABLE [PRO_DUIT] ADD  CONSTRAINT [DF_PRO_DUIT_DIT_QTDE]  DEFAULT ((0)) FOR [DIT_QTDE]
ALTER TABLE [PRO_DUIT] ADD  CONSTRAINT [DF_PRO_DUIT_DIT_TAXA]  DEFAULT ((0)) FOR [DIT_TAXA]
ALTER TABLE [PRO_DUIT] ADD  CONSTRAINT [DF_PRO_DUIT_DIT_TXVL]  DEFAULT ((0)) FOR [DIT_TXVL]
ALTER TABLE [PRO_DULO] ADD  CONSTRAINT [DF_PRO_DULO_DUL_MONT]  DEFAULT ((0)) FOR [DUL_MONT]
ALTER TABLE [PRO_DULO] ADD  CONSTRAINT [DF_PRO_DULO_DUL_RPRO]  DEFAULT ((0)) FOR [DUL_RPRO]
ALTER TABLE [PRO_DULO] ADD  CONSTRAINT [DF_PRO_DULO_DUL_MTAG]  DEFAULT ((0)) FOR [DUL_MTAG]
ALTER TABLE [PRO_DULR] ADD  CONSTRAINT [DF_PRO_DULR_DUL_MTAG]  DEFAULT ((0)) FOR [DUL_MTAG]
ALTER TABLE [PRO_DUMI] ADD  CONSTRAINT [DF_PRO_DUMI_DMI_CAPA]  DEFAULT ((0)) FOR [DMI_CAPA]
ALTER TABLE [PRO_DUMI] ADD  CONSTRAINT [DF_PRO_DUMI_DMI_NEMB]  DEFAULT ((0)) FOR [DMI_NEMB]
ALTER TABLE [PRO_DUMI] ADD  CONSTRAINT [DF_PRO_DUMI_DMI_TEOR]  DEFAULT ((0)) FOR [DMI_TEOR]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_DUO_TIPO]  DEFAULT ((0)) FOR [DUO_TIPO]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_RRE_AGRO]  DEFAULT ((0)) FOR [RRE_AGRO]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_RRE_LIVA]  DEFAULT ((0)) FOR [RRE_LIVA]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_DUO_AUTO]  DEFAULT ((0)) FOR [DUO_AUTO]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_DUO_BMAN]  DEFAULT ((0)) FOR [DUO_BMAN]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_DUO_DEST]  DEFAULT ((0)) FOR [DUO_DEST]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_DUO_MTAG]  DEFAULT ((0)) FOR [DUO_MTAG]
ALTER TABLE [PRO_DUOI] ADD  CONSTRAINT [DF_PRO_DUOI_DUO_QTDE]  DEFAULT ((0)) FOR [DUO_QTDE]
ALTER TABLE [PRO_DUPD] ADD  CONSTRAINT [DF_PRO_DUPD_DPD_ORIG]  DEFAULT ((0)) FOR [DPD_ORIG]
ALTER TABLE [PRO_DURA] ADD  CONSTRAINT [DF_PRO_DURA_DRA_AUTO]  DEFAULT ((0)) FOR [DRA_AUTO]
ALTER TABLE [PRO_DURP] ADD  CONSTRAINT [DF_PRO_DURP_DRP_EXPO]  DEFAULT ((0)) FOR [DRP_EXPO]
ALTER TABLE [PRO_DURP] ADD  CONSTRAINT [DF_PRO_DURP_DRP_SUCE]  DEFAULT ((0)) FOR [DRP_SUCE]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_CS7A]  DEFAULT ((0)) FOR [DV1_C7AS]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7AS1]  DEFAULT ((0)) FOR [DV1_C7AN]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7AS2]  DEFAULT ((0)) FOR [DV1_C7BS]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7AS3]  DEFAULT ((0)) FOR [DV1_C7BN]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7AS4]  DEFAULT ((0)) FOR [DV1_C7CS]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7AS5]  DEFAULT ((0)) FOR [DV1_C7CN]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7AS1_1]  DEFAULT ((0)) FOR [DV1_C8AS]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7AN1]  DEFAULT ((0)) FOR [DV1_C8AN]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7BS1]  DEFAULT ((0)) FOR [DV1_C8BS]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DVI_C7BN1]  DEFAULT ((0)) FOR [DV1_C8BN]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DV1_C8AS1]  DEFAULT ((0)) FOR [DV1_C9AS]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DV1_C8AN1]  DEFAULT ((0)) FOR [DV1_C9AN]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DV1_C8BS1]  DEFAULT ((0)) FOR [DV1_C9BS]
ALTER TABLE [PRO_DV1C] ADD  CONSTRAINT [DF_PRO_DV1C_DV1_C8BN1]  DEFAULT ((0)) FOR [DV1_C9BN]
ALTER TABLE [PRO_DVER] ADD  CONSTRAINT [DF_PRO_DVER_DVE_C2IP]  DEFAULT (0) FOR [DVE_C2IP]
ALTER TABLE [PRO_DVER] ADD  CONSTRAINT [DF_PRO_DVER_DVE_C2IT]  DEFAULT (0) FOR [DVE_C2IT]
ALTER TABLE [PRO_DVER] ADD  CONSTRAINT [DF_PRO_DVER_DVE_C2EX]  DEFAULT (0) FOR [DVE_C2EX]
ALTER TABLE [PRO_EUR1] ADD  CONSTRAINT [DF_PRO_EUR1_DEC_CODI]  DEFAULT ((0)) FOR [DEC_CODI]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_ANXC]  DEFAULT ((0)) FOR [EXA_ANXC]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_ANXC1]  DEFAULT ((0)) FOR [EXA_ANXD]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_CPMV]  DEFAULT ((0)) FOR [EXA_CPMV]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_ORIG]  DEFAULT ((0)) FOR [EXA_ORIG]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_NUNI]  DEFAULT ((0)) FOR [EXA_NUNI]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_NVOL]  DEFAULT ((0)) FOR [EXA_NVOL]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_VEOR]  DEFAULT ((0)) FOR [EXA_VEOR]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_PMRP]  DEFAULT ((1)) FOR [EXA_PMRP]
ALTER TABLE [PRO_EXAD] ADD  CONSTRAINT [DF_PRO_EXAD_EXA_AJUS]  DEFAULT ((0)) FOR [EXA_AJUS]
ALTER TABLE [PRO_EXCD] ADD  CONSTRAINT [DF_PRO_EXCD_EXD_QTDE]  DEFAULT ((0)) FOR [EXD_QTDE]
ALTER TABLE [PRO_EXCD] ADD  CONSTRAINT [DF_PRO_EXCD_EXD_PART]  DEFAULT ((0)) FOR [EXD_PART]
ALTER TABLE [PRO_EXCD] ADD  CONSTRAINT [DF_PRO_EXCD_EXD_REST]  DEFAULT ((0)) FOR [EXD_REST]
ALTER TABLE [PRO_EXCR] ADD  CONSTRAINT [DF_PRO_EXCR_EXC_NADI]  DEFAULT ((1)) FOR [EXC_NADI]
ALTER TABLE [PRO_EXCT] ADD  CONSTRAINT [DF_PRO_EXCT_EXC_PMRP]  DEFAULT ((1)) FOR [EXC_PMRP]
ALTER TABLE [PRO_EXDA] ADD  CONSTRAINT [DF_PRO_EXDA_EXD_AUTO]  DEFAULT ((0)) FOR [EXD_AUTO]
ALTER TABLE [PRO_EXDM] ADD  CONSTRAINT [DF_PRO_EXDM_EXM_VALO]  DEFAULT (0) FOR [EXM_VALO]
ALTER TABLE [PRO_EXDM] ADD  CONSTRAINT [DF_PRO_EXDM_EXM_PESO]  DEFAULT (0) FOR [EXM_PESO]
ALTER TABLE [PRO_EXDS] ADD  CONSTRAINT [DF_PRO_EXDS_EXD_NUME]  DEFAULT ((0)) FOR [EXD_NUME]
ALTER TABLE [PRO_EXFI] ADD  CONSTRAINT [DF_PRO_EXFI_EXF_ENVI]  DEFAULT (0) FOR [EXF_ENVI]
ALTER TABLE [PRO_EXFI] ADD  CONSTRAINT [DF_PRO_EXFI_EXF_ISER]  DEFAULT ((0)) FOR [EXF_ISER]
ALTER TABLE [PRO_EXFI] ADD  CONSTRAINT [DF_PRO_EXFI_EXF_ODDM]  DEFAULT ((0)) FOR [EXF_ODDM]
ALTER TABLE [PRO_EXFI] ADD  CONSTRAINT [DF_PRO_EXFI_EXF_ORIG]  DEFAULT ((0)) FOR [EXF_ORIG]
ALTER TABLE [PRO_EXFI] ADD  CONSTRAINT [DF_PRO_EXFI_EXF_PMRP]  DEFAULT ((1)) FOR [EXF_PMRP]
ALTER TABLE [PRO_EXIC] ADD  CONSTRAINT [DF_PRO_EXIC_EXC_AUTO]  DEFAULT ((0)) FOR [EXC_AUTO]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_TPRO]  DEFAULT ('A') FOR [EXM_TPRO]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_IROR]  DEFAULT ((0)) FOR [EXM_IROR]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_UFOB]  DEFAULT ((0)) FOR [EXM_UFOB]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_CA54]  DEFAULT ('C') FOR [EXM_CA54]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_NRII]  DEFAULT ((0)) FOR [EXM_NRII]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_2M22]  DEFAULT ((0)) FOR [EXM_2M22]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_2MLQ]  DEFAULT ((0)) FOR [EXM_2MLQ]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_2MBR]  DEFAULT ((0)) FOR [EXM_2MBR]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_BLOQ]  DEFAULT ((0)) FOR [EXM_BLOQ]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_TMSF]  DEFAULT ((0)) FOR [EXM_TMSF]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_IMSR]  DEFAULT ((0)) FOR [EXM_IMSR]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_EMSR]  DEFAULT ((0)) FOR [EXM_EMSR]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_CRTD]  DEFAULT ((0)) FOR [EXM_CRTD]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_CRTF]  DEFAULT ((0)) FOR [EXM_CRTF]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_CRTA]  DEFAULT ((0)) FOR [EXM_CRTA]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_ASAI]  DEFAULT ((0)) FOR [EXM_ASAI]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_PIUP]  DEFAULT ((0)) FOR [EXM_PIUP]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_ARGW]  DEFAULT ((0)) FOR [EXM_ARGW]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_ENPC]  DEFAULT ((0)) FOR [EXM_ENPC]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_DDDM]  DEFAULT ((0)) FOR [EXM_DDDM]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_EMMA]  DEFAULT ((0)) FOR [EXM_EMMA]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_PLET]  DEFAULT ((0)) FOR [EXM_PLET]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_EXPE]  DEFAULT ('000') FOR [EXM_EXPE]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_EXPK]  DEFAULT ((0)) FOR [EXM_EXPK]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_EXPO]  DEFAULT ((0)) FOR [EXM_EXPO]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_CNTX]  DEFAULT ((0)) FOR [EXM_CNTX]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_SEGU]  DEFAULT ((0)) FOR [EXM_SEGU]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_CFRE]  DEFAULT ((0)) FOR [EXM_CFRE]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_CSEG]  DEFAULT ((0)) FOR [EXM_CSEG]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_VRBA]  DEFAULT ((1)) FOR [EXM_VRBA]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_TLOC]  DEFAULT ('B') FOR [EXM_TLOC]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_QUAL]  DEFAULT ('Y') FOR [EXM_QUAL]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_PART]  DEFAULT ((0)) FOR [EXM_PART]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_VMUL]  DEFAULT ((0)) FOR [EXM_VMUL]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_VSCA]  DEFAULT ((0)) FOR [EXM_VSCA]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_ANXB]  DEFAULT ('B1') FOR [EXM_ANXB]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_PMRP]  DEFAULT ((1)) FOR [EXM_PMRP]
ALTER TABLE [PRO_EXML] ADD  CONSTRAINT [DF_PRO_EXML_EXM_DCEN]  DEFAULT ((0)) FOR [EXM_DCEN]
ALTER TABLE [PRO_EXMV] ADD  CONSTRAINT [DF_PRO_EXMV_EXM_PART]  DEFAULT ((0)) FOR [EXM_PART]
ALTER TABLE [PRO_EXMV] ADD  CONSTRAINT [DF_PRO_EXMV_EXM_PART1]  DEFAULT ((0)) FOR [EXM_REST]
ALTER TABLE [PRO_EXMV] ADD  CONSTRAINT [DF_PRO_EXMV_EXM_TVOL]  DEFAULT ((0)) FOR [EXM_TVOL]
ALTER TABLE [PRO_EXMV] ADD  CONSTRAINT [DF_PRO_EXMV_EXM_AUTO]  DEFAULT ((0)) FOR [EXM_AUTO]
ALTER TABLE [PRO_EXPA] ADD  CONSTRAINT [DF_PRO_EXPA_EXP_ORIG]  DEFAULT ((0)) FOR [EXP_ORIG]
ALTER TABLE [PRO_EXPI] ADD  CONSTRAINT [DF_PRO_EXPI_EXP_ORIG]  DEFAULT ((0)) FOR [EXP_ORIG]
ALTER TABLE [PRO_EXPS] ADD  CONSTRAINT [DF_PRO_EXPS_MIA_OBRI]  DEFAULT (0) FOR [MIA_OBRI]
ALTER TABLE [PRO_EXRP] ADD  CONSTRAINT [DF_PRO_EXRP_EXR_TEOR]  DEFAULT (0) FOR [EXR_TEOR]
ALTER TABLE [PRO_EXRP] ADD  CONSTRAINT [DF_PRO_EXRP_EXR_PESO]  DEFAULT (0) FOR [EXR_PESO]
ALTER TABLE [PRO_G156] ADD  CONSTRAINT [DF_PRO_G156_G15_TIPO]  DEFAULT (1) FOR [G15_TIPO]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_R561]  DEFAULT (0) FOR [GEM_R561]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_R721]  DEFAULT (0) FOR [GEM_R721]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_R722]  DEFAULT (0) FOR [GEM_R722]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_R726]  DEFAULT (0) FOR [GEM_R726]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_REST]  DEFAULT (0) FOR [GEM_REST]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_R371]  DEFAULT (0) FOR [GEM_R371]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_R372]  DEFAULT (0) FOR [GEM_R372]
ALTER TABLE [PRO_GEMO] ADD  CONSTRAINT [DF_PRO_GEMO_GEM_999T]  DEFAULT (0) FOR [GEM_999T]
ALTER TABLE [PRO_GREX] ADD  CONSTRAINT [DF_PRO_GREX_GRE_STAT]  DEFAULT (0) FOR [GRE_STAT]
ALTER TABLE [PRO_GREX] ADD  CONSTRAINT [DF_PRO_GREX_GRE_MTGA]  DEFAULT (0) FOR [GRE_MTGA]
ALTER TABLE [PRO_GREX] ADD  CONSTRAINT [DF_PRO_GREX_GRE_QUAN]  DEFAULT (0) FOR [GRE_QUAN]
ALTER TABLE [PRO_GREX] ADD  CONSTRAINT [DF_PRO_GREX_GRE_TOLE]  DEFAULT (0) FOR [GRE_TOLE]
ALTER TABLE [PRO_GRIM] ADD  CONSTRAINT [DF_PRO_GRIM_GRI_STAT]  DEFAULT ((0)) FOR [GRI_STAT]
ALTER TABLE [PRO_GRIM] ADD  CONSTRAINT [DF_PRO_GRIM_GRI_MTGA]  DEFAULT ((0)) FOR [GRI_MTGA]
ALTER TABLE [PRO_GRIM] ADD  CONSTRAINT [DF_PRO_GRIM_GRI_QUAN]  DEFAULT ((0)) FOR [GRI_QUAN]
ALTER TABLE [PRO_GRIM] ADD  CONSTRAINT [DF_PRO_GRIM_GRI_TOLE]  DEFAULT ((0)) FOR [GRI_TOLE]
ALTER TABLE [PRO_GSSL] ADD  CONSTRAINT [DF_PRO_GSSL_SSL_STAT]  DEFAULT ((0)) FOR [SSL_STAT]
ALTER TABLE [PRO_IL9A] ADD  CONSTRAINT [DF_PRO_IL9A_IL9_TXVL]  DEFAULT (0) FOR [IL9_TXVL]
ALTER TABLE [PRO_ILAD] ADD  CONSTRAINT [DF_PRO_ILAD_ILG_TXVL]  DEFAULT (0) FOR [ILG_TXVL]
ALTER TABLE [PRO_LIMP] ADD  CONSTRAINT [DF_PRO_LIMP_LIM_QUAN]  DEFAULT (0) FOR [LIM_QUAN]
ALTER TABLE [PRO_LIMP] ADD  CONSTRAINT [DF_PRO_LIMP_LIM_CAUC]  DEFAULT (0) FOR [LIM_CAUC]
ALTER TABLE [PRO_MCAU] ADD  CONSTRAINT [DF_PRO_DCAU_DCA_PROV]  DEFAULT ((0)) FOR [MCA_PROV]
ALTER TABLE [PRO_MCAU] ADD  CONSTRAINT [DF_PRO_DCAU_DCA_LIQD]  DEFAULT ((0)) FOR [MCA_LIQD]
ALTER TABLE [PRO_MCAU] ADD  CONSTRAINT [DF_PRO_MCAU_MCA_ANUL]  DEFAULT ((0)) FOR [MCA_ANUL]
ALTER TABLE [PRO_MCAU] ADD  CONSTRAINT [DF_PRO_MCAU_MCA_NDIA]  DEFAULT ((0)) FOR [MCA_NDIA]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_MBRT]  DEFAULT ((0)) FOR [NAD_MBRT]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_MLIQ]  DEFAULT ((0)) FOR [NAD_MLIQ]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_TPSP]  DEFAULT ((1)) FOR [NAD_TPSP]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_VMER]  DEFAULT ((0)) FOR [NAD_VMER]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_VALO]  DEFAULT ((1)) FOR [NAD_VALO]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_TAXA]  DEFAULT ((0)) FOR [NAD_TAXA]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_MONT]  DEFAULT ((0)) FOR [NAD_MONT]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_OIMP]  DEFAULT ((1)) FOR [NAD_OIMP]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_TAX1]  DEFAULT ((0)) FOR [NAD_TAX1]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_MTT1]  DEFAULT ((0)) FOR [NAD_MTT1]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_IVA]  DEFAULT ((0)) FOR [NAD_IVA]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_AGAR]  DEFAULT ((0)) FOR [NAD_AGAR]
ALTER TABLE [PRO_NADI] ADD  CONSTRAINT [DF_PRO_NADI_NAD_AJUS]  DEFAULT ((0)) FOR [NAD_AJUS]
ALTER TABLE [PRO_NAMA] ADD  CONSTRAINT [DF_PRO_NAMA_NMA_NVOL]  DEFAULT (0) FOR [NMA_NVOL]
ALTER TABLE [PRO_NAMA] ADD  CONSTRAINT [DF_PRO_NAMA_NMA_NUNI]  DEFAULT (0) FOR [NMA_NUNI]
ALTER TABLE [PRO_NAMS] ADD  CONSTRAINT [DF_PRO_NAMS_NAM_QUAN]  DEFAULT (0) FOR [NAM_QUAN]
ALTER TABLE [PRO_NOAD] ADD  CONSTRAINT [DF_PRO_NOAD_NOA_MBRT]  DEFAULT (0) FOR [NOA_MBRT]
ALTER TABLE [PRO_NOAD] ADD  CONSTRAINT [DF_PRO_NOAD_NOA_VADI]  DEFAULT (0) FOR [NOA_VADI]
ALTER TABLE [PRO_NOTI] ADD  CONSTRAINT [DF_PRO_NOTI_NOT_STAT]  DEFAULT (0) FOR [NOT_STAT]
ALTER TABLE [PRO_NOTI] ADD  CONSTRAINT [DF_PRO_NOTI_NOT_NCON]  DEFAULT (0) FOR [NOT_NCON]
ALTER TABLE [PRO_NOTI] ADD  CONSTRAINT [DF_PRO_NOTI_NOT_DECS]  DEFAULT (0) FOR [NOT_DECS]
ALTER TABLE [PRO_NOTI] ADD  CONSTRAINT [DF_PRO_NOTI_NOT_DOCP]  DEFAULT (0) FOR [NOT_DOCP]
ALTER TABLE [PRO_NOTI] ADD  CONSTRAINT [DF_PRO_NOTI_NOT_REEX]  DEFAULT (0) FOR [NOT_REEX]
ALTER TABLE [PRO_NOTI] ADD  CONSTRAINT [DF_PRO_NOTI_NOT_TINT]  DEFAULT (0) FOR [NOT_TINT]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_STAT]  DEFAULT ((0)) FOR [NST_STAT]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_LCRG]  DEFAULT ((0)) FOR [NST_LCRG]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_MLTO]  DEFAULT ((0)) FOR [NST_MLTO]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_MBTO]  DEFAULT ((0)) FOR [NST_MBTO]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_AUTZ]  DEFAULT ((0)) FOR [NST_AUTZ]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_CONT]  DEFAULT ((0)) FOR [NST_CONT]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_NSEL]  DEFAULT ((0)) FOR [NST_NSEL]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_NCEE]  DEFAULT ((0)) FOR [NST_NCEE]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_CSEG]  DEFAULT ((0)) FOR [NST_CSEG]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_PZAP]  DEFAULT ((0)) FOR [NST_PZAP]
ALTER TABLE [PRO_NSTI] ADD  CONSTRAINT [DF_PRO_NSTI_NST_NRMV]  DEFAULT ((0)) FOR [NST_NRMV]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_TIPO]  DEFAULT ((0)) FOR [DSC_TIPO]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_NREM]  DEFAULT ((0)) FOR [DSC_NREM]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_NRRR]  DEFAULT ((0)) FOR [DSC_NRRR]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_IXML]  DEFAULT ((1)) FOR [DSC_IXML]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_ACTI]  DEFAULT ((1)) FOR [DSC_ACTI]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_STRD]  DEFAULT ((0)) FOR [DSC_STRD]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_NRER]  DEFAULT ((0)) FOR [DSC_NRER]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_NRRD]  DEFAULT ((0)) FOR [DSC_NRRD]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_STMS]  DEFAULT ((0)) FOR [DSC_STMS]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_NRES]  DEFAULT ((0)) FOR [DSC_NRES]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_NRMS]  DEFAULT ((0)) FOR [DSC_NRMS]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_PPRV]  DEFAULT ((0)) FOR [DSC_PPRV]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_VPRV]  DEFAULT ((0)) FOR [DSC_VPRV]
ALTER TABLE [PRO_SDSC] ADD  CONSTRAINT [DF_PRO_SDSC_DSC_STCM]  DEFAULT ((0)) FOR [DSC_STCM]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_TCTU]  DEFAULT ((0)) FOR [DSD_TCTU]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_TMEX]  DEFAULT ((0)) FOR [DSD_TMEX]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_PESO]  DEFAULT ((0)) FOR [DSD_PESO]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_VOLS]  DEFAULT ((0)) FOR [DSD_VOLS]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_CAPO]  DEFAULT ((0)) FOR [DSD_CAPO]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_STAT]  DEFAULT ((0)) FOR [DSD_STAT]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_ANUL]  DEFAULT ((0)) FOR [DSD_ANUL]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_DNOW]  DEFAULT (getdate()) FOR [DSD_DNOW]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_ORIG]  DEFAULT ((0)) FOR [DSD_ORIG]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_VALO]  DEFAULT ((0)) FOR [DSD_VALO]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_ASAI]  DEFAULT ((0)) FOR [DSD_ASAI]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_PDEP]  DEFAULT ((0)) FOR [DSD_PDEP]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_ALTD]  DEFAULT ((0)) FOR [DSD_ALTD]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_PES2]  DEFAULT ((0)) FOR [DSD_PES2]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_VOL2]  DEFAULT ((0)) FOR [DSD_VOL2]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_ENVI]  DEFAULT ((1)) FOR [DSD_ENVI]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_PSIM]  DEFAULT ((0)) FOR [DSD_PSIM]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_CPER]  DEFAULT ((0)) FOR [DSD_CPER]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_STRD]  DEFAULT ((0)) FOR [DSD_STRD]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_STMS]  DEFAULT ((0)) FOR [DSD_STMS]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_EFRQ]  DEFAULT ((0)) FOR [DSD_EFRQ]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_SIRD]  DEFAULT ((0)) FOR [DSD_SIRD]
ALTER TABLE [PRO_SDSD] ADD  CONSTRAINT [DF_PRO_SDSD_DSD_SIMS]  DEFAULT ((0)) FOR [DSD_SIMS]
ALTER TABLE [PRO_SSDD] ADD  CONSTRAINT [DF_PRO_SSDD_SDD_ORIG]  DEFAULT ((0)) FOR [SDD_ORIG]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_MBRT]  DEFAULT (0) FOR [T5A_MBRT]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_MLIQ]  DEFAULT (0) FOR [T5A_MLIQ]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_UNSQ]  DEFAULT (0) FOR [T5A_UNSQ]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_STAD]  DEFAULT (0) FOR [T5A_STAD]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_FORP]  DEFAULT (0) FOR [T5A_FORP]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_FORB]  DEFAULT (0) FOR [T5A_FORB]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_FFAR]  DEFAULT (0) FOR [T5A_FFAR]
ALTER TABLE [PRO_T5AD] ADD  CONSTRAINT [DF_PRO_T5AD_T5A_OUTR]  DEFAULT (0) FOR [T5A_OUTR]
ALTER TABLE [PRO_T5TR] ADD  CONSTRAINT [DF_PRO_T5TR_T5T_STAT]  DEFAULT (0) FOR [T5T_STAT]
ALTER TABLE [PRO_T5TR] ADD  CONSTRAINT [DF_PRO_T5TR_T5T_NCON]  DEFAULT (0) FOR [T5T_NCON]
ALTER TABLE [PRO_T5TR] ADD  CONSTRAINT [DF_PRO_T5TR_T5T_ADIC]  DEFAULT (0) FOR [T5T_ADIC]
ALTER TABLE [PRO_T5TR] ADD  CONSTRAINT [DF_PRO_T5TR_T5T_TVOL]  DEFAULT (0) FOR [T5T_TVOL]
ALTER TABLE [PRO_T5TR] ADD  CONSTRAINT [DF_PRO_T5TR_T5T_CONT]  DEFAULT (0) FOR [T5T_CONT]
ALTER TABLE [PRO_TADI] ADD  CONSTRAINT [DF_PRO_TADI_TAD_MBRT]  DEFAULT (0) FOR [TAD_MBRT]
ALTER TABLE [PRO_TADI] ADD  CONSTRAINT [DF_PRO_TADI_TAD_MLIQ]  DEFAULT (0) FOR [TAD_MLIQ]
ALTER TABLE [PRO_TADI] ADD  CONSTRAINT [DF_PRO_TADI_TAD_DSUM]  DEFAULT (0) FOR [TAD_DSUM]
ALTER TABLE [PRO_TADI] ADD  CONSTRAINT [DF_PRO_TADI_TAD_DPRE]  DEFAULT (0) FOR [TAD_DPRE]
ALTER TABLE [PRO_TMAN] ADD  CONSTRAINT [DF_PRO_TMAN_TMA_STAT]  DEFAULT (0) FOR [TMA_STAT]
ALTER TABLE [PRO_TMAN] ADD  CONSTRAINT [DF_PRO_TMAN_TMA_NCON]  DEFAULT (0) FOR [TMA_NCON]
ALTER TABLE [PRO_TMAN] ADD  CONSTRAINT [DF_PRO_TMAN_TMA_ADIC]  DEFAULT (0) FOR [TMA_ADIC]
ALTER TABLE [PRO_TMAN] ADD  CONSTRAINT [DF_PRO_TMAN_TMA_TVOL]  DEFAULT (0) FOR [TMA_TVOL]
ALTER TABLE [PRO_TMAN] ADD  CONSTRAINT [DF_PRO_TMAN_TMA_CONT]  DEFAULT (0) FOR [TMA_CONT]
ALTER TABLE [PRO_TMAN] ADD  CONSTRAINT [DF_PRO_TMAN_TMA_MLTO]  DEFAULT (0) FOR [TMA_MLTO]
ALTER TABLE [TAB_ADOC] ADD  CONSTRAINT [DF_TAB_ADOC_ADC_UIMP]  DEFAULT (0) FOR [ADC_UIMP]
ALTER TABLE [TAB_ADOC] ADD  CONSTRAINT [DF_TAB_ADOC_ADC_UEXP]  DEFAULT (0) FOR [ADC_UEXP]
ALTER TABLE [TAB_ADUM] ADD  CONSTRAINT [DF_TAB_ADUM_ADU_TAXA]  DEFAULT ((0)) FOR [ADU_TAXA]
ALTER TABLE [TAB_AETR] ADD  CONSTRAINT [DF_TAB_AETR_AET_TAXA]  DEFAULT ((0)) FOR [AET_TAXA]
ALTER TABLE [TAB_AETR] ADD  CONSTRAINT [DF_TAB_AETR_AET_TXVL]  DEFAULT ((0)) FOR [AET_TXVL]
ALTER TABLE [TAB_AGEN] ADD  CONSTRAINT [DF_TAB_AGEN_AGE_INAC]  DEFAULT (0) FOR [AGE_INAC]
ALTER TABLE [TAB_AGEN] ADD  CONSTRAINT [DF_TAB_AGEN_AGE_TIPO]  DEFAULT (0) FOR [AGE_TIPO]
ALTER TABLE [TAB_ALFA] ADD  CONSTRAINT [DF_TAB_ALFA_ALF_DEPE]  DEFAULT (0) FOR [ALF_DEPE]
ALTER TABLE [TAB_ALFA] ADD  CONSTRAINT [DF_TAB_ALFA_ALF_PRIN]  DEFAULT (0) FOR [ALF_PRIN]
ALTER TABLE [TAB_ALFA] ADD  CONSTRAINT [DF_TAB_ALFA_ALF_CONT]  DEFAULT ((0)) FOR [ALF_CONT]
ALTER TABLE [TAB_AMEN] ADD  CONSTRAINT [DF_TAB_AMEN_AME_UIMP]  DEFAULT ((0)) FOR [AME_UIMP]
ALTER TABLE [TAB_AMEN] ADD  CONSTRAINT [DF_TAB_AMEN_AME_UEXP]  DEFAULT ((0)) FOR [AME_UEXP]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU1_APA_INAC]  DEFAULT ((0)) FOR [APA_INAC]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU1_APA_EUR1]  DEFAULT ((0)) FOR [APA_EUR1]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU1_APA_ATR]  DEFAULT ((0)) FOR [APA_ATR]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU1_APA_AGRX]  DEFAULT ((0)) FOR [APA_AGRX]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU1_APA_LIMP]  DEFAULT ((0)) FOR [APA_LIMP]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU1_APA_CORI]  DEFAULT ((0)) FOR [APA_CORI]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU1_APA_G156]  DEFAULT ((0)) FOR [APA_G156]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_TXCO]  DEFAULT ((0)) FOR [APA_TXCO]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_ANXC]  DEFAULT ((0)) FOR [APA_ANXC]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_ANXD]  DEFAULT ((0)) FOR [APA_ANXD]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_TXIA]  DEFAULT ((0)) FOR [APA_TXIA]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_DPUT]  DEFAULT ((0)) FOR [APA_DPUT]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_CS50]  DEFAULT ((0)) FOR [APA_CS50]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_FLUX]  DEFAULT ((0)) FOR [APA_FLUX]
ALTER TABLE [TAB_APAU] ADD  CONSTRAINT [DF_TAB_APAU_APA_EDAR]  DEFAULT ((0)) FOR [APA_EDAR]
ALTER TABLE [TAB_APTF] ADD  CONSTRAINT [DF_TAB_APTF_APT_INCR]  DEFAULT (0) FOR [APT_INCR]
ALTER TABLE [TAB_CAUC] ADD  CONSTRAINT [DF_TAB_CAUC_CAU_LIQU]  DEFAULT (0) FOR [CAU_LIQU]
ALTER TABLE [TAB_CAUC] ADD  CONSTRAINT [DF_TAB_CAUC_CAU_ATRI]  DEFAULT (0) FOR [CAU_ATRI]
ALTER TABLE [TAB_CAUC] ADD  CONSTRAINT [DF_TAB_CAUC_CAU_UTIL]  DEFAULT (0) FOR [CAU_UTIL]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_FOR1]  DEFAULT ((0)) FOR [CEN_FOR1]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_FOR2]  DEFAULT ((0)) FOR [CEN_FOR2]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_FOR3]  DEFAULT ((0)) FOR [CEN_FOR3]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_FOR4]  DEFAULT ((0)) FOR [CEN_FOR4]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_FOR5]  DEFAULT ((0)) FOR [CEN_FOR5]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_USFR]  DEFAULT ((0)) FOR [CEN_USFR]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_VLFR]  DEFAULT ((0)) FOR [CEN_VLFR]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_VLSG]  DEFAULT ((0)) FOR [CEN_VLSG]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_PACC]  DEFAULT ((0)) FOR [CEN_PACC]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_VLAN]  DEFAULT ((0)) FOR [CEN_VLAN]
ALTER TABLE [TAB_CENT] ADD  CONSTRAINT [DF_TAB_CENT_CEN_FDHL]  DEFAULT ((0)) FOR [CEN_FDHL]
ALTER TABLE [TAB_CLDO] ADD  CONSTRAINT [DF_TAB_CLDO_CLD_UIMP]  DEFAULT ((0)) FOR [CLD_UIMP]
ALTER TABLE [TAB_CLDO] ADD  CONSTRAINT [DF_TAB_CLDO_CLD_UEXP]  DEFAULT ((0)) FOR [CLD_UEXP]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CDG_INAC]  DEFAULT ((0)) FOR [CLI_INAC]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CDG_DESP]  DEFAULT ((0)) FOR [CLI_DESP]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CDG_AUTO]  DEFAULT ((0)) FOR [CLI_AUTO]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CDC_INAC]  DEFAULT ((0)) FOR [CLI_INA1]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_INA11]  DEFAULT ((0)) FOR [CLI_INA2]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_INA11_1]  DEFAULT ((0)) FOR [CLI_INA3]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_INA11_2]  DEFAULT ((0)) FOR [CLI_INA4]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_INA11_3]  DEFAULT ((0)) FOR [CLI_INA5]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CCO_ISAL]  DEFAULT ((0)) FOR [CLI_ISAL]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_STAN]  DEFAULT ((0)) FOR [CLI_STAN]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_CLIE]  DEFAULT ((0)) FOR [CLI_CLIE]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_CODF]  DEFAULT ((0)) FOR [CLI_CODC]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_DUCT]  DEFAULT ((1)) FOR [CLI_DUCT]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_LMCR]  DEFAULT ((0)) FOR [CLI_LMCR]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_CACC]  DEFAULT ((0)) FOR [CLI_CACC]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_CEXB]  DEFAULT ((0)) FOR [CLI_CEXB]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_CDAS]  DEFAULT ((0)) FOR [CLI_CDAS]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_FXOE]  DEFAULT ((0)) FOR [CLI_FXOE]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_VEVD]  DEFAULT ((0)) FOR [CLI_VEVD]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_INTR]  DEFAULT ((0)) FOR [CLI_INTR]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_IEEN]  DEFAULT ((0)) FOR [CLI_IEEN]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_IESA]  DEFAULT ((0)) FOR [CLI_IESA]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_INDI]  DEFAULT ((0)) FOR [CLI_INDI]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_ITFT]  DEFAULT ((0)) FOR [CLI_ITFT]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_IVLF]  DEFAULT ((0)) FOR [CLI_IVLF]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_DPRO]  DEFAULT ((0)) FOR [CLI_DPRO]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_CTRO]  DEFAULT ((0)) FOR [CLI_CTRO]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_IESE]  DEFAULT ((0)) FOR [CLI_IESE]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_SYNC]  DEFAULT ((0)) FOR [CLI_SYNC]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_PLET]  DEFAULT ((0)) FOR [CLI_PLET]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_BIVA]  DEFAULT ((0)) FOR [CLI_BIVA]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_EILC]  DEFAULT ((0)) FOR [CLI_EILC]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_CGLO]  DEFAULT ((0)) FOR [CLI_CGLO]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_DCON]  DEFAULT ((0)) FOR [CLI_DCON]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_DESQ]  DEFAULT ((0)) FOR [CLI_DESQ]
ALTER TABLE [TAB_CLIE] ADD  CONSTRAINT [DF_TAB_CLIE_CLI_IEDA]  DEFAULT ((0)) FOR [CLI_IEDA]
ALTER TABLE [TAB_COSM] ADD  CONSTRAINT [DF_TAB_COSM_COS_RELI]  DEFAULT ((0)) FOR [COS_RELI]
ALTER TABLE [TAB_COSM] ADD  CONSTRAINT [DF_TAB_COSM_COS_HOLD]  DEFAULT ((0)) FOR [COS_HOLD]
ALTER TABLE [TAB_COSM] ADD  CONSTRAINT [DF_TAB_COSM_COS_ANAT]  DEFAULT ((0)) FOR [COS_ANAT]
ALTER TABLE [TAB_DDOC] ADD  CONSTRAINT [DF_TAB_DDOC_DDO_IMPR]  DEFAULT ((0)) FOR [DDO_IMPR]
ALTER TABLE [TAB_DDOC] ADD  CONSTRAINT [DF_TAB_DDOC_DIN_CCDO]  DEFAULT ((0)) FOR [DDO_CCDO]
ALTER TABLE [TAB_DDOC] ADD  CONSTRAINT [DF_TAB_DDOC_DIN_CNAV]  DEFAULT ((0)) FOR [DDO_CNAV]
ALTER TABLE [TAB_DDOC] ADD  CONSTRAINT [DF_TAB_DDOC_DIN_UCTE]  DEFAULT ((0)) FOR [DDO_UCTE]
ALTER TABLE [TAB_DDOC] ADD  CONSTRAINT [DF_TAB_DDOC_DDO_DGEP]  DEFAULT ((0)) FOR [DDO_DGEP]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_INAC]  DEFAULT ((0)) FOR [DEC_INAC]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_CLI_INA2]  DEFAULT ((0)) FOR [DEC_INA1]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_INA11]  DEFAULT ((0)) FOR [DEC_INA2]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_INA11_1]  DEFAULT ((0)) FOR [DEC_INA3]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_INA11_2]  DEFAULT ((0)) FOR [DEC_INA4]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_INA11_3]  DEFAULT ((0)) FOR [DEC_INA5]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_TIPO]  DEFAULT ((1)) FOR [DEC_TIPO]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_LWIN]  DEFAULT ((0)) FOR [DEC_LWIN]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_FXOE]  DEFAULT ((0)) FOR [DEC_FXOE]
ALTER TABLE [TAB_DECL] ADD  CONSTRAINT [DF_TAB_DECL_DEC_XNRA]  DEFAULT ((0)) FOR [DEC_XNRA]
ALTER TABLE [TAB_DECS] ADD  CONSTRAINT [DF_TAB_DECS_DCS_TDEC]  DEFAULT ((3)) FOR [DCS_TDEC]
ALTER TABLE [TAB_DECS] ADD  CONSTRAINT [DF_TAB_DECS_DCS_PNPR]  DEFAULT ((1)) FOR [DCS_PNPR]
ALTER TABLE [TAB_DECS] ADD  CONSTRAINT [DF_TAB_DECS_DCS_INAC]  DEFAULT ((0)) FOR [DCS_INAC]
ALTER TABLE [TAB_DINE] ADD  CONSTRAINT [DF_TAB_DINE_DIN_CCDO]  DEFAULT ((0)) FOR [DIN_CCDO]
ALTER TABLE [TAB_DINE] ADD  CONSTRAINT [DF_TAB_DINE_DIN_CNAV]  DEFAULT ((0)) FOR [DIN_CNAV]
ALTER TABLE [TAB_DINE] ADD  CONSTRAINT [DF_TAB_DINE_DIN_UCTE]  DEFAULT ((0)) FOR [DIN_UCTE]
ALTER TABLE [TAB_DINE] ADD  CONSTRAINT [DF_TAB_DINE_DIN_AGRA]  DEFAULT ((0)) FOR [DIN_AGRA]
ALTER TABLE [TAB_DINE] ADD  CONSTRAINT [DF_TAB_DINE_DIN_IMSL]  DEFAULT ((0)) FOR [DIN_IMSL]
ALTER TABLE [TAB_DINE] ADD  CONSTRAINT [DF_TAB_DINE_DIN_ISEN]  DEFAULT ((0)) FOR [DIN_ISEN]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_RSDA]  DEFAULT (0) FOR [DOC_RSDA]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_IOBC]  DEFAULT (0) FOR [DOC_IOBC]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_TRAN]  DEFAULT (0) FOR [DOC_TRAN]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_DESP]  DEFAULT (0) FOR [DOC_DESP]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_EXPT]  DEFAULT (0) FOR [DOC_EXPT]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_CA40]  DEFAULT (0) FOR [DOC_CA40]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_DTRA]  DEFAULT ((0)) FOR [DOC_DTRA]
ALTER TABLE [TAB_DOCU] ADD  CONSTRAINT [DF_TAB_DOCU_DOC_AUTZ]  DEFAULT ((0)) FOR [DOC_AUTZ]
ALTER TABLE [TAB_EADU] ADD  CONSTRAINT [DF_TAB_EADU_EAD_EPAR]  DEFAULT (0) FOR [EAD_EPAR]
ALTER TABLE [TAB_EADU] ADD  CONSTRAINT [DF_TAB_EADU_EAD_EPAS]  DEFAULT (0) FOR [EAD_EPAS]
ALTER TABLE [TAB_EADU] ADD  CONSTRAINT [DF_TAB_EADU_EAD_EDES]  DEFAULT (0) FOR [EAD_EDES]
ALTER TABLE [TAB_EADU] ADD  CONSTRAINT [DF_TAB_EADU_EAD_CMEU]  DEFAULT (1) FOR [EAD_CMEU]
ALTER TABLE [TAB_EJUR] ADD  CONSTRAINT [DF_TAB_EJUR_EJU_ONUS]  DEFAULT (0) FOR [EJU_ONUS]
ALTER TABLE [TAB_FINC] ADD  CONSTRAINT [DF_TAB_FINC_FIN_VFOB]  DEFAULT (0) FOR [FIN_VFOB]
ALTER TABLE [TAB_FORN] ADD  CONSTRAINT [DF_TAB_FORN_FOR_INAC]  DEFAULT (0) FOR [FOR_INAC]
ALTER TABLE [TAB_FORN] ADD  CONSTRAINT [DF_TAB_FORN_FOR_DESP]  DEFAULT (0) FOR [FOR_DESP]
ALTER TABLE [TAB_FORN] ADD  CONSTRAINT [DF_TAB_FORN_EXM_IROR]  DEFAULT (0) FOR [FOR_IROR]
ALTER TABLE [TAB_FTAC] ADD  CONSTRAINT [DF_TAB_FTAC_FTA_LIMI]  DEFAULT (0) FOR [FTA_LIMI]
ALTER TABLE [TAB_FTAC] ADD  CONSTRAINT [DF_TAB_FTAC_FTA_VLIM]  DEFAULT (0) FOR [FTA_VLIM]
ALTER TABLE [TAB_FTAC] ADD  CONSTRAINT [DF_TAB_FTAC_FTA_VADI]  DEFAULT (0) FOR [FTA_VADI]
ALTER TABLE [TAB_HTEC] ADD  CONSTRAINT [DF_TAB_HTEC_HTE_VISV]  DEFAULT ((0)) FOR [HTE_VISV]
ALTER TABLE [TAB_INFC] ADD  CONSTRAINT [DF_TAB_INFC_INF_GARA]  DEFAULT ((0)) FOR [INF_GARA]
ALTER TABLE [TAB_INFC] ADD  CONSTRAINT [DF_TAB_INFC_INF_EXPT]  DEFAULT ((0)) FOR [INF_EXPT]
ALTER TABLE [TAB_INFC] ADD  CONSTRAINT [DF_TAB_INFC_INF_NSTI]  DEFAULT ((0)) FOR [INF_NSTI]
ALTER TABLE [TAB_INFC] ADD  CONSTRAINT [DF_TAB_INFC_INF_IMPC]  DEFAULT ((0)) FOR [INF_IMPC]
ALTER TABLE [TAB_LMER] ADD  CONSTRAINT [DF_TAB_LMER_LME_PNRE]  DEFAULT ((1)) FOR [LME_PNRE]
ALTER TABLE [TAB_LMER] ADD  CONSTRAINT [DF_TAB_LMER_LME_PNRS]  DEFAULT ((1)) FOR [LME_PNRS]
ALTER TABLE [TAB_MIAU] ADD  CONSTRAINT [DF_TAB_MIAU_MIA_OBRI]  DEFAULT ((0)) FOR [MIA_OBRI]
ALTER TABLE [TAB_MNDO] ADD  CONSTRAINT [DF_TAB_MNDO_MND_VALO]  DEFAULT ((0)) FOR [MND_VALO]
ALTER TABLE [TAB_MNFT] ADD  CONSTRAINT [DF_TAB_MNFT_MNF_VAGR]  DEFAULT ((0)) FOR [MNF_VAGR]
ALTER TABLE [TAB_MNFT] ADD  CONSTRAINT [DF_TAB_MNFT_MNF_VDES]  DEFAULT ((0)) FOR [MNF_VDES]
ALTER TABLE [TAB_MNFT] ADD  CONSTRAINT [DF_TAB_MNFT_MNF_VALO]  DEFAULT ((0)) FOR [MNF_VALO]
ALTER TABLE [TAB_MNIN] ADD  CONSTRAINT [DF_TAB_MNIN_MNI_VALO]  DEFAULT ((0)) FOR [MNI_VALO]
ALTER TABLE [TAB_MTRA] ADD  CONSTRAINT [DF_TAB_MTRA_MTR_PTAX]  DEFAULT ((0)) FOR [MTR_PTAX]
ALTER TABLE [TAB_MTRA] ADD  CONSTRAINT [DF_TAB_MTRA_MTR_OPAU]  DEFAULT ((0)) FOR [MTR_OPAU]
ALTER TABLE [TAB_MTRO] ADD  CONSTRAINT [DF_TAB_MTRO_MTO_LMNP]  DEFAULT ((0)) FOR [MTO_LMNP]
ALTER TABLE [TAB_MTRO] ADD  CONSTRAINT [DF_TAB_MTRO_MTO_LMXP]  DEFAULT ((0)) FOR [MTO_LMXP]
ALTER TABLE [TAB_MTRO] ADD  CONSTRAINT [DF_TAB_MTRO_MTO_LMNV]  DEFAULT ((0)) FOR [MTO_LMNV]
ALTER TABLE [TAB_MTRO] ADD  CONSTRAINT [DF_TAB_MTRO_MTO_LMXV]  DEFAULT ((0)) FOR [MTO_LMXV]
ALTER TABLE [TAB_MTRO] ADD  CONSTRAINT [DF_TAB_MTRO_MTO_VOPT]  DEFAULT ((0)) FOR [MTO_VOPT]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_STCK]  DEFAULT ((0)) FOR [NDE_STCK]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_CTEN]  DEFAULT ((0)) FOR [NDE_CTEN]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_FEDI]  DEFAULT ((0)) FOR [NDE_FEDI]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_UTTD]  DEFAULT ((0)) FOR [NDE_UTTD]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_AADT]  DEFAULT ((0)) FOR [NDE_AADT]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_NDAL]  DEFAULT ((0)) FOR [NDE_NDAL]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_CRCO]  DEFAULT ((1)) FOR [NDE_CRCO]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_DRDR]  DEFAULT ((0)) FOR [NDE_DRDR]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_GADT]  DEFAULT ((0)) FOR [NDE_GADT]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_PART]  DEFAULT ((0)) FOR [NDE_PART]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_VDAR]  DEFAULT ((0)) FOR [NDE_VDAR]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_RETO]  DEFAULT ((0)) FOR [NDE_RETO]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_OSER]  DEFAULT ((0)) FOR [NDE_OSER]
ALTER TABLE [TAB_NDES] ADD  CONSTRAINT [DF_TAB_NDES_NDE_VEXI]  DEFAULT ((0)) FOR [NDE_VEXI]
ALTER TABLE [TAB_NNC8] ADD  CONSTRAINT [DF_TAB_NNC8_NC8_USPL]  DEFAULT ((0)) FOR [NC8_USPL]
ALTER TABLE [TAB_NNC8] ADD  CONSTRAINT [DF_TAB_NNC8_NC8_TIVA]  DEFAULT ((0)) FOR [NC8_TIVA]
ALTER TABLE [TAB_NNC8] ADD  CONSTRAINT [DF_TAB_NNC8_NC8_TMLQ]  DEFAULT ((0)) FOR [NC8_TMLQ]
ALTER TABLE [TAB_NNC8] ADD  CONSTRAINT [DF_TAB_NNC8_NC8_PMDU]  DEFAULT ((0)) FOR [NC8_PMDU]
ALTER TABLE [TAB_PAER] ADD  CONSTRAINT [DF_TAB_PAER_PAE_TIPO]  DEFAULT ((0)) FOR [PAE_TIPO]
ALTER TABLE [TAB_PAIS] ADD  CONSTRAINT [DF_TAB_PAIS_PAI_PRE1]  DEFAULT (0) FOR [PAI_PRE1]
ALTER TABLE [TAB_PAIS] ADD  CONSTRAINT [DF_TAB_PAIS_PAI_PATR]  DEFAULT (0) FOR [PAI_PATR]
ALTER TABLE [TAB_PAIS] ADD  CONSTRAINT [DF_TAB_PAIS_PAI_IFRE]  DEFAULT ((0)) FOR [PAI_IFRE]
ALTER TABLE [TAB_PAIS] ADD  CONSTRAINT [DF_TAB_PAIS_PAI_ZEUR]  DEFAULT ((0)) FOR [PAI_ZEUR]
ALTER TABLE [TAB_PAPL] ADD  CONSTRAINT [DF_TAB_PAPL_PAP_PAUT]  DEFAULT ((0)) FOR [PAP_PAUT]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBE_AHON]  DEFAULT ((0)) FOR [CBE_AHON]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBL_VHON]  DEFAULT ((0)) FOR [CBE_VHON]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBL_PHON]  DEFAULT ((0)) FOR [CBE_PHON]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBE_PDES]  DEFAULT ((0)) FOR [CBE_PDES]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBE_ACAU]  DEFAULT ((0)) FOR [CBE_ACAU]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBL_VCAU]  DEFAULT ((0)) FOR [CBE_VCAU]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBL_PCAU]  DEFAULT ((0)) FOR [CBE_PCAU]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBE_PVIL]  DEFAULT ((0)) FOR [CBE_PVIL]
ALTER TABLE [TAB_PCBE] ADD  CONSTRAINT [DF_TAB_PCBE_CBE_UDTL]  DEFAULT ((0)) FOR [CBE_UDTL]
ALTER TABLE [TAB_PCBI] ADD  CONSTRAINT [DF_TAB_PCBI_CBI_NADF]  DEFAULT ((0)) FOR [CBI_NADF]
ALTER TABLE [TAB_PCBI] ADD  CONSTRAINT [DF_TAB_PCBI_CBI_VLAD]  DEFAULT ((0)) FOR [CBI_VLAD]
ALTER TABLE [TAB_PCBI] ADD  CONSTRAINT [DF_TAB_PCBI_CBI_VLCO]  DEFAULT ((0)) FOR [CBI_VLCO]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_LINF]  DEFAULT ((0)) FOR [CBL_LINF]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_LSUP]  DEFAULT ((0)) FOR [CBL_LSUP]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_VHON]  DEFAULT ((0)) FOR [CBL_VHON]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_PHON]  DEFAULT ((0)) FOR [CBL_PHON]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_VCAU]  DEFAULT ((0)) FOR [CBL_VCAU]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_PCAU]  DEFAULT ((0)) FOR [CBL_PCAU]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_TIPO]  DEFAULT ((0)) FOR [CBL_TIPO]
ALTER TABLE [TAB_PCBL] ADD  CONSTRAINT [DF_TAB_PCBL_CBL_MHON]  DEFAULT ((0)) FOR [CBL_MHON]
ALTER TABLE [TAB_PCBT] ADD  CONSTRAINT [DF_TAB_PCBT_CBT_VREF]  DEFAULT ((0)) FOR [CBT_VREF]
ALTER TABLE [TAB_PCBT] ADD  CONSTRAINT [DF_TAB_PCBT_CBT_VRFP]  DEFAULT ((0)) FOR [CBT_VRFP]
ALTER TABLE [TAB_PCBX] ADD  CONSTRAINT [DF_TAB_PCBX_CBX_LINF]  DEFAULT ((0)) FOR [CBX_LINF]
ALTER TABLE [TAB_PCBX] ADD  CONSTRAINT [DF_TAB_PCBX_CBX_LSUP]  DEFAULT ((0)) FOR [CBX_LSUP]
ALTER TABLE [TAB_PCBX] ADD  CONSTRAINT [DF_TAB_PCBX_CBX_VHON]  DEFAULT ((0)) FOR [CBX_VHON]
ALTER TABLE [TAB_PCBX] ADD  CONSTRAINT [DF_TAB_PCBX_CBX_PDES]  DEFAULT ((0)) FOR [CBX_PDES]
ALTER TABLE [TAB_PCBX] ADD  CONSTRAINT [DF_TAB_PCBX_CBX_PHON]  DEFAULT ((0)) FOR [CBX_PHON]
ALTER TABLE [TAB_PDCA] ADD  CONSTRAINT [DF_TAB_PDCA_DCA_ECDI]  DEFAULT ((0)) FOR [DCA_ECDI]
ALTER TABLE [TAB_PDCA] ADD  CONSTRAINT [DF_TAB_PDCA_DCA_ECFI]  DEFAULT ((0)) FOR [DCA_ECFI]
ALTER TABLE [TAB_PDCA] ADD  CONSTRAINT [DF_TAB_PDCA_DCA_ECAI]  DEFAULT ((0)) FOR [DCA_ECAI]
ALTER TABLE [TAB_PDCA] ADD  CONSTRAINT [DF_TAB_PDCA_DCA_ECDE]  DEFAULT ((0)) FOR [DCA_ECDE]
ALTER TABLE [TAB_PDCA] ADD  CONSTRAINT [DF_TAB_PDCA_DCA_ECFE]  DEFAULT ((0)) FOR [DCA_ECFE]
ALTER TABLE [TAB_PDCA] ADD  CONSTRAINT [DF_TAB_PDCA_DCA_ECAE]  DEFAULT ((0)) FOR [DCA_ECAE]
ALTER TABLE [TAB_PDER] ADD  CONSTRAINT [DF_TAB_PDER_DER_ACTI]  DEFAULT ((0)) FOR [DER_ACTI]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_CIMP]  DEFAULT ((0)) FOR [PDE_CIMP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_CIMP1]  DEFAULT ((0)) FOR [PDE_CEXP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_ACNT]  DEFAULT ((0)) FOR [PDE_CONT]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_LIMP]  DEFAULT ((0)) FOR [PDE_LIMP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_LIMP1]  DEFAULT ((0)) FOR [PDE_LEXP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_NPRO]  DEFAULT ((0)) FOR [PDE_NPRO]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_CPES]  DEFAULT ((0)) FOR [PDE_CPES]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_NPDT]  DEFAULT ((1)) FOR [PDE_NPDT]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VPDT]  DEFAULT ((1)) FOR [PDE_VPDT]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_NTDP]  DEFAULT ((1)) FOR [PDE_NTDP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VTDP]  DEFAULT ((1)) FOR [PDE_VTDP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_BCNR]  DEFAULT ((0)) FOR [PDE_BCNR]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_NGLE]  DEFAULT ((0)) FOR [PDE_NGLE]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VGLE]  DEFAULT ((1)) FOR [PDE_VGLE]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_PGLE]  DEFAULT ((20)) FOR [PDE_PGLE]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VCFC]  DEFAULT ((0)) FOR [PDE_VCFC]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VLAD]  DEFAULT ((0)) FOR [PDE_VLAD]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VFMN]  DEFAULT ((22)) FOR [PDE_VFMN]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VFMX]  DEFAULT ((22)) FOR [PDE_VFMX]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_PSFR]  DEFAULT ((3)) FOR [PDE_PSFR]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_XVAL]  DEFAULT ((75)) FOR [PDE_XVAL]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_XPES]  DEFAULT ((20)) FOR [PDE_XPES]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_NPDP]  DEFAULT ((1)) FOR [PDE_NPDP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_PNTD]  DEFAULT ((1)) FOR [PDE_PNTD]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_IDCV]  DEFAULT ((0)) FOR [PDE_IDCV]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_TPDF]  DEFAULT ((0)) FOR [PDE_TPDF]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_ECBO]  DEFAULT ((0)) FOR [PDE_ECBO]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_PNAL]  DEFAULT ((1)) FOR [PDE_PNAL]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_PNAP]  DEFAULT ((1)) FOR [PDE_PNAP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VCPI]  DEFAULT ((0)) FOR [PDE_VCPI]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_VCPE]  DEFAULT ((0)) FOR [PDE_VCPE]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_NTRP]  DEFAULT ((0)) FOR [PDE_NTRP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_OTIR]  DEFAULT ((0)) FOR [PDE_OTIR]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_GTPR]  DEFAULT ((0)) FOR [PDE_GTPR]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_NGLP]  DEFAULT ((0)) FOR [PDE_NGLP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_PRXA]  DEFAULT ((0)) FOR [PDE_PRXA]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_ICAU]  DEFAULT ((0)) FOR [PDE_ICAU]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_CSTD]  DEFAULT ((1)) FOR [PDE_CSTD]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_TSAP]  DEFAULT ((0)) FOR [PDE_TSAP]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_ECAU]  DEFAULT ((0)) FOR [PDE_ECAU]
ALTER TABLE [TAB_PDES] ADD  CONSTRAINT [DF_TAB_PDES_PDE_PTEX]  DEFAULT ((0)) FOR [PDE_PTEX]
ALTER TABLE [TAB_PDTP] ADD  CONSTRAINT [DF_TAB_PDTP_DTP_INTE]  DEFAULT ((0)) FOR [DTP_INTE]
ALTER TABLE [TAB_PDTP] ADD  CONSTRAINT [DF_TAB_PDTP_DTP_RENA]  DEFAULT ((0)) FOR [DTP_RENA]
ALTER TABLE [TAB_PDTP] ADD  CONSTRAINT [DF_TAB_PDTP_DTP_COPY]  DEFAULT ((0)) FOR [DTP_COPY]
ALTER TABLE [TAB_PDTP] ADD  CONSTRAINT [DF_TAB_PDTP_DTP_DELE]  DEFAULT ((0)) FOR [DTP_DELE]
ALTER TABLE [TAB_PDTP] ADD  CONSTRAINT [DF_TAB_PDTP_DTP_ARQI]  DEFAULT ((0)) FOR [DTP_ARQI]
ALTER TABLE [TAB_PDTP] ADD  CONSTRAINT [DF_TAB_PDTP_DTP_ISER]  DEFAULT ((0)) FOR [DTP_ISER]
ALTER TABLE [TAB_PDTP] ADD  CONSTRAINT [DF_TAB_PDTP_DTP_EMAI]  DEFAULT ((0)) FOR [DTP_EMAI]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_CONT]  DEFAULT (0) FOR [PFC_CONT]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_IMPP]  DEFAULT (0) FOR [PFC_IMPP]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_VBHO]  DEFAULT (0) FOR [PFC_VBHO]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_VDAT]  DEFAULT (0) FOR [PFC_VDAT]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_UFDV]  DEFAULT (0) FOR [PFC_UFDV]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_ISAP]  DEFAULT (0) FOR [PFC_ISAP]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_VBGE]  DEFAULT (0) FOR [PFC_VBGE]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_PNPG]  DEFAULT ((9000000)) FOR [PFC_PNPG]
ALTER TABLE [TAB_PFCT] ADD  CONSTRAINT [DF_TAB_PFCT_PFC_BCLZ]  DEFAULT ((0)) FOR [PFC_BCLZ]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_ACTI]  DEFAULT ((0)) FOR [FTA_ACTI]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_DUAS]  DEFAULT ((1)) FOR [FTA_DUAS]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_DUVR]  DEFAULT ((0)) FOR [FTA_DUVR]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_ETCC]  DEFAULT ((0)) FOR [FTA_ETCC]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_ECDS]  DEFAULT ((0)) FOR [FTA_ECDS]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_ECEC]  DEFAULT ((0)) FOR [FTA_ECEC]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_ECCG]  DEFAULT ((0)) FOR [FTA_ECCG]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_ENAD]  DEFAULT ((0)) FOR [FTA_ENAD]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_CKIN]  DEFAULT ((0)) FOR [FTA_CKIN]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_EPTR]  DEFAULT ((0)) FOR [FTA_EPTR]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_DDRI]  DEFAULT ((0)) FOR [FTA_DDRI]
ALTER TABLE [TAB_PFTA] ADD  CONSTRAINT [DF_TAB_PFTA_FTA_DDBI]  DEFAULT ((0)) FOR [FTA_DDBI]
ALTER TABLE [TAB_PFTE] ADD  CONSTRAINT [DF_TAB_PFTE_FTE_ETIP]  DEFAULT ((0)) FOR [FTE_ETIP]
ALTER TABLE [TAB_PFTI] ADD  CONSTRAINT [DF_TAB_PFTI_FTI_DDVU]  DEFAULT ((0)) FOR [FTI_DDVU]
ALTER TABLE [TAB_PFTI] ADD  CONSTRAINT [DF_TAB_PFTI_FTI_DIMP]  DEFAULT ((0)) FOR [FTI_DIMP]
ALTER TABLE [TAB_PFTI] ADD  CONSTRAINT [DF_TAB_PFTI_FTI_SADT]  DEFAULT ((0)) FOR [FTI_SADT]
ALTER TABLE [TAB_PFTI] ADD  CONSTRAINT [DF_TAB_PFTI_FTI_IAUT]  DEFAULT ((0)) FOR [FTI_IAUT]
ALTER TABLE [TAB_PINT] ADD  CONSTRAINT [DF_TAB_PINT_PIN_PNLN]  DEFAULT ((0)) FOR [PIN_PNLN]
ALTER TABLE [TAB_PINT] ADD  CONSTRAINT [DF_TAB_PINT_PIN_PPAC]  DEFAULT ((1)) FOR [PIN_PPAC]
ALTER TABLE [TAB_PINT] ADD  CONSTRAINT [DF_TAB_PINT_PIN_URFI]  DEFAULT ((0)) FOR [PIN_URFI]
ALTER TABLE [TAB_PSDD] ADD  CONSTRAINT [DF_TAB_PSDD_PDD_NVPR]  DEFAULT ((2)) FOR [PDD_NVPR]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_NVPR]  DEFAULT ((2)) FOR [PSD_NVPR]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_PRNR]  DEFAULT ((1)) FOR [PSD_PRNR]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_ERIM]  DEFAULT ((2)) FOR [PSD_ERIM]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_EREX]  DEFAULT ((2)) FOR [PSD_EREX]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_IXML]  DEFAULT ((0)) FOR [PSD_IXML]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_NPDL]  DEFAULT ((0)) FOR [PSD_NPDL]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_NPDP]  DEFAULT ((0)) FOR [PSD_NPDP]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_ISTN]  DEFAULT ((1)) FOR [PSD_ISTN]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_BDEX]  DEFAULT ((0)) FOR [PSD_BDEX]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_GAEX]  DEFAULT ((0)) FOR [PSD_GAEX]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_VCP0]  DEFAULT ((0)) FOR [PSD_VCP0]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_VCP1]  DEFAULT ((0)) FOR [PSD_VCP1]
ALTER TABLE [TAB_PSDS] ADD  CONSTRAINT [DF_TAB_PSDS_PSD_NPRP]  DEFAULT ((2)) FOR [PSD_NPRP]
ALTER TABLE [TAB_RFCT] ADD  CONSTRAINT [DF_TAB_RFCT_RFC_VLNC]  DEFAULT ((0)) FOR [RFC_VLNC]
ALTER TABLE [TAB_RFCT] ADD  CONSTRAINT [DF_TAB_RFCT_RFC_VLNS]  DEFAULT ((0)) FOR [RFC_VLNS]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_IVA]  DEFAULT ((0)) FOR [RRE_IVA]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_RPRO]  DEFAULT ((0)) FOR [RRE_RPRO]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_PAGR]  DEFAULT ((0)) FOR [RRE_PAGR]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_IOBS]  DEFAULT ((0)) FOR [RRE_IOBS]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_VERB]  DEFAULT ((1)) FOR [RRE_VERB]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_VALO]  DEFAULT ((0)) FOR [RRE_VALO]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_UVAL]  DEFAULT ((0)) FOR [RRE_UVAL]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_TIEC]  DEFAULT ((0)) FOR [RRE_TIEC]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_DUMP]  DEFAULT ((0)) FOR [RRE_DUMP]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_FADT]  DEFAULT ((0)) FOR [RRE_FADT]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_MADT]  DEFAULT ((0)) FOR [RRE_MADT]
ALTER TABLE [TAB_RREC] ADD  CONSTRAINT [DF_TAB_RREC_RRE_DPOT]  DEFAULT ((0)) FOR [RRE_DPOT]
ALTER TABLE [TAB_SINC] ADD  CONSTRAINT [DF_TAB_SINC_SIN_ANAT]  DEFAULT (0) FOR [SIN_ANAT]
ALTER TABLE [TAB_TAMB] ADD  CONSTRAINT [DF_PRO_TAM_ESCA]  DEFAULT (0) FOR [TAM_ESCA]
ALTER TABLE [TAB_TAMB] ADD  CONSTRAINT [DF_PRO_EXFI_TAM_COMN]  DEFAULT (0) FOR [TAM_COMN]
ALTER TABLE [TAB_TAMB] ADD  CONSTRAINT [DF_PRO_EXFI_TAM_COMX]  DEFAULT (0) FOR [TAM_COMX]
ALTER TABLE [TAB_TAMB] ADD  CONSTRAINT [DF_PRO_EXFI_TAM_TAXA]  DEFAULT (0) FOR [TAM_TAXA]
ALTER TABLE [TAB_TAMB] ADD  CONSTRAINT [DF_PRO_EXFI_TAM_ABAT]  DEFAULT (0) FOR [TAM_ABAT]
ALTER TABLE [TAB_TCOM] ADD  CONSTRAINT [DF_TAB_TCOM_TCO_EXCL]  DEFAULT (0) FOR [TCO_EXCL]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC_TDE_NATU]  DEFAULT ((1)) FOR [TDE_NATU]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA01]  DEFAULT ((0)) FOR [TDE_CA01]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA02]  DEFAULT ((0)) FOR [TDE_CA02]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA03]  DEFAULT ((0)) FOR [TDE_CA03]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA04]  DEFAULT ((0)) FOR [TDE_CA04]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA05]  DEFAULT ((0)) FOR [TDE_CA05]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA06]  DEFAULT ((0)) FOR [TDE_CA06]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA07]  DEFAULT ((0)) FOR [TDE_CA07]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA08]  DEFAULT ((0)) FOR [TDE_CA08]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA09]  DEFAULT ((0)) FOR [TDE_CA09]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA10]  DEFAULT ((0)) FOR [TDE_CA10]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA11]  DEFAULT ((0)) FOR [TDE_CA11]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA12]  DEFAULT ((0)) FOR [TDE_CA12]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA13]  DEFAULT ((0)) FOR [TDE_CA13]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA14]  DEFAULT ((0)) FOR [TDE_CA14]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA15]  DEFAULT ((0)) FOR [TDE_CA15]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA16]  DEFAULT ((0)) FOR [TDE_CA16]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA17]  DEFAULT ((0)) FOR [TDE_CA17]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA18]  DEFAULT ((0)) FOR [TDE_CA18]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA19]  DEFAULT ((0)) FOR [TDE_CA19]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA20]  DEFAULT ((0)) FOR [TDE_CA20]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA21]  DEFAULT ((0)) FOR [TDE_CA21]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA22]  DEFAULT ((0)) FOR [TDE_CA22]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA23]  DEFAULT ((0)) FOR [TDE_CA23]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA24]  DEFAULT ((0)) FOR [TDE_CA24]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA25]  DEFAULT ((0)) FOR [TDE_CA25]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA26]  DEFAULT ((0)) FOR [TDE_CA26]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA27]  DEFAULT ((0)) FOR [TDE_CA27]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA28]  DEFAULT ((0)) FOR [TDE_CA28]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA29]  DEFAULT ((0)) FOR [TDE_CA29]
ALTER TABLE [TAB_TDEC] ADD  CONSTRAINT [DF_TAB_TDEC1_TDE_CA30]  DEFAULT ((0)) FOR [TDE_CA30]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_VALI]  DEFAULT (0) FOR [TDO_VALI]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_MREC]  DEFAULT (0) FOR [TDO_MREC]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_CONC]  DEFAULT (0) FOR [TDO_CONC]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_ISAL]  DEFAULT (0) FOR [TDO_ISAL]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_IRP1]  DEFAULT (0) FOR [TDO_IRP1]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_IRP11]  DEFAULT (0) FOR [TDO_IRP2]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_IRP12]  DEFAULT (0) FOR [TDO_IRP3]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_IRP13]  DEFAULT (0) FOR [TDO_IRP4]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_DCON]  DEFAULT ((0)) FOR [TDO_DCON]
ALTER TABLE [TAB_TDOC] ADD  CONSTRAINT [DF_TAB_TDOC_TDO_EXSF]  DEFAULT ((0)) FOR [TDO_EXSF]
ALTER TABLE [TAB_TEMB] ADD  CONSTRAINT [DF_TAB_TEMB_TEM_DESP]  DEFAULT (0) FOR [TEM_PVOL]
ALTER TABLE [TAB_TEMB] ADD  CONSTRAINT [DF_TAB_TEMB_TEM_TRAN]  DEFAULT (0) FOR [TEM_PUNI]
ALTER TABLE [TAB_TEMB] ADD  CONSTRAINT [DF_TAB_TEMB_TEM_TVOL]  DEFAULT (0) FOR [TEM_TVOL]
ALTER TABLE [TAB_TEMB] ADD  CONSTRAINT [DF_TAB_TEMB_TEM_EXPT]  DEFAULT (1) FOR [TEM_EXPT]
ALTER TABLE [TAB_TEMB] ADD  CONSTRAINT [DF_TAB_TEMB_TEM_NSTI]  DEFAULT (1) FOR [TEM_NSTI]
ALTER TABLE [TAB_TIAU] ADD  CONSTRAINT [DF_TAB_TIAU_TIA_UNID]  DEFAULT (0) FOR [TIA_UNID]
ALTER TABLE [TAB_TIAU] ADD  CONSTRAINT [DF_TAB_TIAU_TIA_RPAR]  DEFAULT (0) FOR [TIA_RPAR]
ALTER TABLE [TAB_TIAU] ADD  CONSTRAINT [DF_TAB_TIAU_TIA_VMIN]  DEFAULT (0) FOR [TIA_VMIN]
ALTER TABLE [TAB_TRAM] ADD  CONSTRAINT [DF_TAB_TRAM_TRA_ESCA]  DEFAULT (0) FOR [TRA_ESCA]
ALTER TABLE [TAB_TRAM] ADD  CONSTRAINT [DF_TAB_TRAM_TRA_COMN]  DEFAULT (0) FOR [TRA_COMN]
ALTER TABLE [TAB_TRAM] ADD  CONSTRAINT [DF_TAB_TRAM_TRA_COMX]  DEFAULT (0) FOR [TRA_COMX]
ALTER TABLE [TAB_TRAM] ADD  CONSTRAINT [DF_TAB_TRAM_TRA_VALO]  DEFAULT (0) FOR [TRA_VALO]
ALTER TABLE [TAB_TVEI] ADD  CONSTRAINT [DF_TAB_TVEI_TVE_EXCL]  DEFAULT (0) FOR [TVE_EXCL]
ALTER TABLE [TAB_UMED] ADD  CONSTRAINT [DF_TAB_UMED_UME_TVOL]  DEFAULT ((0)) FOR [UME_TVOL]
ALTER TABLE [TAB_UMED] ADD  CONSTRAINT [DF_TAB_UMED_UME_IMPT]  DEFAULT ((1)) FOR [UME_IMPT]
ALTER TABLE [TAB_UMED] ADD  CONSTRAINT [DF_TAB_UMED_UME_EXPT]  DEFAULT ((1)) FOR [UME_EXPT]
ALTER TABLE [tb_ConfiguracoesDAR] ADD  CONSTRAINT [DF_tb_ConfiguracoesDAR_proxyAuthentication]  DEFAULT ((0)) FOR [proxyAuthentication]
ALTER TABLE [tb_ConfiguracoesDAR] ADD  CONSTRAINT [DF_tb_ConfiguracoesDAR_diasFreeADT]  DEFAULT ((0)) FOR [diasFreeADT]
ALTER TABLE [tb_ConfiguracoesDAREmailsResposta] ADD  CONSTRAINT [DF_tb_ConfiguracoesDAREmailsResposta_ativo]  DEFAULT ((0)) FOR [ativo]
ALTER TABLE [tb_ConfiguracoesDARNotificacoesControlo] ADD  CONSTRAINT [DF_tb_ConfiguracoesDARNotificacoesControlo_enviaEmailEmCAP]  DEFAULT ((0)) FOR [enviaEmailEmCAP]
ALTER TABLE [tb_ConfiguracoesDARNotificacoesControlo] ADD  CONSTRAINT [DF_tb_ConfiguracoesDARNotificacoesControlo_enviaEmailEmCD]  DEFAULT ((0)) FOR [enviaEmailEmCD]
ALTER TABLE [tb_ConfiguracoesDARNotificacoesControlo] ADD  CONSTRAINT [DF_tb_ConfiguracoesDARNotificacoesControlo_enviaEmailEmCF]  DEFAULT ((0)) FOR [enviaEmailEmCF]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_status]  DEFAULT ((0)) FOR [status]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_controloDocumental]  DEFAULT ((0)) FOR [controloDocumental]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_fechadoControloDocumental]  DEFAULT ((0)) FOR [fechadoControloDocumental]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_controloFisico]  DEFAULT ((0)) FOR [controloFisico]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_fechadoControloFisico]  DEFAULT ((0)) FOR [fechadoControloFisico]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_controloAduaneiro]  DEFAULT ((0)) FOR [controloAduaneiro]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_fechadoControloAduaneiro]  DEFAULT ((0)) FOR [fechadoControloAduaneiro]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_autorizacaoSaida]  DEFAULT ((0)) FOR [autorizacaoSaida]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalAdicoes]  DEFAULT ((0)) FOR [totalAdicoes]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalVolumes]  DEFAULT ((0)) FOR [totalVolumes]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalMassaBruta]  DEFAULT ((0)) FOR [totalMassaBruta]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_cambioCustosTransporte]  DEFAULT ((0)) FOR [cambioCustosTransporte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalCustosTransporte]  DEFAULT ((0)) FOR [totalCustosTransporte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_cambioMontante]  DEFAULT ((0)) FOR [cambioMontante]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalMontante]  DEFAULT ((0)) FOR [totalMontante]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalMontanteEUR]  DEFAULT ((0)) FOR [totalMontanteEUR]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalIVA]  DEFAULT ((0)) FOR [totalIVA]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_volumesDirty]  DEFAULT ((0)) FOR [volumesDirty]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_volumesClean]  DEFAULT ((0)) FOR [volumesClean]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_volumesScan]  DEFAULT ((0)) FOR [volumesScan]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_freteOriginal]  DEFAULT ((0)) FOR [freteOriginal]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_despesasDHL]  DEFAULT ((0)) FOR [despesasDHL]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_participacao]  DEFAULT ((0)) FOR [participacao]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_multa]  DEFAULT ((0)) FOR [multa]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_tipoShipment]  DEFAULT ((0)) FOR [tipoShipment]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_volumesPendentesParte]  DEFAULT ((0)) FOR [volumesPendentesParte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalMassaBrutaParte]  DEFAULT ((0)) FOR [totalMassaBrutaParte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalCustosTransporteParte]  DEFAULT ((0)) FOR [totalCustosTransporteParte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalMontanteParte]  DEFAULT ((0)) FOR [totalMontanteParte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalMontanteEURParte]  DEFAULT ((0)) FOR [totalMontanteEURParte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalIVAParte]  DEFAULT ((0)) FOR [totalIVAParte]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_libertoADT]  DEFAULT ((0)) FOR [libertoADT]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_diasDescontoADT]  DEFAULT ((0)) FOR [diasDescontoADT]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_exportado]  DEFAULT ((0)) FOR [exportado]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_acao]  DEFAULT ((0)) FOR [acao]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_envioEntregue]  DEFAULT ((0)) FOR [envioEntregue]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_statusIVA]  DEFAULT ((0)) FOR [statusIVA]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_bloqueado]  DEFAULT ((0)) FOR [bloqueado]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_taxaIVAMaxima]  DEFAULT ((0)) FOR [taxaIVAMaxima]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_beneficiarioIVACliente]  DEFAULT ((0)) FOR [beneficiarioIVACliente]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_flatFileCaucao]  DEFAULT ((0)) FOR [flatFileCaucao]
ALTER TABLE [tb_DeclaracoesDAR] ADD  CONSTRAINT [DF_tb_DeclaracoesDAR_totalOptativas]  DEFAULT ((0)) FOR [totalOptativas]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_unidades]  DEFAULT ((0)) FOR [unidades]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_massaBruta]  DEFAULT ((0)) FOR [massaBruta]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_volumes]  DEFAULT ((0)) FOR [volumes]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_cambioMontante]  DEFAULT ((0)) FOR [cambioMontante]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_montante]  DEFAULT ((0)) FOR [montante]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_montanteEUR]  DEFAULT ((0)) FOR [montanteEUR]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_baseTributacaoIVA]  DEFAULT ((0)) FOR [baseTributacaoIVA]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_taxaIVA]  DEFAULT ((0)) FOR [taxaIVA]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_valorIVA]  DEFAULT ((0)) FOR [valorIVA]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_cambioCustosTransporte]  DEFAULT ((0)) FOR [cambioCustosTransporte]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_custosTransporte]  DEFAULT ((0)) FOR [custosTransporte]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_custosTransporteEUR]  DEFAULT ((0)) FOR [custosTransporteEUR]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_triggerOff]  DEFAULT ((0)) FOR [triggerOff]
ALTER TABLE [tb_DeclaracoesDARAdicoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoes_optativas]  DEFAULT ((0)) FOR [optativas]
ALTER TABLE [tb_DeclaracoesDARAdicoesDocumentos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoesDocumentos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARAdicoesMencoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoesMencoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARAdicoesPrecedentes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARAdicoesPrecedentes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARArquivos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARArquivos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARDocumentos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARDocumentos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARIncidencias] ADD  CONSTRAINT [DF_tb_DeclaracoesDARIncidencias_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARManifestos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARManifestos_totalMassaBruta]  DEFAULT ((0)) FOR [massaBruta]
ALTER TABLE [tb_DeclaracoesDARManifestos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARManifestos_totalMontante]  DEFAULT ((0)) FOR [valor]
ALTER TABLE [tb_DeclaracoesDARManifestos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARManifestos_totalMontanteEUR]  DEFAULT ((0)) FOR [totalFatura]
ALTER TABLE [tb_DeclaracoesDARManifestos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARManifestos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARManifestos] ADD  CONSTRAINT [DF_tb_DeclaracoesDARManifestos_triggerOff]  DEFAULT ((0)) FOR [triggerOff]
ALTER TABLE [tb_DeclaracoesDARMencoes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARMencoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_DeclaracoesDARMensagens] ADD  CONSTRAINT [DF_tb_DeclaracoesDARMensagens_sucesso]  DEFAULT ((0)) FOR [sucesso]
ALTER TABLE [tb_DeclaracoesDARMensagens] ADD  CONSTRAINT [DF_tb_DeclaracoesDARMensagens_exportado]  DEFAULT ((0)) FOR [exportado]
ALTER TABLE [tb_DeclaracoesDARPrecedentes] ADD  CONSTRAINT [DF_tb_DeclaracoesDARPrecedentes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesAutorizacoes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesAutorizacoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesContentores] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesContentores_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoes_montante]  DEFAULT ((0)) FOR [montante]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_tipoCalculo]  DEFAULT ((0)) FOR [tipoCalculo]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_taxaValor]  DEFAULT ((0)) FOR [taxaValor]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_quantidade]  DEFAULT ((0)) FOR [quantidade]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_valor]  DEFAULT ((0)) FOR [valor]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_montante]  DEFAULT ((0)) FOR [montante]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesIntervenientes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesIntervenientes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPedidos] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesPedidos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesPrecedentes_quantidade]  DEFAULT ((0)) FOR [quantidade]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAdicoesPrecedentes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesAutorizacoes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesAutorizacoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesDocumentos] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesDocumentos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesIncidencias] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesIncidencias_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesIntervenientes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesIntervenientes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesLocaisTransformacao] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesLocaisTransformacao_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesMeiosTransportePartida] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesMeiosTransportePartida_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesMensagens] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesMensagens_sucesso]  DEFAULT ((0)) FOR [sucesso]
ALTER TABLE [tb_EXP_DeclaracoesPrecedentes] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesPrecedentes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_EXP_DeclaracoesProdutosTransformados] ADD  CONSTRAINT [DF_tb_EXP_DeclaracoesProdutosTransformados_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_FAC_DocContasArquivos] ADD  CONSTRAINT [DF_tb_FAC_DocContasArquivos_anexarEmail]  DEFAULT ((0)) FOR [anexarEmail]
ALTER TABLE [tb_FAC_DocContasArquivos] ADD  CONSTRAINT [DF_tb_FAC_DocContasArquivos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_HistoricoDMG] ADD  CONSTRAINT [DF_tb_HistoricoDMG_sucesso]  DEFAULT ((0)) FOR [sucesso]
ALTER TABLE [tb_IMP_DeclaracoesAcrescimosDeducoes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAcrescimosDeducoes_montante]  DEFAULT ((0)) FOR [montante]
ALTER TABLE [tb_IMP_DeclaracoesAcrescimosDeducoes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAcrescimosDeducoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_montante]  DEFAULT ((0)) FOR [montante]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAdicoesEntrepostos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPedidos] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAdicoesPedidos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAdicoesPrecedentes_quantidade]  DEFAULT ((0)) FOR [quantidade]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAdicoesPrecedentes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesReferenciasFiscais] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesAdicoesReferenciasFiscais_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesCondicoesEconomicas] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesCondicoesEconomicas_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesDocumentos] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesDocumentos_montante]  DEFAULT ((0)) FOR [montante]
ALTER TABLE [tb_IMP_DeclaracoesDocumentos] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesDocumentos_quantidade]  DEFAULT ((0)) FOR [quantidade]
ALTER TABLE [tb_IMP_DeclaracoesDocumentos] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesDocumentos_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesEstancias] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesEstancias_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesIntervenientes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesIntervenientes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesLocaisTransformacao] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesLocaisTransformacao_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesMeiosIdentificacao] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesMeiosIdentificacao_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesPrecedentes] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesPrecedentes_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesProdutosTransformados] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesProdutosTransformados_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesProprietarios] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesProprietarios_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesReferenciasFiscais] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesReferenciasFiscais_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_IMP_DeclaracoesTaxasRendimento] ADD  CONSTRAINT [DF_tb_IMP_DeclaracoesTaxasRendimento_origem]  DEFAULT ((0)) FOR [origem]
ALTER TABLE [tb_TBL_HonorariosIMP] ADD  CONSTRAINT [DF_tb_TBL_HonorariosIMP_valorMercadoria]  DEFAULT ((0)) FOR [valorMercadoria]
ALTER TABLE [tb_TBL_HonorariosIMP] ADD  CONSTRAINT [DF_tb_TBL_HonorariosIMP_valorHonorarios]  DEFAULT ((0)) FOR [valorHonorarios]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_quantidade]  DEFAULT ((0)) FOR [quantidade]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_valorUnitario]  DEFAULT ((0)) FOR [valorUnitario]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_numeroVolumes]  DEFAULT ((0)) FOR [numeroVolumes]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_pesoUnitario]  DEFAULT ((0)) FOR [pesoUnitario]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_montante]  DEFAULT ((0)) FOR [montante]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_massaLiquida]  DEFAULT ((0)) FOR [massaLiquida]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_massaBruta]  DEFAULT ((0)) FOR [massaBruta]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_unidades]  DEFAULT ((0)) FOR [unidades]
ALTER TABLE [tb_TBL_LinhasOGMA] ADD  CONSTRAINT [DF_tb_TBL_LinhasOGMA_volumes]  DEFAULT ((0)) FOR [volumes]
ALTER TABLE [AEX_ENDG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENDG_PRO_EXML] FOREIGN KEY([EXM_EANO], [EXM_CODI], [DEC_CODI])
REFERENCES [PRO_EXML] ([EXM_EANO], [EXM_CODI], [DEC_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENDG] CHECK CONSTRAINT [FK_AEX_ENDG_PRO_EXML]
ALTER TABLE [AEX_ENDG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENDG_TAB_AGEN] FOREIGN KEY([AGE_CODI])
REFERENCES [TAB_AGEN] ([AGE_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENDG] CHECK CONSTRAINT [FK_AEX_ENDG_TAB_AGEN]
ALTER TABLE [AEX_ENDG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENDG_TAB_CLIE] FOREIGN KEY([CLI_CODI])
REFERENCES [TAB_CLIE] ([CLI_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENDG] CHECK CONSTRAINT [FK_AEX_ENDG_TAB_CLIE]
ALTER TABLE [AEX_ENDG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENDG_TAB_FORN] FOREIGN KEY([FOR_CODI])
REFERENCES [TAB_FORN] ([FOR_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENDG] CHECK CONSTRAINT [FK_AEX_ENDG_TAB_FORN]
ALTER TABLE [AEX_ENDG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENDG_TAB_LMER] FOREIGN KEY([LME_CODI])
REFERENCES [TAB_LMER] ([LME_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENDG] CHECK CONSTRAINT [FK_AEX_ENDG_TAB_LMER]
ALTER TABLE [AEX_ENDG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENDG_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENDG] CHECK CONSTRAINT [FK_AEX_ENDG_TAB_PAIS]
ALTER TABLE [AEX_ENDG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENDG_TAB_PAIS1] FOREIGN KEY([PAI_CODI1])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ALTER TABLE [AEX_ENDG] CHECK CONSTRAINT [FK_AEX_ENDG_TAB_PAIS1]
ALTER TABLE [AEX_ENLN]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENLN_AEX_ENDG] FOREIGN KEY([EDG_EANO], [LME_CODI], [EDG_NUME])
REFERENCES [AEX_ENDG] ([EDG_EANO], [LME_CODI], [EDG_NUME])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [AEX_ENLN] CHECK CONSTRAINT [FK_AEX_ENLN_AEX_ENDG]
ALTER TABLE [AEX_ENLN]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENLN_TAB_APAU] FOREIGN KEY([APA_CODI])
REFERENCES [TAB_APAU] ([APA_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENLN] CHECK CONSTRAINT [FK_AEX_ENLN_TAB_APAU]
ALTER TABLE [AEX_ENLN]  WITH CHECK ADD  CONSTRAINT [FK_AEX_ENLN_TAB_TEMB] FOREIGN KEY([TEM_CODI])
REFERENCES [TAB_TEMB] ([TEM_CODI])
ON UPDATE CASCADE
ALTER TABLE [AEX_ENLN] CHECK CONSTRAINT [FK_AEX_ENLN_TAB_TEMB]
ALTER TABLE [AEX_SADG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_SADG_AEX_ENDG] FOREIGN KEY([EDG_EANO], [LME_CODI], [EDG_NUME])
REFERENCES [AEX_ENDG] ([EDG_EANO], [LME_CODI], [EDG_NUME])
ON UPDATE CASCADE
ALTER TABLE [AEX_SADG] CHECK CONSTRAINT [FK_AEX_SADG_AEX_ENDG]
ALTER TABLE [AEX_SADG]  WITH CHECK ADD  CONSTRAINT [FK_AEX_SADG_TAB_LMER] FOREIGN KEY([LME_CODI])
REFERENCES [TAB_LMER] ([LME_CODI])
ALTER TABLE [AEX_SADG] CHECK CONSTRAINT [FK_AEX_SADG_TAB_LMER]
ALTER TABLE [FAC_CDOC]  WITH CHECK ADD  CONSTRAINT [FK_FAC_CDOC_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [FAC_CDOC] CHECK CONSTRAINT [FK_FAC_CDOC_DHL_CCOD]
ALTER TABLE [FAC_CDOC]  WITH CHECK ADD  CONSTRAINT [FK_FAC_CDOC_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ALTER TABLE [FAC_CDOC] CHECK CONSTRAINT [FK_FAC_CDOC_tb_DeclaracoesDAR]
ALTER TABLE [FAC_DCDO]  WITH CHECK ADD  CONSTRAINT [FK_FAC_DCDO_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [FAC_DCDO] CHECK CONSTRAINT [FK_FAC_DCDO_DHL_CCOD]
ALTER TABLE [FAC_DVDT]  WITH CHECK ADD  CONSTRAINT [FK_FAC_DVDT_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [FAC_DVDT] CHECK CONSTRAINT [FK_FAC_DVDT_DHL_CCOD]
ALTER TABLE [FAC_DVEN]  WITH CHECK ADD  CONSTRAINT [FK_FAC_DVEN_tb_DeclaracoesDAR] FOREIGN KEY([DVE_IDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ALTER TABLE [FAC_DVEN] CHECK CONSTRAINT [FK_FAC_DVEN_tb_DeclaracoesDAR]
ALTER TABLE [FAC_ICDO]  WITH CHECK ADD  CONSTRAINT [FK_FAC_ICDO_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [FAC_ICDO] CHECK CONSTRAINT [FK_FAC_ICDO_DHL_CCOD]
ALTER TABLE [HST_SDSI]  WITH CHECK ADD  CONSTRAINT [FK_HST_SDSI_PRO_SDSC] FOREIGN KEY([DSC_EANO], [DSC_NPRO])
REFERENCES [PRO_SDSC] ([DSC_EANO], [DSC_NPRO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [HST_SDSI] CHECK CONSTRAINT [FK_HST_SDSI_PRO_SDSC]
ALTER TABLE [INT_LNCC]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCC_TAB_CLIE] FOREIGN KEY([CLI_CODI])
REFERENCES [TAB_CLIE] ([CLI_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCC] CHECK CONSTRAINT [FK_INT_LNCC_TAB_CLIE]
ALTER TABLE [INT_LNCC]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCC_TAB_DECL] FOREIGN KEY([DEC_CODI])
REFERENCES [TAB_DECL] ([DEC_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCC] CHECK CONSTRAINT [FK_INT_LNCC_TAB_DECL]
ALTER TABLE [INT_LNCC]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCC_TAB_FORN] FOREIGN KEY([FOR_CODI])
REFERENCES [TAB_FORN] ([FOR_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCC] CHECK CONSTRAINT [FK_INT_LNCC_TAB_FORN]
ALTER TABLE [INT_LNCC]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCC_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCC] CHECK CONSTRAINT [FK_INT_LNCC_TAB_PAIS]
ALTER TABLE [INT_LNCC]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCC_TAB_PAIS1] FOREIGN KEY([PAI_CODI1])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ALTER TABLE [INT_LNCC] CHECK CONSTRAINT [FK_INT_LNCC_TAB_PAIS1]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_INT_LNCC] FOREIGN KEY([LNC_EANO], [LNC_NUME])
REFERENCES [INT_LNCC] ([LNC_EANO], [LNC_NUME])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_INT_LNCC]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_CENT] FOREIGN KEY([CEN_CODI])
REFERENCES [TAB_CENT] ([CEN_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_CENT]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_MTRA] FOREIGN KEY([MTR_CODI])
REFERENCES [TAB_MTRA] ([MTR_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_MTRA]
ALTER TABLE [INT_LNCD]  WITH NOCHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_NNC8] FOREIGN KEY([LNC_EANO], [NC8_CODI])
REFERENCES [TAB_NNC8] ([NC8_EANO], [NC8_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_NNC8]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_NTRA] FOREIGN KEY([NTR_CODI])
REFERENCES [TAB_NTRA] ([NTR_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_NTRA]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_PAER] FOREIGN KEY([PAE_CODI])
REFERENCES [TAB_PAER] ([PAE_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_PAER]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_PAIS]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_PAIS1] FOREIGN KEY([PAI_CODI1])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_PAIS1]
ALTER TABLE [INT_LNCD]  WITH CHECK ADD  CONSTRAINT [FK_INT_LNCD_TAB_REST] FOREIGN KEY([RES_CODI])
REFERENCES [TAB_REST] ([RES_CODI])
ON UPDATE CASCADE
ALTER TABLE [INT_LNCD] CHECK CONSTRAINT [FK_INT_LNCD_TAB_REST]
ALTER TABLE [PRO_DCON]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DCON_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DCON] CHECK CONSTRAINT [FK_PRO_DCON_PRO_DUAD]
ALTER TABLE [PRO_DDOC]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DDOC_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DDOC] CHECK CONSTRAINT [FK_PRO_DDOC_PRO_DUAD]
ALTER TABLE [PRO_DSAC]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSAC_PRO_DSSA] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
REFERENCES [PRO_DSSA] ([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DSAC] CHECK CONSTRAINT [FK_PRO_DSAC_PRO_DSSA]
ALTER TABLE [PRO_DSAD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSAD_PRO_DSSA] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
REFERENCES [PRO_DSSA] ([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DSAD] CHECK CONSTRAINT [FK_PRO_DSAD_PRO_DSSA]
ALTER TABLE [PRO_DSAM]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSAM_PRO_DSSA] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
REFERENCES [PRO_DSSA] ([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DSAM] CHECK CONSTRAINT [FK_PRO_DSAM_PRO_DSSA]
ALTER TABLE [PRO_DSAS]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSAS_PRO_DSSA] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
REFERENCES [PRO_DSSA] ([DSS_EANO], [DCS_CODI], [DSS_NPRO], [DSA_NUME])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DSAS] CHECK CONSTRAINT [FK_PRO_DSAS_PRO_DSSA]
ALTER TABLE [PRO_DSSA]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSSA_PRO_DESS] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO])
REFERENCES [PRO_DESS] ([DSS_EANO], [DCS_CODI], [DSS_NPRO])
ON DELETE CASCADE
ALTER TABLE [PRO_DSSA] CHECK CONSTRAINT [FK_PRO_DSSA_PRO_DESS]
ALTER TABLE [PRO_DSSA]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSSA_PRO_SDSD] FOREIGN KEY([DSD_IDNN])
REFERENCES [PRO_SDSD] ([DSD_IDNN])
ALTER TABLE [PRO_DSSA] CHECK CONSTRAINT [FK_PRO_DSSA_PRO_SDSD]
ALTER TABLE [PRO_DSSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSSD_PRO_DESS] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO])
REFERENCES [PRO_DESS] ([DSS_EANO], [DCS_CODI], [DSS_NPRO])
ON DELETE CASCADE
ALTER TABLE [PRO_DSSD] CHECK CONSTRAINT [FK_PRO_DSSD_PRO_DESS]
ALTER TABLE [PRO_DSSI]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSSI_PRO_DESS] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO])
REFERENCES [PRO_DESS] ([DSS_EANO], [DCS_CODI], [DSS_NPRO])
ON DELETE CASCADE
ALTER TABLE [PRO_DSSI] CHECK CONSTRAINT [FK_PRO_DSSI_PRO_DESS]
ALTER TABLE [PRO_DSSS]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DSSS_PRO_DESS] FOREIGN KEY([DSS_EANO], [DCS_CODI], [DSS_NPRO])
REFERENCES [PRO_DESS] ([DSS_EANO], [DCS_CODI], [DSS_NPRO])
ON DELETE CASCADE
ALTER TABLE [PRO_DSSS] CHECK CONSTRAINT [FK_PRO_DSSS_PRO_DESS]
ALTER TABLE [PRO_DU31]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DU31_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DU31] CHECK CONSTRAINT [FK_PRO_DU31_PRO_DUAD]
ALTER TABLE [PRO_DUAD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUAD_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUAD] CHECK CONSTRAINT [FK_PRO_DUAD_PRO_DUCG]
ALTER TABLE [PRO_DUAD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUAD_tb_TBL_Desdobramentos] FOREIGN KEY([id_desdobramento])
REFERENCES [tb_TBL_Desdobramentos] ([id])
ALTER TABLE [PRO_DUAD] CHECK CONSTRAINT [FK_PRO_DUAD_tb_TBL_Desdobramentos]
ALTER TABLE [PRO_DUBT]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUBT_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUBT] CHECK CONSTRAINT [FK_PRO_DUBT_PRO_DUAD]
ALTER TABLE [PRO_DUCG]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUCG_PRO_NSTI] FOREIGN KEY([NST_CODI], [NST_EANO], [CLI_OPER])
REFERENCES [PRO_NSTI] ([NST_CODI], [NST_EANO], [CLI_OPER])
ON UPDATE CASCADE
ALTER TABLE [PRO_DUCG] CHECK CONSTRAINT [FK_PRO_DUCG_PRO_NSTI]
ALTER TABLE [PRO_DUCN]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUCN_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUCN] CHECK CONSTRAINT [FK_PRO_DUCN_PRO_DUCG]
ALTER TABLE [PRO_DUDA]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUDA_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUDA] CHECK CONSTRAINT [FK_PRO_DUDA_PRO_DUCG]
ALTER TABLE [PRO_DUDA]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUDA_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_DUDA] CHECK CONSTRAINT [FK_PRO_DUDA_TAB_EADU]
ALTER TABLE [PRO_DUDD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUDD_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUDD] CHECK CONSTRAINT [FK_PRO_DUDD_PRO_DUCG]
ALTER TABLE [PRO_DUET]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUET_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUET] CHECK CONSTRAINT [FK_PRO_DUET_PRO_DUAD]
ALTER TABLE [PRO_DUET]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUET_TAB_UMED] FOREIGN KEY([UME_CODI])
REFERENCES [TAB_UMED] ([UME_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_DUET] CHECK CONSTRAINT [FK_PRO_DUET_TAB_UMED]
ALTER TABLE [PRO_DUFI]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUFI_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUFI] CHECK CONSTRAINT [FK_PRO_DUFI_PRO_DUCG]
ALTER TABLE [PRO_DUFW]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUFW_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUFW] CHECK CONSTRAINT [FK_PRO_DUFW_PRO_DUCG]
ALTER TABLE [PRO_DUIN]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUIN_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUIN] CHECK CONSTRAINT [FK_PRO_DUIN_PRO_DUCG]
ALTER TABLE [PRO_DUIT]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUIT_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUIT] CHECK CONSTRAINT [FK_PRO_DUIT_PRO_DUAD]
ALTER TABLE [PRO_DUIT]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUIT_TAB_UMED] FOREIGN KEY([UME_CODI])
REFERENCES [TAB_UMED] ([UME_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_DUIT] CHECK CONSTRAINT [FK_PRO_DUIT_TAB_UMED]
ALTER TABLE [PRO_DULO]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DULO_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DULO] CHECK CONSTRAINT [FK_PRO_DULO_PRO_DUCG]
ALTER TABLE [PRO_DULO]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DULO_TAB_RREC] FOREIGN KEY([RRE_CODI])
REFERENCES [TAB_RREC] ([RRE_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_DULO] CHECK CONSTRAINT [FK_PRO_DULO_TAB_RREC]
ALTER TABLE [PRO_DULR]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DULR_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DULR] CHECK CONSTRAINT [FK_PRO_DULR_PRO_DUCG]
ALTER TABLE [PRO_DUMI]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUMI_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUMI] CHECK CONSTRAINT [FK_PRO_DUMI_PRO_DUAD]
ALTER TABLE [PRO_DUOI]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUOI_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUOI] CHECK CONSTRAINT [FK_PRO_DUOI_PRO_DUAD]
ALTER TABLE [PRO_DUPD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUPD_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUPD] CHECK CONSTRAINT [FK_PRO_DUPD_PRO_DUCG]
ALTER TABLE [PRO_DUPD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUPD_TAB_TXML] FOREIGN KEY([TXM_CODI])
REFERENCES [TAB_TXML] ([TXM_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_DUPD] CHECK CONSTRAINT [FK_PRO_DUPD_TAB_TXML]
ALTER TABLE [PRO_DURA]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DURA_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DURA] CHECK CONSTRAINT [FK_PRO_DURA_PRO_DUAD]
ALTER TABLE [PRO_DURP]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DURP_PRO_DUCG] FOREIGN KEY([DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUCG] ([DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DURP] CHECK CONSTRAINT [FK_PRO_DURP_PRO_DUCG]
ALTER TABLE [PRO_DUVE]  WITH CHECK ADD  CONSTRAINT [FK_PRO_DUVE_PRO_DUAD] FOREIGN KEY([DUA_CODI], [DUC_PNUM], [DUC_EANO])
REFERENCES [PRO_DUAD] ([DUA_CODI], [DUC_PNUM], [DUC_EANO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_DUVE] CHECK CONSTRAINT [FK_PRO_DUVE_PRO_DUAD]
ALTER TABLE [PRO_EXAD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_EXAD_tb_TBL_Desdobramentos] FOREIGN KEY([id_desdobramento])
REFERENCES [tb_TBL_Desdobramentos] ([id])
ALTER TABLE [PRO_EXAD] CHECK CONSTRAINT [FK_PRO_EXAD_tb_TBL_Desdobramentos]
ALTER TABLE [PRO_EXCD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_EXCD_TAB_TEMB] FOREIGN KEY([TEM_CODI])
REFERENCES [TAB_TEMB] ([TEM_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_EXCD] CHECK CONSTRAINT [FK_PRO_EXCD_TAB_TEMB]
ALTER TABLE [PRO_EXDA]  WITH CHECK ADD  CONSTRAINT [FK_PRO_EXDA_PRO_EXAD] FOREIGN KEY([EXA_CHVE], [EXM_EANO], [EXM_COPE], [EXM_CODI], [EXA_LINH])
REFERENCES [PRO_EXAD] ([EXA_CHVE], [EXM_EANO], [EXM_COPE], [EXM_CODI], [EXA_LINH])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_EXDA] CHECK CONSTRAINT [FK_PRO_EXDA_PRO_EXAD]
ALTER TABLE [PRO_EXFW]  WITH CHECK ADD  CONSTRAINT [FK_PRO_EXFW_PRO_EXML] FOREIGN KEY([EXM_EANO], [EXM_CODI], [EXM_COPE])
REFERENCES [PRO_EXML] ([EXM_EANO], [EXM_CODI], [DEC_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_EXFW] CHECK CONSTRAINT [FK_PRO_EXFW_PRO_EXML]
ALTER TABLE [PRO_EXIC]  WITH CHECK ADD  CONSTRAINT [FK_PRO_EXIC_PRO_EXAD] FOREIGN KEY([EXA_CHVE])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_EXIC] CHECK CONSTRAINT [FK_PRO_EXIC_PRO_EXAD]
ALTER TABLE [PRO_EXML]  WITH CHECK ADD  CONSTRAINT [FK_PRO_EXML_PRO_NSTI] FOREIGN KEY([NST_CODI], [NST_EANO], [CLI_OPER])
REFERENCES [PRO_NSTI] ([NST_CODI], [NST_EANO], [CLI_OPER])
ON UPDATE CASCADE
ALTER TABLE [PRO_EXML] CHECK CONSTRAINT [FK_PRO_EXML_PRO_NSTI]
ALTER TABLE [PRO_GSSL]  WITH CHECK ADD  CONSTRAINT [FK_PRO_GSSL_PRO_NSTI] FOREIGN KEY([NST_CODI], [NST_EANO], [CLI_OPER])
REFERENCES [PRO_NSTI] ([NST_CODI], [NST_EANO], [CLI_OPER])
ON UPDATE CASCADE
ALTER TABLE [PRO_GSSL] CHECK CONSTRAINT [FK_PRO_GSSL_PRO_NSTI]
ALTER TABLE [PRO_MCAU]  WITH CHECK ADD  CONSTRAINT [FK_PRO_MCAU_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ALTER TABLE [PRO_MCAU] CHECK CONSTRAINT [FK_PRO_MCAU_tb_DeclaracoesDAR]
ALTER TABLE [PRO_SDSC]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSC_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSC] CHECK CONSTRAINT [FK_PRO_SDSC_TAB_EADU]
ALTER TABLE [PRO_SDSC]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSC_TAB_EADU1] FOREIGN KEY([EAD_CODI1])
REFERENCES [TAB_EADU] ([EAD_CODI])
ALTER TABLE [PRO_SDSC] CHECK CONSTRAINT [FK_PRO_SDSC_TAB_EADU1]
ALTER TABLE [PRO_SDSC]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSC_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ALTER TABLE [PRO_SDSC] CHECK CONSTRAINT [FK_PRO_SDSC_TAB_PAIS]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_PRO_EXAD] FOREIGN KEY([EXA_CHVE])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_PRO_EXAD]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_PRO_SDSC] FOREIGN KEY([DSC_EANO], [DSC_NPRO])
REFERENCES [PRO_SDSC] ([DSC_EANO], [DSC_NPRO])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_PRO_SDSC]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_APAU] FOREIGN KEY([APA_CODI])
REFERENCES [TAB_APAU] ([APA_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_APAU]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_DOCU] FOREIGN KEY([DOC_CODI])
REFERENCES [TAB_DOCU] ([DOC_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_DOCU]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_LMER] FOREIGN KEY([LME_CODI])
REFERENCES [TAB_LMER] ([LME_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_LMER]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_PAER] FOREIGN KEY([PAE_CODI])
REFERENCES [TAB_PAER] ([PAE_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_PAER]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_PAER1] FOREIGN KEY([PAE_CODI1])
REFERENCES [TAB_PAER] ([PAE_CODI])
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_PAER1]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_PAER2] FOREIGN KEY([PAE_CODI2])
REFERENCES [TAB_PAER] ([PAE_CODI])
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_PAER2]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_PAER3] FOREIGN KEY([PAE_CODI3])
REFERENCES [TAB_PAER] ([PAE_CODI])
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_PAER3]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_PAIS]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_TEMB] FOREIGN KEY([TEM_CODI])
REFERENCES [TAB_TEMB] ([TEM_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_TEMB]
ALTER TABLE [PRO_SDSD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SDSD_TAB_TXML] FOREIGN KEY([TXM_CODI])
REFERENCES [TAB_TXML] ([TXM_CODI])
ON UPDATE CASCADE
ALTER TABLE [PRO_SDSD] CHECK CONSTRAINT [FK_PRO_SDSD_TAB_TXML]
ALTER TABLE [PRO_SSDD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SSDD_PRO_SDSD] FOREIGN KEY([DSC_EANO], [DSC_NPRO], [DSD_NUME])
REFERENCES [PRO_SDSD] ([DSC_EANO], [DSC_NPRO], [DSD_NUME])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [PRO_SSDD] CHECK CONSTRAINT [FK_PRO_SSDD_PRO_SDSD]
ALTER TABLE [PRO_SSDD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SSDD_TAB_DOCU] FOREIGN KEY([DOC_CODI])
REFERENCES [TAB_DOCU] ([DOC_CODI])
ALTER TABLE [PRO_SSDD] CHECK CONSTRAINT [FK_PRO_SSDD_TAB_DOCU]
ALTER TABLE [PRO_SSDD]  WITH CHECK ADD  CONSTRAINT [FK_PRO_SSDD_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ALTER TABLE [PRO_SSDD] CHECK CONSTRAINT [FK_PRO_SSDD_TAB_EADU]
ALTER TABLE [TAB_ADUM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_ADUM_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_ADUM] CHECK CONSTRAINT [FK_TAB_ADUM_TAB_PAIS]
ALTER TABLE [TAB_ADUM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_ADUM_TAB_RREC] FOREIGN KEY([RRE_CODI])
REFERENCES [TAB_RREC] ([RRE_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_ADUM] CHECK CONSTRAINT [FK_TAB_ADUM_TAB_RREC]
ALTER TABLE [TAB_AETR]  WITH CHECK ADD  CONSTRAINT [FK_TAB_AETR_TAB_RREC] FOREIGN KEY([RRE_CODI])
REFERENCES [TAB_RREC] ([RRE_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_AETR] CHECK CONSTRAINT [FK_TAB_AETR_TAB_RREC]
ALTER TABLE [TAB_AETR]  WITH CHECK ADD  CONSTRAINT [FK_TAB_AETR_TAB_UMED] FOREIGN KEY([UME_CODI])
REFERENCES [TAB_UMED] ([UME_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_AETR] CHECK CONSTRAINT [FK_TAB_AETR_TAB_UMED]
ALTER TABLE [TAB_ALFA]  WITH CHECK ADD  CONSTRAINT [FK_TAB_ALFA_TAB_PAER] FOREIGN KEY([PAE_CODI])
REFERENCES [TAB_PAER] ([PAE_CODI])
ALTER TABLE [TAB_ALFA] CHECK CONSTRAINT [FK_TAB_ALFA_TAB_PAER]
ALTER TABLE [TAB_ALFM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_ALFM_TAB_ALFA] FOREIGN KEY([ALF_CODI])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_ALFM] CHECK CONSTRAINT [FK_TAB_ALFM_TAB_ALFA]
ALTER TABLE [TAB_ALFM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_ALFM_TAB_INFC] FOREIGN KEY([INF_CODI])
REFERENCES [TAB_INFC] ([INF_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_ALFM] CHECK CONSTRAINT [FK_TAB_ALFM_TAB_INFC]
ALTER TABLE [TAB_AMEN]  WITH CHECK ADD  CONSTRAINT [FK_TAB_AMEN_TAB_INFC] FOREIGN KEY([INF_CODI])
REFERENCES [TAB_INFC] ([INF_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_AMEN] CHECK CONSTRAINT [FK_TAB_AMEN_TAB_INFC]
ALTER TABLE [TAB_ARMZ]  WITH CHECK ADD  CONSTRAINT [FK_TAB_ARMZ_TAB_DOCU] FOREIGN KEY([DOC_CODI])
REFERENCES [TAB_DOCU] ([DOC_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_ARMZ] CHECK CONSTRAINT [FK_TAB_ARMZ_TAB_DOCU]
ALTER TABLE [TAB_ARMZ]  WITH CHECK ADD  CONSTRAINT [FK_TAB_ARMZ_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_ARMZ] CHECK CONSTRAINT [FK_TAB_ARMZ_TAB_EADU]
ALTER TABLE [TAB_CLAU]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLAU_TAB_CLIE] FOREIGN KEY([CLI_CODI])
REFERENCES [TAB_CLIE] ([CLI_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLAU] CHECK CONSTRAINT [FK_TAB_CLAU_TAB_CLIE]
ALTER TABLE [TAB_CLAU]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLAU_TAB_DOCU] FOREIGN KEY([DOC_CODI])
REFERENCES [TAB_DOCU] ([DOC_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLAU] CHECK CONSTRAINT [FK_TAB_CLAU_TAB_DOCU]
ALTER TABLE [TAB_CLDO]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLDO_TAB_CLIE] FOREIGN KEY([CLI_CODI])
REFERENCES [TAB_CLIE] ([CLI_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLDO] CHECK CONSTRAINT [FK_TAB_CLDO_TAB_CLIE]
ALTER TABLE [TAB_CLDO]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLDO_TAB_DOCU] FOREIGN KEY([DOC_CODI])
REFERENCES [TAB_DOCU] ([DOC_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLDO] CHECK CONSTRAINT [FK_TAB_CLDO_TAB_DOCU]
ALTER TABLE [TAB_CLFA]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLFA_TAB_APAU] FOREIGN KEY([APA_CODI])
REFERENCES [TAB_APAU] ([APA_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLFA] CHECK CONSTRAINT [FK_TAB_CLFA_TAB_APAU]
ALTER TABLE [TAB_CLFA]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLFA_TAB_CLIE] FOREIGN KEY([CLI_CODI])
REFERENCES [TAB_CLIE] ([CLI_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLFA] CHECK CONSTRAINT [FK_TAB_CLFA_TAB_CLIE]
ALTER TABLE [TAB_CLFA]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLFA_TAB_FORN] FOREIGN KEY([FOR_CODI])
REFERENCES [TAB_FORN] ([FOR_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLFA] CHECK CONSTRAINT [FK_TAB_CLFA_TAB_FORN]
ALTER TABLE [TAB_CLFI]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLFI_TAB_CLIE] FOREIGN KEY([CLI_CODI])
REFERENCES [TAB_CLIE] ([CLI_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_CLFI] CHECK CONSTRAINT [FK_TAB_CLFI_TAB_CLIE]
ALTER TABLE [TAB_CLIE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLIE_TAB_ALFA] FOREIGN KEY([ALF_CODI1])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_CLIE] CHECK CONSTRAINT [FK_TAB_CLIE_TAB_ALFA]
ALTER TABLE [TAB_CLIE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLIE_TAB_ALFA1] FOREIGN KEY([ALF_CODI2])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_CLIE] CHECK CONSTRAINT [FK_TAB_CLIE_TAB_ALFA1]
ALTER TABLE [TAB_CLIE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLIE_TAB_ALFA2] FOREIGN KEY([ALF_CODI3])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_CLIE] CHECK CONSTRAINT [FK_TAB_CLIE_TAB_ALFA2]
ALTER TABLE [TAB_CLIE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLIE_TAB_ALFA3] FOREIGN KEY([ALF_CODI4])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_CLIE] CHECK CONSTRAINT [FK_TAB_CLIE_TAB_ALFA3]
ALTER TABLE [TAB_CLIE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLIE_TAB_ALFA4] FOREIGN KEY([ALF_CODI5])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_CLIE] CHECK CONSTRAINT [FK_TAB_CLIE_TAB_ALFA4]
ALTER TABLE [TAB_CLIE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLIE_TAB_DECL] FOREIGN KEY([DEC_CODI])
REFERENCES [TAB_DECL] ([DEC_CODI])
ALTER TABLE [TAB_CLIE] CHECK CONSTRAINT [FK_TAB_CLIE_TAB_DECL]
ALTER TABLE [TAB_CLIE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_CLIE_TAB_DINE] FOREIGN KEY([DIN_CODI1])
REFERENCES [TAB_DINE] ([DIN_CODI])
ALTER TABLE [TAB_CLIE] CHECK CONSTRAINT [FK_TAB_CLIE_TAB_DINE]
ALTER TABLE [TAB_DCSR]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DCSR_TAB_DECS] FOREIGN KEY([DCS_CODI])
REFERENCES [TAB_DECS] ([DCS_CODI])
ON DELETE CASCADE
ALTER TABLE [TAB_DCSR] CHECK CONSTRAINT [FK_TAB_DCSR_TAB_DECS]
ALTER TABLE [TAB_DDOC]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DDOC_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_DDOC] CHECK CONSTRAINT [FK_TAB_DDOC_DHL_CCOD]
ALTER TABLE [TAB_DECL]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECL_TAB_ALFA] FOREIGN KEY([ALF_CODI1])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_DECL] CHECK CONSTRAINT [FK_TAB_DECL_TAB_ALFA]
ALTER TABLE [TAB_DECL]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECL_TAB_ALFA1] FOREIGN KEY([ALF_CODI2])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_DECL] CHECK CONSTRAINT [FK_TAB_DECL_TAB_ALFA1]
ALTER TABLE [TAB_DECL]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECL_TAB_ALFA2] FOREIGN KEY([ALF_CODI3])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_DECL] CHECK CONSTRAINT [FK_TAB_DECL_TAB_ALFA2]
ALTER TABLE [TAB_DECL]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECL_TAB_ALFA3] FOREIGN KEY([ALF_CODI4])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_DECL] CHECK CONSTRAINT [FK_TAB_DECL_TAB_ALFA3]
ALTER TABLE [TAB_DECL]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECL_TAB_ALFA4] FOREIGN KEY([ALF_CODI5])
REFERENCES [TAB_ALFA] ([ALF_CODI])
ALTER TABLE [TAB_DECL] CHECK CONSTRAINT [FK_TAB_DECL_TAB_ALFA4]
ALTER TABLE [TAB_DECL]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECL_TAB_DOCU] FOREIGN KEY([DOC_CODI2])
REFERENCES [TAB_DOCU] ([DOC_CODI])
ALTER TABLE [TAB_DECL] CHECK CONSTRAINT [FK_TAB_DECL_TAB_DOCU]
ALTER TABLE [TAB_DECR]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECR_TAB_DECL] FOREIGN KEY([DEC_CODI])
REFERENCES [TAB_DECL] ([DEC_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_DECR] CHECK CONSTRAINT [FK_TAB_DECR_TAB_DECL]
ALTER TABLE [TAB_DECR]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DECR_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ALTER TABLE [TAB_DECR] CHECK CONSTRAINT [FK_TAB_DECR_TAB_EADU]
ALTER TABLE [TAB_DINE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DINE_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_DINE] CHECK CONSTRAINT [FK_TAB_DINE_DHL_CCOD]
ALTER TABLE [TAB_DOCU]  WITH CHECK ADD  CONSTRAINT [FK_TAB_DOCU_TAB_INFC] FOREIGN KEY([INF_CODI])
REFERENCES [TAB_INFC] ([INF_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_DOCU] CHECK CONSTRAINT [FK_TAB_DOCU_TAB_INFC]
ALTER TABLE [TAB_EADM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_EADM_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_EADM] CHECK CONSTRAINT [FK_TAB_EADM_TAB_EADU]
ALTER TABLE [TAB_EADM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_EADM_TAB_INFC] FOREIGN KEY([INF_CODI])
REFERENCES [TAB_INFC] ([INF_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_EADM] CHECK CONSTRAINT [FK_TAB_EADM_TAB_INFC]
ALTER TABLE [TAB_LEMB]  WITH CHECK ADD  CONSTRAINT [FK_TAB_LEMB_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_LEMB] CHECK CONSTRAINT [FK_TAB_LEMB_TAB_EADU]
ALTER TABLE [TAB_LMER]  WITH CHECK ADD  CONSTRAINT [FK_TAB_LMER_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ALTER TABLE [TAB_LMER] CHECK CONSTRAINT [FK_TAB_LMER_TAB_PAIS]
ALTER TABLE [TAB_MTRO]  WITH CHECK ADD  CONSTRAINT [FK_TAB_MTRO_TAB_MTRA] FOREIGN KEY([MTR_IDTY])
REFERENCES [TAB_MTRA] ([MTR_IDTY])
ON DELETE CASCADE
ALTER TABLE [TAB_MTRO] CHECK CONSTRAINT [FK_TAB_MTRO_TAB_MTRA]
ALTER TABLE [TAB_NDES]  WITH CHECK ADD  CONSTRAINT [FK_TAB_NDES_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_NDES] CHECK CONSTRAINT [FK_TAB_NDES_DHL_CCOD]
ALTER TABLE [TAB_NDES]  WITH CHECK ADD  CONSTRAINT [FK_TAB_NDES_TAB_NDES] FOREIGN KEY([NDE_CODI1])
REFERENCES [TAB_NDES] ([NDE_CODI])
ALTER TABLE [TAB_NDES] CHECK CONSTRAINT [FK_TAB_NDES_TAB_NDES]
ALTER TABLE [TAB_NDES]  WITH CHECK ADD  CONSTRAINT [FK_TAB_NDES_TAB_NDES1] FOREIGN KEY([NDE_CODI2])
REFERENCES [TAB_NDES] ([NDE_CODI])
ALTER TABLE [TAB_NDES] CHECK CONSTRAINT [FK_TAB_NDES_TAB_NDES1]
ALTER TABLE [TAB_NDES]  WITH CHECK ADD  CONSTRAINT [FK_TAB_NDES_TAB_NDES2] FOREIGN KEY([NDE_CODI3])
REFERENCES [TAB_NDES] ([NDE_CODI])
ALTER TABLE [TAB_NDES] CHECK CONSTRAINT [FK_TAB_NDES_TAB_NDES2]
ALTER TABLE [TAB_NDES]  WITH CHECK ADD  CONSTRAINT [FK_TAB_NDES_TAB_PCBT] FOREIGN KEY([CBT_IDEN])
REFERENCES [TAB_PCBT] ([CBT_IDEN])
ON UPDATE CASCADE
ALTER TABLE [TAB_NDES] CHECK CONSTRAINT [FK_TAB_NDES_TAB_PCBT]
ALTER TABLE [TAB_PCBE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBE_TAB_CLIE] FOREIGN KEY([CLI_CODI])
REFERENCES [TAB_CLIE] ([CLI_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PCBE] CHECK CONSTRAINT [FK_TAB_PCBE_TAB_CLIE]
ALTER TABLE [TAB_PCBE]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBE_TAB_PCBT] FOREIGN KEY([CBT_IDEN])
REFERENCES [TAB_PCBT] ([CBT_IDEN])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PCBE] CHECK CONSTRAINT [FK_TAB_PCBE_TAB_PCBT]
ALTER TABLE [TAB_PCBI]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBI_TAB_DINE] FOREIGN KEY([DIN_CODI])
REFERENCES [TAB_DINE] ([DIN_CODI])
ALTER TABLE [TAB_PCBI] CHECK CONSTRAINT [FK_TAB_PCBI_TAB_DINE]
ALTER TABLE [TAB_PCBI]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBI_TAB_DINE1] FOREIGN KEY([DIN_CODI1])
REFERENCES [TAB_DINE] ([DIN_CODI])
ALTER TABLE [TAB_PCBI] CHECK CONSTRAINT [FK_TAB_PCBI_TAB_DINE1]
ALTER TABLE [TAB_PCBI]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBI_TAB_DINE2] FOREIGN KEY([DIN_CODI2])
REFERENCES [TAB_DINE] ([DIN_CODI])
ALTER TABLE [TAB_PCBI] CHECK CONSTRAINT [FK_TAB_PCBI_TAB_DINE2]
ALTER TABLE [TAB_PCBI]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBI_TAB_DINE3] FOREIGN KEY([DIN_CODI3])
REFERENCES [TAB_DINE] ([DIN_CODI])
ALTER TABLE [TAB_PCBI] CHECK CONSTRAINT [FK_TAB_PCBI_TAB_DINE3]
ALTER TABLE [TAB_PCBL]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBL_TAB_PCBT] FOREIGN KEY([CBT_IDEN])
REFERENCES [TAB_PCBT] ([CBT_IDEN])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PCBL] CHECK CONSTRAINT [FK_TAB_PCBL_TAB_PCBT]
ALTER TABLE [TAB_PCBT]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBT_TAB_PCBI] FOREIGN KEY([CBI_IDEN])
REFERENCES [TAB_PCBI] ([CBI_IDEN])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PCBT] CHECK CONSTRAINT [FK_TAB_PCBT_TAB_PCBI]
ALTER TABLE [TAB_PCBX]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PCBX_TAB_PCBE] FOREIGN KEY([CBE_IDEN])
REFERENCES [TAB_PCBE] ([CBE_IDEN])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PCBX] CHECK CONSTRAINT [FK_TAB_PCBX_TAB_PCBE]
ALTER TABLE [TAB_PDCA]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PDCA_TAB_PDES] FOREIGN KEY([PDE_CODI])
REFERENCES [TAB_PDES] ([PDE_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PDCA] CHECK CONSTRAINT [FK_TAB_PDCA_TAB_PDES]
ALTER TABLE [TAB_PDER]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PDER_TAB_PDES] FOREIGN KEY([PDE_CODI])
REFERENCES [TAB_PDES] ([PDE_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PDER] CHECK CONSTRAINT [FK_TAB_PDER_TAB_PDES]
ALTER TABLE [TAB_PDTP]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PDTP_TAB_PDES] FOREIGN KEY([PDE_CODI])
REFERENCES [TAB_PDES] ([PDE_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PDTP] CHECK CONSTRAINT [FK_TAB_PDTP_TAB_PDES]
ALTER TABLE [TAB_PFTI]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PFTI_TAB_PFTA] FOREIGN KEY([FTA_IDEN])
REFERENCES [TAB_PFTA] ([FTA_IDEN])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_PFTI] CHECK CONSTRAINT [FK_TAB_PFTI_TAB_PFTA]
ALTER TABLE [TAB_PFTI]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PFTI_TAB_TDOC] FOREIGN KEY([TDO_DOCU])
REFERENCES [TAB_TDOC] ([TDO_DOCU])
ON UPDATE CASCADE
ALTER TABLE [TAB_PFTI] CHECK CONSTRAINT [FK_TAB_PFTI_TAB_TDOC]
ALTER TABLE [TAB_PSDD]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDD_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_PSDD] CHECK CONSTRAINT [FK_TAB_PSDD_TAB_EADU]
ALTER TABLE [TAB_PSDD]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDD_TAB_LMER] FOREIGN KEY([LME_CODI])
REFERENCES [TAB_LMER] ([LME_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_PSDD] CHECK CONSTRAINT [FK_TAB_PSDD_TAB_LMER]
ALTER TABLE [TAB_PSDD]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDD_TAB_LMER1] FOREIGN KEY([LME_CODI1])
REFERENCES [TAB_LMER] ([LME_CODI])
ALTER TABLE [TAB_PSDD] CHECK CONSTRAINT [FK_TAB_PSDD_TAB_LMER1]
ALTER TABLE [TAB_PSDD]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDD_TAB_PSDS] FOREIGN KEY([PSD_IDEN])
REFERENCES [TAB_PSDS] ([PSD_IDEN])
ON DELETE CASCADE
ALTER TABLE [TAB_PSDD] CHECK CONSTRAINT [FK_TAB_PSDD_TAB_PSDS]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_EADU] FOREIGN KEY([EAD_CODI])
REFERENCES [TAB_EADU] ([EAD_CODI])
ON UPDATE CASCADE
ON DELETE SET NULL
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_EADU]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_EADU1] FOREIGN KEY([EAD_CODI1])
REFERENCES [TAB_EADU] ([EAD_CODI])
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_EADU1]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_EADU2] FOREIGN KEY([EAD_CODI2])
REFERENCES [TAB_EADU] ([EAD_CODI])
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_EADU2]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_LMER] FOREIGN KEY([LME_CODI])
REFERENCES [TAB_LMER] ([LME_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_LMER]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_LMER1] FOREIGN KEY([LME_CODI1])
REFERENCES [TAB_LMER] ([LME_CODI])
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_LMER1]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_LMER2] FOREIGN KEY([LME_CODI2])
REFERENCES [TAB_LMER] ([LME_CODI])
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_LMER2]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_LMER3] FOREIGN KEY([LME_CODI3])
REFERENCES [TAB_LMER] ([LME_CODI])
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_LMER3]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_PAER] FOREIGN KEY([PAE_CODI])
REFERENCES [TAB_PAER] ([PAE_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_PAER]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_PAER1] FOREIGN KEY([PAE_CODI1])
REFERENCES [TAB_PAER] ([PAE_CODI])
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_PAER1]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_PAIS] FOREIGN KEY([PAI_CODI])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_PAIS]
ALTER TABLE [TAB_PSDS]  WITH CHECK ADD  CONSTRAINT [FK_TAB_PSDS_TAB_PAIS1] FOREIGN KEY([PAI_CODI1])
REFERENCES [TAB_PAIS] ([PAI_CODI])
ALTER TABLE [TAB_PSDS] CHECK CONSTRAINT [FK_TAB_PSDS_TAB_PAIS1]
ALTER TABLE [TAB_RFCT]  WITH CHECK ADD  CONSTRAINT [FK_TAB_RFCT_DHL_CCOD] FOREIGN KEY([CCO_CODI])
REFERENCES [DHL_CCOD] ([CCO_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_RFCT] CHECK CONSTRAINT [FK_TAB_RFCT_DHL_CCOD]
ALTER TABLE [TAB_TDED]  WITH CHECK ADD  CONSTRAINT [FK_TAB_TDED_TAB_DOCU] FOREIGN KEY([DOC_CODI])
REFERENCES [TAB_DOCU] ([DOC_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_TDED] CHECK CONSTRAINT [FK_TAB_TDED_TAB_DOCU]
ALTER TABLE [TAB_TDED]  WITH CHECK ADD  CONSTRAINT [FK_TAB_TDED_TAB_TDEC] FOREIGN KEY([TDE_CODI])
REFERENCES [TAB_TDEC] ([TDE_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_TDED] CHECK CONSTRAINT [FK_TAB_TDED_TAB_TDEC]
ALTER TABLE [TAB_TDEM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_TDEM_TAB_INFC] FOREIGN KEY([INF_CODI])
REFERENCES [TAB_INFC] ([INF_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_TDEM] CHECK CONSTRAINT [FK_TAB_TDEM_TAB_INFC]
ALTER TABLE [TAB_TDEM]  WITH CHECK ADD  CONSTRAINT [FK_TAB_TDEM_TAB_TDEC] FOREIGN KEY([TDE_CODI])
REFERENCES [TAB_TDEC] ([TDE_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_TDEM] CHECK CONSTRAINT [FK_TAB_TDEM_TAB_TDEC]
ALTER TABLE [TAB_TDEP]  WITH CHECK ADD  CONSTRAINT [FK_TAB_TDEP_TAB_TDEC] FOREIGN KEY([TDE_CODI])
REFERENCES [TAB_TDEC] ([TDE_CODI])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [TAB_TDEP] CHECK CONSTRAINT [FK_TAB_TDEP_TAB_TDEC]
ALTER TABLE [TAB_TDEP]  WITH CHECK ADD  CONSTRAINT [FK_TAB_TDEP_TAB_TXML] FOREIGN KEY([TXM_CODI])
REFERENCES [TAB_TXML] ([TXM_CODI])
ON UPDATE CASCADE
ALTER TABLE [TAB_TDEP] CHECK CONSTRAINT [FK_TAB_TDEP_TAB_TXML]
ALTER TABLE [tb_ConfiguracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_ConfiguracoesDAR_TAB_PAIS] FOREIGN KEY([id_paisMeioTransporte])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_ConfiguracoesDAR] CHECK CONSTRAINT [FK_tb_ConfiguracoesDAR_TAB_PAIS]
ALTER TABLE [tb_ConfiguracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_ConfiguracoesDAR_TAB_TDEC] FOREIGN KEY([id_tipoDeclaracaoEU])
REFERENCES [TAB_TDEC] ([TDE_IDTY])
ALTER TABLE [tb_ConfiguracoesDAR] CHECK CONSTRAINT [FK_tb_ConfiguracoesDAR_TAB_TDEC]
ALTER TABLE [tb_ConfiguracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_ConfiguracoesDAR_TAB_TDEC1] FOREIGN KEY([id_tipoDeclaracaoIM])
REFERENCES [TAB_TDEC] ([TDE_IDTY])
ALTER TABLE [tb_ConfiguracoesDAR] CHECK CONSTRAINT [FK_tb_ConfiguracoesDAR_TAB_TDEC1]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_FAC_CDOC] FOREIGN KEY([id_conta])
REFERENCES [FAC_CDOC] ([CDO_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_FAC_CDOC]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_ALFA] FOREIGN KEY([id_estancia])
REFERENCES [TAB_ALFA] ([ALF_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_ALFA]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_ALFA1] FOREIGN KEY([id_estanciaMercadorias])
REFERENCES [TAB_ALFA] ([ALF_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_ALFA1]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_CENT] FOREIGN KEY([id_condicaoEntrega])
REFERENCES [TAB_CENT] ([CEN_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_CENT]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_CLIE] FOREIGN KEY([id_cliente])
REFERENCES [TAB_CLIE] ([CLI_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_CLIE]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_DECL] FOREIGN KEY([id_declarante])
REFERENCES [TAB_DECL] ([DEC_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_DECL]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_FORN] FOREIGN KEY([id_fornecedor])
REFERENCES [TAB_FORN] ([FOR_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_FORN]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_LMER] FOREIGN KEY([id_localAutorizado])
REFERENCES [TAB_LMER] ([LME_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_LMER]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_MTRA] FOREIGN KEY([id_meioTransporte])
REFERENCES [TAB_MTRA] ([MTR_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_MTRA]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_NDES] FOREIGN KEY([id_natureza])
REFERENCES [TAB_NDES] ([NDE_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_NDES]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS] FOREIGN KEY([id_paisCliente])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS1] FOREIGN KEY([id_paisDeclarante])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS1]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS2] FOREIGN KEY([id_paisFornecedor])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS2]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS3] FOREIGN KEY([id_paisMoedaCustosTransporte])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS3]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS4] FOREIGN KEY([id_paisMoedaMontante])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_PAIS4]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_TDOC] FOREIGN KEY([id_tipoDocumentoConta])
REFERENCES [TAB_TDOC] ([TDO_IDTY])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_TAB_TDOC]
ALTER TABLE [tb_DeclaracoesDAR]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDAR_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ALTER TABLE [tb_DeclaracoesDAR] CHECK CONSTRAINT [FK_tb_DeclaracoesDAR_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARAdicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_APAU] FOREIGN KEY([id_artigo])
REFERENCES [TAB_APAU] ([APA_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_APAU]
ALTER TABLE [tb_DeclaracoesDARAdicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_FORN] FOREIGN KEY([id_fornecedor])
REFERENCES [TAB_FORN] ([FOR_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_FORN]
ALTER TABLE [tb_DeclaracoesDARAdicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS] FOREIGN KEY([id_paisFornecedor])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS]
ALTER TABLE [tb_DeclaracoesDARAdicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS1] FOREIGN KEY([id_paisMoedaCustosTransporte])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS1]
ALTER TABLE [tb_DeclaracoesDARAdicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS2] FOREIGN KEY([id_paisMoedaMontante])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS2]
ALTER TABLE [tb_DeclaracoesDARAdicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS3] FOREIGN KEY([id_paisOrigem])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_TAB_PAIS3]
ALTER TABLE [tb_DeclaracoesDARAdicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARAdicoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoes_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARAdicoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoesDocumentos_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoesDocumentos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoesDocumentos_TAB_DOCU]
ALTER TABLE [tb_DeclaracoesDARAdicoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoesDocumentos_tb_DeclaracoesDARAdicoes] FOREIGN KEY([id_adicao])
REFERENCES [tb_DeclaracoesDARAdicoes] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARAdicoesDocumentos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoesDocumentos_tb_DeclaracoesDARAdicoes]
ALTER TABLE [tb_DeclaracoesDARAdicoesMencoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoesMencoes_TAB_INFC] FOREIGN KEY([id_mencao])
REFERENCES [TAB_INFC] ([INF_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoesMencoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoesMencoes_TAB_INFC]
ALTER TABLE [tb_DeclaracoesDARAdicoesMencoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoesMencoes_tb_DeclaracoesDARAdicoes] FOREIGN KEY([id_adicao])
REFERENCES [tb_DeclaracoesDARAdicoes] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARAdicoesMencoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoesMencoes_tb_DeclaracoesDARAdicoes]
ALTER TABLE [tb_DeclaracoesDARAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoesPrecedentes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_DeclaracoesDARAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoesPrecedentes_TAB_DOCU]
ALTER TABLE [tb_DeclaracoesDARAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARAdicoesPrecedentes_tb_DeclaracoesDARAdicoes] FOREIGN KEY([id_adicao])
REFERENCES [tb_DeclaracoesDARAdicoes] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARAdicoesPrecedentes_tb_DeclaracoesDARAdicoes]
ALTER TABLE [tb_DeclaracoesDARArquivos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARArquivos_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARArquivos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARArquivos_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARContactos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARContactos_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARContactos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARContactos_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARDocumentos_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_DeclaracoesDARDocumentos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARDocumentos_TAB_DOCU]
ALTER TABLE [tb_DeclaracoesDARDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARDocumentos_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARDocumentos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARDocumentos_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARFollowUps]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARFollowUps_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARFollowUps] CHECK CONSTRAINT [FK_tb_DeclaracoesDARFollowUps_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARIncidencias]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARIncidencias_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARIncidencias] CHECK CONSTRAINT [FK_tb_DeclaracoesDARIncidencias_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARManifestos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARManifestos_TAB_PAIS] FOREIGN KEY([id_pais])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDARManifestos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARManifestos_TAB_PAIS]
ALTER TABLE [tb_DeclaracoesDARManifestos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARManifestos_TAB_PAIS1] FOREIGN KEY([id_paisMoeda])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_DeclaracoesDARManifestos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARManifestos_TAB_PAIS1]
ALTER TABLE [tb_DeclaracoesDARManifestos]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARManifestos_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARManifestos] CHECK CONSTRAINT [FK_tb_DeclaracoesDARManifestos_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARMencoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARMencoes_TAB_INFC] FOREIGN KEY([id_mencao])
REFERENCES [TAB_INFC] ([INF_IDTY])
ALTER TABLE [tb_DeclaracoesDARMencoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARMencoes_TAB_INFC]
ALTER TABLE [tb_DeclaracoesDARMencoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARMencoes_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARMencoes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARMencoes_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARMensagens]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARMensagens_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARMensagens] CHECK CONSTRAINT [FK_tb_DeclaracoesDARMensagens_tb_DeclaracoesDAR]
ALTER TABLE [tb_DeclaracoesDARPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARPrecedentes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_DeclaracoesDARPrecedentes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARPrecedentes_TAB_DOCU]
ALTER TABLE [tb_DeclaracoesDARPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_DeclaracoesDARPrecedentes_tb_DeclaracoesDAR] FOREIGN KEY([id_declaracaoDAR])
REFERENCES [tb_DeclaracoesDAR] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_DeclaracoesDARPrecedentes] CHECK CONSTRAINT [FK_tb_DeclaracoesDARPrecedentes_tb_DeclaracoesDAR]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesAutorizacoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesAutorizacoes_PRO_EXAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAdicoesAutorizacoes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesAutorizacoes_PRO_EXAD]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesAutorizacoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesAutorizacoes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesAutorizacoes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesAutorizacoes_TAB_DOCU]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesContentores]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesContentores_PRO_EXAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAdicoesContentores] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesContentores_PRO_EXAD]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesContentores]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesContentores_PRO_EXCT] FOREIGN KEY([id_contentor])
REFERENCES [PRO_EXCT] ([EXC_CHVE])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesContentores] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesContentores_PRO_EXCT]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoes_PRO_EXAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoes_PRO_EXAD]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoes_TAB_RREC] FOREIGN KEY([id_rubricaReceita])
REFERENCES [TAB_RREC] ([RRE_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoes_TAB_RREC]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_TAB_UMED] FOREIGN KEY([id_unidadeMedida])
REFERENCES [TAB_UMED] ([UME_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_TAB_UMED]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_tb_EXP_DeclaracoesAdicoesImposicoes] FOREIGN KEY([id_imposicao])
REFERENCES [tb_EXP_DeclaracoesAdicoesImposicoes] ([id])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesImposicoesTaxas_tb_EXP_DeclaracoesAdicoesImposicoes]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesIntervenientes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesIntervenientes_PRO_EXAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAdicoesIntervenientes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesIntervenientes_PRO_EXAD]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPedidos]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPedidos_PRO_EXAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPedidos] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPedidos_PRO_EXAD]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPedidos]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPedidos_TAB_TXML] FOREIGN KEY([id_pedido])
REFERENCES [TAB_TXML] ([TXM_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPedidos] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPedidos_TAB_TXML]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_PRO_EXAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_EXAD] ([EXA_CHVE])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_PRO_EXAD]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_TAB_DOCU]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_TAB_UMED] FOREIGN KEY([id_unidadeMedidaQualificador])
REFERENCES [TAB_UMED] ([UME_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_TAB_UMED]
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_TAB_UMED1] FOREIGN KEY([id_unidadeMedidaVolumes])
REFERENCES [TAB_UMED] ([UME_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAdicoesPrecedentes_TAB_UMED1]
ALTER TABLE [tb_EXP_DeclaracoesAutorizacoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAutorizacoes_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesAutorizacoes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAutorizacoes_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesAutorizacoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesAutorizacoes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesAutorizacoes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesAutorizacoes_TAB_DOCU]
ALTER TABLE [tb_EXP_DeclaracoesContentoresSelos]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesContentoresSelos_PRO_EXCT] FOREIGN KEY([id_contentor])
REFERENCES [PRO_EXCT] ([EXC_CHVE])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesContentoresSelos] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesContentoresSelos_PRO_EXCT]
ALTER TABLE [tb_EXP_DeclaracoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesDocumentos_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesDocumentos] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesDocumentos_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesDocumentos_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesDocumentos] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesDocumentos_TAB_DOCU]
ALTER TABLE [tb_EXP_DeclaracoesIncidencias]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesIncidencias_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesIncidencias] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesIncidencias_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesIntervenientes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesIntervenientes_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesIntervenientes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesIntervenientes_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesLocaisTransformacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesLocaisTransformacao_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesLocaisTransformacao] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesLocaisTransformacao_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesLocaisTransformacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesLocaisTransformacao_TAB_LMER] FOREIGN KEY([id_localAutorizado])
REFERENCES [TAB_LMER] ([LME_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesLocaisTransformacao] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesLocaisTransformacao_TAB_LMER]
ALTER TABLE [tb_EXP_DeclaracoesLocaisTransformacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesLocaisTransformacao_TAB_PAIS] FOREIGN KEY([id_pais])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesLocaisTransformacao] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesLocaisTransformacao_TAB_PAIS]
ALTER TABLE [tb_EXP_DeclaracoesMeiosTransportePartida]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesMeiosTransportePartida_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesMeiosTransportePartida] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesMeiosTransportePartida_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesMeiosTransportePartida]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesMeiosTransportePartida_TAB_MTRA] FOREIGN KEY([id_meioTransporte])
REFERENCES [TAB_MTRA] ([MTR_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesMeiosTransportePartida] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesMeiosTransportePartida_TAB_MTRA]
ALTER TABLE [tb_EXP_DeclaracoesMeiosTransportePartida]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesMeiosTransportePartida_TAB_PAIS] FOREIGN KEY([id_pais])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesMeiosTransportePartida] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesMeiosTransportePartida_TAB_PAIS]
ALTER TABLE [tb_EXP_DeclaracoesMensagens]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesMensagens_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesMensagens] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesMensagens_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesPrecedentes_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesPrecedentes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesPrecedentes_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesPrecedentes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesPrecedentes] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesPrecedentes_TAB_DOCU]
ALTER TABLE [tb_EXP_DeclaracoesProdutosTransformados]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesProdutosTransformados_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_EXP_DeclaracoesProdutosTransformados] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesProdutosTransformados_PRO_EXML]
ALTER TABLE [tb_EXP_DeclaracoesProdutosTransformados]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesProdutosTransformados_TAB_APAU] FOREIGN KEY([id_artigo])
REFERENCES [TAB_APAU] ([APA_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesProdutosTransformados] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesProdutosTransformados_TAB_APAU]
ALTER TABLE [tb_EXP_DeclaracoesProdutosTransformados]  WITH CHECK ADD  CONSTRAINT [FK_tb_EXP_DeclaracoesProdutosTransformados_TAB_MIAU] FOREIGN KEY([id_meioIdentificacao])
REFERENCES [TAB_MIAU] ([MIA_IDTY])
ALTER TABLE [tb_EXP_DeclaracoesProdutosTransformados] CHECK CONSTRAINT [FK_tb_EXP_DeclaracoesProdutosTransformados_TAB_MIAU]
ALTER TABLE [tb_FAC_DocContasArquivos]  WITH CHECK ADD  CONSTRAINT [FK_tb_FAC_DocContasArquivos_FAC_CDOC] FOREIGN KEY([id_docConta])
REFERENCES [FAC_CDOC] ([CDO_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_FAC_DocContasArquivos] CHECK CONSTRAINT [FK_tb_FAC_DocContasArquivos_FAC_CDOC]
ALTER TABLE [tb_IMP_DeclaracoesAcrescimosDeducoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAcrescimosDeducoes_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesAcrescimosDeducoes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAcrescimosDeducoes_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_PRO_DUAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_DUAD] ([DUA_IDEN])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes_PRO_DUAD]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_PRO_DUAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_DUAD] ([DUA_IDEN])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_PRO_DUAD]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_TAB_ARMZ] FOREIGN KEY([id_armazem])
REFERENCES [TAB_ARMZ] ([ARM_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_TAB_ARMZ]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_TAB_DOCU]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_TAB_TARM] FOREIGN KEY([id_tipoArmazem])
REFERENCES [TAB_TARM] ([TAR_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesAdicoesEntrepostos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesEntrepostos_TAB_TARM]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPedidos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPedidos_PRO_DUAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_DUAD] ([DUA_IDEN])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPedidos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPedidos_PRO_DUAD]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPedidos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPedidos_TAB_TXML] FOREIGN KEY([id_pedido])
REFERENCES [TAB_TXML] ([TXM_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPedidos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPedidos_TAB_TXML]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_PRO_DUAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_DUAD] ([DUA_IDEN])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_PRO_DUAD]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_TAB_DOCU]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_TAB_UMED] FOREIGN KEY([id_unidadeMedidaQualificador])
REFERENCES [TAB_UMED] ([UME_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_TAB_UMED]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_TAB_UMED1] FOREIGN KEY([id_unidadeMedidaVolumes])
REFERENCES [TAB_UMED] ([UME_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesAdicoesPrecedentes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesPrecedentes_TAB_UMED1]
ALTER TABLE [tb_IMP_DeclaracoesAdicoesReferenciasFiscais]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesReferenciasFiscais_PRO_DUAD] FOREIGN KEY([id_adicao])
REFERENCES [PRO_DUAD] ([DUA_IDEN])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesAdicoesReferenciasFiscais] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesAdicoesReferenciasFiscais_PRO_DUAD]
ALTER TABLE [tb_IMP_DeclaracoesCondicoesEconomicas]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesCondicoesEconomicas_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesCondicoesEconomicas] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesCondicoesEconomicas_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesDocumentos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesDocumentos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_TAB_DOCU]
ALTER TABLE [tb_IMP_DeclaracoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_TAB_PAIS] FOREIGN KEY([id_paisMoeda])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesDocumentos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_TAB_PAIS]
ALTER TABLE [tb_IMP_DeclaracoesDocumentos]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_TAB_UMED] FOREIGN KEY([id_unidadeMedida])
REFERENCES [TAB_UMED] ([UME_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesDocumentos] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesDocumentos_TAB_UMED]
ALTER TABLE [tb_IMP_DeclaracoesEstancias]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesEstancias_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesEstancias] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesEstancias_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesEstancias]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesEstancias_TAB_EADU] FOREIGN KEY([id_estancia])
REFERENCES [TAB_EADU] ([EAD_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesEstancias] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesEstancias_TAB_EADU]
ALTER TABLE [tb_IMP_DeclaracoesIntervenientes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesIntervenientes_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesIntervenientes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesIntervenientes_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesLocaisTransformacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesLocaisTransformacao_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesLocaisTransformacao] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesLocaisTransformacao_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesLocaisTransformacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesLocaisTransformacao_TAB_LMER] FOREIGN KEY([id_localAutorizado])
REFERENCES [TAB_LMER] ([LME_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesLocaisTransformacao] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesLocaisTransformacao_TAB_LMER]
ALTER TABLE [tb_IMP_DeclaracoesLocaisTransformacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesLocaisTransformacao_TAB_PAIS] FOREIGN KEY([id_pais])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesLocaisTransformacao] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesLocaisTransformacao_TAB_PAIS]
ALTER TABLE [tb_IMP_DeclaracoesMeiosIdentificacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesMeiosIdentificacao_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesMeiosIdentificacao] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesMeiosIdentificacao_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesMeiosIdentificacao]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesMeiosIdentificacao_TAB_MIAU] FOREIGN KEY([id_meioIdentificacao])
REFERENCES [TAB_MIAU] ([MIA_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesMeiosIdentificacao] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesMeiosIdentificacao_TAB_MIAU]
ALTER TABLE [tb_IMP_DeclaracoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesPrecedentes_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesPrecedentes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesPrecedentes_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesPrecedentes]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesPrecedentes_TAB_DOCU] FOREIGN KEY([id_documento])
REFERENCES [TAB_DOCU] ([DOC_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesPrecedentes] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesPrecedentes_TAB_DOCU]
ALTER TABLE [tb_IMP_DeclaracoesProdutosTransformados]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesProdutosTransformados_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesProdutosTransformados] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesProdutosTransformados_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesProdutosTransformados]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesProdutosTransformados_TAB_APAU] FOREIGN KEY([id_artigo])
REFERENCES [TAB_APAU] ([APA_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesProdutosTransformados] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesProdutosTransformados_TAB_APAU]
ALTER TABLE [tb_IMP_DeclaracoesProprietarios]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesProprietarios_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesProprietarios] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesProprietarios_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesProprietarios]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesProprietarios_TAB_CLIE] FOREIGN KEY([id_cliente])
REFERENCES [TAB_CLIE] ([CLI_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesProprietarios] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesProprietarios_TAB_CLIE]
ALTER TABLE [tb_IMP_DeclaracoesProprietarios]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesProprietarios_TAB_PAIS] FOREIGN KEY([id_pais])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_IMP_DeclaracoesProprietarios] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesProprietarios_TAB_PAIS]
ALTER TABLE [tb_IMP_DeclaracoesReferenciasFiscais]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesReferenciasFiscais_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesReferenciasFiscais] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesReferenciasFiscais_PRO_DUCG]
ALTER TABLE [tb_IMP_DeclaracoesTaxasRendimento]  WITH CHECK ADD  CONSTRAINT [FK_tb_IMP_DeclaracoesTaxasRendimento_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_IMP_DeclaracoesTaxasRendimento] CHECK CONSTRAINT [FK_tb_IMP_DeclaracoesTaxasRendimento_PRO_DUCG]
ALTER TABLE [tb_TBL_LinhasOGMA]  WITH CHECK ADD  CONSTRAINT [FK_tb_TBL_LinhasOGMA_PRO_DUCG] FOREIGN KEY([id_declaracaoIMP])
REFERENCES [PRO_DUCG] ([DUC_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_TBL_LinhasOGMA] CHECK CONSTRAINT [FK_tb_TBL_LinhasOGMA_PRO_DUCG]
ALTER TABLE [tb_TBL_LinhasOGMA]  WITH CHECK ADD  CONSTRAINT [FK_tb_TBL_LinhasOGMA_PRO_EXML] FOREIGN KEY([id_declaracaoEXP])
REFERENCES [PRO_EXML] ([EXM_IDTY])
ON DELETE CASCADE
ALTER TABLE [tb_TBL_LinhasOGMA] CHECK CONSTRAINT [FK_tb_TBL_LinhasOGMA_PRO_EXML]
ALTER TABLE [tb_TBL_LinhasOGMA]  WITH CHECK ADD  CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_APAU] FOREIGN KEY([id_artigo])
REFERENCES [TAB_APAU] ([APA_IDTY])
ALTER TABLE [tb_TBL_LinhasOGMA] CHECK CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_APAU]
ALTER TABLE [tb_TBL_LinhasOGMA]  WITH CHECK ADD  CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_PAIS] FOREIGN KEY([id_paisOrigem])
REFERENCES [TAB_PAIS] ([PAI_IDTY])
ALTER TABLE [tb_TBL_LinhasOGMA] CHECK CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_PAIS]
ALTER TABLE [tb_TBL_LinhasOGMA]  WITH CHECK ADD  CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_PREF] FOREIGN KEY([id_preferencia])
REFERENCES [TAB_PREF] ([PRE_IDTY])
ALTER TABLE [tb_TBL_LinhasOGMA] CHECK CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_PREF]
ALTER TABLE [tb_TBL_LinhasOGMA]  WITH CHECK ADD  CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_UMED] FOREIGN KEY([id_unidadeMedida])
REFERENCES [TAB_UMED] ([UME_IDTY])
ALTER TABLE [tb_TBL_LinhasOGMA] CHECK CONSTRAINT [FK_tb_TBL_LinhasOGMA_TAB_UMED]
/****** Object:  StoredProcedure [sp_APL_DeclaracoesImportaFicheirosXMLStandard]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_APL_DeclaracoesImportaFicheirosXMLStandard] @TipoDeclaracao varchar(3), @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), 
	@DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30), @ConverteStandardIMPToStandardIMPCAU bit = 0 AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdUtilizador int, @IntegracaoIMPCAUAtiva bit, @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml, @Erros varchar(MAX), 
		@ErroFicheiro varchar(MAX), @i int, @PathFicheiroErro varchar(500), @Linha varchar(MAX)
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador	
-- obtem se integração IMP-CAU ativa
	SELECT TOP 1 @IntegracaoIMPCAUAtiva = PDE_ICAU
	FROM TAB_PDES WITH(NOLOCK)
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]	
	OPEN Ficheiros
	FETCH NEXT FROM Ficheiros INTO @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN										
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'			
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			SET @Erros = ''
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)	
-- obtem o xml do ficheiro xml importado					
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- inicia variaveis
			SET @Erros = ''
-- processa a geração da declaração DAR, DUI2, IMP-CAU ou EXP 
			IF @TipoDeclaracao = 'DAR'
			BEGIN
				EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @FicheiroXML, @IdUtilizador, @Erros OUTPUT					
				IF @NumErro <> 0
					SET @Erros = 'Erro na importação da declaração DAR do ficheiro "' + @NomeFicheiro + '": ' + CHAR(13) + @Erros + CHAR(13)					
			END
			ELSE
			IF @TipoDeclaracao = 'IMP'
			BEGIN
				IF @IntegracaoIMPCAUAtiva = 0
				BEGIN
					EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @FicheiroXML, @Utilizador, @Erros OUTPUT						
					IF @NumErro <> 0
						SET @Erros = 'Erro na importação da declaração DUI2 do ficheiro "' + @NomeFicheiro + '": ' + CHAR(13) + @Erros + CHAR(13)					
				END		
				ELSE
				BEGIN
					IF @ConverteStandardIMPToStandardIMPCAU = 1
					BEGIN
						EXEC @NumErro = SP_DeclImportacao_ConverteXMLStandardParaIMPCAU @FicheiroXML OUTPUT, @Erros OUTPUT						
						IF @NumErro <> 0
							SET @Erros = 'Erro na conversão da declaração DUI2 para IMP-CAU do ficheiro "' + @NomeFicheiro + '": ' + CHAR(13) + @Erros + CHAR(13)					
					END
					EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @FicheiroXML, @IdUtilizador, @Erros OUTPUT						
					IF @NumErro <> 0
						SET @Erros = 'Erro na importação da declaração IMP-CAU do ficheiro "' + @NomeFicheiro + '": ' + CHAR(13) + @Erros + CHAR(13)					
				END
			END
			ELSE
			IF @TipoDeclaracao = 'EXP'
			BEGIN
				EXEC @NumErro = SP_ExportacaoXML_GeraDeclaracoesDeXML @FicheiroXML, @Utilizador, @Erros OUTPUT						
				IF @NumErro <> 0
					SET @Erros = 'Erro na importação da declaração EXP do ficheiro "' + @NomeFicheiro + '": ' + CHAR(13) + @Erros + CHAR(13)
			END		
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('%s', 16, 2, @Erros)						
		END TRY
		BEGIN CATCH			
-- constroi mensagem de erro detalhada p/ gerar ficheiro de erro
			SET @ErroFicheiro = '**********************************************************************************************************' + CHAR(12) +
								'** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								'**********************************************************************************************************' + CHAR(12) + 
								'.Nome Ficheiro STD:  ' + @NomeFicheiro + CHAR(12) +								   
								'.Detalhe Erro:       ' + CHAR(12) +
								'		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
								'		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								'		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								'		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								'		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								'		*N. Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								'		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH		
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ErroFicheiro, '') <> ''
		BEGIN									
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ErroFicheiro, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ErroFicheiro = STUFF(@ErroFicheiro, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			END								
		END		
		FETCH NEXT FROM Ficheiros INTO @PathFicheiro, @NomeFicheiro
	END
	CLOSE Ficheiros
	DEALLOCATE Ficheiros
-- remove a tabela temporária	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [sp_APL_DeclaracoesImportaFicheirosXMLStandard] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_APL_DeclaracoesImportaFicheirosXMLStandard] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_APL_DeclaracoesImportaFicheirosXMLStandardDeSFTP]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_APL_DeclaracoesImportaFicheirosXMLStandardDeSFTP] @TipoDeclaracao varchar(3), @psFTPAppPath varchar(1000), @ServidorSFTP varchar(100), 
	@UtilizadorSFTP varchar(100), @PasswordSFTP varchar(100), @PortaSFTP int, @HostKeyServidorSFTP varchar(100), @DirOrigemFicheirosSFTP varchar(100), 
	@DirDestinoFicheirosSFTP varchar(100), @DirFicheirosTmpLocal varchar(500), @DirDestinoFicheiroErros varchar(500), @ConverteStandardIMPToStandardIMPCAU bit, 
	@Utilizador varchar(30) AS	
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @psFPTAppArgs varchar(2000), @PathFicheiroComandosFTP varchar(1000), @Erros varchar(MAX), @Linha varchar(MAX), @DirFicheirosDestinoTmpLocal varchar(500)
-- valida se a aplicação p/ sFTP é a correta
	IF REVERSE(SUBSTRING(REVERSE(@psFTPAppPath), 1, CHARINDEX('\', REVERSE(@psFTPAppPath)) - 1)) <> 'psftp.exe'
	BEGIN
		RAISERROR('A aplicação de envio de ficheiros p/ sFTP especificada não é válida!', 16, 1)
		RETURN 1
	END
-- substitui caracteres especiais p/ utilização no comando "echo"
	SET @ServidorSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@ServidorSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @UtilizadorSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@UtilizadorSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @PasswordSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@PasswordSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirOrigemFicheirosSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@DirOrigemFicheirosSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirDestinoFicheirosSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@DirDestinoFicheirosSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
-- verifica se diretorias SFTP tem separador no início
	IF SUBSTRING(@DirOrigemFicheirosSFTP, 1, 1) <> '/'
		SET @DirOrigemFicheirosSFTP = '/' + @DirOrigemFicheirosSFTP
	IF SUBSTRING(@DirDestinoFicheirosSFTP, 1, 1) <> '/'
		SET @DirDestinoFicheirosSFTP = '/' + @DirDestinoFicheirosSFTP
-- verfica se diretorias locais tem backslash no final
	IF SUBSTRING(REVERSE(@DirFicheirosTmpLocal), 1, 1) <> '\'
		SET @DirFicheirosTmpLocal = @DirFicheirosTmpLocal + '\'		
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'					
-- constroi nome p/ diretoria local tmp
	SET @DirFicheirosTmpLocal = @DirFicheirosTmpLocal + REPLACE(CAST(CONVERT(numeric(38, 12), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) as varchar(20)), '.', '_') + '\'	
-- processa a criação da diretoria local tmp 
	EXEC GIDWIN.dbo.SP_Externo_CriaDiretoria @DirFicheirosTmpLocal, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível criar a diretoria "%s"! ERRO: "%s".', 16, 2, @DirFicheirosTmpLocal, @Erros)
-- constroi nome p/ diretoria local tmp para destino de ficheiros
	SET @DirFicheirosDestinoTmpLocal = @DirFicheirosTmpLocal + 'tmpOUT\'
-- processa a criação da diretoria local tmp para destino de ficheiros
	EXEC GIDWIN.dbo.SP_Externo_CriaDiretoria @DirFicheirosDestinoTmpLocal, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível criar a diretoria "%s"! ERRO: "%s".', 16, 3, @DirFicheirosDestinoTmpLocal, @Erros)
-- gera o ficheiro de comandos SFTP na diretoria local tmp p/ download de ficheiros XML
	SET @PathFicheiroComandosFTP = @DirFicheirosTmpLocal + 'comandosSFTP.txt'			
	SET @Linha = 'cd ' + @DirOrigemFicheirosSFTP
	EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 4, @PathFicheiroComandosFTP, @Erros)	
	SET @Linha = 'lcd ' + @DirFicheirosTmpLocal
	EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 5, @PathFicheiroComandosFTP, @Erros)					
	SET @Linha = 'mget *.xml'
	EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 6, @PathFicheiroComandosFTP, @Erros)			
	SET @Linha = 'mv *.xml ' + @DirDestinoFicheirosSFTP
	EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 7, @PathFicheiroComandosFTP, @Erros)									
	SET @Linha = 'quit'
	EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 8, @PathFicheiroComandosFTP, @Erros)				
-- constroi os argumentos p/ a aplicação sFTP
	SET @psFPTAppArgs = @ServidorSFTP
	IF @PortaSFTP IS NOT NULL
		SET @psFPTAppArgs = @psFPTAppArgs + ' -P ' + CAST(@PortaSFTP as varchar(5)) 
	SET @psFPTAppArgs = @psFPTAppArgs + ' -l ' + @UtilizadorSFTP + ' -pw ' + @PasswordSFTP + ' -b "' + @PathFicheiroComandosFTP + '" -batch' 
	IF ISNULL(@HostKeyServidorSFTP, '') <> ''
		SET @psFPTAppArgs = @psFPTAppArgs + ' -hostkey ' + @HostKeyServidorSFTP /* hostkey no formato: "db:4f:fc:cc:ac:92:38:d5:be:57:5b:20:e0:86:b6:96"*/
	/*DECLARE @CommandString AS varchar(8000) --SCRIPT P/ EXTRAIR A hostkey
	--Create Batch fle with login credentials
    SET @CommandString = 'echo ' + @@psFTPAppPath + ' ' + @ServidorSFTP + ' -l ' + @UtilizadorSFTP + ' -pw ' + @PasswordSFTP + ' -b "' + @PathFicheiroComandosFTP + '" > "' + @DirFicheirosTmpLocal + 'SFTPUploadScript.bat"'
    EXEC master..xp_cmdshell @CommandString
	--Run the Batch File
    SET @CommandString = @DirFicheirosTmpLocal + 'SFTPUploadScript.bat'
    EXEC master..xp_cmdshell @CommandString */
-- processa o download dos ficheiros XML do sFTP p/ diretoria local tmp 
	EXEC GIDWIN.dbo.SP_Externo_ExecutaPrograma @psFTPAppPath, @psFPTAppArgs, @Erros OUTPUT		
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível efetuar o download dos ficheiros "*.xml" do servidor SFTP "%s"! ERRO: "%s".', 16, 9, @ServidorSFTP, @Erros)
-- remove o ficheiro de comandos sFTP na diretoria local tmp
	EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroComandosFTP, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 10, @PathFicheiroComandosFTP, @Erros)	
-- processa a importação ficheiros XML obtidos do sFTP
	EXEC sp_APL_DeclaracoesImportaFicheirosXMLStandard @TipoDeclaracao, @DirFicheirosTmpLocal, @DirFicheirosDestinoTmpLocal, @DirDestinoFicheiroErros, @Utilizador, @ConverteStandardIMPToStandardIMPCAU	
-- processo a remoção da diretoria local tmp para destino de ficheiros
	EXEC GIDWIN.dbo.SP_Externo_RemoveDiretoria @DirFicheirosDestinoTmpLocal, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível remover a diretoria "%s"! ERRO: "%s".', 16, 11, @DirFicheirosDestinoTmpLocal, @Erros)
-- processo a remoção da diretoria local tmp
	EXEC GIDWIN.dbo.SP_Externo_RemoveDiretoria @DirFicheirosTmpLocal, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR('Não foi possível remover a diretoria "%s"! ERRO: "%s".', 16, 12, @DirFicheirosTmpLocal, @Erros)
END

ALTER AUTHORIZATION ON [sp_APL_DeclaracoesImportaFicheirosXMLStandardDeSFTP] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_APL_DeclaracoesImportaFicheirosXMLStandardDeSFTP] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_APL_DescodificaTexto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_APL_DescodificaTexto] @Id int, @Tabela varchar(100), @CampoID varchar(100), @Texto varchar(MAX) OUTPUT AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @SQLAExecutar nvarchar(MAX), @LstVarSQL nvarchar(1000), @Valor varchar(MAX), @IdxInicio int, @IdxFim int, @NomeCampo varchar(100), 
		@NomeCampoComLimitadores varchar(100)
-- verifica a existência de limitadores para proceder à respetiva substituição
	IF (CHARINDEX('[<', @Texto) > 0) AND (CHARINDEX('>]', @Texto) > 0)
	BEGIN
-- obtem posições dos limitadores
		SET @IdxInicio = CHARINDEX('[<', @Texto) + 2
		SET @IdxFim = CHARINDEX('>]', @Texto)
-- obtem campo através da sua extração dos limitadores	
		SET @NomeCampo = SUBSTRING(@Texto, @IdxInicio, (@IdxFim - @IdxInicio))
		SET @NomeCampoComLimitadores = '[<' + @NomeCampo + '>]'
-- obtem valor do campo (se coluna existir na tabela)
		IF EXISTS(SELECT object_id FROM sys.columns WHERE name = @NomeCampo AND object_id = Object_ID(@Tabela))
		BEGIN
			SET @LstVarSQL = N'@OUTValor varchar(MAX) OUTPUT, @INId int'
			SET @SQLAExecutar = N'SELECT @OUTVALOR = (CASE WHEN ISDATE(' + @NomeCampo + ') = 1 THEN CONVERT(varchar(10), ' + @NomeCampo + ', 105) ELSE CAST(' + @NomeCampo + ' AS varchar(MAX)) END)'
			SET @SQLAExecutar = @SQLAExecutar + ' FROM ' + @Tabela + ' WITH(NOLOCK)'
			SET @SQLAExecutar = @SQLAExecutar + ' WHERE ' + @CampoID + ' = @INId'
			EXEC sp_executesql @SQLAExecutar, @LstVarSQL, @OUTValor = @Valor OUTPUT, @INId = @Id	
		END
		ELSE
			SET @Valor = '????????'
-- substitui a variável ao campo pelo respetivo valor		
		SET @Texto = REPLACE(@Texto, @NomeCampoComLimitadores, @Valor)
-- verifica se ainda existe variaveis a substituir no texto
		EXEC sp_APL_DescodificaTexto @Id, @Tabela, @CampoID, @Texto OUTPUT
	END
END

ALTER AUTHORIZATION ON [sp_APL_DescodificaTexto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_APL_DescodificaTexto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_Auditoria_ObtemRegistosLog]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_Auditoria_ObtemRegistosLog] @Contexto varchar(100), @DataDe datetime, @DataA datetime, @IdUtilizador int, @IdRegisto int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os registos de log da tabela de dados gerais de declarações DAR
		IF @Contexto = 'tb_DeclaracoesDAR'
		BEGIN
			SELECT aud.idAuditoria, 
				(CASE aud.acaoAuditoria WHEN 'I' THEN 'Inserção' WHEN 'U' THEN 'Alteração' WHEN 'D' THEN 'Remoção' END) AS "Tipo", 
				aud.dataAuditoria AS "Data/Hora", 
				ISNULL(uti.UTI_UTIL, '<' + CAST(aud.id_utilizadorAuditoria AS varchar(10)) + '>') AS "Utilizador", 
				aud.aplicacaoAuditoria AS "_Programa", 
				aud.maquinaAuditoria AS "_PC", 
				aud.loginAuditoria AS "_Login", 
				aud.id AS "ID Declaração", 				
				aud.ano AS "Ano", 
				aud.numero AS "Número", 
				aud.data AS "Data", 
				aud.numeroReferenciaLocal AS "N.º Referência Local", 
				aud.documentoTransporte AS "Documento Transporte", 				
				ISNULL(nat.NDE_CODI, '<' + CAST(aud.id_natureza AS varchar(10)) + '>') AS "Natureza", 
				aud.regimeIVA AS "Regime IVA", 
				aud.regimeAdicional AS "Ad. Regime", 
				aud.status AS "Status", 
				aud.dataEnvio AS "Data Envio", 
				aud.versao AS "Versão", 	
				aud.revisao AS "Revisão", 	
				aud.numeroProvisorio AS "Número Provisório", 
				aud.estadoOperacao AS "Estado da Operação", 	
				aud.controloDocumental AS "_CD", 
				aud.dataControloDocumental AS "_Data CD", 
				aud.conferenteControloDocumental AS "_Conferente CD", 
				aud.verificadorControloDocumental AS "_Verificador CD", 
				aud.fechadoControloDocumental AS "_Fechado CD", 	
				aud.dataFechoControloDocumental AS "_Data Fecho CD", 	
				aud.controloFisico AS "_CF", 
				aud.dataControloFisico AS "_Data CF", 
				aud.conferenteControloFisico AS "_Conferente CF", 	
				aud.verificadorControloFisico AS "_Verificador CF", 	
				aud.fechadoControloFisico AS "_Fechado CF", 	
				aud.dataFechoControloFisico AS "_Data Fecho CF", 	
				aud.controloAduaneiro AS "_CAP", 	
				aud.dataControloAduaneiro AS "_Data CAP", 	
				aud.conferenteControloAduaneiro AS "_Conferente CAP", 	
				aud.verificadorControloAduaneiro AS "_Verificador CAP", 	
				aud.fechadoControloAduaneiro AS "_Fechado CAP", 	
				aud.dataFechoControloAduaneiro AS "_Data Fecho CAP", 
				aud.autorizacaoSaida AS "AS", 	
				aud.dataAutorizacaoSaida AS "Data AS", 	
				aud.numeroNRM AS "Número NRM", 	
				aud.dataNRM AS "Data NRM", 	
				aud.numeroNRMExportacao AS "_NRM Exportação", 					
				ISNULL(frn.FOR_CODI, '<' + CAST(aud.id_fornecedor AS varchar(10)) + '>') AS "Exportador", 
				aud.nomeFornecedor AS "Nome Exportador", 
				ISNULL(pfr.PAI_CODI, '<' + CAST(aud.id_paisFornecedor AS varchar(10)) + '>') AS "País Exportador", 	
				aud.moradaFornecedor AS "Morada Exportador", 	
				aud.localidadeFornecedor AS "Localidade Exportador", 	
				aud.codPostalFornecedor AS "Cód. Postal Exportador", 
				aud.locPostalFornecedor AS "Loc. Postal Exportador", 
				ISNULL(cli.CLI_CODI, '<' + CAST(aud.id_cliente AS varchar(10)) + '>') AS "Importador", 	
				aud.nomeCliente AS "Nome Importador", 
				ISNULL(pcl.PAI_CODI, '<' + CAST(aud.id_paisCliente AS varchar(10)) + '>') AS "País Importador", 
				aud.nifCliente AS "NIF Importador", 
				aud.moradaCliente AS "Morada Importador", 
				aud.localidadeCliente AS "Localidade Importador", 	
				aud.codPostalCliente AS "Cód. Postal Importador", 	
				aud.locPostalCliente AS "Loc. Postal Importador", 
				aud.tipoContaCliente AS "Tipo Conta Importador", 
				aud.telefoneCliente AS "Telefone Importador", 
				aud.emailCliente AS "E-mail Importador", 
				aud.beneficiarioIVACliente AS "Beneficiário IVA Importador", 	
				ISNULL(dcl.DEC_CODI, '<' + CAST(aud.id_declarante AS varchar(10)) + '>') AS "Declarante", 	
				aud.nomeDeclarante AS "Nome Declarante", 	
				ISNULL(pdc.PAI_CODI, '<' + CAST(aud.id_paisDeclarante AS varchar(10)) + '>') AS "País Declarante", 
				aud.nifDeclarante AS "NIF Declarante", 	
				aud.moradaDeclarante AS "Morada Declarante", 	
				aud.localidadeDeclarante AS "Localidade Declarante", 	
				aud.codPostalDeclarante AS "Cód. Postal Declarante", 
				aud.locPostalDeclarante AS "Loc. Postal Declarante", 
				aud.estatutoDeclarante AS "Estatuto", 
				aud.nifRepresentante AS "Representante", 	
				aud.caucao AS "Garantia", 
				aud.funcaoRegimeIOSS AS "Função IOSS", 
				aud.numeroIdentificacaoIVA AS "N.º Identificação IVA", 
				ISNULL(alf.ALF_CODI, '<' + CAST(aud.id_estancia AS varchar(10)) + '>') AS "Estância", 
				aud.tipoDeclaracao AS "Tipo Declaração", 	
				aud.numeroNRUR AS "_N.º Referência/NRUR", 	
				aud.numeroVossaReferencia AS "Vossa Referência", 	
				aud.localizacaoMercadorias AS "Tipo de Localização", 	
				aud.qualificador AS "Qualificador de Identificação", 
				ISNULL(alm.ALF_CODI, '<' + CAST(aud.id_estanciaMercadorias AS varchar(10)) + '>') AS "Estância LM", 
				ISNULL(lme.LME_CODI, '<' + CAST(aud.id_localAutorizado AS varchar(10)) + '>') AS "Armazém DTP",								
				ISNULL(pmm.PAI_CODI, '<' + CAST(aud.id_paisMoedaMontante AS varchar(10)) + '>') AS "Moeda Montante", 
				aud.cambioMontante AS "Câmbio Montante", 	
				aud.totalMontante AS "Montante Total", 
				aud.totalMontanteEUR AS "Montante Total EUR", 	
				ISNULL(pmc.PAI_CODI, '<' + CAST(aud.id_paisMoedaCustosTransporte AS varchar(10)) + '>') AS "Moeda Custos", 
				aud.cambioCustosTransporte AS "Câmbio Custos", 	
				aud.totalCustosTransporte AS "Custos Transporte", 
				aud.totalAdicoes AS "Adições", 	
				aud.totalVolumes AS "Volumes", 	
				aud.totalMassaBruta AS "Massa Bruta Total", 
				aud.totalIVA AS "Dívida Aduaneira", 	
				ISNULL(ISNULL(NULLIF(cdo.CDO_INVN, ''), (cdo.CDO_TDOC + ' ?/?')), '<' + CAST(aud.id_conta AS varchar(10)) + '>') AS "Conta", 
				aud.numeroRegistoLiquidacao AS "N.º Liquidação", 
				aud.dataRegistoLiquidacao AS "Data Liquidação", 	
				aud.dataLimitePagamento AS "Data Pagamento Liquidação", 	
				aud.participacao AS "_Participação", 
				aud.dataParticipacao AS "_Data Participação", 
				aud.numeroContraOrdenacao AS "_N.º Contra Ordenação", 
				aud.multa AS "_Valor da Multa", 
				aud.motivoMulta AS "_Motivo da Multa", 
				aud.debitarMultaA AS "_Debitar Multa a...", 
				aud.reembolsoMulta AS "_Reembolso", 
				aud.numeroPDDT AS "N.º PDDT", 
				aud.numeroPDDTDEV AS "N.º PDDT/DEV", 	
				aud.numeroTD AS "N.º TD", 
				aud.numeroACTM AS "N.º ACTM", 
				aud.numeroContaExpedidor AS "_Conta Expedidor", 	
				aud.numeroContaDestinatario AS "_Conta Destinatário", 
				aud.nomeOriginalDestinatario AS "_Nome Original Destinatário", 	
				aud.moradaOriginalDestinatario AS "_Morada Original Destinatário", 
				aud.localidadeOriginalDestinatario AS "_Localidade Original Destinatário", 	
				aud.codPostalOriginalDestinatario AS "_Cód. Postal Original Destinatário", 
				aud.locPostalOriginalDestinatario AS "_Loc. Postal Original Destinatário", 
				aud.referenciaExterna1 AS "_Referência 1", 
				aud.referenciaExterna2 AS "_Referência 2", 
				aud.shipID AS "_Ship ID", 
				aud.miniCPA AS "Mini CPA", 
				aud.dataVoo AS "Data Voo", 	
				aud.aeroportoOrigem AS "_Aeroporto de Origem", 
				aud.numeroVoo AS "_Número do Voo", 
				aud.posicaoAviao AS "_Posição do Avião", 
				aud.tracking AS "_Tracking", 
				aud.tipoCarga AS "_Tipo de Carga", 
				aud.dutyType AS "Duty Type",
				aud.payment AS "Payment", 
				aud.numeroRequerimento AS "N.º Requerimento", 	
				aud.numeroDURetorno AS "N.º DU Retorno", 
				aud.numeroT1Retorno AS "T1 de Retorno",
				ISNULL(fup.FUP_DESC, '<' + CAST(aud.id_followUp AS varchar(10)) + '>') AS "Follow-Up", 
				ISNULL(uno.UTI_UTIL, '<' + CAST(aud.id_utilizadorNomeado AS varchar(10)) + '>') AS "Utilizador Nomeado",  
				aud.volumesDirty AS "Vols. Dirty", 
				aud.volumesClean AS "Vols. Clean", 	
				aud.volumesScan AS "Vols. Scan", 
				aud.nivelServico AS "_Serv. Level", 
				aud.nomeFicheiroUPS AS "_Ficheiro UPS", 
				aud.condicaoEntregaUPS AS "_C. Entrega", 
				aud.freteOriginal AS "Frete Original", 
				aud.moedaFreteOriginal AS "Moeda Frete Original", 
				aud.gatewayFEDEX AS "Gateway", 
				aud.locIDFEDEX AS "Loc. ID", 
				aud.portesAccFEDEX AS "Portes ACC#", 
				aud.portesFEDEX AS "Portes", 
				aud.despachoAccFEDEX AS "Despacho ACC#", 
				aud.despesasDHL AS "Despesas", 
				aud.dataDocumentoTransporte AS "_Data Doc. Transporte", 
				aud.tipoShipment AS "_Tipo Shipment", 
				aud.volumesPendentesParte AS "_Volumes Parte", 
				aud.totalMassaBrutaParte AS "_Massa Bruta Total Parte", 
				aud.totalCustosTransporteParte AS "_Custos Total Parte", 
				aud.totalMontanteParte AS "_Montante Total Parte", 
				aud.totalMontanteEURParte AS "_Montante Total EUR Parte", 
				aud.totalIVAParte AS "_Dívida Aduaneira Parte", 
				aud.origem AS "_Origem", 
				ISNULL((CAST(dar.ano AS varchar(4)) + '/' + CAST(dar.numero AS varchar(10))), '<' + CAST(aud.id_declaracaoDAR AS varchar(10)) + '>') AS "_Declaração DAR Origem", 				
				aud.libertoADT AS "Liberto ADT", 
				aud.dataADT AS "Data ADT", 
				ISNULL(udt.UTI_UTIL, '<' + CAST(aud.id_utilizadorADT AS varchar(10)) + '>') AS "Utilizador ADT", 	
				aud.diasDescontoADT AS "_Dias Desconto ADT", 
				aud.numeroSequencia AS "_N.º Sequência", 
				ISNULL(tdo.TDO_DOCU, '<' + CAST(aud.id_tipoDocumentoConta AS varchar(10)) + '>') AS "_Tipo Doc. Conta", 	
				aud.exportado AS "_Exportado", 
				aud.acao AS "_Ação", 
				aud.envioEntregue AS "Envio Entregue", 
				aud.statusIVA AS "Status IVA", 
				aud.bloqueado AS "_Bloqueado", 
				aud.taxaIVAMaxima AS "_Taxa IVA Max."
			FROM tb_DeclaracoesDARAuditoria AS aud WITH(NOLOCK) LEFT OUTER JOIN GIDWIN.dbo.FAP_UTIL AS uti ON aud.id_utilizadorAuditoria = uti.UTI_IDTY				
				LEFT OUTER JOIN TAB_NDES AS nat WITH(NOLOCK) ON aud.id_natureza = nat.NDE_IDTY
				LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON aud.id_fornecedor = frn.FOR_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pfr WITH(NOLOCK) ON aud.id_paisFornecedor = pfr.PAI_IDTY
				LEFT OUTER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON aud.id_cliente = cli.CLI_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON aud.id_paisCliente = pcl.PAI_IDTY
				LEFT OUTER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON aud.id_declarante = dcl.DEC_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pdc WITH(NOLOCK) ON aud.id_paisDeclarante = pdc.PAI_IDTY
				LEFT OUTER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON aud.id_estancia = alf.ALF_IDTY
				LEFT OUTER JOIN TAB_ALFA AS alm WITH(NOLOCK) ON aud.id_estanciaMercadorias = alm.ALF_IDTY
				LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON aud.id_localAutorizado = lme.LME_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pmm WITH(NOLOCK) ON aud.id_paisMoedaMontante = pmm.PAI_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pmc WITH(NOLOCK) ON aud.id_paisMoedaCustosTransporte = pmc.PAI_IDTY
				LEFT OUTER JOIN FAC_CDOC AS cdo WITH(NOLOCK) ON aud.id_conta = cdo.CDO_IDTY
				LEFT OUTER JOIN GIDWIN.dbo.FAP_FWUP AS fup ON aud.id_followUp = fup.FUP_IDTY
				LEFT OUTER JOIN GIDWIN.dbo.FAP_UTIL AS uno ON aud.id_utilizadorNomeado = uno.UTI_IDTY	
				LEFT OUTER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON aud.id_declaracaoDAR = dar.id
				LEFT OUTER JOIN GIDWIN.dbo.FAP_UTIL AS udt ON aud.id_utilizadorADT = udt.UTI_IDTY	
				LEFT OUTER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON aud.id_tipoDocumentoConta = tdo.TDO_IDTY
			WHERE aud.dataAuditoria >= ISNULL(@DataDe, aud.dataAuditoria) AND aud.dataAuditoria <= ISNULL(@DataA, aud.dataAuditoria) AND aud.id_utilizadorAuditoria = ISNULL(@IdUtilizador, aud.id_utilizadorAuditoria)
				AND aud.id = ISNULL(@IdRegisto, aud.id)
			ORDER BY aud.dataAuditoria DESC
		END
		ELSE
-- obtem os registos de log da tabela de adições de declarações DAR
		IF @Contexto = 'tb_DeclaracoesDARAdicoes'
		BEGIN
			SELECT aud.idAuditoria, 
				(CASE aud.acaoAuditoria WHEN 'I' THEN 'Inserção' WHEN 'U' THEN 'Alteração' WHEN 'D' THEN 'Remoção' END) AS "Tipo", 
				aud.dataAuditoria AS "Data/Hora", 
				ISNULL(uti.UTI_UTIL, '<' + CAST(aud.id_utilizadorAuditoria AS varchar(10)) + '>') AS "Utilizador", 
				aud.aplicacaoAuditoria AS "_Programa", 
				aud.maquinaAuditoria AS "_PC", 
				aud.loginAuditoria AS "_Login", 
				aud.id AS "ID Adição", 
				aud.id_declaracaoDAR AS "ID Declaração", 
				aud.numeroAdicao AS "Número", 
				ISNULL(art.APA_CODI, '<' + CAST(aud.id_artigo AS varchar(10)) + '>') AS "Artigo", 	
				aud.codigoPautal AS "Código Pautal", 
				aud.codigoNC AS "NC", 
				aud.codigoTARIC AS "TARIC", 
				aud.adicionalTARIC1 AS "Ad. TARIC 1", 
				aud.adicionalTARIC2 AS "Ad. TARIC 2", 
				aud.adicionalTARIC3 AS "Ad. TARIC 3", 
				aud.adicionalNacional1 AS "Ad. Nacional 1", 
				aud.adicionalNacional2 AS "Ad. Nacional 2", 
				aud.adicionalNacional3 AS "Ad. Nacional 3", 
				aud.designacao AS "Designação", 
				aud.regimeAdicional AS "Ad. Regime", 
				ISNULL(por.PAI_CODI, '<' + CAST(aud.id_paisOrigem AS varchar(10)) + '>') AS "País Origem", 				
				aud.metodoPagamento AS "Método de Pagamento", 
				aud.numeroNRUR AS "_N.º Referência/NRUR", 				
				aud.unidades AS "Unidades", 
				aud.massaBruta AS "Massa Bruta", 
				aud.volumes AS "Volumes", 
				ISNULL(pmm.PAI_CODI, '<' + CAST(aud.id_paisMoedaMontante AS varchar(10)) + '>') AS "Moeda Montante", 
				aud.cambioMontante AS "Câmbio Montante", 
				aud.montante AS "Montante", 
				aud.montanteEUR AS "Montante EUR", 
				ISNULL(pmc.PAI_CODI, '<' + CAST(aud.id_paisMoedaCustosTransporte AS varchar(10)) + '>') AS "Moeda Custos", 
				aud.cambioCustosTransporte AS "Câmbio Custos", 
				aud.custosTransporte AS "Custos Transporte", 
				aud.custosTransporteEUR AS "Custos Transporte EUR", 
				aud.baseTributacaoIVA AS "Base Tributação", 
				aud.taxaIVA AS "Taxa IVA", 
				aud.valorIVA AS "Valor IVA", 				
				ISNULL(frn.FOR_CODI, '<' + CAST(aud.id_fornecedor AS varchar(10)) + '>') AS "_Fornecedor",
				aud.nomeFornecedor AS "_Nome Fornecedor", 				 
				aud.moradaFornecedor AS "_Morada Fornecedor", 
				aud.localidadeFornecedor AS "_Localidade Fornecedor", 
				aud.codPostalFornecedor AS "_Cód. Postal Fornecedor", 
				aud.locPostalFornecedor AS "_Loc. Postal Fornecedor", 
				aud.codigoBarrasCTT AS "_Código de Barras", 
				aud.numeroObjetoCTT AS "_Número do Objeto", 
				aud.origem AS "_Origem"
			FROM tb_DeclaracoesDARAdicoesAuditoria AS aud WITH(NOLOCK) LEFT OUTER JOIN GIDWIN.dbo.FAP_UTIL AS uti ON aud.id_utilizadorAuditoria = uti.UTI_IDTY				
				LEFT OUTER JOIN TAB_APAU AS art WITH(NOLOCK) ON aud.id_artigo = art.APA_IDTY
				LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON aud.id_paisOrigem = por.PAI_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pmm WITH(NOLOCK) ON aud.id_paisMoedaMontante = pmm.PAI_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pmc WITH(NOLOCK) ON aud.id_paisMoedaCustosTransporte = pmc.PAI_IDTY
				LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON aud.id_fornecedor = frn.FOR_IDTY
			WHERE aud.dataAuditoria >= ISNULL(@DataDe, aud.dataAuditoria) AND aud.dataAuditoria <= ISNULL(@DataA, aud.dataAuditoria) AND aud.id_utilizadorAuditoria = ISNULL(@IdUtilizador, aud.id_utilizadorAuditoria)
				AND aud.id_declaracaoDAR = ISNULL(@IdRegisto, aud.id_declaracaoDAR)
			ORDER BY aud.dataAuditoria DESC
		END		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_Auditoria_ObtemRegistosLog] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_Auditoria_ObtemRegistosLog] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_Auditoria_ProcessaGestaoTabela]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_Auditoria_ProcessaGestaoTabela] @NomeTabelaAAuditar varchar(150) AS
BEGIN
-- declaração de variáveis
	DECLARE @NomeCompletoTabelaAAuditar varchar(300), @NomeTabelaDeAuditoria varchar(150), @NomeCompletoTabelaDeAuditoria varchar(150), @NomeTriggerAuditoria varchar(150), @NomeCompletoTriggerAuditoria varchar(150), 
		@NomeColuna varchar(150), @TipoColuna varchar(150), @TamanhoColuna smallint, @ColunaNula int, @CollationColuna sysname, @PrecisaoColuna tinyint, @ScaleColuna tinyint, @NomeDefaultConstraintColuna varchar(150), @ValorDefaultConstraintColuna nvarchar(MAX), 
		@SQLAExecutar varchar(MAX), @TabelaAlterada bit, @ListaCamposAAuditar varchar(4000)
-- inicia variaveis
	SET @NomeCompletoTabelaAAuditar = '[dbo].[' + @NomeTabelaAAuditar + ']'
	SET @NomeTabelaDeAuditoria = @NomeTabelaAAuditar + 'Auditoria'
	SET @NomeCompletoTabelaDeAuditoria = '[dbo].[' + @NomeTabelaDeAuditoria + ']'
	SET @NomeTriggerAuditoria = 'tr_' + REPLACE(@NomeTabelaAAuditar, 'tb_', '') + '_Auditoria_IUD'
	SET @NomeCompletoTriggerAuditoria = '[dbo].[' + @NomeTriggerAuditoria + ']'
	SET @ListaCamposAAuditar = ''
-- verifica se tabela normal tem a coluna "id_utilizadorControlo" e tem a propriedade "Auditar" com o valor "1" que assinalada que a tabela pode ser auditada	
	IF NOT EXISTS(SELECT obj.id FROM sysobjects AS obj WHERE obj.id = OBJECT_ID(@NomeCompletoTabelaAAuditar) AND OBJECTPROPERTY(obj.id, N'IsUserTable') = 1 AND EXISTS(SELECT id FROM syscolumns WHERE id = obj.id AND name = 'id_utilizadorControlo') AND ISNULL((SELECT CAST(value AS varchar(1)) FROM sys.extended_properties WHERE major_id = obj.id AND minor_id = 0 AND class = 1 AND name = 'Auditar'), '1') = '1')
		RETURN
-- se tabela de auditoria existe, processa sincronização de colunas
	IF EXISTS (SELECT id FROM sysobjects WHERE id = OBJECT_ID(@NomeCompletoTabelaDeAuditoria) AND OBJECTPROPERTY(id, N'IsUserTable') = 1) 
	BEGIN
		SET @TabelaAlterada = 0
-- processa a remoção das colunas na tabela de auditoria que já não existem na tabela normal
		DECLARE ColunasARemover CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT aco.name, def.name
			FROM sysobjects AS aob 
				INNER JOIN syscolumns AS aco on aob.id = aco.id 
				LEFT OUTER JOIN sys.default_constraints AS def ON aco.cdefault = def.object_id
			WHERE aob.id = OBJECT_ID(@NomeCompletoTabelaDeAuditoria) AND OBJECTPROPERTY(aob.id, N'IsUserTable') = 1 AND aco.name NOT LIKE '%Auditoria'
				AND NOT EXISTS(SELECT obj.id
					FROM sysobjects AS obj 
						INNER JOIN syscolumns AS col on obj.id = col.id 	
					WHERE obj.id = OBJECT_ID(@NomeCompletoTabelaAAuditar) AND OBJECTPROPERTY(obj.id, N'IsUserTable') = 1 AND col.name = aco.name)
			ORDER BY aco.colId
		OPEN ColunasARemover
		FETCH NEXT FROM ColunasARemover INTO @NomeColuna, @NomeDefaultConstraintColuna
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @TabelaAlterada = 1		
			IF @NomeDefaultConstraintColuna IS NOT NULL
				EXEC ('ALTER TABLE ' + @NomeCompletoTabelaDeAuditoria + ' DROP CONSTRAINT [' + @NomeDefaultConstraintColuna + ']')  
			EXEC ('ALTER TABLE ' + @NomeCompletoTabelaDeAuditoria + ' DROP COLUMN [' + @NomeColuna + ']')  
			FETCH NEXT FROM ColunasARemover INTO @NomeColuna, @NomeDefaultConstraintColuna
		END
		CLOSE ColunasARemover
		DEALLOCATE ColunasARemover
-- processa a inserção das colunas na tabela de auditoria que existem na tabela normal e não existem na tabela de auditoria
		DECLARE ColunasAInserir CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT col.name, typ.name, col.length, col.isnullable, col.collation, col.xprec, col.xscale, def.definition
			FROM sysobjects AS obj 
				INNER JOIN syscolumns AS col on obj.id = col.id 
				INNER JOIN systypes AS typ on col.xtype = typ.xtype and typ.name <> 'sysname' 
				LEFT OUTER JOIN sys.default_constraints AS def ON col.cdefault = def.object_id
			WHERE obj.id = OBJECT_ID(@NomeCompletoTabelaAAuditar) AND OBJECTPROPERTY(obj.id, N'IsUserTable') = 1 AND typ.name NOT IN ('text', 'ntext', 'image', 'timestamp') 
				AND col.name NOT IN ('id_utilizadorControlo', 'dataControlo')
				AND NOT EXISTS(SELECT aob.id
					FROM sysobjects AS aob 
						INNER JOIN syscolumns AS aco on aob.id = aco.id 	
					WHERE aob.id = OBJECT_ID(@NomeCompletoTabelaDeAuditoria) AND OBJECTPROPERTY(aob.id, N'IsUserTable') = 1 AND aco.name = col.name)
			ORDER BY col.colId			
		OPEN ColunasAInserir
		FETCH NEXT FROM ColunasAInserir INTO @NomeColuna, @TipoColuna, @TamanhoColuna, @ColunaNula, @CollationColuna, @PrecisaoColuna, @ScaleColuna, @ValorDefaultConstraintColuna
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @TabelaAlterada = 1			
			SET @SQLAExecutar = 'ALTER TABLE ' + @NomeCompletoTabelaDeAuditoria + ' ADD [' + @NomeColuna + '] [' + @TipoColuna + '] '				
			IF @TipoColuna IN ('binary', 'char', 'nchar', 'nvarchar', 'varbinary', 'varchar')
			BEGIN
				IF (@TamanhoColuna = -1)
					SET @SQLAExecutar = @SQLAExecutar + '(MAX) '	 	
				ELSE
					SET @SQLAExecutar = @SQLAExecutar + '(' + CAST(@TamanhoColuna AS varchar(10)) + ') '	 	
			END	
			ELSE	
				IF @TipoColuna IN ('decimal', 'numeric')
					SET @SQLAExecutar = @SQLAExecutar + '(' + CAST(@PrecisaoColuna AS varchar(10)) + ',' + CAST(@ScaleColuna AS varchar(10)) + ') '	 			
			IF @TipoColuna IN ('char', 'nchar', 'nvarchar', 'varchar')
				SET @SQLAExecutar = @SQLAExecutar + 'COLLATE ' + @CollationColuna + ' '		
			IF @ColunaNula = 0
				SET @SQLAExecutar = @SQLAExecutar + 'NOT '	 			
			SET @SQLAExecutar = @SQLAExecutar + 'NULL '
			IF @ValorDefaultConstraintColuna IS NOT NULL
				SET @SQLAExecutar = @SQLAExecutar + 'CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_' + @NomeColuna + '] DEFAULT (' + @ValorDefaultConstraintColuna + ')'			
			EXEC (@SQLAExecutar)  
			FETCH NEXT FROM ColunasAInserir INTO @NomeColuna, @TipoColuna, @TamanhoColuna, @ColunaNula, @CollationColuna, @PrecisaoColuna, @ScaleColuna, @ValorDefaultConstraintColuna
		END
		CLOSE ColunasAInserir
		DEALLOCATE ColunasAInserir
-- processa a alteração das colunas na tabela de auditoria que existem em ambas as tabelas mas com propriedades diferentes
		DECLARE ColunasAAlterar CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT col.name, typ.name, col.length, col.isnullable, col.collation, col.xprec, col.xscale, def.definition
			FROM sysobjects AS obj 
				INNER JOIN syscolumns AS col on obj.id = col.id 
				INNER JOIN systypes AS typ on col.xtype = typ.xtype and typ.name <> 'sysname' 
				LEFT OUTER JOIN sys.default_constraints AS def ON col.cdefault = def.object_id
			WHERE obj.id = OBJECT_ID(@NomeCompletoTabelaAAuditar) AND OBJECTPROPERTY(obj.id, N'IsUserTable') = 1 AND typ.name NOT IN ('text', 'ntext', 'image', 'timestamp')
				AND col.name NOT IN ('id_utilizadorControlo', 'dataControlo')
				AND EXISTS(SELECT aob.id
					FROM sysobjects AS aob 
						INNER JOIN syscolumns AS aco on aob.id = aco.id 	
						INNER JOIN systypes AS aty on aco.xtype = aty.xtype and aty.name <> 'sysname' 
						LEFT OUTER JOIN sys.default_constraints AS ade ON aco.cdefault = ade.object_id
					WHERE aob.id = OBJECT_ID(@NomeCompletoTabelaDeAuditoria) AND OBJECTPROPERTY(aob.id, N'IsUserTable') = 1 AND aco.name = col.name 
						AND (aty.name <> typ.name OR aco.length <> col.length OR aco.isnullable <> col.isnullable OR aco.collation <> col.collation OR aco.xprec <> col.xprec OR aco.xscale <> col.xscale OR ISNULL(ade.definition, '') <> ISNULL(def.definition, '')))
			ORDER BY col.colId
		OPEN ColunasAAlterar
		FETCH NEXT FROM ColunasAAlterar INTO @NomeColuna, @TipoColuna, @TamanhoColuna, @ColunaNula, @CollationColuna, @PrecisaoColuna, @ScaleColuna, @ValorDefaultConstraintColuna
		WHILE @@FETCH_STATUS = 0
		BEGIN					
			SET @SQLAExecutar = 'IF EXISTS(SELECT object_id FROM sys.default_constraints WHERE name = ''DF_' + @NomeTabelaDeAuditoria + '_' + @NomeColuna + ''') '
			SET @SQLAExecutar = @SQLAExecutar + 'ALTER TABLE ' + @NomeCompletoTabelaDeAuditoria + ' DROP CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_' + @NomeColuna + ']'  
			EXEC (@SQLAExecutar)
			IF @ValorDefaultConstraintColuna IS NOT NULL
			BEGIN
				SET @SQLAExecutar = 'ALTER TABLE ' + @NomeCompletoTabelaDeAuditoria + ' ADD CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_' + @NomeColuna + '] DEFAULT (' + @ValorDefaultConstraintColuna + ') FOR [' + @NomeColuna + ']'
				EXEC (@SQLAExecutar)
			END
			SET @SQLAExecutar = 'ALTER TABLE ' + @NomeCompletoTabelaDeAuditoria + ' ALTER COLUMN [' + @NomeColuna + '] [' + @TipoColuna + '] '				
			IF @TipoColuna IN ('binary', 'char', 'nchar', 'nvarchar', 'varbinary', 'varchar')
			BEGIN
				IF (@TamanhoColuna = -1)
					SET @SQLAExecutar = @SQLAExecutar + '(MAX) '	 	
				ELSE
					SET @SQLAExecutar = @SQLAExecutar + '(' + CAST(@TamanhoColuna AS varchar(10)) + ') '	 	
			END	
			ELSE	
				IF @TipoColuna IN ('decimal', 'numeric')
					SET @SQLAExecutar = @SQLAExecutar + '(' + CAST(@PrecisaoColuna AS varchar(10)) + ',' + CAST(@ScaleColuna AS varchar(10)) + ') '	 			
			IF @TipoColuna IN ('char', 'nchar', 'nvarchar', 'varchar')
				SET @SQLAExecutar = @SQLAExecutar + 'COLLATE ' + @CollationColuna + ' '		
			IF @ColunaNula = 0
				SET @SQLAExecutar = @SQLAExecutar + 'NOT '	 			
			SET @SQLAExecutar = @SQLAExecutar + 'NULL'			
			EXEC (@SQLAExecutar)  
			FETCH NEXT FROM ColunasAAlterar INTO @NomeColuna, @TipoColuna, @TamanhoColuna, @ColunaNula, @CollationColuna, @PrecisaoColuna, @ScaleColuna, @ValorDefaultConstraintColuna
		END
		CLOSE ColunasAAlterar
		DEALLOCATE ColunasAAlterar
-- se houve alterações na tabela de auditoria, obtem a lista de colunas a auditar no trigger
		IF @TabelaAlterada = 1
		BEGIN
			DECLARE Colunas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT col.name
				FROM sysobjects AS obj 
					INNER JOIN syscolumns AS col on obj.id = col.id 
					INNER JOIN systypes AS typ on col.xtype = typ.xtype and typ.name <> 'sysname' 										
				WHERE obj.id = OBJECT_ID(@NomeCompletoTabelaAAuditar) AND OBJECTPROPERTY(obj.id, N'IsUserTable') = 1 AND typ.name NOT IN ('text', 'ntext', 'image', 'timestamp')			
					AND col.name NOT IN ('id_utilizadorControlo', 'dataControlo')
				ORDER BY col.colId
			OPEN Colunas
			FETCH NEXT FROM Colunas INTO @NomeColuna		
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ListaCamposAAuditar = @ListaCamposAAuditar + '[' + @NomeColuna + '],'
				FETCH NEXT FROM Colunas INTO @NomeColuna	
			END
			CLOSE Colunas
			DEALLOCATE Colunas
		END
	END
	ELSE
	BEGIN		
-- inicia o SQL para criação da tabela de auditoria
		SET @SQLAExecutar = 'CREATE TABLE ' + @NomeCompletoTabelaDeAuditoria + ' ( ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '[idAuditoria] [bigint] IDENTITY (1, 1) NOT NULL, ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '[acaoAuditoria] [char] (1) NOT NULL, ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '[dataAuditoria] [datetime] NOT NULL, ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '[id_utilizadorAuditoria] [int] NOT NULL, ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '[aplicacaoAuditoria] [varchar](250) NOT NULL, ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '[maquinaAuditoria] [varchar](250) NOT NULL, ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '[loginAuditoria] [varchar] (150) NOT NULL, ' + CHAR(13) + CHAR(10)
-- adiciona ao SQL de criação da tabela de auditoria as colunas existentes na tabela normal
		DECLARE Colunas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT col.name, typ.name, col.length, col.isnullable, col.collation, col.xprec, col.xscale, def.definition
			FROM sysobjects AS obj 
				INNER JOIN syscolumns AS col on obj.id = col.id 
				INNER JOIN systypes AS typ on col.xtype = typ.xtype and typ.name <> 'sysname' 
				LEFT OUTER JOIN sys.default_constraints AS def ON col.cdefault = def.object_id
			WHERE obj.id = OBJECT_ID(@NomeCompletoTabelaAAuditar) AND OBJECTPROPERTY(obj.id, N'IsUserTable') = 1 AND typ.name NOT IN ('text', 'ntext', 'image', 'timestamp')			
				AND col.name NOT IN ('id_utilizadorControlo', 'dataControlo')
			ORDER BY col.colId
		OPEN Colunas
		FETCH NEXT FROM Colunas INTO @NomeColuna, @TipoColuna, @TamanhoColuna, @ColunaNula, @CollationColuna, @PrecisaoColuna, @ScaleColuna, @ValorDefaultConstraintColuna	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @ListaCamposAAuditar = @ListaCamposAAuditar + '[' + @NomeColuna + '],'
			SET @SQLAExecutar = @SQLAExecutar + '[' + @NomeColuna + '] [' + @TipoColuna + '] '				
			IF @TipoColuna in ('binary', 'char', 'nchar', 'nvarchar', 'varbinary', 'varchar')
			BEGIN
				IF (@TamanhoColuna = -1)
					Set @SQLAExecutar = @SQLAExecutar + '(MAX) '	 	
				ELSE
					SET @SQLAExecutar = @SQLAExecutar + '(' + CAST(@TamanhoColuna AS varchar(10)) + ') '	 	
			END
			ELSE
				IF @TipoColuna in ('decimal', 'numeric')
					SET @SQLAExecutar = @SQLAExecutar + '(' + CAST(@PrecisaoColuna AS varchar(10)) + ',' + CAST(@ScaleColuna AS varchar(10)) + ') '	 			
			IF @TipoColuna in ('char', 'nchar', 'nvarchar', 'varchar')
				SET @SQLAExecutar = @SQLAExecutar + 'COLLATE ' + @CollationColuna + ' '		
			IF @ColunaNula = 0
				SET @SQLAExecutar = @SQLAExecutar + 'NOT '	 			
			SET @SQLAExecutar = @SQLAExecutar + 'NULL'
			IF @ValorDefaultConstraintColuna IS NOT NULL
				SET @SQLAExecutar = @SQLAExecutar + ' CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_' + @NomeColuna + '] DEFAULT (' + @ValorDefaultConstraintColuna + ')'
			SET @SQLAExecutar = @SQLAExecutar + ', ' + CHAR(13) + CHAR(10)	 				
			FETCH NEXT FROM Colunas INTO @NomeColuna, @TipoColuna, @TamanhoColuna, @ColunaNula, @CollationColuna, @PrecisaoColuna, @ScaleColuna, @ValorDefaultConstraintColuna
		END		
		CLOSE Colunas
		DEALLOCATE Colunas
-- retira ao SQL de criação da tabela de auditoria os últimos caracteres de ", CHAR(13)CHAR(10)" para fechar o script com o caracter ")"
		SET @SQLAExecutar = LEFT(@SQLAExecutar, LEN(@SQLAExecutar) - 4) + ')'
-- executa o SQL para a criação da tabela de auditoria
		EXEC (@SQLAExecutar)
-- constroi o SQL para a criação das constraints PK, FK e DF na tabela de auditoria
		SET @SQLAExecutar = 'ALTER TABLE ' + @NomeCompletoTabelaDeAuditoria + ' ADD ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + 'CONSTRAINT [PK_' + @NomeTabelaDeAuditoria + '] PRIMARY KEY CLUSTERED ([idAuditoria]) ON [PRIMARY], ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + 'CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_dataAuditoria] DEFAULT (GETDATE()) FOR [dataAuditoria], ' + CHAR(13) + CHAR(10)		
		SET @SQLAExecutar = @SQLAExecutar + 'CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_aplicacaoAuditoria] DEFAULT (ISNULL(APP_NAME(), ''n.d.'')) FOR [aplicacaoAuditoria], ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + 'CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_maquinaAuditoria] DEFAULT (ISNULL(HOST_NAME(), ''n.d.'')) FOR [maquinaAuditoria], ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + 'CONSTRAINT [DF_' + @NomeTabelaDeAuditoria + '_loginAuditoria] DEFAULT (SUSER_SNAME()) FOR [loginAuditoria]'		
-- executa o SQL para a criação das constraints PK, FK e DF na tabela de auditoria
		EXEC (@SQLAExecutar)
-- constroi o SQL para a criação dos indexes na tabela de auditoria
		SET @SQLAExecutar = 'CREATE NONCLUSTERED INDEX [IX_' + @NomeTabelaDeAuditoria + '_dataAuditoria] ON ' + @NomeCompletoTabelaDeAuditoria + '([dataAuditoria]) ON [PRIMARY] ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + 'CREATE NONCLUSTERED INDEX IX_' + @NomeTabelaDeAuditoria + '_id_utilizadorAuditoria ON ' + @NomeCompletoTabelaDeAuditoria + ' ([id_utilizadorAuditoria]) ON [PRIMARY]'
-- executa o SQL para a criação dos indexes na tabela de auditoria		
		EXEC (@SQLAExecutar)
-- executa o SQL para adicionar a propriedade "Auditar" a "0" na tabela de auditoria
		EXEC ('EXEC sys.sp_addextendedproperty @name=N''Auditar'', @value=N''0'' , @level0type=N''SCHEMA'',@level0name=N''dbo'', @level1type=N''TABLE'',@level1name=N''' + @NomeTabelaDeAuditoria + '''')
	END
-- se tabela de auditoria modificada ou criada, cria o trigger de auditoria na tabela normal
	IF ISNULL(@ListaCamposAAuditar, '') <> ''
	BEGIN		
-- executa o SQL para a remoção do trigger de auditoria na tabela normal caso ele exista
		IF EXISTS (SELECT id FROM sysobjects WHERE id = OBJECT_ID(@NomeCompletoTriggerAuditoria) and OBJECTPROPERTY(id, N'IsTrigger') = 1) 
			EXEC ('DROP TRIGGER ' + @NomeCompletoTriggerAuditoria)			
-- constroi o SQL para a criação do trigger de auditoria na tabela normal				
		SET @SQLAExecutar = 'CREATE TRIGGER ' + @NomeTriggerAuditoria + ' ON ' + @NomeCompletoTabelaAAuditar + ' WITH ENCRYPTION AFTER INSERT, UPDATE, DELETE AS ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + 'BEGIN ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '	SET NOCOUNT ON; ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '	IF EXISTS(SELECT id FROM inserted) ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '	BEGIN ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '		INSERT INTO ' + @NomeCompletoTabelaDeAuditoria + '(' +  @ListaCamposAAuditar + '[acaoAuditoria],[id_utilizadorAuditoria]) ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '		SELECT ' + @ListaCamposAAuditar + '(CASE WHEN EXISTS(SELECT id FROM deleted) THEN ''U'' ELSE ''I'' END),[id_utilizadorControlo] ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '		FROM Inserted ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '	END ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '	ELSE ' + CHAR(13) + CHAR(10)		
		SET @SQLAExecutar = @SQLAExecutar + '	BEGIN ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '		INSERT INTO ' + @NomeCompletoTabelaDeAuditoria + '(' +  @ListaCamposAAuditar + '[acaoAuditoria],[id_utilizadorAuditoria]) ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '		SELECT ' + @ListaCamposAAuditar + '''D'',[id_utilizadorControlo] ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '		FROM deleted ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + '	END ' + CHAR(13) + CHAR(10)
		SET @SQLAExecutar = @SQLAExecutar + 'END ' + CHAR(13) + CHAR(10)		
-- executa o SQL para a criação do trigger de auditoria na tabela normal				
		EXEC (@SQLAExecutar)
	END
END

ALTER AUTHORIZATION ON [sp_Auditoria_ProcessaGestaoTabela] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_Auditoria_ProcessaGestaoTabela] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Clientes_InsereOuEdita]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_Clientes_InsereOuEdita] @Acao tinyint, @Codigo varchar(18), @Nome varchar(70), @Morada varchar(70), @NIF varchar(18), @TipoNIF int, @RegiaoEstatistica int, 
	@Localidade varchar(35), @CodPostal varchar(12), @LocPostal varchar(35), @Pais varchar(2), @Email varchar(200), @Telefone varchar(14), @CodEAN varchar(13), @Utilizador varchar(30), 
	@Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de inserção ou edição do cliente
	BEGIN TRY	
		SET @NumErro = 0
-- se ação for "2" (insere ou edita), verifica se o cliente já existe ou não
		IF @Acao = 2 
		BEGIN
			IF EXISTS(SELECT CLI_CODI FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_CODI = @Codigo) 
				SET @Acao = 1
			ELSE
				SET @Acao = 0
		END
-- se ação for "0" (insere), verifica se necessita de calcular o EAN por defeito quando é DHL
		IF (@Acao = 0) AND (ISNULL(@CodEAN, '') = '') AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 3))
		BEGIN
			SELECT TOP 1 @CodEAN = DHL_ACCT
			FROM DHL_CEAN WITH(NOLOCK)
			WHERE DHL_ACCT = 'DUTYPTSCH'
		END
-- se tipo de NIF não definido, calcula em função do NIF
		IF @TipoNIF IS NULL
		BEGIN
			IF @Pais = 'PT'
			BEGIN
				IF (SUBSTRING(@NIF, 1, 1) IN ('5', '6', '7', '8', '9')) AND (@NIF <> '999999990')
					SET @TipoNIF = 0 --C
				ELSE
					SET @TipoNIF = 1 --S
			END
			ELSE
				IF EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @Pais AND PAI_ZEUR = 1)
					SET @TipoNIF = 6 --NE
				ELSE
					SET @TipoNIF = 3 --NP
		END
-- se região estatistica não definida, calcula em função do código postal
		IF @RegiaoEstatistica IS NULL
			SET @RegiaoEstatistica = dbo.fn_Geral_ObtemRegiaoEstatisiticaDeCodPostal(@CodPostal)
-- cria novo cliente
		IF @Acao = 0
		BEGIN
			INSERT INTO TAB_CLIE(CLI_CODI, CLI_CEAN, CLI_DESP, CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_TELF, CLI_EMAI, CLI_NIF, CLI_TNIF, PAI_CODI, RES_CODI, CLI_CODC, CLI_CPAG, 
				CLI_MPAG, CLI_UCRI, CLI_DCRI, CLI_UALT, CLI_DALT)
			VALUES (@Codigo, @CodEAN, 1, @Nome, @Morada, @Localidade, @CodPostal, @LocPostal, @Telefone, @Email, @NIF, @TipoNIF, @Pais, @RegiaoEstatistica, 1, 0, 
				871, @Utilizador, @DataAtual, @Utilizador, @DataAtual)
		END
		ELSE
-- edita o cliente
			IF @Acao = 1
			BEGIN
				UPDATE TAB_CLIE SET CLI_INAC = 0, 					
					CLI_NOME = @Nome, 
					CLI_MORA = @Morada, 
					CLI_LOCA = @Localidade, 
					CLI_CPOS = @CodPostal, 
					CLI_LPOS = @LocPostal, 
					CLI_TELF = @Telefone, 
					CLI_EMAI = @Email, 
					CLI_NIF = @NIF, 
					CLI_TNIF = @TipoNIF, 					
					PAI_CODI = @Pais, 
					RES_CODI = @RegiaoEstatistica, 
					CLI_UALT = @Utilizador, 
					CLI_DALT = @DataAtual
				WHERE CLI_CODI = @Codigo 
			END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_Clientes_InsereOuEdita] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Clientes_InsereOuEdita] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Contas_EmissaoDocumentosFaturacaoAutomatica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_Contas_EmissaoDocumentosFaturacaoAutomatica] @DirReportsEmpresa varchar(250), @DirFicheirosTmpLocal varchar(250), @PathGIDWinPDFExportTool varchar(250), 
	@DirDestinoDocsImportacao varchar(250), @Utilizador varchar(30), @PwLoginGIDWin varchar(30), @DirDestinoPDFsEXB varchar(250) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoConta int, @TipoDocConta varchar(4), @IDConta int, @NumeroProcesso int, @AnoProcesso int, @TipoCliente varchar(3), @CtxTipoDoc int, @ContaDVU bit, 
		@IdUtilizador int, @FaturacaoAutoAtiva bit, @ExcluiClientesTipoConta int, @ExcluiClientesSync int, @ExcluiClientesEAN int, @ExcluiClientesContaGlobalizada int, 
		@ExcluiProcessosNumeroACTM int, @ExcluiProcessosParteResto int, @DataConta datetime, @NumeroConta int, @DocsAImprimir int, @Impressora varchar(250), 
		@PathFicheiroArquivo varchar(500), @NomeReportImprimir varchar(20), @RadicalPDF varchar(2), @DescricaoFicheiroAnexar varchar(150), @NomeFicheiroAnexar varchar(100), 
		@PathFicheiroPDFAnexar varchar(500), @ArgsGIDWinPDFExportTool varchar(2000), @MsgErro varchar(MAX), @DataHoraImpressao datetime, @CheckInAtivo bit, @CMDia bit, 
		@CtxDeclaracao varchar(4), @IdDeclaracaoDAR int, @DataAtual datetime, @SQLString nvarchar(500), @SQLParams nvarchar(500), @FicheiroBinario varbinary(MAX), 
		@AcaoProcesso tinyint, @SerieConta varchar(20), @ValorTotal numeric(38, 6), @ArquivaReportBinario bit
-- coloca caracter '"' na path
	SET @PathGIDWinPDFExportTool = QUOTENAME(@PathGIDWinPDFExportTool, '"')		
-- verfica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirReportsEmpresa), 1, 1) <> '\'
		SET @DirReportsEmpresa = @DirReportsEmpresa + '\'	
	IF SUBSTRING(REVERSE(@DirFicheirosTmpLocal), 1, 1) <> '\'
		SET @DirFicheirosTmpLocal = @DirFicheirosTmpLocal + '\'		
	IF SUBSTRING(REVERSE(@DirDestinoPDFsEXB), 1, 1) <> '\'
		SET @DirDestinoPDFsEXB = @DirDestinoPDFsEXB + '\'		
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador
-- obtem campos de exclusão dos Parâmetros de Faturação Automática
	SELECT TOP 1 @FaturacaoAutoAtiva = FTA_ACTI, @ExcluiClientesTipoConta = FTA_ETCC, @ExcluiClientesSync = FTA_ECDS, @ExcluiClientesEAN = FTA_ECEC, 
		@ExcluiClientesContaGlobalizada = FTA_ECCG, @ExcluiProcessosNumeroACTM = FTA_ENAD, @ExcluiProcessosParteResto = FTA_EPTR, @CheckInAtivo = FTA_CKIN
	FROM TAB_PFTA WITH(NOLOCK)
-- se faturação automática não estiver ativa, não faz nada
	IF @FaturacaoAutoAtiva = 0
		RETURN
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem a data de emissão GMT a atribuir às Contas
	SET @DataConta = CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)
-- obtem lista de Contas c/ origem em "Faturação Automática" e ainda não emitidos (s/ numero), não anulados e que não stisfaçam os critérios de exclusão
	DECLARE Contas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
		SELECT cdo.CDO_EANO, cdo.CDO_TDOC, cdo.CDO_IDEN, cdo.CDO_NPRO, cdo.CDO_PANO, cdo.CDO_CTIP, cdo.CDO_TTPR, cdo.id_declaracaoDAR, tdo.TDO_TDOC, 
			(CASE WHEN cdo.CDO_TDOC = duc.TDO_DOCU1 THEN 1 ELSE 0 END), duc.DUC_ACAO, (CASE duc.DUC_DUNO WHEN 2 THEN 1 ELSE 0 END), 
			(CASE WHEN (CAST(CONVERT(varchar(10), dua.DUA_DDAT, 105) AS datetime) = @DataConta) THEN 1 ELSE 0 END)			
		FROM FAC_CDOC AS cdo WITH(NOLOCK) 
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU
			INNER JOIN TAB_CLIE AS cdp WITH(NOLOCK) ON cdo.CLI_DESP = cdp.CLI_CODI
			INNER JOIN TAB_CLIE AS ccc WITH(NOLOCK) ON cdo.CLI_CCOR = ccc.CLI_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON cdo.CDO_NPRO = duc.DUC_PNUM AND cdo.CDO_PANO = duc.DUC_EANO
			INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM AND dua.DUA_CODI = 1
		WHERE cdo.CDO_CNUM IS NULL AND cdo.CDO_STAT = 0 AND cdo.CDO_IMPR = 0 AND cdo.CDO_ANUL = 0 AND cdo.CDO_IMEX = 0 AND cdo.CDO_ORIG = 1 AND cdo.id_declaracaoDAR IS NULL
			AND (((ISNULL(cdo.CDO_TTPR, 0) > 0) AND (cdo.CDO_TDOC NOT IN ('CEXB', 'TEXB'))) OR ((ISNULL(cdo.CDO_TTPR, 0) >= 0) AND (cdo.CDO_TDOC IN ('CEXB', 'TEXB'))))
			AND EXISTS(SELECT DDO_CODI FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)
			AND EXISTS(SELECT DIN_CODI FROM FAC_ICDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)
			AND NOT EXISTS(SELECT DDO_CODI FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN AND ISNULL(DCD_VTOT, 0) < 0)			
			AND cdo.CDO_TTDC = (SELECT SUM(ISNULL(DCD_VTOT, 0)) FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)
			AND cdo.CDO_TTIN = (SELECT SUM(ISNULL(ICD_VTOT, 0)) FROM FAC_ICDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)
			AND (CASE @ExcluiClientesTipoConta WHEN 1 THEN (CASE WHEN ISNULL(cdo.CDO_CTIP, '') <> '' THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN ISNULL(cdo.CDO_CTIP, '') = '' THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiClientesSync WHEN 1 THEN (CASE WHEN cdp.CLI_SYNC = 1 THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN cdp.CLI_SYNC = 0 THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiClientesEAN WHEN 1 THEN (CASE WHEN ISNULL(cdo.CDO_CEAN, '') <> '' THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN ISNULL(cdo.CDO_CEAN, '') = '' THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiClientesContaGlobalizada WHEN 1 THEN (CASE WHEN ccc.CLI_CGLO = 1 THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN ccc.CLI_CGLO = 0 THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiProcessosNumeroACTM WHEN 1 THEN (CASE WHEN duc.DUC_NACT IS NOT NULL THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN duc.DUC_NACT IS NULL THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiProcessosParteResto WHEN 1 THEN (CASE WHEN ISNULL(duc.DUC_MBRT, 0) <> ISNULL(duc.DUC_TREM, 0) THEN 0 ELSE 1 END) ELSE 1 END) = 1
		UNION ALL
		SELECT cdo.CDO_EANO, cdo.CDO_TDOC, cdo.CDO_IDEN, cdo.CDO_NPRO, cdo.CDO_PANO, cdo.CDO_CTIP, cdo.CDO_TTPR, cdo.id_declaracaoDAR, tdo.TDO_TDOC, 
			0, dar.acao, 1, 
			(CASE WHEN (CAST(CONVERT(varchar(10), (SELECT TOP 1 dataContramarca FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id), 105) AS datetime) = @DataConta) THEN 1 ELSE 0 END)			
		FROM FAC_CDOC AS cdo WITH(NOLOCK) 
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU
			INNER JOIN TAB_CLIE AS cdp WITH(NOLOCK) ON cdo.CLI_DESP = cdp.CLI_CODI
			INNER JOIN TAB_CLIE AS ccc WITH(NOLOCK) ON cdo.CLI_CCOR = ccc.CLI_CODI
			INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON cdo.id_declaracaoDAR = dar.id 			
		WHERE cdo.CDO_CNUM IS NULL AND cdo.CDO_STAT = 0 AND cdo.CDO_IMPR = 0 AND cdo.CDO_ANUL = 0 AND cdo.CDO_IMEX = 0 AND cdo.CDO_ORIG = 1 AND cdo.id_declaracaoDAR IS NOT NULL			
			AND (((ISNULL(cdo.CDO_TTPR, 0) > 0) AND (cdo.CDO_TDOC NOT IN ('CEXB', 'TEXB'))) OR ((ISNULL(cdo.CDO_TTPR, 0) >= 0) AND (cdo.CDO_TDOC IN ('CEXB', 'TEXB'))))
			AND EXISTS(SELECT DDO_CODI FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)
			AND EXISTS(SELECT DIN_CODI FROM FAC_ICDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)			
			AND NOT EXISTS(SELECT DDO_CODI FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN AND ISNULL(DCD_VTOT, 0) < 0)
			AND cdo.CDO_TTDC = (SELECT SUM(ISNULL(DCD_VTOT, 0)) FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)
			AND cdo.CDO_TTIN = (SELECT SUM(ISNULL(ICD_VTOT, 0)) FROM FAC_ICDO WITH(NOLOCK) WHERE CDO_EANO = cdo.CDO_EANO AND CDO_TDOC = cdo.CDO_TDOC AND CDO_IDEN = cdo.CDO_IDEN)
			AND (CASE @ExcluiClientesTipoConta WHEN 1 THEN (CASE WHEN ISNULL(cdo.CDO_CTIP, '') <> '' THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN ISNULL(cdo.CDO_CTIP, '') = '' THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiClientesSync WHEN 1 THEN (CASE WHEN cdp.CLI_SYNC = 1 THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN cdp.CLI_SYNC = 0 THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiClientesEAN WHEN 1 THEN (CASE WHEN ISNULL(cdo.CDO_CEAN, '') <> '' THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN ISNULL(cdo.CDO_CEAN, '') = '' THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiClientesContaGlobalizada WHEN 1 THEN (CASE WHEN ccc.CLI_CGLO = 1 THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN ccc.CLI_CGLO = 0 THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiProcessosNumeroACTM WHEN 1 THEN (CASE WHEN dar.numeroACTM IS NOT NULL THEN 0 ELSE 1 END) WHEN 2 THEN (CASE WHEN dar.numeroACTM IS NULL THEN 0 ELSE 1 END) ELSE 1 END) = 1
			AND (CASE @ExcluiProcessosParteResto WHEN 1 THEN (CASE WHEN dar.totalVolumes <> dar.volumesDirty THEN 0 ELSE 1 END) ELSE 1 END) = 1			
	OPEN Contas
	FETCH NEXT FROM Contas INTO @AnoConta, @TipoDocConta, @IDConta, @NumeroProcesso, @AnoProcesso, @TipoCliente, @ValorTotal, @IdDeclaracaoDAR, @CtxTipoDoc, @ContaDVU, 
		@AcaoProcesso, @ArquivaReportBinario, @CMDia
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @NomeReportImprimir = NULL
		SET @MsgErro = NULL		
-- obtem número para o documento de Conta na tabela de Numeradores
		SELECT @NumeroConta = (NUM_NUME + 1), @SerieConta = ISNULL(NULLIF(NUM_SERI, ''), '1')
		FROM TAB_NUMD 
		WHERE TDO_DOCU = @TipoDocConta AND NUM_EANO = @AnoConta
-- atualiza número e data na tabela de Numeradores (processo "puxado" p/ antes da numeração da conta p/ evitar ter várias contas c/ mesmo número face ao delay existente no update da FAC_CDOC)
		UPDATE TAB_NUMD SET NUM_NUME = NUM_NUME + 1, NUM_DATA = @DataConta
		WHERE TDO_DOCU = @TipoDocConta AND NUM_EANO = @AnoConta
-- atualiza documento de Conta c/ número, data e status
		UPDATE FAC_CDOC SET CDO_DTEM = @DataConta, CDO_CNUM = @NumeroConta, CDO_IMPR = 1, CDO_STAT = 1, CDO_UALT = @Utilizador, CDO_DTAL = @DataAtual, CDO_SERI = @SerieConta
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @TipoDocConta AND CDO_IDEN = @IDConta
-- atualiza número da Conta e dados ADT no processo DUI2 de origem
		IF @IdDeclaracaoDAR IS NULL
		BEGIN
			UPDATE PRO_DUCG SET DUC_CNTN = @NumeroConta, 
				DUC_LADT = (CASE WHEN (@CheckInAtivo = 1) AND (@CMDia = 1) THEN 1 ELSE DUC_LADT END), 			
				DUC_DADT = (CASE WHEN (@CheckInAtivo = 1) AND (@CMDia = 1) THEN @DataAtual ELSE DUC_DADT END), 
				DUC_UADT = (CASE WHEN (@CheckInAtivo = 1) AND (@CMDia = 1) THEN @Utilizador ELSE DUC_UADT END)
			WHERE DUC_PNUM = @NumeroProcesso AND DUC_EANO = @AnoProcesso
		END
		ELSE
-- atualiza dados ADT no processo DAR de origem se o "Check-In" estiver ativo e a "Contramarca" for do dia
			IF (@CheckInAtivo = 1) AND (@CMDia = 1)
			BEGIN
				UPDATE tb_DeclaracoesDAR SET libertoADT = 1, 			
					id_utilizadorADT = @IdUtilizador, 
					dataADT = @DataAtual, 					
					id_utilizadorControlo = @IdUtilizador,
					dataControlo = @DataAtual
				WHERE id = @IdDeclaracaoDAR
			END
-- obtem nome do 1º report FRF configurado p/ imprimir e anexar no tipo de documento da Conta
		SELECT @NomeReportImprimir = (CASE WHEN TDO_IRP1 = 1 AND TDO_ARP1 IN (1, 3) THEN TDO_REP1 WHEN TDO_IRP2 = 1 AND TDO_ARP2 IN (1, 3) THEN TDO_REP2 WHEN TDO_IRP3 = 1 AND TDO_ARP3 IN (1, 3) THEN TDO_REP3 WHEN TDO_IRP4 = 1 AND TDO_ARP4 IN (1, 3) THEN TDO_REP4 ELSE NULL END), 
			@RadicalPDF = (CASE WHEN TDO_IRP1 = 1 AND TDO_ARP1 IN (1, 3) THEN '' WHEN TDO_IRP2 = 1 AND TDO_ARP2 IN (1, 3) THEN '_2' WHEN TDO_IRP3 = 1 AND TDO_ARP3 IN (1, 3) THEN '_3' WHEN TDO_IRP4 = 1 AND TDO_ARP4 IN (1, 3) THEN '_4' ELSE NULL END)
		FROM TAB_TDOC WITH(NOLOCK) 
		WHERE TDO_DOCU = @TipoDocConta
-- procede à geração do report em PDF para o documento de Conta
		IF ISNULL(@NomeReportImprimir, '') <> ''
		BEGIN
			SET @NomeFicheiroAnexar = CAST(@NumeroProcesso AS varchar(10)) + '.' + @TipoDocConta + '.' + CAST(@NumeroConta AS varchar(10)) + '.' + CAST(@AnoConta AS varchar(4)) + @RadicalPDF + '.pdf';		
			SET @PathFicheiroPDFAnexar = @DirFicheirosTmpLocal + @NomeFicheiroAnexar
			SET @ArgsGIDWinPDFExportTool = '-s' + @@SERVERNAME + ' -p' + @PwLoginGIDWin + ' -b' + DB_NAME() + ' -r' + QUOTENAME((@DirReportsEmpresa + @NomeReportImprimir), '"') + ' -c' + CAST(@CtxTipoDoc AS varchar(2)) + ' -a' + CAST(@AnoConta AS varchar(4)) + ' -t' + @TipoDocConta + ' -i' + CAST(@IDConta AS varchar(20)) + ' -f' + QUOTENAME(@PathFicheiroPDFAnexar, '"')					 
			EXEC GIDWIN.dbo.SP_Externo_ExecutaPrograma @PathGIDWinPDFExportTool, @ArgsGIDWinPDFExportTool, @MsgErro OUTPUT
-- procede à anexação no documento no Arquivo no processo de origem
			IF ISNULL(@MsgErro, '') = ''
			BEGIN
				SET @DescricaoFicheiroAnexar = 'Fatura N.º ' + CAST(@NumeroConta AS varchar(10))
-- anexa o ficheiro à declaração DUI2				
				IF (@IdDeclaracaoDAR IS NULL) AND (@ArquivaReportBinario = 0)
					EXEC SP_DeclImportacao_AnexaDocumento @PathFicheiroPDFAnexar, @DirDestinoDocsImportacao, @AnoProcesso, @NumeroProcesso, @DescricaoFicheiroAnexar, @NomeFicheiroAnexar, @Utilizador, 1, 'FTINTERN', 2
				ELSE
				BEGIN								
-- inicia variaveis para executar o SQL dinamicamente
					SET @SQLString = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiroPDFAnexar + ''', SINGLE_BLOB) AS t)'
					SET @SQLParams = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'			
-- obtem o ficheiro em binario
					EXECUTE sp_executesql @SQLString, @SQLParams, @OUTFicheiroBinario = @FicheiroBinario OUTPUT	
-- anexa o ficheiro à declaração IMP-CAU
					IF @IdDeclaracaoDAR IS NULL
					BEGIN
						INSERT INTO PRO_DUFI(DUC_PNUM, DUC_EANO, DUF_DESC, DUF_DATA, DUF_NOMF, DUF_UTIL, DUF_ISER, DUF_TMSG, DUF_ORIG, DUF_FICH)
						VALUES(@NumeroProcesso, @AnoProcesso, @DescricaoFicheiroAnexar, @DataAtual, @NomeFicheiroAnexar, @Utilizador, 1, 'FTINTERN', 2, @FicheiroBinario)		
					END
					ELSE
					BEGIN
-- anexa o ficheiro à declaração DAR										
						INSERT INTO tb_DeclaracoesDARArquivos(id_declaracaoDAR, descricao, tipo, nomeFicheiro, ficheiro, id_utilizadorArquivo, dataArquivo, origem, 
							id_utilizadorControlo, dataControlo)
						VALUES(@IdDeclaracaoDAR, @DescricaoFicheiroAnexar, 1, @NomeFicheiroAnexar, @FicheiroBinario, @IdUtilizador, @DataAtual, 2, 
							@IdUtilizador, @DataAtual)
					END
-- remove o ficheiro anexado
					EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroPDFAnexar, @MsgErro OUTPUT
					IF ISNULL(@MsgErro, '') <> ''
						RAISERROR ('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroPDFAnexar, @MsgErro)
				END
			END
		END
-- processa as impressões apenas p/ Contas cujo valor total seja superior a 5€ 
		IF @ValorTotal > 5
		BEGIN
-- obtem a lista de impressoras configuradas para o documento de Conta
			DECLARE Impressoras CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT fti.FTI_DIMP, (CASE WHEN (fta.FTA_CKIN = 1) AND (@CMDia = 1) AND (ISNULL(fta.FTA_IADT, '') <> '') AND (fti.FTI_SADT = 1) THEN fta.FTA_IADT ELSE fti.FTI_IMPR END)
				FROM TAB_PFTI AS fti WITH(NOLOCK) 
					INNER JOIN TAB_PFTA AS fta WITH(NOLOCK) ON fti.FTA_IDEN = fta.FTA_IDEN
				WHERE fti.TDO_DOCU = @TipoDocConta AND fti.FTI_CTIP = @TipoCliente AND fti.FTI_DDVU = @ContaDVU 
					AND (CASE WHEN (fti.FTI_IAUT = 1) AND (@AcaoProcesso = 1) THEN 1 WHEN (fti.FTI_IAUT = 1) AND (@AcaoProcesso = 0) THEN 0 ELSE 1 END) = 1 
			OPEN Impressoras
			FETCH NEXT FROM Impressoras INTO @DocsAImprimir, @Impressora
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @DataHoraImpressao = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- processa impressão da Fatura anexada no detalhe do Arquivo do processo de origem		
				IF @DocsAImprimir IN (0, 1)
				BEGIN
					SET @PathFicheiroArquivo = NULL
					SET @FicheiroBinario = NULL
					IF @IdDeclaracaoDAR IS NULL
					BEGIN
						SELECT TOP 1 @PathFicheiroArquivo = DUF_LINK
						FROM PRO_DUFI WITH(NOLOCK) 
						WHERE DUF_ORIG = 2 AND DUF_TMSG = 'FTINTERN' AND DUC_PNUM = @NumeroProcesso AND DUC_EANO = @AnoProcesso
						ORDER BY DUC_IDEN DESC
					END
					ELSE
					BEGIN
						SELECT TOP 1 @FicheiroBinario = ficheiro
						FROM tb_DeclaracoesDARArquivos WITH(NOLOCK) 
						WHERE id_declaracaoDAR = @IdDeclaracaoDAR AND tipo = 1 AND origem = 2
						ORDER BY id DESC
					END
-- se existir ficheiro anexado ao processo de origem do tipo "Fatura Interna", gera pedido de impressão
					IF (ISNULL(@PathFicheiroArquivo, '') <> '') OR (@FicheiroBinario IS NOT NULL)
					BEGIN
						INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_FICH, IMF_IMPR, IMF_STAT, IMF_DTST, IMF_FBIN)
						VALUES(@DataHoraImpressao, @PathFicheiroArquivo, @Impressora, 0, @DataHoraImpressao, @FicheiroBinario)
					END
				END
-- processa impressão do DU anexado no detalhe do Arquivo apenas no processo DUI2 de origem
				IF (@IdDeclaracaoDAR IS NULL) AND (@DocsAImprimir IN (0, 2))
				BEGIN
					SET @PathFicheiroArquivo = NULL
					SELECT TOP 1 @PathFicheiroArquivo = DUF_LINK
					FROM PRO_DUFI WITH(NOLOCK) 
					WHERE DUF_ORIG = 1 AND DUF_TMSG = 'IM006A.1' AND DUC_PNUM = @NumeroProcesso AND DUC_EANO = @AnoProcesso
					ORDER BY DUC_IDEN DESC
-- se existir ficheiro anexado ao processo de origem do tipo "IM006A.1", gera pedido de impressão				
					IF ISNULL(@PathFicheiroArquivo, '') <> ''
					BEGIN
						INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_FICH, IMF_IMPR, IMF_STAT, IMF_DTST)
						VALUES(@DataHoraImpressao, @PathFicheiroArquivo, @Impressora, 0, @DataHoraImpressao)
					END
				END
				FETCH NEXT FROM Impressoras INTO @DocsAImprimir, @Impressora
			END
			CLOSE Impressoras
			DEALLOCATE Impressoras		
		END
		FETCH NEXT FROM Contas INTO @AnoConta, @TipoDocConta, @IDConta, @NumeroProcesso, @AnoProcesso, @TipoCliente, @ValorTotal, @IdDeclaracaoDAR, @CtxTipoDoc, @ContaDVU, 
			@AcaoProcesso, @ArquivaReportBinario, @CMDia
	END
	CLOSE Contas
	DEALLOCATE Contas
-- se "Check-In" ADT ativo, procede à libertação ADT das declarações DUI2 que tenham a "Data CM" como a atual e a natureza "Gere ADT" e não "Cria Conta" ou não "Gere ADT" e "Cria Conta" e cliente é "Conta Globalizada"
	IF @CheckInAtivo = 1
	BEGIN
		DECLARE DeclaracoesDUI2 CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_CNTX, DUC_IDTY, DUC_EANO, DUC_PNUM
			FROM VW_Importacao_GestaoADT
			WHERE CAST(CONVERT(varchar(10), DUA_DDAT, 105) as datetime) = @DataConta AND ((NDE_GADT = 1 AND NDE_CRCO = 0) OR (NDE_GADT = 0 AND NDE_CRCO = 1 AND CLI_CGLO = 1))
		OPEN DeclaracoesDUI2
		FETCH NEXT FROM DeclaracoesDUI2 INTO @CtxDeclaracao, @IdDeclaracaoDAR, @AnoProcesso, @NumeroProcesso
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- liberta ADT na declaração DAR/DUI2
			IF @CtxDeclaracao = 'DAR'
			BEGIN
				UPDATE tb_DeclaracoesDAR SET libertoADT = 1, 			
					id_utilizadorADT = @IdUtilizador, 
					dataADT = @DataAtual, 					
					id_utilizadorControlo = @IdUtilizador,
					dataControlo = @DataAtual
				WHERE id = @IdDeclaracaoDAR
			END
			ELSE
			BEGIN
				UPDATE PRO_DUCG SET DUC_LADT = 1, 
					DUC_DADT = @DataAtual, 
					DUC_UADT = @Utilizador
				WHERE DUC_PNUM = @NumeroProcesso AND DUC_EANO = @AnoProcesso			
			END
			FETCH NEXT FROM DeclaracoesDUI2 INTO @CtxDeclaracao, @IdDeclaracaoDAR, @AnoProcesso, @NumeroProcesso
		END
		CLOSE DeclaracoesDUI2
		DEALLOCATE DeclaracoesDUI2
	END
END

ALTER AUTHORIZATION ON [SP_Contas_EmissaoDocumentosFaturacaoAutomatica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Contas_EmissaoDocumentosFaturacaoAutomatica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Contas_GeraContaGlobalizada]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Contas_GeraContaGlobalizada] @LstContasOrigem xml, @CodCliente varchar(18), @CodNatureza varchar(3), @CodDespachante varchar(6), @CodAlfandega varchar(8), @Utilizador varchar(30), 
	@AnoContaGlobal int OUTPUT, @TipoDocContaGlobal varchar(4) OUTPUT, @IdContaGlobal int OUTPUT, @MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Handle int, @CodDespHonorarios int, @NumLinhaDespesa int, @CodDespesa int, @DescricaoDespesa varchar(70), @ValorDespesa numeric(38, 6), @TotalDocumentadas numeric(38, 6), 
		@TotalInerentes numeric(38, 6), @TotalInerentesIsentoIVA numeric(38, 6), @TotalHonorarios numeric(38, 6), @TotalQuantidade numeric(38, 6), @TotalPesoBrt numeric(38, 6), 
		@TotalPesoLiq numeric(38, 6), @TxIVAIsenta numeric(38, 6), @TxIVAReduzida numeric(38, 6), @TxIVAIntermedia numeric(38, 6), @TxIVANormal numeric(38, 6), @ProxNumeroProcesso int, 
		@PercRetencao numeric(38, 6), @Erro int, @ChargeCodeDespesa varchar(4), @DataAberturaMin datetime, @DataAberturaMax datetime, @IsentaIVADespesa bit, @CodIsencaoIVADespesa varchar(3), 
		@MencaoIsencaoIVADespesa varchar(100), @CodDespInerenteHonGlob int, @FormulaDespInerenteHonGlob varchar(4000), @OUTValorNumerico numeric(38, 6)
-- prepara XML para leitura
	EXEC sp_xml_preparedocument @Handle OUTPUT, @LstContasOrigem, ''
-- carrega dados XML para tabela TMP 
	SELECT CDO_EANO, CDO_TDOC, CDO_IDEN
	INTO #Contas
	FROM OPENXML(@Handle, N'/DocumentosConta/Conta')
	WITH (CDO_EANO int 'CDO_EANO', CDO_TDOC varchar(4) 'CDO_TDOC', CDO_IDEN int 'CDO_IDEN')
-- liberta XML carregado
	EXEC sp_xml_removedocument @Handle	
-- inicia transacção para inserção dados CAB e DET da conta
	BEGIN TRANSACTION		
	BEGIN TRY
-- obtem dados das contas a globalizar
		SELECT @CodDespHonorarios = MIN(cn.DIN_HONO), @TotalDocumentadas = SUM(ISNULL(cn.CDO_TTDC, 0)), @TotalInerentes = SUM(ISNULL(cn.CDO_TTIN, 0)), @TotalHonorarios = SUM(ISNULL(cn.CDO_TTHO, 0)), 
			@TotalQuantidade = SUM(ISNULL(cn.CDO_QUNT, 0)), @TotalPesoBrt = SUM(ISNULL(cn.CDO_PBRT, 0)), @TotalPesoLiq = SUM(ISNULL(cn.CDO_PLIQ, 0)), @DataAberturaMin = MIN(cn.CDO_DTAB), 
			@DataAberturaMax = MAX(cn.CDO_DTAB)
		FROM #Contas AS tc 
			INNER JOIN FAC_CDOC AS cn WITH(NOLOCK) ON tc.CDO_EANO = cn.CDO_EANO and tc.CDO_TDOC = cn.CDO_TDOC and tc.CDO_IDEN = cn.CDO_IDEN
-- obtem soma das despesas inerentes isentas de IVA das contas a globalizar
		SET @TotalInerentesIsentoIVA = ISNULL((SELECT SUM(ISNULL(di.ICD_VTOT, 0)) 
											FROM #Contas AS tc 
												INNER JOIN FAC_ICDO AS di WITH(NOLOCK) ON tc.CDO_EANO = di.CDO_EANO and tc.CDO_TDOC = di.CDO_TDOC and tc.CDO_IDEN = di.CDO_IDEN
											WHERE di.ICD_ISEN = 1), 0)
--  obtem taxas IVA dos parametros da aplicação
		SELECT TOP 1 @TxIVAIsenta = PAP_TXIS, @TxIVAReduzida = PAP_TXRD, @TxIVAIntermedia = PAP_TXIN, @TxIVANormal = PAP_TXNR
		FROM TAB_PAPL WITH(NOLOCK) 
-- obtem dados dos parametros de facturação
		SELECT TOP 1 @ProxNumeroProcesso = PFC_PNPG, @PercRetencao = ISNULL(PFC_RFNT, 0)
		FROM TAB_PFCT
-- obtem ID para nova conta
		SELECT @IdContaGlobal = ISNULL((SELECT MAX(CDO_IDEN) FROM FAC_CDOC WHERE CDO_EANO = @AnoContaGlobal and CDO_TDOC = @TipoDocContaGlobal), 0) + 1
-- insere CAB da conta
		INSERT INTO FAC_CDOC (CDO_EANO, CDO_TDOC, CDO_IDEN, NDE_CODI, CDO_NPRO, CDO_TCNT, DEC_CODI, ALF_CODI, CDO_STAT, CDO_DTAB, CDO_DTIN, CLI_DESP, CLI_CCOR, CLI_ENDC, DIN_HONO, CDO_AGRA, 
			CDO_DESA, CDO_FORH, CDO_TTDC, CDO_TTIN, CDO_TTHO, CDO_TTRF, CDO_BIVA, CDO_IVA, CDO_TXIV, CDO_RTFO, CDO_TTPR, CDO_ISIV, CDO_QUNT, CDO_QUAL, CDO_DESC, CDO_PBRT, CDO_PLIQ, CDO_VADU, 
			CDO_UCRI, CDO_DTCR, CDO_UALT, CDO_DTAL, CDO_TONE, CDO_OBSR, CDO_IN01, CDO_IN02, CDO_IN03, CDO_IN04, CDO_VI01, CDO_VI02, CDO_VI03, CDO_VI04, CDO_MPAG, CDO_CTIP, CDO_CNOM, CDO_CMOR, 
			CDO_CLOC, CDO_CCPO, CDO_CLPO, CDO_CNIF, CDO_CPAI, CDO_CEAN, IIV_CODI, CCO_CODI, CDO_CPAG)
		SELECT @AnoContaGlobal, @TipoDocContaGlobal, @IdContaGlobal, @CodNatureza, @ProxNumeroProcesso, (CASE td.TDO_TCNT WHEN 0 THEN CAST(0 as bit) ELSE CAST(1 as bit) END), @CodDespachante, 
			@CodAlfandega, 0, CAST(CONVERT(varchar(10), GETDATE(), 105) as datetime), CAST(CONVERT(varchar(10), GETDATE(), 105) as datetime), @CodCliente, @CodCliente, @CodCliente, 
			@CodDespHonorarios, 0, 0, nd.NDE_FORM, @TotalDocumentadas, @TotalInerentes, @TotalHonorarios, ROUND((@TotalInerentes + @TotalHonorarios) * (@PercRetencao / 100), 2), 
			(@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios), ROUND(((@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) * nd.NDE_TIVA / 100), 2), nd.NDE_TIVA, 
			@PercRetencao, (@TotalDocumentadas + @TotalInerentes + @TotalHonorarios + (ROUND(((@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) * nd.NDE_TIVA / 100), 2))), 
			mi.IIV_MENC, @TotalQuantidade, 'Diversos', 'Diversos', @TotalPesoBrt, @TotalPesoLiq, 0, @Utilizador, GETDATE(), @Utilizador, GETDATE(), 0, 
			('Faturação relativa ao período compreendido entre ' + CONVERT(varchar(10), @DataAberturaMin, 105) + ' e ' + CONVERT(varchar(10), @DataAberturaMax, 105) + ', conforme lista anexa.'), 
			(@TotalDocumentadas + (CASE nd.NDE_TIVA WHEN @TxIVAIsenta THEN (@TotalInerentes + @TotalHonorarios) ELSE @TotalInerentesIsentoIVA END)), 			
			(CASE nd.NDE_TIVA WHEN @TxIVAReduzida THEN (@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) ELSE 0 END), 
			(CASE nd.NDE_TIVA WHEN @TxIVAIntermedia THEN (@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) ELSE 0 END), 
			(CASE nd.NDE_TIVA WHEN @TxIVANormal THEN (@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) ELSE 0 END), 						
			0, 
			(CASE nd.NDE_TIVA WHEN @TxIVAReduzida THEN ROUND(((@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) * nd.NDE_TIVA / 100), 2) ELSE 0 END), 
			(CASE nd.NDE_TIVA WHEN @TxIVAIntermedia THEN ROUND(((@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) * nd.NDE_TIVA / 100), 2) ELSE 0 END), 
			(CASE nd.NDE_TIVA WHEN @TxIVANormal THEN ROUND(((@TotalInerentes - @TotalInerentesIsentoIVA + @TotalHonorarios) * nd.NDE_TIVA / 100), 2) ELSE 0 END), 
			cl.CLI_MPAG, (CASE WHEN cl.CLI_CODC = 1 THEN 'COD' WHEN cl.CLI_CACC = 1 THEN 'ACC' WHEN cl.CLI_CEXB = 1 THEN 'CEXB' WHEN cl.CLI_CDAS = 1 THEN 'CDAS' ELSE NULL END), cl.CLI_NOME, 
			cl.CLI_MORA, cl.CLI_LOCA, cl.CLI_CPOS, cl.CLI_LPOS, cl.CLI_NIF, cl.PAI_CODI, cl.CLI_CEAN, nd.IIV_CODI, nd.CCO_CODI, cl.CLI_CPAG
		FROM TAB_TDOC AS td WITH(NOLOCK) 
			INNER JOIN TAB_NDES AS nd WITH(NOLOCK) ON nd.NDE_CODI = @CodNatureza
			INNER JOIN TAB_CLIE AS cl WITH(NOLOCK) ON cl.CLI_CODI = @CodCliente
			LEFT OUTER JOIN GIDWIN.dbo.FAP_MIIV AS mi WITH(NOLOCK) ON nd.IIV_CODI = mi.IIV_CODI
		WHERE td.TDO_DOCU = @TipoDocContaGlobal
-- incrementa Nº. Prox. Processo
		UPDATE TAB_PFCT SET PFC_PNPG = PFC_PNPG + 1		
-- inicia variaveis
		SET @NumLinhaDespesa = 0
-- obtem despesas documentadas a inserir
		DECLARE DespDocumentadasAInserir CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dd.DDO_CODI, td.DDO_NOME, td.CCO_CODI, SUM(ISNULL(dd.DCD_VTOT, 0))
			FROM #Contas as tc 
				INNER JOIN FAC_DCDO AS dd WITH(NOLOCK) ON tc.CDO_EANO = dd.CDO_EANO and tc.CDO_TDOC = dd.CDO_TDOC and tc.CDO_IDEN = dd.CDO_IDEN
				INNER JOIN TAB_DDOC AS td WITH(NOLOCK) ON dd.DDO_CODI = td.DDO_CODI
			WHERE dd.DDO_CODI IS NOT NULL
			GROUP BY dd.DDO_CODI, td.DDO_NOME, td.CCO_CODI
			ORDER BY dd.DDO_CODI	
		OPEN DespDocumentadasAInserir
		FETCH NEXT FROM DespDocumentadasAInserir INTO @CodDespesa, @DescricaoDespesa, @ChargeCodeDespesa, @ValorDespesa
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SELECT @NumLinhaDespesa = @NumLinhaDespesa + 1	
-- insere DET de despasas documentadas na conta
			INSERT INTO FAC_DCDO (CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DDO_CODI, DCD_DESC, DCD_VTOT, CCO_CODI)
			VALUES (@AnoContaGlobal, @TipoDocContaGlobal, @IdContaGlobal, @NumLinhaDespesa, @CodDespesa, @DescricaoDespesa, @ValorDespesa, @ChargeCodeDespesa)						
			FETCH NEXT from DespDocumentadasAInserir into @CodDespesa, @DescricaoDespesa, @ChargeCodeDespesa, @ValorDespesa
		END
		CLOSE DespDocumentadasAInserir
		DEALLOCATE DespDocumentadasAInserir
-- insere DET de despasas documentadas na conta s/ despesa associada
		WHILE @NumLinhaDespesa < 9
		BEGIN
			SELECT @NumLinhaDespesa = @NumLinhaDespesa + 1
-- insere DET de despasas documentadas na conta
			INSERT INTO FAC_DCDO (CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DCD_VTOT)
			VALUES (@AnoContaGlobal, @TipoDocContaGlobal, @IdContaGlobal, @NumLinhaDespesa, 0)					
		END
-- inicia variaveis
		SET @NumLinhaDespesa = 0
-- obtem despesas inerentes a inserir
		DECLARE DespInerentesAInserir CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT di.DIN_CODI, ti.DIN_NOME, ti.CCO_CODI, di.ICD_ISEN, di.IIV_CODI, di.IIV_MENC, SUM(ISNULL(di.ICD_VTOT, 0))
			FROM #Contas AS tc 
				INNER JOIN FAC_ICDO AS di WITH(NOLOCK) ON tc.CDO_EANO = di.CDO_EANO and tc.CDO_TDOC = di.CDO_TDOC and tc.CDO_IDEN = di.CDO_IDEN
				INNER JOIN TAB_DINE AS ti WITH(NOLOCK) ON di.DIN_CODI = ti.DIN_CODI
			WHERE di.DIN_CODI IS NOT NULL
			GROUP BY di.DIN_CODI, ti.DIN_NOME, ti.CCO_CODI, di.ICD_ISEN, di.IIV_CODI, di.IIV_MENC
			ORDER BY di.DIN_CODI	
		OPEN DespInerentesAInserir
		FETCH NEXT FROM DespInerentesAInserir INTO @CodDespesa, @DescricaoDespesa, @ChargeCodeDespesa, @IsentaIVADespesa, @CodIsencaoIVADespesa, @MencaoIsencaoIVADespesa, @ValorDespesa
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SELECT @NumLinhaDespesa = @NumLinhaDespesa + 1	
-- insere DET de despasas inerentes na conta
			INSERT INTO FAC_ICDO (CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, DIN_CODI, ICD_DESC, ICD_VTOT, CCO_CODI, ICD_ISEN, IIV_CODI, IIV_MENC)
			VALUES (@AnoContaGlobal, @TipoDocContaGlobal, @IdContaGlobal, @NumLinhaDespesa, @CodDespesa, @DescricaoDespesa, @ValorDespesa, @ChargeCodeDespesa, @IsentaIVADespesa, @CodIsencaoIVADespesa,
				@MencaoIsencaoIVADespesa)						
			FETCH NEXT from DespInerentesAInserir into @CodDespesa, @DescricaoDespesa, @ChargeCodeDespesa, @IsentaIVADespesa, @CodIsencaoIVADespesa, @MencaoIsencaoIVADespesa, @ValorDespesa
		END
		CLOSE DespInerentesAInserir
		DEALLOCATE DespInerentesAInserir
-- insere DET de despesas inerentes na conta s/ despesa associada
		WHILE @NumLinhaDespesa < 12
		BEGIN
			SELECT @NumLinhaDespesa = @NumLinhaDespesa + 1
-- insere DET de despasas inerentes na conta
			INSERT INTO FAC_ICDO (CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, ICD_VTOT)
			VALUES (@AnoContaGlobal, @TipoDocContaGlobal, @IdContaGlobal, @NumLinhaDespesa, 0)					
		END		
-- obtem a despesa inerente de honorários em globalização definida no cliente da Conta gerada		
		SELECT @CodDespInerenteHonGlob = di.DIN_CODI, @FormulaDespInerenteHonGlob = di.DIN_FCLG
		FROM TAB_CLIE AS cl WITH(NOLOCK)
			INNER JOIN TAB_DINE AS di WITH(NOLOCK) ON cl.DIN_CODI1 = di.DIN_CODI
		WHERE CLI_CODI = @CodCliente
-- se despesa inerente de honorários p/ globalização definida e a mesma tem atribuida uma formula de calculo, processa o ajuste do valor da inerente na Conta gerada 
		IF (@CodDespInerenteHonGlob IS NOT NULL) AND (ISNULL(@FormulaDespInerenteHonGlob, '') <> '') AND (EXISTS(SELECT 1 FROM FAC_ICDO WITH(NOLOCK) WHERE CDO_EANO = @AnoContaGlobal AND CDO_TDOC = @TipoDocContaGlobal AND CDO_IDEN = @IdContaGlobal AND DIN_CODI = @CodDespInerenteHonGlob))
		BEGIN
			SET @OUTValorNumerico = 0
			EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaDespInerenteHonGlob, @OUTValorNumerico OUTPUT, @AnoContaGlobal, @TipoDocContaGlobal, @IdContaGlobal
			SET @ValorDespesa = @OUTValorNumerico
-- atualiza a linha da despesa inerente
			UPDATE FAC_ICDO SET ICD_VTOT = @ValorDespesa
			WHERE CDO_EANO = @AnoContaGlobal AND CDO_TDOC = @TipoDocContaGlobal AND CDO_IDEN = @IdContaGlobal AND DIN_CODI = @CodDespInerenteHonGlob			
-- obtém o valor total de inerentes
			SELECT @TotalInerentes =  SUM(ISNULL(ICD_VTOT, 0)), @TotalInerentesIsentoIVA = SUM((CASE ICD_ISEN WHEN 1 THEN ISNULL(ICD_VTOT, 0) ELSE 0 END))
			FROM FAC_ICDO WITH(NOLOCK) 
			WHERE CDO_EANO = @AnoContaGlobal AND CDO_TDOC = @TipoDocContaGlobal AND CDO_IDEN = @IdContaGlobal
-- atualiza totais do documento de conta
			UPDATE FAC_CDOC SET 
				CDO_TTIN = @TotalInerentes, 
				CDO_TTRF = ROUND((@TotalInerentes + ISNULL(CDO_TTHO, 0)) * ISNULL(CDO_RTFO, 0) / 100, 2), 
				CDO_BIVA = (@TotalInerentes - @TotalInerentesIsentoIVA + ISNULL(CDO_TTHO, 0)), 
				CDO_IVA = ROUND((@TotalInerentes - @TotalInerentesIsentoIVA + ISNULL(CDO_TTHO, 0)) * ISNULL(CDO_TXIV, 0) / 100, 2), 
				CDO_TTPR = (ISNULL(CDO_TTDC, 0) + @TotalInerentes + ISNULL(CDO_TTHO, 0) + ROUND((@TotalInerentes - @TotalInerentesIsentoIVA + ISNULL(CDO_TTHO, 0)) * ISNULL(CDO_TXIV, 0) / 100, 2)), 
				CDO_IN01 = (ISNULL(CDO_TTDC, 0) + (CASE WHEN (CDO_TXIV = 0) THEN (@TotalInerentes + ISNULL(CDO_TTHO, 0)) ELSE @TotalInerentesIsentoIVA END)), 
				CDO_IN02 = 0, 
				CDO_IN03 = 0, 
				CDO_IN04 = (CASE WHEN (CDO_TXIV > 0) THEN (@TotalInerentes - @TotalInerentesIsentoIVA + ISNULL(CDO_TTHO, 0)) ELSE 0 END), 
				CDO_VI01 = 0, 
				CDO_VI02 = 0, 
				CDO_VI03 = 0, 
				CDO_VI04 = ROUND((@TotalInerentes - @TotalInerentesIsentoIVA + ISNULL(CDO_TTHO, 0)) * ISNULL(CDO_TXIV, 0) / 100, 2)
			WHERE CDO_EANO = @AnoContaGlobal and CDO_TDOC = @TipoDocContaGlobal and CDO_IDEN = @IdContaGlobal
		END
-- actualiza contas globalizadas para o status de "Anulado" c/ ligação à respectiva conta globalizada
		UPDATE FAC_CDOC SET CDO_ANUL = 1, CDO_STAT = 3, CDO_UALT = @Utilizador, CDO_DTAL = GETDATE(), CDO_ANOG = @AnoContaGlobal, CDO_TDOG = @TipoDocContaGlobal, CDO_IDEG = @IdContaGlobal			
		FROM FAC_CDOC AS cn WITH(NOLOCK) 
			INNER JOIN #Contas AS tc ON cn.CDO_EANO = tc.CDO_EANO and cn.CDO_TDOC = tc.CDO_TDOC and cn.CDO_IDEN = tc.CDO_IDEN
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) 
			+ ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- remove tabela TMP
	DROP TABLE #Contas
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_Contas_GeraContaGlobalizada] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Contas_GeraContaGlobalizada] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Contas_GeraNotaCredito]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Contas_GeraNotaCredito] @AnoConta int, @TipoDocConta varchar(4), @IDConta int, @NumeroConta int, @CodNaturezaConta varchar(3), @NumProcessoConta int, @AnoProcessoConta int, 
	@CodDeclProcessoConta varchar(6), @ExpProcessoConta bit, @CartaPorteConta varchar(35), @CodClienteConta varchar(18), @CodIsencaoIVAConta varchar(3), @IdDeclaracaoDARConta int, 
	@Observacoes varchar(1000), @LstDespesasConta xml, @Utilizador varchar(30), @CodMotivoCredito int, @DescMotivoCredito varchar(50), @MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis
	DECLARE @CodTipoDocNC varchar(4), @TipoDocSAFT varchar(2), @TxIVAIsenta numeric(38, 6), @TxIVAReduzida numeric(38, 6), @TxIVAIntermedia numeric(38, 6), @TxIVANormal numeric(38, 6), 
		@NomeCliente varchar(70), @MoradaCliente varchar(70), @LocalidadeCliente varchar(35), @CodPostalCliente varchar(12), @LocPostalCliente varchar(35), @NIFCliente varchar(18), 
		@CodPaisCliente varchar(2), @IdContaCC int, @NumeroDocNC int, @NumLinha int, @ValorDespesa numeric(38, 6), @CodRubrica int, @NomeRubrica varchar(70), @TxIVARubrica numeric(38, 6), 
		@RubricaLancaHonorarios bit, @CodIsencaoIVA varchar(3), @MencaoIsencaoIVA varchar(100), @CodChargeCode varchar(4), @IVALinha numeric(38, 6), @TotalLiquido numeric(38, 6), 
		@TotalIVA numeric(38, 6), @IncidenciaTxIVA01 numeric(38, 6), @IncidenciaTxIVA02 numeric(38, 6), @IncidenciaTxIVA03 numeric(38, 6), @IncidenciaTxIVA04 numeric(38, 6), 
		@ValorTxIVA01 numeric(38, 6), @ValorTxIVA02 numeric(38, 6), @ValorTxIVA03 numeric(38, 6), @ValorTxIVA04 numeric(38, 6), @Erro int, @SerieDocNC varchar(20)
-- inicia transacção para inserção dados da declaração
	BEGIN TRANSACTION	
	BEGIN TRY	
-- obtem taxas de IVA configuradas
		SELECT @TxIVAIsenta = PAP_TXIS, @TxIVAReduzida = PAP_TXRD, @TxIVAIntermedia = PAP_TXIN, @TxIVANormal = PAP_TXNR
		FROM TAB_PAPL WITH(NOLOCK)
-- obtem tipo de documento "Nota de Credito" configurado
		SELECT @CodTipoDocNC = td.TDO_DVED, @TipoDocSAFT = (SELECT TDO_TDSF FROM TAB_TDOC WITH(NOLOCK) WHERE TDO_DOCU = td.TDO_DVED)
		FROM TAB_TDOC AS td WITH(NOLOCK)
		WHERE td.TDO_TDOC = 0 and td.TDO_DOCU = @TipoDocConta	
-- obtem dados do cliente 
		SELECT @NomeCliente = CLI_NOME, @MoradaCliente = CLI_MORA, @LocalidadeCliente = CLI_LOCA, @CodPostalCliente = CLI_CPOS, @LocPostalCliente = CLI_LPOS, @NIFCliente = CLI_NIF, 
			@CodPaisCliente = PAI_CODI
		FROM TAB_CLIE WITH(NOLOCK)
		WHERE CLI_CODI = @CodClienteConta 
-- obtem ID documento da Conta na C.C.
		SELECT @IdContaCC = MVC_IDEN
		FROM FAC_MVCC WITH(NOLOCK)
		WHERE MVC_TDOC = @TipoDocConta and MVC_NDOC = @NumeroConta and MVC_EANO = @AnoConta
-- obtem numero do documento Nota de Credito
		SELECT @NumeroDocNC = isnull(NUM_NUME, 0) + 1, @SerieDocNC = ISNULL(NULLIF(NUM_SERI, ''), '1')
		FROM TAB_NUMD
		WHERE NUM_TDOC = 1 and TDO_DOCU = @CodTipoDocNC and NUM_EANO = @AnoConta	
-- inserir dados gerais do documento Nota de Credito
		INSERT INTO FAC_DVEN (DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_CTXT, DVE_DATA, CLI_CODI, DVE_CNOM, DVE_CMOR, DVE_CLOC, DVE_CCPO, DVE_CLPO, DVE_CNIF, PAI_CLIV, NDE_CODI, DVE_NPRO, DVE_UTIC, 
			DVE_DTCR, DVE_UTIA, DVE_DTAL, DVE_DIPS, DVE_DFPS, DVE_VLIQ, DVE_VIVA, DVE_VTOT, DVE_STAT, DVE_ANUL, DVE_IN01, DVE_IN02, DVE_IN03, DVE_IN04, DVE_VI01, DVE_VI02, DVE_VI03, DVE_VI04, 
			DVE_OBSV, DVE_PANO, DVE_IMEX, TDO_TDSF, MVC_IDEN, MCR_CODI, DVE_MCRE, DEC_CODI, DVE_IDAR, DVE_CPRT, DVE_SERI)
		VALUES(@CodTipoDocNC, @NumeroDocNC, @AnoConta, 1, CAST(CONVERT(varchar(10), GETDATE(), 105) AS datetime), @CodClienteConta, @NomeCliente, @MoradaCliente, @LocalidadeCliente, 
			@CodPostalCliente, @LocPostalCliente, @NIFCliente, @CodPaisCliente, @CodNaturezaConta, @NumProcessoConta, @Utilizador, GETDATE(), @Utilizador, GETDATE(), 
			CAST(CONVERT(varchar(10), GETDATE(), 105) AS datetime), CAST(CONVERT(varchar(10), GETDATE(), 105) AS datetime), 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, @Observacoes, @AnoProcessoConta, 
			@ExpProcessoConta, @TipoDocSAFT, @IdContaCC, @CodMotivoCredito, @DescMotivoCredito, @CodDeclProcessoConta, @IdDeclaracaoDARConta, @CartaPorteConta, @SerieDocNC)
-- actulaiza numerador do documento 
		UPDATE TAB_NUMD SET NUM_NUME = @NumeroDocNC, NUM_DATA = CAST(CONVERT(varchar(10), GETDATE(), 105) AS datetime)
		WHERE NUM_TDOC = 1 and TDO_DOCU = @CodTipoDocNC and NUM_EANO = @AnoConta		
-- inicia variaveis
		SET @NumLinha = 0
		SET @TotalLiquido = 0
		SET @TotalIVA = 0
		SET @IncidenciaTxIVA01 = 0
		SET @IncidenciaTxIVA02 = 0
		SET @IncidenciaTxIVA03 = 0
		SET @IncidenciaTxIVA04 = 0
		SET @ValorTxIVA01 = 0
		SET @ValorTxIVA02 = 0
		SET @ValorTxIVA03 = 0
		SET @ValorTxIVA04 = 0
-- obtem despesas documentadas a inserir da lista XML 
		DECLARE DespDocumentadas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT XML_DESP.DES_DOCU.value('DCD_VTOT[1]', 'numeric(38, 6)'), rft.RFC_CODI, rft.RFC_NOME, rft.RFC_IVA, rft.CCO_CODI, 
				(CASE rft.RFC_TIPO WHEN 2 THEN 1 ELSE 0 END), 
				(CASE rft.RFC_IVA WHEN 0 THEN 'M01' ELSE NULL END), 
				(CASE rft.RFC_IVA WHEN 0 THEN (SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = 'M01') ELSE NULL END)
			FROM @LstDespesasConta.nodes('Despesas/Documentadas/Despesa') AS XML_DESP(DES_DOCU)	
				INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON XML_DESP.DES_DOCU.value('DDO_CODI[1]', 'int') = rft.RFC_CODI		
		OPEN DespDocumentadas
		FETCH NEXT FROM DespDocumentadas INTO @ValorDespesa, @CodRubrica, @NomeRubrica, @TxIVARubrica, @CodChargeCode, @RubricaLancaHonorarios, @CodIsencaoIVA, @MencaoIsencaoIVA
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @NumLinha = @NumLinha + 1	
-- insere linha de rubrica no documento de Nota de Credito
			INSERT INTO FAC_DVDT(DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_CTXT, DVD_LHON, IIV_CODI, IIV_MENC, CCO_CODI)
			VALUES(@CodTipoDocNC, @NumeroDocNC, @AnoConta, @NumLinha, @CodRubrica, @NomeRubrica, 1, @ValorDespesa, @TxIVARubrica, 1, 1, @RubricaLancaHonorarios, @CodIsencaoIVA, 
				@MencaoIsencaoIVA, @CodChargeCode)
-- incrementa variaveis			
			SET @IVALinha = @ValorDespesa * (@TxIVARubrica / 100)
			SET @TotalLiquido = @TotalLiquido + @ValorDespesa
			SET @TotalIVA = @TotalIVA + @IVALinha			
			IF @TxIVAIsenta = @TxIVARubrica
			BEGIN
				SELECT @IncidenciaTxIVA01 = @IncidenciaTxIVA01 + @ValorDespesa
				SELECT @ValorTxIVA01 = @ValorTxIVA01 + @IVALinha
			END
			ELSE 
				IF @TxIVAReduzida = @TxIVARubrica
				BEGIN
					SELECT @IncidenciaTxIVA02 = @IncidenciaTxIVA02 + @ValorDespesa
					SELECT @ValorTxIVA02 = @ValorTxIVA02 + @IVALinha
				END
				ELSE 
					IF @TxIVAIntermedia = @TxIVARubrica
					BEGIN
						SELECT @IncidenciaTxIVA03 = @IncidenciaTxIVA03 + @ValorDespesa
						SELECT @ValorTxIVA03 = @ValorTxIVA03 + @IVALinha
					END
					ELSE 
						IF @TxIVANormal = @TxIVARubrica
						BEGIN
							SELECT @IncidenciaTxIVA04 = @IncidenciaTxIVA04 + @ValorDespesa
							SELECT @ValorTxIVA04 = @ValorTxIVA04 + @IVALinha
						END		
			FETCH NEXT FROM DespDocumentadas INTO @ValorDespesa, @CodRubrica, @NomeRubrica, @TxIVARubrica, @CodChargeCode, @RubricaLancaHonorarios, @CodIsencaoIVA, @MencaoIsencaoIVA
		END
		CLOSE DespDocumentadas
		DEALLOCATE DespDocumentadas
-- obtem despesas inerentes a inserir da lista XML 
		DECLARE DespInerentes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT XML_DESP.DES_DOCU.value('ICD_VTOT[1]', 'numeric(38, 6)'), rft.RFC_CODI, rft.RFC_NOME, rft.RFC_IVA, rft.CCO_CODI, 
				(CASE rft.RFC_TIPO WHEN 2 THEN 1 ELSE 0 END), 
				(CASE rft.RFC_IVA WHEN 0 THEN ISNULL(NULLIF(@CodIsencaoIVAConta, ''), rft.IIV_CODI) ELSE NULL END), 
				(CASE rft.RFC_IVA WHEN 0 THEN (SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = ISNULL(NULLIF(@CodIsencaoIVAConta, ''), rft.IIV_CODI)) ELSE NULL END)
			FROM @LstDespesasConta.nodes('Despesas/Inerentes/Despesa') AS XML_DESP(DES_DOCU) 
				INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON XML_DESP.DES_DOCU.value('DIN_CODI[1]', 'int') = rft.RFC_CODI		
		OPEN DespInerentes
		FETCH NEXT FROM DespInerentes INTO @ValorDespesa, @CodRubrica, @NomeRubrica, @TxIVARubrica, @CodChargeCode, @RubricaLancaHonorarios, @CodIsencaoIVA, @MencaoIsencaoIVA
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @NumLinha = @NumLinha + 1	
-- insere linha de rubrica no documento de Nota de Credito
			INSERT INTO FAC_DVDT(DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_CTXT, DVD_LHON, IIV_CODI, IIV_MENC, CCO_CODI)
			VALUES(@CodTipoDocNC, @NumeroDocNC, @AnoConta, @NumLinha, @CodRubrica, @NomeRubrica, 1, @ValorDespesa, @TxIVARubrica, 1, 1, @RubricaLancaHonorarios, @CodIsencaoIVA, 
				@MencaoIsencaoIVA, @CodChargeCode)			
-- incrementa variaveis			
			SET @IVALinha = @ValorDespesa * (@TxIVARubrica / 100)
			SET @TotalLiquido = @TotalLiquido + @ValorDespesa
			SET @TotalIVA = @TotalIVA + @IVALinha
			IF @TxIVAIsenta = @TxIVARubrica
			BEGIN
				SELECT @IncidenciaTxIVA01 = @IncidenciaTxIVA01 + @ValorDespesa
				SELECT @ValorTxIVA01 = @ValorTxIVA01 + @IVALinha
			END
			ELSE 
				IF @TxIVAReduzida = @TxIVARubrica
				BEGIN
					SELECT @IncidenciaTxIVA02 = @IncidenciaTxIVA02 + @ValorDespesa
					SELECT @ValorTxIVA02 = @ValorTxIVA02 + @IVALinha
				END
				ELSE 
					IF @TxIVAIntermedia = @TxIVARubrica
					BEGIN
						SELECT @IncidenciaTxIVA03 = @IncidenciaTxIVA03 + @ValorDespesa
						SELECT @ValorTxIVA03 = @ValorTxIVA03 + @IVALinha
					END
					ELSE 
						IF @TxIVANormal = @TxIVARubrica
						BEGIN
							SELECT @IncidenciaTxIVA04 = @IncidenciaTxIVA04 + @ValorDespesa
							SELECT @ValorTxIVA04 = @ValorTxIVA04 + @IVALinha
						END		
			FETCH NEXT FROM DespInerentes INTO @ValorDespesa, @CodRubrica, @NomeRubrica, @TxIVARubrica, @CodChargeCode, @RubricaLancaHonorarios, @CodIsencaoIVA, @MencaoIsencaoIVA
		END
		CLOSE DespInerentes
		DEALLOCATE DespInerentes			
-- actualiza totais do documento Nota de Credito
		UPDATE FAC_DVEN SET DVE_VLIQ = @TotalLiquido, DVE_VIVA = ROUND(@TotalIVA, 2), DVE_VTOT = (@TotalLiquido + ROUND(@TotalIVA, 2)), DVE_IN01 = @IncidenciaTxIVA01, 
			DVE_IN02 = @IncidenciaTxIVA02, DVE_IN03 = @IncidenciaTxIVA03, DVE_IN04 = @IncidenciaTxIVA04, DVE_VI01 = ROUND(@ValorTxIVA01, 2), DVE_VI02 = ROUND(@ValorTxIVA02, 2), 
			DVE_VI03 = ROUND(@ValorTxIVA03, 2), DVE_VI04 = ROUND(@ValorTxIVA04, 2)
		WHERE DVE_TDOC = @CodTipoDocNC and DVE_NDOC = @NumeroDocNC and DVE_EANO = @AnoConta
-- actualiza conta
		ALTER TABLE FAC_CDOC DISABLE TRIGGER TAU_FAC_CDOC
		UPDATE FAC_CDOC SET DVE_TDOC = @CodTipoDocNC, DVE_NDOC = @NumeroDocNC, DVE_EANO = @AnoConta
		WHERE CDO_EANO = @AnoConta and CDO_TDOC = @TipoDocConta AND CDO_IDEN = @IDConta
		ALTER TABLE FAC_CDOC ENABLE TRIGGER TAU_FAC_CDOC
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @Erro = 1 
		SET @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) 
			+ ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_Contas_GeraNotaCredito] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Contas_GeraNotaCredito] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Contas_GerarMensagemFREINV]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Contas_GerarMensagemFREINV] @AnoConta int, @TipoDocConta varchar(4), @IDConta int, @FicheiroXML xml OUTPUT, @LinhaXMLEncoding varchar(200) OUTPUT, @NomeFicheiroXML varchar(100) OUTPUT AS
BEGIN 
	SET DATEFORMAT DMY
-- constroi o nome a dar ao ficheiro XML
	SELECT @NomeFicheiroXML = 'SAMSUNG.EDI_' + CAST(CDO_EANO AS varchar(4)) + CDO_TDOC + CAST(CDO_CNUM AS varchar(10)) + '_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), '-', ''), ':', ''), '.', ''), ' ', '') + '.xml'
	FROM FAC_CDOC WITH(NOLOCK)
	WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @TipoDocConta AND CDO_IDEN = @IDConta	
-- atribui linha de encoding (definido no schema) para depois ser incluída no ficheiro XML a gerar
	SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="UTF-8"?>'
-- constroi XML para ficheiro FREINV (SAMSUNG)
	;WITH XMLNAMESPACES ('http://edi.sec.samsung.com/GLS_ECC_LE/LEM' AS nr1)
	SELECT @FicheiroXML = 				
		(SELECT 	
			'4E0ASETE0T1' AS "MessageSenderIdentifier", 
			NULLIF((SELECT SUBSTRING(EMP_NOME, 1, 35) FROM GIDWIN.dbo.FAP_EMPR WITH(NOLOCK) WHERE EMP_CODI = DB_NAME()), '') AS "MessageSenderName", 
			'4E0ASET' AS "MessageReceiverIdentifier", 
			'SEP' AS "MessageReceiverName", 
			'FREINV' AS "MessageTypeIdentifier",
			'Freight Invoice' AS "MessageName",
			(CAST(cdo.CDO_EANO AS varchar(4)) + cdo.CDO_TDOC + CAST(cdo.CDO_IDEN AS varchar(10))) AS "MessageNumber",
			(CASE cdo.CDO_ANUL WHEN 1 THEN '3' ELSE '9' END) AS "MessageFunctionCode",
			cdo.CDO_CNUM AS "DocumentNumber",
			CONVERT(varchar(10), cdo.CDO_DTEM, 112) AS "DocumentDate", 
			CONVERT(varchar(10), cdo.CDO_DTEM, 112) AS "BillingDate", 
			(SELECT 
				'IM' AS "Code", 
				'Import' AS "CodeDescription"
			FOR XML PATH('BusinessType'), TYPE), 
			(SELECT 
				'716' AS "Code", 
				'Inbound Process ID' AS "CodeDescription"
			FOR XML PATH('RelatedDocument'), TYPE),
			CONVERT(varchar(10), cdo.CDO_DTAC, 112) AS "RelatedDocumentNumber1", 
			(CAST(cdo.CDO_NPRO AS varchar(10)) + '/' + RIGHT(cdo.CDO_NORD, 8)) AS "RelatedDocumentNumber2",
			(SELECT 
				(CASE cdo.MTR_CODI WHEN '10' THEN 'S1' WHEN '40' THEN 'P1' ELSE 'T1' END) AS "Code", 
				(CASE cdo.MTR_CODI WHEN '10' THEN 'Vessel (FCL)' WHEN '40' THEN 'AIR' ELSE 'Truck' END) AS "CodeDescription"
            FOR XML PATH('MeansOfTransport'), TYPE),
			CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 112) AS "ActualDate", 
			(SELECT 
				SUBSTRING(cdo.CDO_OPER, 1, 5) AS "Code"
			FOR XML PATH('Carrier'), TYPE), 	
			(SELECT 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dsd.DCD_LINH) AS "SequenceNumber",
					'ZEQUIP_TYPE' AS "CalculationBase", 					
					(CASE ddo.DDO_SPSC WHEN '302' THEN 'T-Factor 101' ELSE 'T-Factor 101 - If you include in FREVIN T Factor 101 =1, and container info / Shipping lines-  system should calculate price based on 1 container cost' END) AS "CalculationBaseValue" 
				FROM FAC_DCDO AS dsd WITH(NOLOCK) 
					INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON dsd.DDO_CODI = ddo.DDO_CODI
				WHERE dsd.CDO_EANO = cdo.CDO_EANO AND dsd.CDO_TDOC = cdo.CDO_TDOC AND dsd.CDO_IDEN = cdo.CDO_IDEN AND dsd.DDO_CODI IS NOT NULL AND ISNULL(ddo.DDO_SPCD, '') = '1002' 
					AND ISNULL(ddo.DDO_SPSC, '') IN ('300', '301', '302', '304', '305', '400', '401', '402', '403', '404', '405', '406', '408')
				FOR XML PATH('MsrItem'), TYPE)		
			FOR XML PATH('MsrList'), TYPE),		
			(SELECT TOP 1
				(SELECT 
					DCO_CODI AS "SequenceNumber",
					'0002' AS "TruckCntrClassification", 
					(SELECT 
						NULLIF(DCO_CNUM, '') AS "Number", 
						NULLIF(DCO_TIPO, '') AS "Type"
					FOR XML PATH('TruckCntrNumber'), TYPE), 
					NULLIF(DCO_CNUM, '') AS "ConsolidationNumber"					
				FROM PRO_DCON WITH(NOLOCK)
				WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1 
				FOR XML PATH('TrkItem'), TYPE)	
			FROM PRO_DCON WITH(NOLOCK)
			WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1 			
			FOR XML PATH('TrkList'), TYPE), 
			(SELECT 
				(SELECT 
					tbl.DSP_NUME AS "SequenceNumber",					
					(SELECT 
						NULLIF(SUBSTRING((tbl.DDO_SPCD + tbl.DDO_SPSC), 1, 15), '') AS "ChargeTypeCode", 
						NULLIF(tbl.DCD_DESC, '') AS "ChargeTypeDescription"
					FOR XML PATH('ChargeType'), TYPE), 
					CONVERT(varchar(10), cdo.CDO_DTEM, 112) AS "FreightIssueDate", 
					(SELECT 
						CAST(tbl.DCD_VTOT AS decimal(31, 3)) AS "Amount", 
						'EUR' AS "CurrencyCode"
					FOR XML PATH('RequestAmount'), TYPE), 
					(SELECT 
						CAST(tbl.DCD_VTOT AS decimal(31, 3)) AS "Amount", 
						'EUR' AS "CurrencyCode"
					FOR XML PATH('SupplyAmount'), TYPE),
					(SELECT TOP 3
						NULLIF(DDO_NUME, '') AS "Remark"
					FROM PRO_DDOC WITH(NOLOCK)
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1 AND DOC_CODI IN ('N704', 'N740') AND duc.DUC_DUNO <> 2 AND tbl.DSP_NUME = tbl.DSP_TOTA
					FOR XML PATH(''), TYPE), 
					(SELECT TOP 3
						NULLIF(ddo.numero, '') AS "Remark"
					FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK)
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND doc.DOC_CODI IN ('N704', 'N740') AND duc.DUC_DUNO = 2 AND tbl.DSP_NUME = tbl.DSP_TOTA
					FOR XML PATH(''), TYPE)
				FROM (SELECT ROW_NUMBER() OVER(ORDER BY dsp.TIPO, dsp.DCD_LINH) AS DSP_NUME, dsp.DDO_CODI, dsp.DCD_DESC, dsp.DCD_VTOT, dsp.DDO_SPCD, dsp.DDO_SPSC,
					((SELECT COUNT(*) 
						FROM FAC_DCDO AS dsd WITH(NOLOCK) 
							INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON dsd.DDO_CODI = ddo.DDO_CODI 
						WHERE dsd.CDO_EANO = cdo.CDO_EANO AND dsd.CDO_TDOC = cdo.CDO_TDOC AND dsd.CDO_IDEN = cdo.CDO_IDEN AND dsd.DDO_CODI IS NOT NULL AND ISNULL(ddo.DDO_SPCD, '') <> '' AND ISNULL(dsd.DCD_VTOT, 0) > 0)
						+ (SELECT COUNT(*) 
						FROM FAC_ICDO AS dsi WITH(NOLOCK) 
							INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON dsi.DIN_CODI = din.DIN_CODI
						WHERE dsi.CDO_EANO = cdo.CDO_EANO AND dsi.CDO_TDOC = cdo.CDO_TDOC AND dsi.CDO_IDEN = cdo.CDO_IDEN AND dsi.DIN_CODI IS NOT NULL AND ISNULL(dsi.ICD_VTOT, 0) > 0)
						+ (SELECT COUNT(*) 
						FROM FAC_CDOC AS dsh WITH(NOLOCK) 
							INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON dsh.DIN_HONO = din.DIN_CODI
						WHERE dsh.CDO_EANO = cdo.CDO_EANO AND dsh.CDO_TDOC = cdo.CDO_TDOC AND dsh.CDO_IDEN = cdo.CDO_IDEN AND dsh.DIN_HONO IS NOT NULL AND ISNULL(dsh.CDO_TTHO, 0) > 0)) AS DSP_TOTA
					FROM (SELECT 0 AS TIPO, dsd.DCD_LINH, dsd.DDO_CODI, dsd.DCD_DESC, dsd.DCD_VTOT, ddo.DDO_SPCD, ddo.DDO_SPSC
						FROM FAC_DCDO AS dsd WITH(NOLOCK) 
							INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON dsd.DDO_CODI = ddo.DDO_CODI
						WHERE dsd.CDO_EANO = cdo.CDO_EANO AND dsd.CDO_TDOC = cdo.CDO_TDOC AND dsd.CDO_IDEN = cdo.CDO_IDEN AND dsd.DDO_CODI IS NOT NULL AND ISNULL(ddo.DDO_SPCD, '') <> '' AND ISNULL(dsd.DCD_VTOT, 0) > 0
						UNION
						SELECT 1 AS TIPO, dsi.ICD_LINH, dsi.DIN_CODI, dsi.ICD_DESC, dsi.ICD_VTOT, din.DIN_SPCD, din.DIN_SPSC
						FROM FAC_ICDO AS dsi WITH(NOLOCK) 
							INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON dsi.DIN_CODI = din.DIN_CODI
						WHERE dsi.CDO_EANO = cdo.CDO_EANO AND dsi.CDO_TDOC = cdo.CDO_TDOC AND dsi.CDO_IDEN = cdo.CDO_IDEN AND dsi.DIN_CODI IS NOT NULL AND ISNULL(dsi.ICD_VTOT, 0) > 0
						UNION
						SELECT 2 AS TIPO, 1, dsh.DIN_HONO, din.DIN_NOME, dsh.CDO_TTHO, din.DIN_SPCD, din.DIN_SPSC
						FROM FAC_CDOC AS dsh WITH(NOLOCK) 
							INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON dsh.DIN_HONO = din.DIN_CODI
						WHERE dsh.CDO_EANO = cdo.CDO_EANO AND dsh.CDO_TDOC = cdo.CDO_TDOC AND dsh.CDO_IDEN = cdo.CDO_IDEN AND dsh.DIN_HONO IS NOT NULL AND ISNULL(dsh.CDO_TTHO, 0) > 0) AS dsp) AS tbl
				FOR XML PATH('FreItem'), TYPE)				
			FOR XML PATH('FreList'), TYPE)
		FROM FAC_CDOC AS cdo WITH(NOLOCK) 
			LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON cdo.CDO_IMEX = 0 AND cdo.CDO_NPRO = duc.DUC_PNUM AND cdo.CDO_PANO = duc.DUC_EANO
		WHERE cdo.CDO_EANO = @AnoConta AND cdo.CDO_TDOC = @TipoDocConta AND cdo.CDO_IDEN = @IDConta			
		FOR XML PATH('nr1:FREINV'), ELEMENTS)						
END

ALTER AUTHORIZATION ON [SP_Contas_GerarMensagemFREINV] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Contas_GerarMensagemFREINV] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Contas_ProcessaExportacaoADC]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Contas_ProcessaExportacaoADC] @DataReferencia datetime, @DirGeracaoFicheiro varchar(500) AS
BEGIN 
/****** SP DESCONTINUADO. INUMERAS ALTERAÇÕES POR PARTE DA DHL. PASSOU A SER DA RESPONSABILIDADE E GERIDO PELA DHL [decisão tomada e comunicada pelo PL em 28/06/2021] ********/
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoConta int, @TipoDocConta varchar(4), @IDConta int, @NumConta int, @ExportadoADC int, @FicheiroXML xml, @PathFicheiroTmpXML nvarchar(4000), 
		@MsgErro varchar(MAX)
-- cria tabela temporária p/ Product Codes
	CREATE TABLE #ProductCodes(BILLINGCODE varchar(1) COLLATE Latin1_General_CI_AI NOT NULL, OPERATIONSCODE varchar(3) COLLATE Latin1_General_CI_AI NOT NULL)	
-- insere Product Codes
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('0', 'LOG')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('1', 'DOT')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('2', 'BTC')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('3', 'B2C')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('4', 'NFO')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('5', 'SPL')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('6', 'ACS')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('7', 'XED')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('8', 'XEP')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('9', 'PPD')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('A', 'N/A')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('B', 'BBX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('C', 'CMX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('D', 'DOX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('E', 'TDE')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('F', 'FRT')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('G', 'DES')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('H', 'ESI')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('I', 'DOK')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('J', 'WPX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('K', 'TDK')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('L', 'TDL')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('M', 'TDM')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('N', 'DOM')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('O', 'DOL')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('P', 'WPX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('Q', 'WMX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('R', 'GMB')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('S', 'SDX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('T', 'TDT')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('U', 'ECX')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('V', 'PPP')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('W', 'ESU')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('X', 'XPD')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('Y', 'TDY')
	INSERT INTO #ProductCodes(BILLINGCODE, OPERATIONSCODE) VALUES('Z', 'N/A')	
-- obtem a lista de contas já emitidas e ainda n enviadas juntamente c/ as já enviadas e q tenham relação c/ NC
	DECLARE Contas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT CDO_EANO, CDO_TDOC, CDO_IDEN, CDO_CNUM, CDO_EADC
		FROM FAC_CDOC WITH (NOLOCK)
		WHERE CDO_CNUM IS NOT NULL AND CAST(CONVERT(varchar(10), CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime) 
			AND CDO_TDOC IN ('CCOD', 'CCDO') AND NDE_CODI <> '2.7' AND ISNULL(CDO_CPAG, 0) = 0 AND CDO_EADC = 0
			AND CDO_CCPO NOT IN ('2000-005', '2025-201', '2065-009', '2125-011', '2140-010', '2205-645', '2250-211', '2260-011', '2350-010', '2435-001', '2490-001', '2510-001',
				'2560-070', '2565-001', '2565-427', '2565-710', '2565-853', '2580-022', '2580-062', '2580-066', '2580-401', '2580-513', '2580-515', '2580-583', '2580-599', '2580-607',
				'2580-620', '2580-639', '2580-652', '2580-656', '2580-663', '2580-668', '2590-001', '2600-581', '2600-763', '2605-698', '2605-718', '2605-732', '2605-787', '2605-822',
				'2605-855', '2615-621', '2615-637', '2630-011', '2640-111', '2640-601', '2640-745', '2655-009', '2655-150', '2665-001', '2665-150', '2665-191', '2665-301', '2665-371',
				'2665-383', '2665-625', '2670-346', '2670-502', '2670-522', '2670-558', '2670-629', '2670-674', '2670-683', '2670-742', '2670-883', '2705-001', '2705-164', '2705-255', 
				'2705-410', '2705-415', '2705-525', '2705-565', '2705-569', '2705-703', '2705-795', '2705-997', '2705-999', '2715-211', '2715-357', '2715-402', '2750-521', '2750-772', 
				'2750-806', '2755-001', '2755-024', '2755-081', '2755-118', '2755-300', '2755-669', '2890-524', '2910-061', '2910-129', '2910-200', '2910-221', '2910-302', '2910-307', 
				'2910-746', '2910-780', '2910-790', '2910-802', '2910-852', '2925-083', '2925-366', '2925-533', '2925-614', '2925-690', '2925-721', '2925-747', '2925-761', '2950-035', 
				'2950-053', '2950-084', '2950-086', '2950-122', '2950-320', '2950-340', '2950-438', '2950-486', '2950-770', '2965-201', '2985-001', '3060-580', '3060-798', '3060-850', 
				'3060-856', '3060-998', '3070-011', '3105-176', '3130-001', '3200-001', '3250-016', '3475-010', '3550-011', '3740-011', '3840-001', '4540-011', '4575-001', '4600-001', 
				'4615-010', '4615-200', '4625-001', '4660-011', '4720-001', '4840-010', '4910-010', '4930-001', '4935-250', '4935-500', '4939-001', '6285-051', '6360-010', '7000-010', 
				'8100-010', '8100-110', '8100-350', '8100-996', '8150-010', '8300-010', '8375-009', '8550-011', '8700-201', '8700-582', '8700-898', '8700-996', '8800-011', '2025-154', 
				'2040-999', '2100-999', '2125-999', '2205-643', '2240-999', '2250-998', '2334-001', '2350-031', '2435-999', '2495-037', '2550-999', '2560-103', '2565-328', '2565-619',
				'2565-758', '2580-020', '2580-057', '2580-064', '2580-282', '2580-460', '2580-513', '2580-515', '2580-585', '2580-599', '2580-616', '2580-623', '2580-646', '2580-652', 
				'2580-661', '2580-663', '2580-997', '2594-522', '2600-585', '2600-866', '2605-699', '2605-718', '2605-732', '2605-787', '2605-822', '2605-855', '2615-626', '2615-648', 
				'2634-502', '2640-191', '2640-647', '2640-745', '2655-138', '2655-150', '2665-138', '2665-151', '2665-192', '2665-316', '2665-377', '2665-383', '2665-625', '2670-346', 
				'2670-502', '2670-522', '2670-558', '2670-632', '2670-679', '2670-683', '2670-767', '2670-883', '2705-160', '2705-211', '2705-363', '2705-410', '2705-415', '2705-525', 
				'2705-565', '2705-645', '2705-736', '2705-795', '2705-997', '2705-999', '2715-311', '2715-362', '2715-475', '2750-549', '2750-772', '2750-828', '2755-001', '2755-024', 
				'2755-093', '2755-208', '2755-347', '2755-669', '2890-530', '2910-064', '2910-141', '2910-219', '2910-225', '2910-302', '2910-319', '2910-747', '2910-780', '2910-792', 
				'2910-803', '2910-856', '2925-083', '2925-377', '2925-533', '2925-661', '2925-690', '2925-723', '2925-747', '2925-772', '2950-035', '2950-069', '2950-084', '2950-086', 
				'2950-146', '2950-320', '2950-341', '2950-438', '2950-494', '2950-770', '2970-999', '2985-999', '3060-723', '3060-818', '3060-850', '3060-857', '3060-998', '3074-001', 
				'3105-217', '3144-002', '3220-999', '3360-999', '3475-999', '3660-999', '3744-010', '3840-999', '4550-999', '4575-999', '4605-999', '4615-198', '4615-220', '4640-999', 
				'4690-999', '4720-999', '4890-999', '4924-001', '4930-999', '4935-250', '4935-559', '5470-999', '6285-999', '6370-999', '7960-999', '8100-057', '8100-216', '8100-400', 
				'8100-996', '8150-999', '8300-999', '8375-999', '8700-131', '8700-201', '8700-582', '8700-898', '8700-998', '8970-999')
		UNION
		SELECT CDO_EANO, CDO_TDOC, CDO_IDEN, CDO_CNUM, CDO_EADC
		FROM FAC_CDOC WITH (NOLOCK)
		WHERE CDO_CNUM IS NOT NULL AND CAST(CONVERT(varchar(10), CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime) 
			AND CDO_TDOC IN ('CCOD', 'CCDO') AND NDE_CODI <> '2.7' AND ISNULL(CDO_CPAG, 0) = 0 AND CDO_EADC = 1 AND DVE_NDOC IS NOT NULL
			AND CDO_CCPO NOT IN ('2000-005', '2025-201', '2065-009', '2125-011', '2140-010', '2205-645', '2250-211', '2260-011', '2350-010', '2435-001', '2490-001', '2510-001',
				'2560-070', '2565-001', '2565-427', '2565-710', '2565-853', '2580-022', '2580-062', '2580-066', '2580-401', '2580-513', '2580-515', '2580-583', '2580-599', '2580-607',
				'2580-620', '2580-639', '2580-652', '2580-656', '2580-663', '2580-668', '2590-001', '2600-581', '2600-763', '2605-698', '2605-718', '2605-732', '2605-787', '2605-822',
				'2605-855', '2615-621', '2615-637', '2630-011', '2640-111', '2640-601', '2640-745', '2655-009', '2655-150', '2665-001', '2665-150', '2665-191', '2665-301', '2665-371',
				'2665-383', '2665-625', '2670-346', '2670-502', '2670-522', '2670-558', '2670-629', '2670-674', '2670-683', '2670-742', '2670-883', '2705-001', '2705-164', '2705-255', 
				'2705-410', '2705-415', '2705-525', '2705-565', '2705-569', '2705-703', '2705-795', '2705-997', '2705-999', '2715-211', '2715-357', '2715-402', '2750-521', '2750-772', 
				'2750-806', '2755-001', '2755-024', '2755-081', '2755-118', '2755-300', '2755-669', '2890-524', '2910-061', '2910-129', '2910-200', '2910-221', '2910-302', '2910-307', 
				'2910-746', '2910-780', '2910-790', '2910-802', '2910-852', '2925-083', '2925-366', '2925-533', '2925-614', '2925-690', '2925-721', '2925-747', '2925-761', '2950-035', 
				'2950-053', '2950-084', '2950-086', '2950-122', '2950-320', '2950-340', '2950-438', '2950-486', '2950-770', '2965-201', '2985-001', '3060-580', '3060-798', '3060-850', 
				'3060-856', '3060-998', '3070-011', '3105-176', '3130-001', '3200-001', '3250-016', '3475-010', '3550-011', '3740-011', '3840-001', '4540-011', '4575-001', '4600-001', 
				'4615-010', '4615-200', '4625-001', '4660-011', '4720-001', '4840-010', '4910-010', '4930-001', '4935-250', '4935-500', '4939-001', '6285-051', '6360-010', '7000-010', 
				'8100-010', '8100-110', '8100-350', '8100-996', '8150-010', '8300-010', '8375-009', '8550-011', '8700-201', '8700-582', '8700-898', '8700-996', '8800-011', '2025-154', 
				'2040-999', '2100-999', '2125-999', '2205-643', '2240-999', '2250-998', '2334-001', '2350-031', '2435-999', '2495-037', '2550-999', '2560-103', '2565-328', '2565-619',
				'2565-758', '2580-020', '2580-057', '2580-064', '2580-282', '2580-460', '2580-513', '2580-515', '2580-585', '2580-599', '2580-616', '2580-623', '2580-646', '2580-652', 
				'2580-661', '2580-663', '2580-997', '2594-522', '2600-585', '2600-866', '2605-699', '2605-718', '2605-732', '2605-787', '2605-822', '2605-855', '2615-626', '2615-648', 
				'2634-502', '2640-191', '2640-647', '2640-745', '2655-138', '2655-150', '2665-138', '2665-151', '2665-192', '2665-316', '2665-377', '2665-383', '2665-625', '2670-346', 
				'2670-502', '2670-522', '2670-558', '2670-632', '2670-679', '2670-683', '2670-767', '2670-883', '2705-160', '2705-211', '2705-363', '2705-410', '2705-415', '2705-525', 
				'2705-565', '2705-645', '2705-736', '2705-795', '2705-997', '2705-999', '2715-311', '2715-362', '2715-475', '2750-549', '2750-772', '2750-828', '2755-001', '2755-024', 
				'2755-093', '2755-208', '2755-347', '2755-669', '2890-530', '2910-064', '2910-141', '2910-219', '2910-225', '2910-302', '2910-319', '2910-747', '2910-780', '2910-792', 
				'2910-803', '2910-856', '2925-083', '2925-377', '2925-533', '2925-661', '2925-690', '2925-723', '2925-747', '2925-772', '2950-035', '2950-069', '2950-084', '2950-086', 
				'2950-146', '2950-320', '2950-341', '2950-438', '2950-494', '2950-770', '2970-999', '2985-999', '3060-723', '3060-818', '3060-850', '3060-857', '3060-998', '3074-001', 
				'3105-217', '3144-002', '3220-999', '3360-999', '3475-999', '3660-999', '3744-010', '3840-999', '4550-999', '4575-999', '4605-999', '4615-198', '4615-220', '4640-999', 
				'4690-999', '4720-999', '4890-999', '4924-001', '4930-999', '4935-250', '4935-559', '5470-999', '6285-999', '6370-999', '7960-999', '8100-057', '8100-216', '8100-400', 
				'8100-996', '8150-999', '8300-999', '8375-999', '8700-131', '8700-201', '8700-582', '8700-898', '8700-998', '8970-999')
		ORDER BY CDO_EANO, CDO_TDOC, CDO_CNUM, CDO_IDEN
	OPEN Contas
	FETCH NEXT FROM Contas INTO @AnoConta, @TipoDocConta, @IDConta, @NumConta, @ExportadoADC
	WHILE @@FETCH_STATUS = 0
	BEGIN			
		SET @MsgErro = NULL
-- constroi XML para ficheiro ADC
		SET @FicheiroXML = 				
			(SELECT 	
				(SELECT 'INV-POD' AS "@Id", 
					'1.033' AS "@Ver", 
					CONVERT(varchar(19), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 120) AS "@Dtm", 
					'+01:00' AS "@GmtOff",
					(SELECT 'PT' AS "@CtryCd",
						'GIDWIN' AS "@AppCd", 
						PAP_VERS AS "@AppVer", 
						'POD' AS "@PrcsId"
					FROM TAB_PAPL WITH (NOLOCK)
					FOR XML PATH('Sndr'), TYPE)					
				FOR XML PATH('Hdr'), TYPE),			
				(SELECT 					
					(SELECT SUBSTRING(EMP_NOME, 1, 35) AS "@Nm", 
						EMP_NIF AS "@Rmk",
						(SELECT SUBSTRING(EMP_MORA, 1, 45) AS "@Ln1",
							'' AS "@Ln2",
							'' AS "@Ln3",
							'' AS "@BldNm", 
							EMP_LOCA AS "@CtyNm", 
							'PT' AS "@CtryCd", 
							EMP_LOCA AS "@Prvn", 
							EMP_LOCA AS "@Dist", 
							'' AS "@StCd", 
							SUBSTRING(EMP_MORA, 1, 45) AS "@StrNm", 
							'' AS "@StrNo", 
							EMP_CPOS AS "@Zip"
						FOR XML PATH('FcAddr'), TYPE),
						(SELECT 'TEL' AS "@CDevTyCd", 
							EMP_TELF AS "@CDevNo"
						FOR XML PATH('FcCDev'), TYPE), 
						(SELECT 'FAX' AS "@CDevTyCd", 
							EMP_FAX AS "@CDevNo"
						FOR XML PATH('FcCDev'), TYPE), 
						(SELECT 'EML' AS "@CDevTyCd", 
							'lispagamentosclientes@dhl.com' AS "@CDevNo"
						FOR XML PATH('FcCDev'), TYPE)
					FROM GIDWIN..FAP_EMPR WITH (NOLOCK)
					WHERE EMP_CODI = DB_NAME()
					FOR XML PATH('Fclt'), TYPE),
					(SELECT cdo.CDO_CPRT AS "@Id", 
						(SELECT cdo.CDO_DESC AS "@DscGds"
						FOR XML PATH('ShpDsc'), TYPE),
						(SELECT 
							(SELECT duc.CEN_CO20 AS "@InctrmCd"
							FOR XML PATH('SDoc'), TYPE)
						FOR XML PATH('ShpInDoc'), TYPE),
						(SELECT cdo.CDO_CPRT AS "@ShpRef",
							(SELECT 'MAB' AS "@Cd"
							FOR XML PATH('TrcRefTy'), TYPE)
						FOR XML PATH('ShpRef'), TYPE), 
						(SELECT (CASE cdo.ALF_CODI WHEN 'PT00015' THEN 'LIS' ELSE 'OPO' END) AS "@DstSrvaCd",
							(CASE cdo.ALF_CODI WHEN 'PT00015' THEN 'LIS' ELSE 'OPO' END) AS "@DstFcCd", 
							(CASE cdo.ALF_CODI WHEN 'PT00015' THEN 'LIS' ELSE 'OPO' END) AS "@OrgSrvaCd", 
							SUBSTRING(duc.DUC_FUPS, 1, 3) AS "@OrgFcCd", 
							(SELECT TOP 1 BILLINGCODE FROM #ProductCodes WHERE OPERATIONSCODE = duc.DUC_SHIP) AS "@MgNProdCd",  
							CONVERT(varchar(19), duc.DUC_DDDT, 120) AS "@PuDtm", 
							(SELECT 'BT' AS "@CRlTyCd",
								SUBSTRING(cdo.CDO_CEAN, 1, 12) AS "@AccNo",
								cdo.CDO_CNOM AS "@CustNm",
								cdo.CDO_CNOM AS "@CntNm",  
								SUBSTRING(cdo.CDO_CMOR, 1, 45) AS "@Addr1",  
								'' AS "@Addr2", 
								'' AS "@Addr3", 
								cdo.CDO_CLOC AS "@CtyNm", 
								'' AS "@Addr4",  
								cdo.CDO_CCPO AS "@Zip", 
								cdo.CDO_CPAI AS "@CtryCd",
								(SELECT 'TEL' AS "@CDevTyCd", 
									cli.CLI_TELF AS "@CDevNo"
								FOR XML PATH('SCCDev'), TYPE),
								(SELECT 'EML' AS "@CDevTyCd", 
									SUBSTRING(cli.CLI_EMAI, 1, 70) AS "@CDevNo"
								FOR XML PATH('SCCDev'), TYPE)
							FOR XML PATH('SCDtl'), TYPE), 
							(SELECT 'RV' AS "@CRlTyCd",								
								duc.DUC_DNOM AS "@CustNm",
								duc.DUC_DNOM AS "@CntNm",  
								SUBSTRING(duc.DUC_DMOR, 1, 45) AS "@Addr1",  
								'' AS "@Addr2", 
								'' AS "@Addr3", 
								duc.DUC_DLOC AS "@CtyNm", 
								'' AS "@Addr4",  
								duc.DUC_DCPO AS "@Zip", 
								duc.PAI_DLIV AS "@CtryCd"								
							FOR XML PATH('SCDtl'), TYPE), 
							(SELECT 'SP' AS "@CRlTyCd",								
								duc.DUC_ENOM AS "@CustNm",
								duc.DUC_ENOM AS "@CntNm",  
								SUBSTRING(duc.DUC_EMOR, 1, 45) AS "@Addr1",  
								'' AS "@Addr2", 
								'' AS "@Addr3", 
								duc.DUC_ELOC AS "@CtyNm", 
								'' AS "@Addr4",  
								duc.DUC_ECPO AS "@Zip", 
								duc.PAI_ELIV AS "@CtryCd"								
							FOR XML PATH('SCDtl'), TYPE)
						FOR XML PATH('ShpTr'), TYPE)
					FROM FAC_CDOC AS cdo WITH (NOLOCK) INNER JOIN PRO_DUCG AS duc ON cdo.CDO_IMEX = 0 AND cdo.CDO_NPRO = duc.DUC_PNUM AND cdo.CDO_PANO = duc.DUC_EANO	
						INNER JOIN TAB_CLIE AS cli WITH (NOLOCK) ON cdo.CLI_CCOR = cli.CLI_CODI					
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @TipoDocConta AND CDO_IDEN = @IDConta					
					FOR XML PATH('Shp'), TYPE),
					(SELECT 'MA' AS "@LEvtCd", 
						duc.DUC_NVOO AS "@MvmtId", 
						CONVERT(varchar(19), duc.DUC_DTVO, 120) AS "@EvtDtm"
					FROM FAC_CDOC AS cdo WITH (NOLOCK) INNER JOIN PRO_DUCG AS duc WITH (NOLOCK) ON cdo.CDO_IMEX = 0 AND cdo.CDO_NPRO = duc.DUC_PNUM AND cdo.CDO_PANO = duc.DUC_EANO						
						INNER JOIN TAB_CLIE AS cli WITH (NOLOCK) ON cdo.CLI_CCOR = cli.CLI_CODI
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @TipoDocConta AND CDO_IDEN = @IDConta					
					FOR XML PATH('GEvt'), TYPE),
					'' AS "Acc",
					(SELECT CONVERT(varchar(19), ISNULL(cdo.CDO_DTAL, cdo.CDO_DTCR), 120) AS "@Dt", 
						CONVERT(varchar(19), DATEADD(day, ISNULL(cdo.CDO_CPAG, 0), cdo.CDO_DTEM), 120) AS "@DueDt", 
						cdo.CDO_CNUM AS "@LglNo", 
						'CSH' AS "@PMthTyCd", 
						CAST(cdo.CDO_TTPR AS numeric(18, 3)) AS "@TotAmt", 
						CAST(cdo.CDO_PBRT AS numeric(15, 3)) AS "@TotChrgWgt", 
						CAST(cdo.CDO_QUNT AS numeric(6, 0)) AS "@TotNOfPcs", 
						'EUR' AS "@PayCurCd",
						(SELECT 'REG' AS "@InvDcTyCd", 
							(CASE cdo.CDO_EADC WHEN 0 THEN 'C' ELSE 'D' END) AS "@StCd"
						FOR XML PATH('InvDocTy'), TYPE), 
						(SELECT 'C' AS "@EvtCd", 
							CONVERT(varchar(19), cdo.CDO_DTCR, 120) AS "@Dtm"
						FOR XML PATH('InvEvt'), TYPE),
						(SELECT 'U' AS "@EvtCd", 
							CONVERT(varchar(19), cdo.CDO_DTAL, 120) AS "@Dtm"
						FOR XML PATH('InvEvt'), TYPE), 
						(SELECT 'PT' AS "@SrcCtryCd", 
							(CASE cdo.ALF_CODI WHEN 'PT00015' THEN 'LIS' ELSE 'OPO' END) AS "@SrcSrvaCd", 
							(CASE cdo.ALF_CODI WHEN 'PT00015' THEN 'LIS' ELSE 'OPO' END) AS "@SrcFcCd", 
							'PORTUGAL' AS "@SrcCtryNm"
						FOR XML PATH('GI'), TYPE),
						(SELECT '1' AS "@Ord"
						FOR XML PATH('InvAdv'), TYPE),
						(SELECT ROW_NUMBER() OVER(ORDER BY TIPO, dsp.DCD_LINH) AS "@OrdLnNo",
							CAST(dsp.DCD_VTOT AS numeric(18, 3)) AS "@PayChrg", 
							CAST(dsp.DCD_VTOT AS numeric(18, 3)) AS "@PayNtChrg",
							(SELECT 'CHARGE CODE' AS "@AttNm", 
								dsp.CCO_CODI AS "@AttVal"
							FOR XML PATH('OrdLnTrAdInf'), TYPE), 
							(SELECT 'CHARGE DESCRIPTION' AS "@AttNm", 
								dsp.DCD_DESC AS "@AttVal"
							FOR XML PATH('OrdLnTrAdInf'), TYPE), 
							(SELECT 'POD FLAG' AS "@AttNm", 
								'Y' AS "@AttVal"
							FOR XML PATH('OrdLnTrAdInf'), TYPE), 
							(SELECT 'BILLING FLAG' AS "@AttNm", 
								'N' AS "@AttVal"
							FOR XML PATH('OrdLnTrAdInf'), TYPE), 
							(SELECT 'A/R FLAG' AS "@AttNm", 
								'Y' AS "@AttVal"
							FOR XML PATH('OrdLnTrAdInf'), TYPE), 
							(SELECT 'EXCL CONS FLAG' AS "@AttNm", 
								'N' AS "@AttVal"
							FOR XML PATH('OrdLnTrAdInf'), TYPE), 
							(SELECT CAST((CASE TIPO WHEN 0 THEN 0 ELSE ROUND(dsp.DCD_VTOT * cdo.CDO_TXIV / 100, 2) END) AS numeric(18, 3))  AS "@PayTxChrg", 
								CAST((CASE TIPO WHEN 0 THEN 0 ELSE (cdo.CDO_TXIV) END) AS numeric(6, 3)) AS "@TxRt",
								(SELECT (CASE WHEN (TIPO = 0) AND (CCO_CODI = 'XB') THEN 'VAT' ELSE '' END) AS "@TxTyCd"
								FOR XML PATH('TxTy'), TYPE)
							FOR XML PATH('OrdLnTrTx'), TYPE)
						FROM (SELECT 0 AS TIPO, dsd.DCD_LINH, dsd.DDO_CODI, dsd.DCD_DESC, dsd.DCD_VTOT, ddo.CCO_CODI
							FROM FAC_DCDO AS dsd WITH (NOLOCK) INNER JOIN TAB_DDOC AS ddo WITH (NOLOCK) ON dsd.DDO_CODI = ddo.DDO_CODI
							WHERE dsd.CDO_EANO = cdo.CDO_EANO AND dsd.CDO_TDOC = cdo.CDO_TDOC AND dsd.CDO_IDEN = cdo.CDO_IDEN AND dsd.DDO_CODI IS NOT NULL 
								AND ISNULL(dsd.DCD_VTOT, 0) > 0
							UNION
							SELECT 1 AS TIPO, dsi.ICD_LINH, dsi.DIN_CODI, dsi.ICD_DESC, dsi.ICD_VTOT, din.CCO_CODI
							FROM FAC_ICDO AS dsi WITH (NOLOCK) INNER JOIN TAB_DINE AS din WITH (NOLOCK) ON dsi.DIN_CODI = din.DIN_CODI
							WHERE dsi.CDO_EANO = cdo.CDO_EANO AND dsi.CDO_TDOC = cdo.CDO_TDOC AND dsi.CDO_IDEN = cdo.CDO_IDEN AND dsi.DIN_CODI IS NOT NULL 
								AND ISNULL(dsi.ICD_VTOT, 0) > 0
							UNION
							SELECT 2 AS TIPO, 1, dsh.DIN_HONO, din.DIN_NOME, dsh.CDO_TTHO, din.CCO_CODI
							FROM FAC_CDOC AS dsh WITH (NOLOCK) INNER JOIN TAB_DINE AS din WITH (NOLOCK) ON dsh.DIN_HONO = din.DIN_CODI
							WHERE dsh.CDO_EANO = cdo.CDO_EANO AND dsh.CDO_TDOC = cdo.CDO_TDOC AND dsh.CDO_IDEN = cdo.CDO_IDEN AND dsh.DIN_HONO IS NOT NULL 
								AND ISNULL(dsh.CDO_TTHO, 0) > 0) AS dsp
						FOR XML PATH('CntOrdLnTr'), TYPE)
					FROM FAC_CDOC AS cdo WITH (NOLOCK) INNER JOIN PRO_DUCG AS duc WITH (NOLOCK) ON cdo.CDO_IMEX = 0 AND cdo.CDO_NPRO = duc.DUC_PNUM AND cdo.CDO_PANO = duc.DUC_EANO						
						INNER JOIN TAB_CLIE AS cli WITH (NOLOCK) ON cdo.CLI_CCOR = cli.CLI_CODI
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @TipoDocConta AND CDO_IDEN = @IDConta
					FOR XML PATH('Inv'), TYPE)
				FOR XML PATH('Bd'), TYPE)				
			FOR XML PATH('MSG'), ELEMENTS)						
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirGeracaoFicheiro + '\PT_IASXML_' + @TipoDocConta + '_' + CAST(@NumConta AS varchar(20)) + '_' + CAST(@AnoConta AS varchar(20)) + '_' + REPLACE(REPLACE(REPLACE(CONVERT(varchar(19), GETDATE(), 120), ':', ''), ' ', ''), '-', '') + '.XML'
-- gera o ficheiro XML ADC c/ encoding UTF-8
		EXEC GIDWIN..SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroTmpXML
-- atualiza conta p/ sinalizar como já exportada p/ ADC
		UPDATE FAC_CDOC SET CDO_EADC = CDO_EADC + 1
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @TipoDocConta AND CDO_IDEN = @IDConta			
		FETCH NEXT FROM Contas INTO @AnoConta, @TipoDocConta, @IDConta, @NumConta, @ExportadoADC
	END
	CLOSE Contas
	DEALLOCATE Contas	
-- remove a tabela temporária	
	DROP TABLE #ProductCodes			
END

ALTER AUTHORIZATION ON [SP_Contas_ProcessaExportacaoADC] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Contas_ProcessaExportacaoADC] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Contas_ProcessaFicheirosXMLCreditosPortalDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_Contas_ProcessaFicheirosXMLCreditosPortalDHL] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), 
	@DirReportsEmpresa varchar(250), @DirFicheirosTmpLocal varchar(250), @PathGIDWinPDFExportTool varchar(250), @DirDestinoDocsImportacao varchar(250), @PwLoginGIDWin varchar(30), 
	@CodMotivoCredito int, @CodNaturezaNovaConta varchar(3), @PerfilSQLEnvioEmail varchar(100), @AssuntoEmail varchar(250), @TextoEmail varchar(MAX), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdUtilizador int, @NomeMotivoCredito varchar(50), @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), 
		@DataAtual datetime, @FicheiroXML xml(XMLSC_FaturasACreditarToGIDWin), @ErroFicheiro varchar(MAX), @i int, @ErroImportacao varchar(MAX), @Erros varchar(MAX), 
		@PathFicheiroErro varchar(500), @Linha varchar(MAX), @TransacaoOK bit, @ObjId int, @PathsFicheirosAnexoEmail varchar(MAX), 
		@XMLCodTipoDocumento varchar(4), @XMLNumeroDocumento int, @XMLDataDocumento datetime, @XMLNIFCliente varchar(18), @XMLNomeCliente varchar(70), 
		@XMLMoradaCliente varchar(70), @XMLLocalidadeCliente varchar(35), @XMLCodPostalCliente varchar(12), @XMLLocPostalCliente varchar(35), @XMLEmailCliente varchar(200), 
		@XMLCodPaisCliente varchar(2),
		@AnoConta int, @IDConta int, @CodNaturezaConta varchar(3), @NumProcessoConta int, @AnoProcessoConta int, @CodClienteCCConta varchar(18), 
		@CodDeclaranteProcessoConta varchar(6), @EXPProcessoConta bit, @CodMotivoIsencaoIVAConta varchar(3), @TipoDocCreditoConta varchar(4), @NumDocCreditoConta int, 
		@AnoDocCreditoConta int, @NumCPAConta varchar(18), @IDDeclaracaoDARConta int, @ArquivaReportBinario bit, @NomeTipoDocumento varchar(100), @ObservacoesConta varchar(MAX), 
		@DespesasConta xml,
		@NomeReportImprimir varchar(20), @RadicalPDF varchar(2), @DescricaoFicheiroAnexar varchar(150), @NomeFicheiroAnexar varchar(100), @PathFicheiroPDFAnexar varchar(500), 
		@PathFicheiroPDFAnexarNC varchar(500), @PathFicheiroPDFAnexarFT varchar(500), @ArgsGIDWinPDFExportTool varchar(2000), @SQLString nvarchar(500), @SQLParams nvarchar(500), 
		@FicheiroBinario varbinary(MAX), 
		@IDNovaConta int, @NumeroNovaConta int, @DataNovaConta datetime, @SerieNovaConta varchar(20), 
		@EANCliente varchar(13), @MeioPagamentoCliente int, @CondPagamentoCliente int, @TipoCliente varchar(13)
-- verfica se diretorias locais tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'	
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'
	IF SUBSTRING(REVERSE(@DirReportsEmpresa), 1, 1) <> '\'
		SET @DirReportsEmpresa = @DirReportsEmpresa + '\'
	IF SUBSTRING(REVERSE(@DirFicheirosTmpLocal), 1, 1) <> '\'
		SET @DirFicheirosTmpLocal = @DirFicheirosTmpLocal + '\'
	IF SUBSTRING(REVERSE(@DirDestinoDocsImportacao), 1, 1) <> '\'
		SET @DirDestinoDocsImportacao = @DirDestinoDocsImportacao + '\'
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador	
-- obtem o nome do motivo de crédito
	SELECT @NomeMotivoCredito = MCR_DESC
	FROM TAB_MCRE WITH(NOLOCK)
	WHERE MCR_CODI = @CodMotivoCredito
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros de creditos do portal DHL a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE FicheirosDHL CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]	
	OPEN FicheirosDHL
	FETCH NEXT FROM FicheirosDHL INTO @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN				
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'			
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			SET @Erros = ''
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)	
-- obtem o xml do ficheiro xml importado					
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- obtem data atual GMT
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia variaveis
			SET @Erros = ''
-- obtem lista de faturas a creditar existentes dentro do ficheiro XML
			DECLARE Faturas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT NULLIF(XML_FACT.FAC_DATA.value('tipoDocumento[1]', 'varchar(4)'), ''), 
					XML_FACT.FAC_DATA.value('numero[1]', 'int'),
					XML_FACT.FAC_DATA.value('data[1]', 'datetime'),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/nif)[1]', 'varchar(18)'), ''),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/nome)[1]', 'varchar(70)'), ''),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/morada)[1]', 'varchar(70)'), ''),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/localidade)[1]', 'varchar(35)'), ''),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/codigoPostal)[1]', 'varchar(12)'), ''),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/localidadePostal)[1]', 'varchar(35)'), ''),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/email)[1]', 'varchar(200)'), ''),
					NULLIF(XML_FACT.FAC_DATA.value('(infoCliente/pais)[1]', 'varchar(2)'), '')
				FROM @FicheiroXML.nodes('FaturasACreditarInGIDWIN/fatura') AS XML_FACT(FAC_DATA)
			OPEN Faturas
			FETCH NEXT FROM Faturas INTO @XMLCodTipoDocumento, @XMLNumeroDocumento, @XMLDataDocumento, @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLLocalidadeCliente, 
				@XMLCodPostalCliente, @XMLLocPostalCliente, @XMLEmailCliente, @XMLCodPaisCliente
			WHILE @@FETCH_STATUS = 0
			BEGIN	
				SET @AnoConta = YEAR(@XMLDataDocumento)		
-- inicia transacção para inserção dos documentos de crédito e nova fatura
				BEGIN TRANSACTION																				
				BEGIN TRY
					SET @TransacaoOK = 1
-- verifica se NIF de cliente existe e insere ou edita dados
					SET @ErroImportacao = ''
					EXEC @NumErro = SP_Clientes_InsereOuEdita 2, @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLNIFCliente, NULL, NULL, @XMLLocalidadeCliente, @XMLCodPostalCliente, @XMLLocPostalCliente, @XMLCodPaisCliente, @XMLEmailCliente, NULL, NULL, @IdUtilizador, @ErroImportacao OUTPUT					
					IF @NumErro <> 0
						RAISERROR('[Fatura N. %s/%d.%d] -> Erro na inserção/edição dos dados do cliente "%s": "%s".', 16, 2, @XMLCodTipoDocumento, @AnoConta, @XMLNumeroDocumento, @XMLNIFCliente, @ErroImportacao) 										
-- verifica se o tipo de documento de conta tem associado um tipo de documento a crédito
					IF NOT EXISTS(SELECT TDO_DOCU FROM TAB_TDOC WITH(NOLOCK) WHERE TDO_TDOC = 0 AND TDO_DOCU = @XMLCodTipoDocumento AND ISNULL(TDO_DVED, '') <> '')
						RAISERROR('[Fatura N. %s/%d.%d] -> Erro no tipo de documento "%s" que não tem configurado um tipo de documento de crédito.', 16, 3, @XMLCodTipoDocumento, @AnoConta, @XMLNumeroDocumento, @XMLCodTipoDocumento)
-- verifica se o documento de conta ainda está em C.C.										
					IF NOT EXISTS(SELECT MVC_IDEN FROM FAC_MVCC WITH(NOLOCK) WHERE MVC_TDOC = @XMLCodTipoDocumento AND MVC_NDOC = @XMLNumeroDocumento AND MVC_EANO = @AnoConta)
						RAISERROR('[Fatura N. %s/%d.%d] -> Erro no documento que não existe em C.C.', 16, 4, @XMLCodTipoDocumento, @AnoConta, @XMLNumeroDocumento)					
-- obtem dados do documento de conta
					SELECT @IDConta = con.CDO_IDEN, @CodNaturezaConta = con.NDE_CODI, @NumProcessoConta = con.CDO_NPRO, @AnoProcessoConta = con.CDO_PANO, 
						@CodClienteCCConta = con.CLI_CCOR, @CodDeclaranteProcessoConta = con.EXM_OPER, @EXPProcessoConta = con.CDO_IMEX, 
						@CodMotivoIsencaoIVAConta = con.IIV_CODI, @NumDocCreditoConta = con.DVE_NDOC, @NumCPAConta = ISNULL(con.CDO_CPRT, ''), 
						@IDDeclaracaoDARConta = con.id_declaracaoDAR, @NomeTipoDocumento = ISNULL(tdo.TDO_DESC, ''),
						@ArquivaReportBinario = (CASE WHEN (con.id_declaracaoDAR IS NOT NULL) OR (ISNULL(duc.DUC_DUNO, 0) = 2) THEN 1 ELSE 0 END)
					FROM FAC_CDOC AS con WITH(NOLOCK) 
						INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON con.CDO_TDOC = tdo.TDO_DOCU
						LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON con.CDO_NPRO = duc.DUC_PNUM AND con.CDO_PANO = duc.DUC_EANO AND con.CDO_IMEX = 0 AND con.id_declaracaoDAR IS NULL
					WHERE con.CDO_EANO = @AnoConta AND con.CDO_TDOC = @XMLCodTipoDocumento AND con.CDO_CNUM = @XMLNumeroDocumento
-- verifica se o documento de conta existe
					IF @IDConta IS NULL
						RAISERROR('[Fatura N. %s/%d.%d] -> Erro no documento que não foi encontrado.', 16, 5, @XMLCodTipoDocumento, @AnoConta, @XMLNumeroDocumento)											
-- verifica se o o documento de conta ainda não foi creditado
					IF @NumDocCreditoConta IS NOT NULL
						RAISERROR('[Fatura N. %s/%d.%d] -> Erro no documento que já tem um crédito associado.', 16, 6, @XMLCodTipoDocumento, @AnoConta, @XMLNumeroDocumento)							
-- calcula as observações para o crédito
					SET @ObservacoesConta = 'Referente à nossa ' + @NomeTipoDocumento + ' N.º ' + CAST(@XMLNumeroDocumento AS varchar(10)) + ' de ' + CONVERT(varchar(10), @XMLDataDocumento, 105)
					IF @NumCPAConta <> '' 
						SET @ObservacoesConta = @ObservacoesConta + CHAR(13) + CHAR(10) + 'CPA Nº.: ' + @NumCPAConta
-- calcula o xml das despesas documentadas e inerentes
					SET @DespesasConta = 
						(SELECT
							(SELECT 
								(SELECT 
									DDO_CODI, 
									CAST(DCD_VTOT AS decimal(18, 3)) AS DCD_VTOT
								FROM FAC_DCDO WITH(NOLOCK)
								WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @XMLCodTipoDocumento AND CDO_IDEN = @IDConta AND DDO_CODI IS NOT NULL
								FOR XML PATH('Despesa'), TYPE)
							FOR XML PATH('Documentadas'), TYPE),
							(SELECT 
								(SELECT 
									DIN_CODI, 
									CAST(ICD_VTOT AS decimal(18, 3)) AS ICD_VTOT
								FROM FAC_ICDO WITH(NOLOCK)
								WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @XMLCodTipoDocumento AND CDO_IDEN = @IDConta AND DIN_CODI IS NOT NULL
								FOR XML PATH('Despesa'), TYPE)
							FOR XML PATH('Inerentes'), TYPE)
						FOR XML PATH('Despesas'), ELEMENTS)
-- processa a geração do documento de crédito								
					SET @ErroImportacao = ''
					EXEC @NumErro = SP_Contas_GeraNotaCredito @AnoConta, @XMLCodTipoDocumento, @IDConta, @XMLNumeroDocumento, @CodNaturezaConta, @NumProcessoConta, @AnoProcessoConta, @CodDeclaranteProcessoConta, @EXPProcessoConta, @NumCPAConta, @CodClienteCCConta, @CodMotivoIsencaoIVAConta, @IDDeclaracaoDARConta, @ObservacoesConta, @DespesasConta, @Utilizador, @CodMotivoCredito, @NomeMotivoCredito, @ErroImportacao OUTPUT
					IF @NumErro <> 0
						RAISERROR('[Fatura N. %s/%d.%d] -> Erro na geração do documento de crédito: "%s".', 16, 7, @XMLCodTipoDocumento, @AnoConta, @XMLNumeroDocumento, @ErroImportacao)						
-- processa a geração do novo documento de conta (fatura atribuída ao cliente)
					EXEC @NumErro = SP_duplicaConta @IDConta, @AnoConta, @XMLCodTipoDocumento, @CodNaturezaNovaConta, @Utilizador, @AnoConta, @XMLCodTipoDocumento
					IF @NumErro <> 0
						RAISERROR('[Fatura N. %s/%d.%d] -> Erro desconhecido na geração do documento de fatura.', 16, 8, @XMLCodTipoDocumento, @AnoConta, @XMLNumeroDocumento)						
-- obtem o ID da nova conta gerada
					SELECT @IDNovaConta = CDO_IDEN						
					FROM FAC_CDOC WITH(NOLOCK)
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @XMLCodTipoDocumento AND CDO_ORID = @IDConta
-- obtem os restantes dados do novo cliente
					SELECT @EANCliente = CLI_CEAN, @MeioPagamentoCliente = CLI_MPAG, @CondPagamentoCliente = CLI_CPAG, 
						@TipoCliente = (CASE WHEN CLI_CODC = 1 THEN 'COD' WHEN CLI_CACC = 1 THEN 'ACC' WHEN CLI_CEXB = 1 THEN 'EXB' WHEN CLI_CDAS = 1 THEN 'DAS' ELSE NULL END) 
					FROM TAB_CLIE WITH(NOLOCK)
					WHERE CLI_CODI = @XMLNIFCliente
-- obtem número para o documento de Conta na tabela de Numeradores
					SELECT @NumeroNovaConta = (NUM_NUME + 1), @DataNovaConta = CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), @SerieNovaConta = ISNULL(NULLIF(NUM_SERI, ''), '1')
					FROM TAB_NUMD 
					WHERE TDO_DOCU = @XMLCodTipoDocumento AND NUM_EANO = @AnoConta
-- atualiza número e data na tabela de Numeradores (processo "puxado" p/ antes da numeração da conta p/ evitar ter várias contas c/ mesmo número face ao delay existente no update da FAC_CDOC)
					UPDATE TAB_NUMD SET NUM_NUME = NUM_NUME + 1, NUM_DATA = @DataNovaConta
					WHERE TDO_DOCU = @XMLCodTipoDocumento AND NUM_EANO = @AnoConta
-- atualiza documento de Conta c/ número, data e status
					UPDATE FAC_CDOC SET CDO_DTEM = @DataNovaConta, CDO_CNUM = @NumeroNovaConta, CDO_IMPR = 1, CDO_STAT = 1, CLI_CCOR = @XMLNIFCliente, CDO_CNOM = @XMLNomeCliente, 
						CDO_CMOR = @XMLMoradaCliente, CDO_CLOC = @XMLLocalidadeCliente, CDO_CCPO = @XMLCodPostalCliente, CDO_CLPO = @XMLLocPostalCliente, CDO_CNIF = @XMLNIFCliente, 
						CDO_CPAI = @XMLCodPaisCliente, CDO_MPAG = @MeioPagamentoCliente, CDO_CEAN = @EANCliente, CDO_CPAG = @CondPagamentoCliente, CDO_CTIP = @TipoCliente, 
						CDO_UALT = @Utilizador, CDO_DTAL = @DataAtual, CDO_SERI = @SerieNovaConta
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @XMLCodTipoDocumento AND CDO_IDEN = @IDNovaConta	
				END TRY
				BEGIN CATCH		
					SET @TransacaoOK = 0
-- constroi mensagem de erro detalhada
					SET @Erros = @Erros + 'Erro N.º: ' + CAST(ERROR_NUMBER() AS varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() AS varchar(5)) 
										+ ', Estado: ' + CAST(ERROR_STATE() AS varchar(5)) + ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() AS varchar(5)) 
										+ ', Mensagem: ' + ERROR_MESSAGE()					
-- em caso de erro faz rollback da transacção iniciada						           
					IF @@TRANCOUNT > 0
						ROLLBACK TRANSACTION					
				END CATCH			
-- se sucesso faz commit da transacção iniciada
				IF @@TRANCOUNT > 0
					COMMIT TRANSACTION
-- se documentos gerados com sucesso, processa as respetivas impressões PDF e consequentes anexos às Declarações DUI2/DAR e posterior envio de email
				IF @TransacaoOK = 1
				BEGIN
-- obtem nome do 1º report FRF configurado p/ imprimir e anexar no tipo de documento de crédito
					SELECT @TipoDocCreditoConta = con.DVE_TDOC, @NumDocCreditoConta = con.DVE_NDOC, @AnoDocCreditoConta = con.DVE_EANO, 
						@NomeReportImprimir = (CASE WHEN tdo.TDO_IRP1 = 1 AND tdo.TDO_ARP1 IN (1, 3) THEN tdo.TDO_REP1 WHEN tdo.TDO_IRP2 = 1 AND tdo.TDO_ARP2 IN (1, 3) THEN tdo.TDO_REP2 WHEN tdo.TDO_IRP3 = 1 AND tdo.TDO_ARP3 IN (1, 3) THEN tdo.TDO_REP3 WHEN tdo.TDO_IRP4 = 1 AND tdo.TDO_ARP4 IN (1, 3) THEN tdo.TDO_REP4 ELSE NULL END), 
						@RadicalPDF = (CASE WHEN tdo.TDO_IRP1 = 1 AND tdo.TDO_ARP1 IN (1, 3) THEN '' WHEN tdo.TDO_IRP2 = 1 AND tdo.TDO_ARP2 IN (1, 3) THEN '_2' WHEN tdo.TDO_IRP3 = 1 AND tdo.TDO_ARP3 IN (1, 3) THEN '_3' WHEN tdo.TDO_IRP4 = 1 AND tdo.TDO_ARP4 IN (1, 3) THEN '_4' ELSE NULL END)
					FROM FAC_CDOC AS con WITH(NOLOCK) 
						INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON con.DVE_TDOC = tdo.TDO_DOCU
					WHERE con.CDO_EANO = @AnoConta AND con.CDO_TDOC = @XMLCodTipoDocumento AND con.CDO_IDEN = @IDConta		
-- procede à geração do report em PDF para o documento de crédito										
					IF (@NumDocCreditoConta IS NOT NULL) AND (ISNULL(@NomeReportImprimir, '') <> '')
					BEGIN											
						SET @NomeFicheiroAnexar = CAST(@NumProcessoConta AS varchar(10)) + '.' + @TipoDocCreditoConta + '.' + CAST(@NumDocCreditoConta AS varchar(10)) + '.' + CAST(@AnoDocCreditoConta AS varchar(4)) + @RadicalPDF + '.pdf';		
						SET @PathFicheiroPDFAnexar = @DirFicheirosTmpLocal + @NomeFicheiroAnexar
						SET @PathFicheiroPDFAnexarNC = @DirFicheirosTmpLocal + 'e' + @NomeFicheiroAnexar
						SET @ArgsGIDWinPDFExportTool = '-s' + @@SERVERNAME + ' -p' + @PwLoginGIDWin + ' -b' + DB_NAME() + ' -r' + QUOTENAME((@DirReportsEmpresa + @NomeReportImprimir), '"') + ' -c1 -a' + CAST(@AnoDocCreditoConta AS varchar(4)) + ' -t' + @TipoDocCreditoConta + ' -i' + CAST(@NumDocCreditoConta AS varchar(20)) + ' -f' + QUOTENAME(@PathFicheiroPDFAnexar, '"')											
						SET @ErroImportacao = ''
						EXEC GIDWIN.dbo.SP_Externo_ExecutaPrograma @PathGIDWinPDFExportTool, @ArgsGIDWinPDFExportTool, @ErroImportacao OUTPUT
-- procede à anexação no documento no Arquivo no processo de origem
						IF ISNULL(@ErroImportacao, '') = ''
						BEGIN								
							SET @DescricaoFicheiroAnexar = 'Nota de Crédito N.º ' + CAST(@NumDocCreditoConta AS varchar(10))
-- copia ficheiro do documento de crédito para posterior envio no email
							EXEC sp_OACreate 'Scripting.FileSystemObject', @ObjId OUTPUT					
							EXEC sp_OAMethod @ObjId, 'CopyFile', NULL, @PathFicheiroPDFAnexar, @PathFicheiroPDFAnexarNC
							EXEC sp_OADestroy @ObjId	
-- anexa o ficheiro à declaração DUI2
							IF (@IDDeclaracaoDARConta IS NULL) AND (@ArquivaReportBinario = 0)
								EXEC SP_DeclImportacao_AnexaDocumento @PathFicheiroPDFAnexar, @DirDestinoDocsImportacao, @AnoProcessoConta, @NumProcessoConta, @DescricaoFicheiroAnexar, @NomeFicheiroAnexar, @Utilizador, 1, 'FTINTERN', 2
							ELSE
							BEGIN								
-- inicia variaveis para executar o SQL dinamicamente
								SET @SQLString = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiroPDFAnexar + ''', SINGLE_BLOB) AS t)'
								SET @SQLParams = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'			
-- obtem o ficheiro em binario
								EXECUTE sp_executesql @SQLString, @SQLParams, @OUTFicheiroBinario = @FicheiroBinario OUTPUT	
-- anexa o ficheiro à declaração IMP-CAU
								IF @IDDeclaracaoDARConta IS NULL
								BEGIN
									INSERT INTO PRO_DUFI(DUC_PNUM, DUC_EANO, DUF_DESC, DUF_DATA, DUF_NOMF, DUF_UTIL, DUF_ISER, DUF_TMSG, DUF_ORIG, DUF_FICH)
									VALUES(@NumProcessoConta, @AnoProcessoConta, @DescricaoFicheiroAnexar, @DataAtual, @NomeFicheiroAnexar, @Utilizador, 1, 'FTINTERN', 2, @FicheiroBinario)		
								END
								ELSE
								BEGIN									
-- anexa o ficheiro à declaração DAR										
									INSERT INTO tb_DeclaracoesDARArquivos(id_declaracaoDAR, descricao, tipo, nomeFicheiro, ficheiro, id_utilizadorArquivo, dataArquivo, origem, 
										id_utilizadorControlo, dataControlo)
									VALUES(@IDDeclaracaoDARConta, @DescricaoFicheiroAnexar, 1, @NomeFicheiroAnexar, @FicheiroBinario, @IdUtilizador, @DataAtual, 2, 
										@IdUtilizador, @DataAtual)
								END
-- remove o ficheiro anexado
								SET @ErroImportacao = ''
								EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroPDFAnexar, @ErroImportacao OUTPUT
								IF ISNULL(@ErroImportacao, '') <> ''
									SET @Erros = @Erros + '[Fatura N. ' + @XMLCodTipoDocumento + '/' + CAST(@AnoConta AS varchar(4)) + '.' + CAST(@XMLNumeroDocumento AS varchar(10)) + '] -> Erro na remoção do ficheiro "' + @PathFicheiroPDFAnexar + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)
							END
						END
						ELSE
							SET @Erros = @Erros + '[Fatura N. ' + @XMLCodTipoDocumento + '/' + CAST(@AnoConta AS varchar(4)) + '.' + CAST(@XMLNumeroDocumento AS varchar(10)) + '] -> Erro na impressão PDF do ficheiro "' + @PathFicheiroPDFAnexar + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)
					END																				
-- obtem nome do 1º report FRF configurado p/ imprimir e anexar no tipo de documento de conta da nova fatura
					SET @NomeReportImprimir = ''
					SELECT @NomeReportImprimir = (CASE WHEN tdo.TDO_IRP1 = 1 AND tdo.TDO_ARP1 IN (1, 3) THEN tdo.TDO_REP1 WHEN tdo.TDO_IRP2 = 1 AND tdo.TDO_ARP2 IN (1, 3) THEN tdo.TDO_REP2 WHEN tdo.TDO_IRP3 = 1 AND tdo.TDO_ARP3 IN (1, 3) THEN tdo.TDO_REP3 WHEN tdo.TDO_IRP4 = 1 AND tdo.TDO_ARP4 IN (1, 3) THEN tdo.TDO_REP4 ELSE NULL END), 
						@RadicalPDF = (CASE WHEN tdo.TDO_IRP1 = 1 AND tdo.TDO_ARP1 IN (1, 3) THEN '' WHEN tdo.TDO_IRP2 = 1 AND tdo.TDO_ARP2 IN (1, 3) THEN '_2' WHEN tdo.TDO_IRP3 = 1 AND tdo.TDO_ARP3 IN (1, 3) THEN '_3' WHEN tdo.TDO_IRP4 = 1 AND tdo.TDO_ARP4 IN (1, 3) THEN '_4' ELSE NULL END)
					FROM FAC_CDOC AS con WITH(NOLOCK) 
						INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON con.CDO_TDOC = tdo.TDO_DOCU
					WHERE con.CDO_EANO = @AnoConta AND con.CDO_TDOC = @XMLCodTipoDocumento AND con.CDO_ORID = @IDConta
-- procede à geração do report em PDF para o documento de crédito										
					IF ISNULL(@NomeReportImprimir, '') <> ''
					BEGIN
						SET @NomeFicheiroAnexar = CAST(@NumProcessoConta AS varchar(10)) + '.' + @XMLCodTipoDocumento + '.' + CAST(@NumeroNovaConta AS varchar(10)) + '.' + CAST(@AnoConta AS varchar(4)) + @RadicalPDF + '.pdf';		
						SET @PathFicheiroPDFAnexar = @DirFicheirosTmpLocal + @NomeFicheiroAnexar
						SET @PathFicheiroPDFAnexarFT = @DirFicheirosTmpLocal + 'e' + @NomeFicheiroAnexar
						SET @ArgsGIDWinPDFExportTool = '-s' + @@SERVERNAME + ' -p' + @PwLoginGIDWin + ' -b' + DB_NAME() + ' -r' + QUOTENAME((@DirReportsEmpresa + @NomeReportImprimir), '"') + ' -c0 -a' + CAST(@AnoConta AS varchar(4)) + ' -t' + @XMLCodTipoDocumento + ' -i' + CAST(@IDNovaConta AS varchar(20)) + ' -f' + QUOTENAME(@PathFicheiroPDFAnexar, '"')											
						SET @ErroImportacao = ''
						EXEC GIDWIN.dbo.SP_Externo_ExecutaPrograma @PathGIDWinPDFExportTool, @ArgsGIDWinPDFExportTool, @ErroImportacao OUTPUT
-- procede à anexação no documento no Arquivo no processo de origem
						IF ISNULL(@ErroImportacao, '') = ''
						BEGIN								
							SET @DescricaoFicheiroAnexar = 'Fatura N.º ' + CAST(@NumeroNovaConta AS varchar(10))
-- copia ficheiro do documento de crédito para posterior envio no email
							EXEC sp_OACreate 'Scripting.FileSystemObject', @ObjId OUTPUT					
							EXEC sp_OAMethod @ObjId, 'CopyFile', NULL, @PathFicheiroPDFAnexar, @PathFicheiroPDFAnexarFT
							EXEC sp_OADestroy @ObjId
-- anexa o ficheiro à declaração DUI2
							IF (@IDDeclaracaoDARConta IS NULL) AND (@ArquivaReportBinario = 0)
								EXEC SP_DeclImportacao_AnexaDocumento @PathFicheiroPDFAnexar, @DirDestinoDocsImportacao, @AnoProcessoConta, @NumProcessoConta, @DescricaoFicheiroAnexar, @NomeFicheiroAnexar, @Utilizador, 1, 'FTINTERN', 2
							ELSE
							BEGIN								
-- inicia variaveis para executar o SQL dinamicamente
								SET @SQLString = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiroPDFAnexar + ''', SINGLE_BLOB) AS t)'
								SET @SQLParams = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'			
-- obtem o ficheiro em binario
								EXECUTE sp_executesql @SQLString, @SQLParams, @OUTFicheiroBinario = @FicheiroBinario OUTPUT	
-- anexa o ficheiro à declaração IMP-CAU
								IF @IDDeclaracaoDARConta IS NULL
								BEGIN
									INSERT INTO PRO_DUFI(DUC_PNUM, DUC_EANO, DUF_DESC, DUF_DATA, DUF_NOMF, DUF_UTIL, DUF_ISER, DUF_TMSG, DUF_ORIG, DUF_FICH)
									VALUES(@NumProcessoConta, @AnoProcessoConta, @DescricaoFicheiroAnexar, @DataAtual, @NomeFicheiroAnexar, @Utilizador, 1, 'FTINTERN', 2, @FicheiroBinario)		
								END
								ELSE
								BEGIN									
-- anexa o ficheiro à declaração DAR										
									INSERT INTO tb_DeclaracoesDARArquivos(id_declaracaoDAR, descricao, tipo, nomeFicheiro, ficheiro, id_utilizadorArquivo, dataArquivo, origem, 
										id_utilizadorControlo, dataControlo)
									VALUES(@IDDeclaracaoDARConta, @DescricaoFicheiroAnexar, 1, @NomeFicheiroAnexar, @FicheiroBinario, @IdUtilizador, @DataAtual, 2, 
										@IdUtilizador, @DataAtual)
								END
-- remove o ficheiro anexado
								SET @ErroImportacao = ''
								EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroPDFAnexar, @ErroImportacao OUTPUT
								IF ISNULL(@ErroImportacao, '') <> ''
									SET @Erros = @Erros + '[Fatura N. ' + @XMLCodTipoDocumento + '/' + CAST(@AnoConta AS varchar(4)) + '.' + CAST(@XMLNumeroDocumento AS varchar(10)) + '] -> Erro na remoção do ficheiro "' + @PathFicheiroPDFAnexar + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)
							END
						END
						ELSE
							SET @Erros = @Erros + '[Fatura N. ' + @XMLCodTipoDocumento + '/' + CAST(@AnoConta AS varchar(4)) + '.' + CAST(@XMLNumeroDocumento AS varchar(10)) + '] -> Erro na impressão PDF do ficheiro "' + @PathFicheiroPDFAnexar + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)														
					END									
-- processa o envio de email com os documentos de credito e documento de conta gerados
					IF (ISNULL(@PerfilSQLEnvioEmail, '') <> '') AND ((ISNULL(@PathFicheiroPDFAnexarNC, '') <> '') OR (ISNULL(@PathFicheiroPDFAnexarFT, '') <> ''))
					BEGIN											
						SET @PathsFicheirosAnexoEmail = ISNULL(@PathFicheiroPDFAnexarNC, '')
						IF ISNULL(@PathsFicheirosAnexoEmail, '') <> ''
							SET @PathsFicheirosAnexoEmail = @PathsFicheirosAnexoEmail + ';'
						SET @PathsFicheirosAnexoEmail = @PathsFicheirosAnexoEmail + ISNULL(@PathFicheiroPDFAnexarFT, '')
-- envia o email com os documentos em anexo para o email do cliente						
						EXEC msdb.dbo.sp_send_dbmail @PerfilSQLEnvioEmail, @XMLEmailCliente, NULL, NULL, @AssuntoEmail, @TextoEmail, NULL, 'NORMAL', 'NORMAL', @PathsFicheirosAnexoEmail
-- remove o ficheiro NC anexado
						SET @ErroImportacao = ''
						EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroPDFAnexarNC, @ErroImportacao OUTPUT
						IF ISNULL(@ErroImportacao, '') <> ''
							SET @Erros = @Erros + '[Fatura N. ' + @XMLCodTipoDocumento + '/' + CAST(@AnoConta AS varchar(4)) + '.' + CAST(@XMLNumeroDocumento AS varchar(10)) + '] -> Erro na remoção do ficheiro "' + @PathFicheiroPDFAnexarNC + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)						  
-- remove o ficheiro FT anexado
						SET @ErroImportacao = ''
						EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroPDFAnexarFT, @ErroImportacao OUTPUT
						IF ISNULL(@ErroImportacao, '') <> ''
							SET @Erros = @Erros + '[Fatura N. ' + @XMLCodTipoDocumento + '/' + CAST(@AnoConta AS varchar(4)) + '.' + CAST(@XMLNumeroDocumento AS varchar(10)) + '] -> Erro na remoção do ficheiro "' + @PathFicheiroPDFAnexarFT + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)						  
					END
				END
-- espera 5 segundos para evitar que haja um bloqueio massivo dos objetos da BD (deadlocks)
				WAITFOR DELAY '00:00:03.000'										
				FETCH NEXT FROM Faturas INTO @XMLCodTipoDocumento, @XMLNumeroDocumento, @XMLDataDocumento, @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLLocalidadeCliente, 
					@XMLCodPostalCliente, @XMLLocPostalCliente, @XMLEmailCliente, @XMLCodPaisCliente
			END
			CLOSE Faturas
			DEALLOCATE Faturas		
-- se houve erros na importação de alguma fatura, gera erro genérico para detalhar os erros ocorridos na importação
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('%s', 16, 99, @Erros)						
		END TRY
		BEGIN CATCH			
-- constroi mensagem de erro detalhada p/ gerar ficheiro de erro
			SET @ErroFicheiro = '**********************************************************************************************************' + CHAR(12) +
								'** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								'**********************************************************************************************************' + CHAR(12) + 
								'.Nome Ficheiro DHL:  ' + @NomeFicheiro + CHAR(12) +								   
								'.Detalhe Erro:       ' + CHAR(12) +
								'		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
								'		*Numero do Erro:     ' + CAST(ERROR_NUMBER() AS varchar) + CHAR(12) + 
								'		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() AS varchar) + CHAR(12) + 
								'		*Estado do Erro:     ' + CAST(ERROR_STATE() AS varchar) + CHAR(12) + 
								'		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								'		*N. Linha do Erro:   ' + CAST(ERROR_LINE() AS varchar) + CHAR(12) + 
								'		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH		
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ErroFicheiro, '') <> ''
		BEGIN									
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ErroFicheiro, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ErroFicheiro = STUFF(@ErroFicheiro, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			END								
		END		
		FETCH NEXT FROM FicheirosDHL INTO @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosDHL
	DEALLOCATE FicheirosDHL
-- remove a tabela temporária	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_Contas_ProcessaFicheirosXMLCreditosPortalDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Contas_ProcessaFicheirosXMLCreditosPortalDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_copiaCliente]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_copiaCliente] @codOrigem varchar(18), @codNovo varchar(18), @eanNovo varchar(18), @Utilizador varchar(30) AS
BEGIN
	-- cria cabeçalho da ficha de cliente ------------------------------------------------------
	INSERT INTO TAB_CLIE(CLI_CODI, CLI_CEAN, CLI_INAC, CLI_DESP, CLI_AUTO, CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_TELF, CLI_TEL2, CLI_FAX, CLI_EMAI, CLI_WEB, CLI_NIF, 
		CLI_TNIF, PAI_CODI, RES_CODI, FLE_CODI, CLI_MDPG, CLI_NDHA, CLI_DTDH, CLI_NCA1, CLI_ANO1, CLI_TCA1, CLI_INA1, CLI_NCA2, CLI_ANO2, CLI_TCA2, CLI_INA2, CLI_NCA3, CLI_ANO3, CLI_TCA3, 
		CLI_INA3, CLI_NCA4, CLI_ANO4, CLI_TCA4, CLI_INA4, CLI_NCA5, CLI_ANO5, CLI_TCA5, CLI_INA5, CLI_CCOR, CLI_CPOC, CLI_ECON, CLI_SUCA, CLI_ISAL, CLI_STAN, CLI_CLIE, CLI_APEL, CLI_FREG, 
		CLI_CONC, CLI_DIST, CLI_NATU, CLI_NACI, CLI_NPAI, CLI_NMAE, CLI_ECIV, CLI_DNAS, CLI_RESI, CLI_PROF, EJU_CODI, CLI_DEST, CLI_BI, CLI_BIEM, CLI_BIDT, CLI_PASS, CLI_PAEM, CLI_PADT, 
		CLI_CCON, CLI_CCEM, CLI_CCDT, CLI_CMIL, CLI_CMEM, CLI_CMDT, CLI_INFO, CLI_CODC, CLI_CPAG, CLI_MPAG, DIN_CODI, CLI_SENT, CLI_DUCT, CLI_LMCR, CLI_VCIL, CLI_CACC, CLI_CEXB, CLI_CDAS, 
		CLI_AURS, CLI_DTRS, DOC_CODI, CLI_NAOE, CLI_DTOE, DOC_CDOE, CLI_FXOE, COS_CDLS, COS_CDPO, CLI_VEVD, CLI_AIVA, CLI_INTR, CLI_IEEN, CLI_IESA, CLI_INDI, CLI_ITFT, CLI_IVLF, DEC_CODI, 
		CLI_TDEC, CLI_UCRI, CLI_DCRI, CLI_UALT, CLI_DALT, CLI_CNIF, ALF_CODI1, CLI_CCA1, CLI_OCA1, ALF_CODI2, CLI_CCA2, CLI_OCA2, ALF_CODI3, CLI_CCA3, CLI_OCA3, ALF_CODI4, CLI_CCA4, CLI_OCA4, 
		ALF_CODI5, CLI_CCA5, CLI_OCA5)
	SELECT @codNovo, @eanNovo, 0, CLI_DESP, CLI_AUTO, CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_TELF, CLI_TEL2, CLI_FAX, CLI_EMAI, CLI_WEB, CLI_NIF, 
		CLI_TNIF, PAI_CODI, RES_CODI, FLE_CODI, CLI_MDPG, CLI_NDHA, CLI_DTDH, CLI_NCA1, CLI_ANO1, CLI_TCA1, CLI_INA1, CLI_NCA2, CLI_ANO2, CLI_TCA2, CLI_INA2, CLI_NCA3, CLI_ANO3, CLI_TCA3, 
		CLI_INA3, CLI_NCA4, CLI_ANO4, CLI_TCA4, CLI_INA4, CLI_NCA5, CLI_ANO5, CLI_TCA5, CLI_INA5, CLI_CCOR, CLI_CPOC, CLI_ECON, CLI_SUCA, CLI_ISAL, CLI_STAN, CLI_CLIE, CLI_APEL, CLI_FREG, 
		CLI_CONC, CLI_DIST, CLI_NATU, CLI_NACI, CLI_NPAI, CLI_NMAE, CLI_ECIV, CLI_DNAS, CLI_RESI, CLI_PROF, EJU_CODI, CLI_DEST, CLI_BI, CLI_BIEM, CLI_BIDT, CLI_PASS, CLI_PAEM, CLI_PADT, 
		CLI_CCON, CLI_CCEM, CLI_CCDT, CLI_CMIL, CLI_CMEM, CLI_CMDT, CLI_INFO, CLI_CODC, CLI_CPAG, CLI_MPAG, DIN_CODI, CLI_SENT, CLI_DUCT, CLI_LMCR, CLI_VCIL, CLI_CACC, CLI_CEXB, CLI_CDAS, 
		CLI_AURS, CLI_DTRS, DOC_CODI, CLI_NAOE, CLI_DTOE, DOC_CDOE, CLI_FXOE, COS_CDLS, COS_CDPO, CLI_VEVD, CLI_AIVA, CLI_INTR, CLI_IEEN, CLI_IESA, CLI_INDI, CLI_ITFT, CLI_IVLF, DEC_CODI, 
		CLI_TDEC, @Utilizador, GETDATE(), @Utilizador, GETDATE(), CLI_CNIF, ALF_CODI1, CLI_CCA1, CLI_OCA1, ALF_CODI2, CLI_CCA2, CLI_OCA2, ALF_CODI3, CLI_CCA3, CLI_OCA3, ALF_CODI4, CLI_CCA4, CLI_OCA4, 
		ALF_CODI5, CLI_CCA5, CLI_OCA5
	FROM TAB_CLIE
	WHERE CLI_CODI = @codOrigem
	-- cabeçalho das máscaras de facturação ----------------------------------------------------
	INSERT INTO TAB_MCFT(CLI_CODI, MCF_CODI, MCF_DESC, NDE_CODI, MCF_VAGR, MCF_VDES, MCF_VALO, MCF_OBSV)
	SELECT @codNovo, MCF_CODI, MCF_DESC, NDE_CODI, MCF_VAGR, MCF_VDES, MCF_VALO, MCF_OBSV
	FROM TAB_MCFT
	WHERE CLI_CODI = @codOrigem
	-- máscaras das documentadas ---------------------------------------------------------------
	INSERT INTO TAB_MCDO(CLI_CODI, MCF_CODI, DDO_CODI, MCD_POSI, MCD_VALO)
	SELECT @codNovo, MCF_CODI, DDO_CODI, MCD_POSI, MCD_VALO
	FROM TAB_MCDO
	WHERE CLI_CODI = @codOrigem
	-- máscaras das inerentes ------------------------------------------------------------------
	INSERT INTO TAB_MCIN(CLI_CODI,MCF_CODI,DIN_CODI,MCI_POSI,MCI_VALO)
	SELECT @codNovo, MCF_CODI, DIN_CODI, MCI_POSI, MCI_VALO
	FROM TAB_MCIN
	WHERE CLI_CODI = @codOrigem
	-- armazens --------------------------------------------------------------------------------
	INSERT INTO TAB_CARM(CLI_CODI, CAR_CODI, CAR_MORA, CAR_LOCA, CAR_CPOS, CAR_LPOS)
	SELECT @codNovo, CAR_CODI, CAR_MORA, CAR_LOCA, CAR_CPOS, CAR_LPOS
	FROM TAB_CARM
	WHERE CLI_CODI = @codOrigem
END

ALTER AUTHORIZATION ON [SP_copiaCliente] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_copiaCliente] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_copiaMascaras]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_copiaMascaras] @cli_codi varchar(18) AS
	DECLARE @mcf_codi int,@mcf_desc varchar(50),@nde_codi varchar(3),@mcf_vagr numeric(38,6)
	,@mcf_vdes numeric(38,6),@mcf_valo numeric(38,6),@nova_linha int,@cliente varchar(18)
	,@ddo_codi int,@mcd_posi int,@mcd_valo numeric(38,6),@din_codi int,@mci_posi int
	,@mci_valo numeric(38,6),@mcf_obsv varchar(7000) 
	-- busca máscaras de facturação do cliente -------------------------------------------
	DECLARE mascara CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT MCF_CODI,MCF_DESC,NDE_CODI,MCF_VAGR,MCF_VDES,MCF_VALO,MCF_OBSV
	FROM TAB_MCFT
	WHERE CLI_CODI=@cli_codi 
	OPEN mascara
	FETCH NEXT from mascara into @mcf_codi,@mcf_desc,@nde_codi,@mcf_vagr,@mcf_vdes,@mcf_valo,@mcf_obsv
	WHILE @@FETCH_STATUS=0
	BEGIN
		-- busca cliente existêntes --------------------------------------------------
		DECLARE clientes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT CLI_CODI
		FROM TAB_CLIE
		WHERE CLI_CODI!=@cli_codi 
		OPEN clientes
		FETCH NEXT FROM clientes INTO @cliente
		WHILE @@FETCH_STATUS=0
		BEGIN
			-- busca código da máscara -------------------------------------------
			SELECT @nova_linha=ISNULL(MAX(MCF_CODI),0)+1
			FROM TAB_MCFT
			WHERE CLI_CODI=@cliente
			-- insere máscara ----------------------------------------------------
			INSERT INTO TAB_MCFT(CLI_CODI,MCF_CODI,MCF_DESC,NDE_CODI,MCF_VAGR,MCF_VDES,MCF_VALO,MCF_OBSV) 
			VALUES(@cliente,@nova_linha,@mcf_desc,@nde_codi,@mcf_vagr,@mcf_vdes,@mcf_valo,@mcf_obsv)
  			-- busca despesas documentadas da máscara ---------------------------- 
			DECLARE detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DDO_CODI,MCD_POSI,MCD_VALO
			FROM TAB_MCDO
			WHERE CLI_CODI=@cli_codi AND MCF_CODI=@mcf_codi
			OPEN detalhe
			FETCH NEXT FROM detalhe INTO @ddo_codi,@mcd_posi,@mcd_valo
			WHILE @@FETCH_STATUS=0
			BEGIN
				-- inserir despesas documentadas -----------------------------
				INSERT INTO TAB_MCDO(CLI_CODI,MCF_CODI,DDO_CODI,MCD_POSI,MCD_VALO) 
				VALUES(@cliente,@nova_linha,@ddo_codi,@mcd_posi,@mcd_valo)
				FETCH NEXT FROM detalhe INTO  @ddo_codi,@mcd_posi,@mcd_valo
			END
			CLOSE detalhe
			DEALLOCATE detalhe
			-- busca despesas inerentes da máscara ------------------------------- 
			DECLARE detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DIN_CODI,MCI_POSI,MCI_VALO
			FROM TAB_MCIN
			WHERE CLI_CODI=@cli_codi AND MCF_CODI=@mcf_codi
	 		OPEN detalhe
			FETCH NEXT FROM detalhe INTO  @din_codi,@mci_posi,@mci_valo
			WHILE @@FETCH_STATUS=0
			BEGIN
				-- inserir despesas inerentes --------------------------------
				INSERT INTO TAB_MCIN(CLI_CODI,MCF_CODI,DIN_CODI,MCI_POSI,MCI_VALO) 
				VALUES(@cliente,@nova_linha,@din_codi,@mci_posi,@mci_valo)
				FETCH NEXT FROM detalhe INTO  @din_codi,@mci_posi,@mci_valo
			END
			CLOSE detalhe
			DEALLOCATE detalhe
			FETCH NEXT FROM clientes INTO @cliente
		END
		CLOSE clientes
		DEALLOCATE clientes
		FETCH NEXT FROM mascara INTO @mcf_codi,@mcf_desc,@nde_codi,@mcf_vagr,@mcf_vdes,@mcf_valo,@mcf_obsv
	END
	CLOSE mascara
	DEALLOCATE mascara

ALTER AUTHORIZATION ON [SP_copiaMascaras] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_copiaMascaras] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_copiaMascarasDePara]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_copiaMascarasDePara] @cli_codi varchar(18), @cliente varchar(18) AS

	DECLARE @mcf_codi int,@mcf_desc varchar(50),@nde_codi varchar(3),@mcf_vagr numeric(38,6)
	,@mcf_vdes numeric(38,6),@mcf_valo numeric(38,6),@nova_linha int,@ddo_codi int,@mcd_posi int
	,@mcd_valo numeric(38,6),@din_codi int,@mci_posi int,@mci_valo numeric(38,6),@mcf_obsv varchar(7000)
	-- busca máscaras de facturação do cliente -------------------------------------------
	DECLARE mascara CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT MCF_CODI,MCF_DESC,NDE_CODI,MCF_VAGR,MCF_VDES,MCF_VALO,MCF_OBSV
	FROM TAB_MCFT
	WHERE CLI_CODI=@cli_codi 
	OPEN mascara
	FETCH NEXT FROM mascara INTO @mcf_codi,@mcf_desc,@nde_codi,@mcf_vagr,@mcf_vdes,@mcf_valo,@mcf_obsv
	WHILE @@FETCH_STATUS=0
	BEGIN
		-- busca código da máscara ---------------------------------------------------
		SELECT @nova_linha=ISNULL(MAX(MCF_CODI),0)+1
		FROM TAB_MCFT
		WHERE CLI_CODI=@cliente
		-- insere máscara ------------------------------------------------------------
		INSERT INTO TAB_MCFT(CLI_CODI,MCF_CODI,MCF_DESC,NDE_CODI,MCF_VAGR,MCF_VDES,MCF_VALO,MCF_OBSV) 
		VALUES(@cliente,@nova_linha,@mcf_desc,@nde_codi,@mcf_vagr,@mcf_vdes,@mcf_valo,@mcf_obsv)
  		-- busca despesas documentadas da máscara ------------------------------------ 
		DECLARE detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT DDO_CODI,MCD_POSI,MCD_VALO
		FROM TAB_MCDO
		WHERE CLI_CODI=@cli_codi AND MCF_CODI=@mcf_codi
		OPEN detalhe
		FETCH NEXT FROM detalhe INTO @ddo_codi,@mcd_posi,@mcd_valo
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- inserir despesas documentadas -------------------------------------
			INSERT INTO TAB_MCDO(CLI_CODI,MCF_CODI,DDO_CODI,MCD_POSI,MCD_VALO) 
			VALUES(@cliente,@nova_linha,@ddo_codi,@mcd_posi,@mcd_valo)
			FETCH NEXT FROM detalhe INTO @ddo_codi,@mcd_posi,@mcd_valo
		END
		CLOSE detalhe
		DEALLOCATE detalhe
		-- busca despesas inerentes da máscara --------------------------------------- 
		DECLARE detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT DIN_CODI,MCI_POSI,MCI_VALO
		FROM TAB_MCIN
		WHERE CLI_CODI=@cli_codi AND MCF_CODI=@mcf_codi
		OPEN detalhe
		FETCH NEXT FROM detalhe INTO @din_codi,@mci_posi,@mci_valo
		WHILE @@FETCH_STATUS=0
		BEGIN
			-- inserir despesas inerentes ----------------------------------------
			INSERT INTO TAB_MCIN(CLI_CODI,MCF_CODI,DIN_CODI,MCI_POSI,MCI_VALO) 
			VALUES(@cliente,@nova_linha,@din_codi,@mci_posi,@mci_valo)
			FETCH NEXT FROM detalhe INTO @din_codi,@mci_posi,@mci_valo
		END
		CLOSE detalhe
		DEALLOCATE detalhe
	    	FETCH NEXT FROM mascara INTO @mcf_codi,@mcf_desc,@nde_codi,@mcf_vagr,@mcf_vdes,@mcf_valo,@mcf_obsv
	END
	CLOSE mascara
	DEALLOCATE mascara

ALTER AUTHORIZATION ON [SP_copiaMascarasDePara] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_copiaMascarasDePara] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclaracaoSumariaSaida_DuplicaRegisto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclaracaoSumariaSaida_DuplicaRegisto] @AnoDeclaracao int, @CodDeclaranteDeclaracao varchar(18), @NumeroDeclaracao int, @NumNovaDeclaracao int OUTPUT, @Utilizador varchar(30) AS
BEGIN
-- declaração de variaveis
	DECLARE @NIFDeclarante varchar(17)
	SET DATEFORMAT DMY
-- obtem novo numero para proxima Declaração
	select @NumNovaDeclaracao = DCS_PNPR, @NIFDeclarante = DCS_NNIF
	from TAB_DECS
	where DCS_CODI = @CodDeclaranteDeclaracao		
-- insere Dados Gerais da nova Declaração
	insert into PRO_DESS(DSS_EANO, DCS_CODI, DSS_NPRO, DCS_NOME, DSS_TDEC, DSR_NOME, DSR_MORA, DSR_CPOS, DSR_LOCA, PAI_CODI, DSR_NNIF, DSS_IESC, DSS_DATA, 
		DSS_NRLO, DSS_STAT, DSS_VERS, DSS_NADI, DSS_TVOL, DSS_MBRT, DSS_MCNT, LEM_CODI, LEM_DESC, LME_CODI, LME_NOME, DSS_DTDC, DSS_LCDC, EAD_CODI, EAD_NOME, 
		EAD_COD2, EAD_NOM2, DSS_DTMP, DSS_NCRF, CLI_CODI, DSS_CNOM, DSS_CMOR, DSS_CLOC, DSS_CCPO, DSS_CLPO, DSS_CPAI, DSS_CNIF, DSS_CTNF, FOR_CODI, DSS_FNOM, 
		DSS_FMOR, DSS_FLOC, DSS_FCPO, DSS_FLPO, DSS_FPAI, DSS_FNIF, DSS_UCRI, DSS_DCRI, DSS_UALT, DSS_DALT)
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DCS_NOME, DSS_TDEC, DSR_NOME, DSR_MORA, DSR_CPOS, DSR_LOCA, PAI_CODI, DSR_NNIF, DSS_IESC, 
		CAST(CONVERT(varchar(10), GETDATE(), 105) as datetime), (CAST(DSS_EANO as varchar(4)) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + 'S' + REPLICATE('0', 6 - LEN(CAST(@NumNovaDeclaracao as varchar(20)))) + CAST(@NumNovaDeclaracao as varchar(20))), 
		0, 1, DSS_NADI, DSS_TVOL, DSS_MBRT, DSS_MCNT, LEM_CODI, LEM_DESC, LME_CODI, LME_NOME, CAST(CONVERT(varchar(10), GETDATE(), 105) as datetime), DSS_LCDC, 
		EAD_CODI, EAD_NOME, EAD_COD2, EAD_NOM2, DSS_DTMP, DSS_NCRF, CLI_CODI, DSS_CNOM, DSS_CMOR, DSS_CLOC, DSS_CCPO, DSS_CLPO, DSS_CPAI, DSS_CNIF, DSS_CTNF, 
		FOR_CODI, DSS_FNOM, DSS_FMOR, DSS_FLOC, DSS_FCPO, DSS_FLPO, DSS_FPAI, DSS_FNIF, @Utilizador, GETDATE(), @Utilizador, GETDATE()	
	from PRO_DESS
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
-- incrementa o numero da proxima Declaração
	update TAB_DECS set DCS_PNPR = DCS_PNPR + 1
	where DCS_CODI = @CodDeclaranteDeclaracao				
-- insere detalhe de Itinerarios da nova Declaração
	insert into PRO_DSSI(DSS_EANO, DCS_CODI, DSS_NPRO, DSI_NUME, PAI_CODI, PAI_NOME)
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DSI_NUME, PAI_CODI, PAI_NOME
	from PRO_DSSI
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
-- insere detalhe de Selos da nova Declaração
	insert into PRO_DSSS(DSS_EANO, DCS_CODI, DSS_NPRO, DSS_NUME, DSS_NSEL)
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DSS_NUME, DSS_NSEL
	from PRO_DSSS
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
-- insere detalhe de Adições da nova Declaração
	insert into PRO_DSSA(DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, APA_CODI, DSA_CPAU, DSA_DESG, DSA_MPUN, DSA_MBRT)
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DSA_NUME, APA_CODI, DSA_CPAU, DSA_DESG, DSA_MPUN, DSA_MBRT
	from PRO_DSSA
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
-- insere sub-detalhe de Documentos das Adições da nova Declaração
	insert into PRO_DSAD(DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAD_NUME, DOC_CODI, DOC_NOME, DAD_NDOC, DAD_DDOC, DAD_AUTO)			
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DSA_NUME, DAD_NUME, DOC_CODI, DOC_NOME, DAD_NDOC, DAD_DDOC, DAD_AUTO
	from PRO_DSAD
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
-- insere sub-detalhe de Marcas das Adições da nova Declaração
	insert into PRO_DSAM(DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAM_NUME, DAM_MRNU, TEM_CODI, TEM_NOME, DAM_NVOL, DAM_NPCS, DAM_PART, DAM_AUTO, DAM_TIPO)
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DSA_NUME, DAM_NUME, DAM_MRNU, TEM_CODI, TEM_NOME, DAM_NVOL, DAM_NPCS, DAM_PART, DAM_AUTO, DAM_TIPO
	from PRO_DSAM
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
-- insere sub-detalhe de Contentores das Adições da nova Declaração
	insert into PRO_DSAC(DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAC_NUME, DAC_NCNT)
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DSA_NUME, DAC_NUME, DAC_NCNT
	from PRO_DSAC
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
-- insere sub-detalhe de Declaração Sumária das Adições da nova Declaração
	insert into PRO_DSAS(DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAS_NUME, DAS_TIPO, DAS_NDOC, DAS_CATE, DAS_DATA)
	select DSS_EANO, DCS_CODI, @NumNovaDeclaracao, DSA_NUME, DAS_NUME, DAS_TIPO, DAS_NDOC, DAS_CATE, DAS_DATA
	from PRO_DSAS
	where DSS_EANO = @AnoDeclaracao and DCS_CODI = @CodDeclaranteDeclaracao and DSS_NPRO = @NumeroDeclaracao
END

ALTER AUTHORIZATION ON [SP_DeclaracaoSumariaSaida_DuplicaRegisto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclaracaoSumariaSaida_DuplicaRegisto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ConverteRegistoParaDUI2]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ConverteRegistoParaDUI2] @Id int, @IdUtilizador int, @IdDeclaracaoDUI2 int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @Utilizador varchar(30), @XMLDeclaracaoDUI2 xml(XMLSC_DeclaracoesImpToGIDWin)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração da declaração	DUI2
	BEGIN TRY	
		SET @NumErro = 0
-- obtem código do utilizador
		SELECT @Utilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- constroi XML para declaração DUI2 a partir da declaração DAR
		SET @XMLDeclaracaoDUI2 = 
			(SELECT
				(SELECT 'I' AS "@Acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "Data", 
					nat.NDE_CODI2 AS "CodNatureza", 
					SUBSTRING(dar.documentoTransporte, 1, 18) AS "NumDocTransporte",
					(SELECT (CASE WHEN pfr.PAI_CODI IN ('GB', 'XU', 'XI', 'CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'SM', 'AD', 'GI', 'UA') THEN tde.TDE_CODI ELSE tdi.TDE_CODI END) FROM tb_ConfiguracoesDAR AS cfg WITH(NOLOCK) INNER JOIN TAB_TDEC AS tdi WITH(NOLOCK) ON cfg.id_tipoDeclaracaoIM = tdi.TDE_IDTY INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON cfg.id_tipoDeclaracaoEU = tde.TDE_IDTY) AS "CodTipoDeclaracao", 
					alf.ALF_CODI AS "CodEstancia", 
					frn.FOR_CODI AS "CodExpedidor", 
					cli.CLI_CODI AS "CodDestinatario", 
					dcl.DEC_CODI AS "CodDeclarante", 
					pfr.PAI_CODI AS "CodPais15A", 		
					pcl.PAI_CODI AS "CodPais17", 				
					ISNULL(mtr.MTR_CODI, (CASE RIGHT(alf.ALF_CODI, 3) WHEN '236' THEN '50' ELSE '40' END)) AS "CodMeioTransporte18", 
					(SELECT NULLIF(RTRIM(LTRIM(identificacaoMeioTransporte)), '') FROM tb_ConfiguracoesDAR WITH(NOLOCK)) AS "IdMeioTransporte", 		
					(CASE RIGHT(alf.ALF_CODI, 3) WHEN '236' THEN NULL ELSE ISNULL(mtr.MTR_CODI, '40') END) AS "CodMeioTransporte21", 
					(SELECT pai.PAI_CODI FROM tb_ConfiguracoesDAR AS cfg WITH(NOLOCK) INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON cfg.id_paisMeioTransporte = pai.PAI_IDTY) AS "CodPais21", 
					0 AS "TemContentores", 
					ISNULL(cen.CEN_CODI, (CASE dar.totalCustosTransporte WHEN 0 THEN 'CPT' ELSE 'FCA' END)) AS "CodCondEntrega", 
					(SELECT (CASE WHEN CEN_LOCT IS NULL THEN NULL ELSE (CASE CEN_LOCD WHEN 0 THEN NULLIF(SUBSTRING(dar.localidadeFornecedor, 1, 30), '') ELSE SUBSTRING(dar.localidadeCliente, 1, 30) END) END) FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = (CASE dar.totalCustosTransporte WHEN 0 THEN 'CPT' ELSE 'FCA' END)) AS "DescricaoCondEntrega", 										
					'11' AS "CodNaturezaTransacao", 
					ame.ALF_CODI AS "CodEstanciaAduaneira", 
					lme.LME_CODI AS "CodLocalAutorizado",
					pmt.PAI_CODI AS "CodPais22", 
					pct.PAI_CODI AS "CodPaisFrete", 
					NULLIF(RTRIM(LTRIM(dar.nomeFornecedor)), '') AS "NomeExpedidor", 
					NULLIF(RTRIM(LTRIM(dar.moradaFornecedor)), '') AS "MoradaExpedidor", 
					NULLIF(RTRIM(LTRIM(dar.localidadeFornecedor)), '') AS "LocalidadeExpedidor", 
					NULLIF(SUBSTRING(RTRIM(LTRIM(dar.codPostalFornecedor)), 1, 12), '') AS "CodPostalExpedidor", 
					NULLIF(RTRIM(LTRIM(dar.locPostalFornecedor)), '') AS "LocPostalExpedidor", 		
					pfr.PAI_CODI AS "CodPaisExpedidor", 					
					RTRIM(LTRIM(dar.nomeCliente)) AS "NomeDestinatario", 
					RTRIM(LTRIM(dar.moradaCliente)) AS "MoradaDestinatario", 
					RTRIM(LTRIM(dar.localidadeCliente)) AS "LocalidadeDestinatario", 
					SUBSTRING(RTRIM(LTRIM(dar.codPostalCliente)), 1, 12) AS "CodPostalDestinatario", 
					RTRIM(LTRIM(dar.locPostalCliente)) AS "LocPostalDestinatario", 					
					NULLIF(SUBSTRING(RTRIM(LTRIM(dar.telefoneCliente)), 1, 14), '') AS "TelefoneDestinatario", 
					NULLIF(RTRIM(LTRIM(dar.emailCliente)), '') AS "EmailDestinatario", 
					RTRIM(LTRIM(dar.nifCliente)) AS "NIFDestinatario", 	
					(CASE cli.CLI_TNIF WHEN 2 THEN 1 ELSE cli.CLI_TNIF END) AS "TipoDestinatario", 				
					pcl.PAI_CODI AS "CodPaisDestinatario",					
					cli.RES_CODI AS "CodRegiaoDestinatario", 		
					NULLIF(RTRIM(LTRIM(dar.numeroRequerimento)), '') AS "NumRequerimento",
					NULLIF(RTRIM(LTRIM(dar.numeroDURetorno)), '') AS "NumDURetorno", 
					NULLIF(RTRIM(LTRIM(dar.numeroT1Retorno)), '') AS "T1Retorno",
					(CONVERT(varchar(10), dar.dataVoo, 127) + 'Z') AS "DataPrevVoo", 
					dar.payment AS "Payment", 
					NULLIF(RTRIM(LTRIM(dar.numeroVossaReferencia)), '') AS "NumVossaReferencia",
					NULLIF(RTRIM(LTRIM(dar.numeroContaExpedidor)), '') AS "NumContaExpedidor",
					ISNULL(NULLIF(RTRIM(LTRIM(dar.portesAccFEDEX)), ''), NULLIF(RTRIM(LTRIM(dar.numeroContaDestinatario)), '')) AS "NumContaDestinatario", 
					NULLIF(RTRIM(LTRIM(dar.aeroportoOrigem)), '') AS "Aeroporto",
					NULLIF(RTRIM(LTRIM(dar.condicaoEntregaUPS)), '') AS "PPouFC", 				
					NULLIF(RTRIM(LTRIM(dar.numeroVoo)), '') AS "NumVoo", 
					NULLIF(RTRIM(LTRIM(dar.miniCPA)), '') AS "MiniCPA",
					ISNULL(NULLIF(RTRIM(LTRIM(dar.despachoAccFEDEX)), ''), NULLIF(RTRIM(LTRIM(dar.referenciaExterna1)), '')) AS "Referencia1", 
					NULLIF(RTRIM(LTRIM(dar.referenciaExterna2)), '') AS "Referencia2",
					NULLIF(RTRIM(LTRIM(dar.shipID)), '') AS "ShipID", 
					NULLIF(RTRIM(LTRIM(dar.tracking)), '') AS "Tracking",
					NULLIF(RTRIM(LTRIM(dar.dutyType)), '') AS "DType",	
					NULLIF(SUBSTRING(RTRIM(LTRIM(dar.portesFEDEX)), 1, 9), '') AS "PosicaoAviao",				
					NULLIF(RTRIM(LTRIM(dar.tipoCarga)), '') AS "TipoCarga",
					NULLIF(RTRIM(LTRIM(dar.nomeFicheiroUPS)), '') AS "NomeFileUPS", 
					NULLIF(RTRIM(LTRIM(dar.nomeOriginalDestinatario)), '') AS "NomeDestinatario2", 
					NULLIF(RTRIM(LTRIM(dar.moradaOriginalDestinatario)), '') AS "MoradaDestinatario2", 
					NULLIF(RTRIM(LTRIM(dar.localidadeOriginalDestinatario)), '') AS "LocalidadeDestinatario2", 
					NULLIF(RTRIM(LTRIM(dar.codPostalOriginalDestinatario)), '') AS "CodPostalDestinatario2", 
					NULLIF(RTRIM(LTRIM(dar.locPostalOriginalDestinatario)), '') AS "LocPostalDestinatario2", 
					NULLIF(RTRIM(LTRIM(dar.gatewayFEDEX)), '') AS "Gateway", 
					NULLIF(RTRIM(LTRIM(dar.locIDFEDEX)), '') AS "Delegacao",  					
					1 AS "EDeclaracaoImportacao", 
					NULLIF(dar.freteOriginal, 0) AS "ValorFreteCompanhia", 
					NULLIF(RTRIM(LTRIM(dar.moedaFreteOriginal)), '') AS "MoedaFreteCompanhia", 
					dar.nivelServico AS "NivelServico", 
					ndu.FUP_CODI AS "CodFollowUp", 
					uno.UTI_UTIL AS "CodUtilizadorNomeado", 
					(CONVERT(varchar(10), dar.dataDocumentoTransporte, 127) + 'Z') AS "DataDocCPA", 
					dar.despesasDHL AS "DespesasDHL", 
					(SELECT TOP 1 SUBSTRING(RTRIM(LTRIM(dpr.numero)), 1, 50) FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY WHERE dpr.id_declaracaoDAR = dar.id AND doc.DOC_CODI = 'N337') AS "NumeroDGASDS", 
					dar.numeroPDDT AS "DepositoTemporario/NumeroPDDT", 
					dar.numeroPDDTDEV AS "DepositoTemporario/NumeroPDDTDev", 
					dar.numeroTD AS "DepositoTemporario/NumeroTD", 
					dar.numeroACTM AS "DepositoTemporario/NumeroACTM", 
					dar.numeroSequencia AS "DepositoTemporario/NumeroSequencia", 
					(SELECT
						(SELECT adi.numeroAdicao AS "NumAdicao", 
							art.APA_CODI AS "CodArtigoPautal", 
							adi.designacao AS "Designacao", 
							por.PAI_CODI AS "CodPaisOrigem",
							dar.regimeAdicional AS "RegimeB", 
							adi.massaBruta AS "MassaBruta",							
							CAST(ROUND((adi.massaBruta * 95 / 100), 3) AS decimal(18, 6)) AS "MassaLiquida",
							adi.unidades AS "QtdUnidades",
							adi.montante AS "PrecoAdicao",							
							adi.custosTransporte AS "Frete", 
							1 AS "MetodoAvaliacao",
							(SELECT
								(SELECT (CASE RIGHT(alf.ALF_CODI, 3) WHEN '236' THEN 'CART.POSTAL' ELSE 'SM' END) AS "Marca", 	
									(CASE RIGHT(alf.ALF_CODI, 3) WHEN '236' THEN adi.numeroObjetoCTT ELSE NULL END) AS "Numero", 								
									CAST(dar.totalVolumes AS decimal(18, 6)) AS "QtdVolumes",
									'CT' AS "CodUnidMedida", 
									(CASE WHEN (dar.totalAdicoes > 1) AND (adi.numeroAdicao < dar.totalAdicoes) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "P", 
									(CASE WHEN (dar.totalAdicoes > 1) AND (adi.numeroAdicao = dar.totalAdicoes) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "R", 
									CAST(0 AS bit) AS "C",
									adi.codigoBarrasCTT AS "LOptica"
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE),
							(SELECT
								(SELECT 'X' AS "Tipo", 
									(CASE WHEN doc.DOC_CODI = 'N750' THEN doc.DOC_CODI WHEN (doc.DOC_CODI = 'N337' AND LEN(dpr.numero) = 12) THEN '821' ELSE '785' END) AS "CodDocumento", 
									RIGHT(dpr.numero, 12) AS "NumeroDeclSumaria", 
									(CONVERT(varchar(10), ISNULL(dar.dataVoo, @DataAtual), 127) + 'Z') AS "DataApresentacao"
								FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) 
									INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
								WHERE dpr.id_declaracaoDAR = dar.id
								FOR XML PATH('DeclaracaoSumaria'), TYPE)
							FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK)
							WHERE id_declaracaoDAR = dar.id
							GROUP BY id_declaracaoDAR
							FOR XML PATH('DeclaracoesSumaria'), TYPE), 
							(SELECT TOP 1
								(SELECT t.DOC_CODI AS "CodDocumento",
									SUBSTRING(t.numero, 1, 35) AS "NumeroDocumento"						
								FROM 
									(SELECT 0 AS tabela, ddo.id, ddo.numero, doc.DOC_CODI 
									FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) 
										INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
									WHERE ddo.id_declaracaoDAR = dar.id AND adi.numeroAdicao = 1
									UNION ALL
									SELECT 1 AS tabela, ado.id, ado.numero, doc.DOC_CODI 
									FROM tb_DeclaracoesDARAdicoesDocumentos AS ado WITH(NOLOCK) 
										INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.id_documento = doc.DOC_IDTY
									WHERE ado.id_adicao = adi.id AND ado.origem <> 1 						
									) AS t
								ORDER BY t.tabela, t.id
								FOR XML PATH('Documento'), TYPE)
							FROM 
								(SELECT 0 AS tabela, ddo.id, ddo.numero, doc.DOC_CODI 
								FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) 
									INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
								WHERE ddo.id_declaracaoDAR = dar.id AND adi.numeroAdicao = 1
								UNION ALL
								SELECT 1 AS tabela, ado.id, ado.numero, doc.DOC_CODI 
								FROM tb_DeclaracoesDARAdicoesDocumentos AS ado WITH(NOLOCK) 
									INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.id_documento = doc.DOC_IDTY
								WHERE ado.id_adicao = adi.id AND ado.origem <> 1 						
								) AS t
							FOR XML PATH('Documentos'), TYPE)
						FROM tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) 
							INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON adi.id_artigo = art.APA_IDTY
							LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON adi.id_paisOrigem = por.PAI_IDTY
						WHERE adi.id_declaracaoDAR = dar.id
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE),
					(SELECT			
						(SELECT pai.PAI_CODI AS "CodPais",
							NULLIF(SUBSTRING(RTRIM(LTRIM(dma.descricao)), 1, 104), '') AS "Descricao",	
							dma.valor AS "Valor", 						
							NULLIF(RTRIM(LTRIM(pmo.PAI_PREF)), '') AS "Moeda",							
							dma.totalFatura AS "TotalFatura",
							RTRIM(LTRIM(dma.documentoTransporte)) AS "NumeroCPA", 
							dma.massaBruta AS "Peso",
							dma.tipoManifesto AS "Tipo"
						FROM tb_DeclaracoesDARManifestos AS dma WITH(NOLOCK) 
							LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dma.id_pais = pai.PAI_IDTY
							LEFT OUTER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dma.id_paisMoeda = pmo.PAI_IDTY
						WHERE dma.id_declaracaoDAR = dar.id AND ISNULL(RTRIM(LTRIM(dma.documentoTransporte)), '') <> ''
						FOR XML PATH('DadosManifesto'), TYPE)
					FROM tb_DeclaracoesDARManifestos WITH(NOLOCK)
					WHERE id_declaracaoDAR = dar.id AND ISNULL(RTRIM(LTRIM(documentoTransporte)), '') <> ''
					GROUP BY id_declaracaoDAR
					FOR XML PATH('Manifestos'), TYPE),
					(SELECT			
						(SELECT ISNULL(CAST(sti.SIN_CODI AS varchar(8)), csc.COS_CODE) AS "CodStatusIncidencia", 
							(CONVERT(varchar(23), din.dataInicio, 127) + 'Z') AS "DataInicio", 
							(CONVERT(varchar(23), din.dataFim, 127) + 'Z') AS "DataFim", 
							NULLIF(din.observacoes, '') AS "Observacoes", 
							NULLIF(din.releaseHold, '') AS "TipoIncidencia"
						FROM tb_DeclaracoesDARIncidencias AS din WITH(NOLOCK) 
							LEFT OUTER JOIN TAB_SINC AS sti WITH(NOLOCK) ON din.id_statusIncidencia = sti.SIN_IDTY
							LEFT OUTER JOIN TAB_COSM AS csc WITH(NOLOCK) ON din.id_statusIncidencia = csc.COS_IDTY
						WHERE din.id_declaracaoDAR = dar.id
						FOR XML PATH('DadosIncidencia'), TYPE)
					FROM tb_DeclaracoesDARIncidencias WITH(NOLOCK) 
					WHERE id_declaracaoDAR = dar.id
					GROUP BY id_declaracaoDAR
					FOR XML PATH('Incidencias'), TYPE)
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
					INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON dar.id_fornecedor = frn.FOR_IDTY
					INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
					INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dar.id_declarante = dcl.DEC_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pfr WITH(NOLOCK) ON dar.id_paisFornecedor = pfr.PAI_IDTY
					INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
					LEFT OUTER JOIN TAB_ALFA AS ame WITH(NOLOCK) ON dar.id_estanciaMercadorias = ame.ALF_IDTY
					LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dar.id_localAutorizado = lme.LME_IDTY
					INNER JOIN TAB_PAIS AS pmt WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmt.PAI_IDTY
					INNER JOIN TAB_PAIS AS pct WITH(NOLOCK) ON dar.id_paisMoedaCustosTransporte = pct.PAI_IDTY
					INNER JOIN TAB_NDES AS ndu WITH(NOLOCK) ON nat.NDE_CODI2 = ndu.NDE_CODI
					LEFT OUTER JOIN GIDWIN.dbo.FAP_UTIL AS uno WITH(NOLOCK) ON dar.id_utilizadorNomeado = uno.UTI_IDTY
					LEFT OUTER JOIN TAB_CENT AS cen WITH(NOLOCK) ON dar.id_condicaoEntrega = cen.CEN_IDTY
					LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dar.id_meioTransporte = mtr.MTR_IDTY
				WHERE dar.id = @Id
				FOR XML PATH('Declaracao'), TYPE)
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)
-- processa a geração da declaração DUI2
		SET @Erro = ''
		EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @XMLDeclaracaoDUI2, @Utilizador, @Erro OUTPUT		
-- senão houver erros na geração, efetua processamentos finais
		IF @NumErro = 0
		BEGIN
-- obtem o id da declaração DUI2 gerada
			SELECT @IdDeclaracaoDUI2 = DUC_IDTY
			FROM PRO_DUCG WITH(NOLOCK)
			WHERE DUC_EANO = YEAR(@DataAtual) AND DUC_CPRT = (SELECT SUBSTRING(documentoTransporte, 1, 18) FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE id = @Id)
-- remove a declaração DAR se for possível; caso contrário coloca a declaração DAR no status de "Anulado"
			BEGIN TRY
				DELETE FROM tb_DeclaracoesDAR 
				WHERE id = @Id
			END TRY
			BEGIN CATCH
				UPDATE tb_DeclaracoesDAR SET documentoTransporte = (documentoTransporte + '_ANULADO'), status = 4 --Anulado
				WHERE id = @Id
			END CATCH
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ConverteRegistoParaDUI2] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ConverteRegistoParaDUI2] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ConverteRegistoParaIMPCAU]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ConverteRegistoParaIMPCAU] @Id int, @IdUtilizador int, @IdDeclaracaoIMPCAU int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracaoIMPCAU xml(XMLSC_DeclaracoesIMPCAUToGIDWin), @AnoDeclaracaoIMPCAU int, @NumDeclaracaoIMPCAU int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração da declaração	IMP-CAU
	BEGIN TRY	
		SET @NumErro = 0
-- constroi XML para declaração IMP-CAU a partir da declaração DAR
		SET @XMLDeclaracaoIMPCAU = 
			(SELECT
				(SELECT 'I' AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
					CAST(0 AS bit) AS "despachoCentralizado", 
					(CASE alf.ALF_CODI WHEN 'PT000236' THEN 'H6' ELSE 'H1' END) AS "anexoB", 
					nat.NDE_CODI2 AS "natureza", 
					SUBSTRING(dar.documentoTransporte, 1, 18) AS "documentoTransporte",
					(SELECT 
						(SELECT 							
							NULLIF(RTRIM(LTRIM(frn.FOR_NIF)), '') AS "nif", 
							NULLIF(RTRIM(LTRIM(dar.nomeFornecedor)), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(dar.moradaFornecedor)), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(dar.localidadeFornecedor)), '') AS "localidade", 
							NULLIF(SUBSTRING(RTRIM(LTRIM(dar.codPostalFornecedor)), 1, 12), '') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(dar.locPostalFornecedor)), '') AS "localidadePostal", 
							pfr.PAI_CODI AS "pais"
						HAVING ISNULL(RTRIM(LTRIM(dar.nomeFornecedor)), '') <> ''
						FOR XML PATH('exportador'), TYPE), 
						(CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE pfr.PAI_CODI END) AS "paisExpedicao", 
						(SELECT 
							ISNULL(NULLIF(RTRIM(LTRIM(dar.nifCliente)), ''), '999999990') AS "nif", 
							(CASE cli.CLI_TNIF WHEN 2 THEN 1 ELSE cli.CLI_TNIF END) AS "tipoNIF", 
							RTRIM(LTRIM(dar.nomeCliente)) AS "nome", 
							RTRIM(LTRIM(dar.moradaCliente)) AS "morada", 
							RTRIM(LTRIM(dar.localidadeCliente)) AS "localidade", 
							SUBSTRING(RTRIM(LTRIM(dar.codPostalCliente)), 1, 12) AS "codigoPostal", 
							RTRIM(LTRIM(dar.locPostalCliente)) AS "localidadePostal", 
							pcl.PAI_CODI AS "pais",
							NULLIF(SUBSTRING(RTRIM(LTRIM(dar.telefoneCliente)), 1, 14), '') AS "telefone", 
							NULLIF(RTRIM(LTRIM(dar.emailCliente)), '') AS "email"
						FOR XML PATH('importador'), TYPE),
						pcl.PAI_CODI AS "paisDestino",
						(SELECT
							dcl.DEC_CODI AS "codigoDeclarante"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE),
					NULLIF(RTRIM(LTRIM(dar.numeroVossaReferencia)), '') AS "vossaReferencia", 
					alf.ALF_CODI AS "estancia", 
					(SELECT tdi.TDE_CODI FROM tb_ConfiguracoesDAR AS cfg WITH(NOLOCK) INNER JOIN TAB_TDEC AS tdi WITH(NOLOCK) ON cfg.id_tipoDeclaracaoIM = tdi.TDE_IDTY) AS "tipoDeclaracao", 
					(CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE '11' END) AS "naturezaTransacao", 
					ISNULL(cen.CEN_CODI, (CASE dar.totalCustosTransporte WHEN 0 THEN 'CPT' ELSE 'FCA' END)) AS "condicaoEntrega", 
					(SELECT
						ISNULL((SELECT (CASE WHEN CEN_LOCT IS NULL THEN NULL ELSE (CASE CEN_LOCD WHEN 0 THEN NULLIF(SUBSTRING(dar.localidadeFornecedor, 1, 30), '') ELSE SUBSTRING(dar.localidadeCliente, 1, 30) END) END) FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = ISNULL(cen.CEN_CODI, (CASE dar.totalCustosTransporte WHEN 0 THEN 'CPT' ELSE 'FCA' END))), '*****N/A*****') AS "localidadeCE", 
						ISNULL((SELECT (CASE WHEN CEN_LOCT IS NULL THEN NULL ELSE (CASE CEN_LOCD WHEN 0 THEN pfr.PAI_CODI ELSE pcl.PAI_CODI END) END) FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = ISNULL(cen.CEN_CODI, (CASE dar.totalCustosTransporte WHEN 0 THEN 'CPT' ELSE 'FCA' END))), '--') AS "paisCE" 
					HAVING ISNULL((CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE alf.ALF_CODI END), '') <> ''
					FOR XML PATH('localizacao'), TYPE), 
					(SELECT 
						(SELECT
							pmt.PAI_CODI AS "pais", 	
							CAST(dar.totalMontante AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							pct.PAI_CODI AS "pais", 							
							CAST(dar.totalCustosTransporte AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							0 AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT
							CAST(ROUND((dar.totalMassaBruta * 95 / 100), 3) AS decimal(18, 6)) AS "massaLiquida", 							
							CAST(dar.totalMassaBruta AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT	
						NULLIF(SUBSTRING(RTRIM(LTRIM(dar.numeroNRUR)), 1, 30), '') AS "numeroNRUR", 
						(SELECT 
							ISNULL(mtr.MTR_CODI, '40') AS "meioTransporte", 
							(SELECT pai.PAI_CODI FROM tb_ConfiguracoesDAR AS cfg WITH(NOLOCK) INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON cfg.id_paisMeioTransporte = pai.PAI_IDTY) AS "pais"
						HAVING ISNULL((CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE alf.ALF_CODI END), '') <> ''						
						FOR XML PATH('fronteira'), TYPE), 
						ISNULL(mtr.MTR_CODI, (CASE alf.ALF_CODI WHEN 'PT000236' THEN '50' ELSE '40' END)) AS "meioTransporteChegada", 
						(CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE (SELECT NULLIF(RTRIM(LTRIM(identificacaoMeioTransporte)), '') FROM tb_ConfiguracoesDAR WITH(NOLOCK)) END) AS "identificacao", 
						0 AS "contentorizada"
					FOR XML PATH('transporte'), TYPE), 
					(SELECT
						dar.localizacaoMercadorias AS "tipoLocalizacao", 
						dar.qualificador AS "qualificador", 
						lme.LME_CODI AS "armazemDTP", 
						ame.ALF_CODI AS "estancia"
					HAVING ISNULL((CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE alf.ALF_CODI END), '') <> ''
					FOR XML PATH('localizacaoMercadorias'), TYPE), 				
					(SELECT 
						NULLIF(RTRIM(LTRIM(dar.locIDFEDEX)), '') AS "locID", 
						NULLIF(RTRIM(LTRIM(dar.gatewayFEDEX)), '') AS "gateway", 	
						dar.nivelServico AS "serviceLevel", 
						NULLIF(RTRIM(LTRIM(dar.portesAccFEDEX)), '') AS "portesAcc", 
						NULLIF(RTRIM(LTRIM(dar.portesFEDEX)), '') AS "portes", 
						NULLIF(RTRIM(LTRIM(dar.despachoAccFEDEX)), '') AS "despachoAcc", 								
						CAST(NULLIF(dar.freteOriginal, 0) AS decimal(18, 2)) AS "freteOriginal", 
						NULLIF(RTRIM(LTRIM(dar.moedaFreteOriginal)), '') AS "moedafreteOriginal", 
						CAST(dar.despesasDHL AS decimal(18, 3)) AS "despesas", 
						NULLIF(RTRIM(LTRIM(dar.condicaoEntregaUPS)), '') AS "condEntrega", 
						NULLIF(RTRIM(LTRIM(dar.nomeFicheiroUPS)), '') AS "nomeFicheiro"					
					FOR XML PATH('dadosEspecificos'), TYPE), 					
 					(SELECT 
						dar.numeroPDDT AS "numeroPDDT", 
						(CONVERT(varchar(10), dar.dataEntradaDT, 127) + 'Z') AS "dataEntrada", 
						dar.numeroPDDTDEV AS "numeroPDDTDEV", 
						dar.numeroTD AS "numeroTD", 
						dar.numeroACTM AS "numeroACTM", 
						dar.numeroSequencia AS "numeroSequencia", 
						NULLIF(SUBSTRING(RTRIM(LTRIM(dar.posicaoArmazem)), 1, 4), '') AS "posicaoArmazem"
					 FOR XML PATH('depositoTemporario'), TYPE), 	
					 (SELECT 
						NULLIF(RTRIM(LTRIM(dar.miniCPA)), '') AS "miniCPA", 	
						(CONVERT(varchar(10), dar.dataVoo, 127) + 'Z') AS "dataVoo", 
						NULLIF(RTRIM(LTRIM(dar.aeroportoOrigem)), '') AS "aeroportoOrigem", 
						NULLIF(RTRIM(LTRIM(dar.numeroVoo)), '') AS "numeroVoo", 
						NULLIF(RTRIM(LTRIM(dar.posicaoAviao)), '') AS "posicaoAviao", 
						NULLIF(RTRIM(LTRIM(dar.tracking)), '') AS "tracking", 
						NULLIF(RTRIM(LTRIM(dar.tipoCarga)), '') AS "tipoCarga"
					FOR XML PATH('dadosAWB'), TYPE), 
					(SELECT 
						NULLIF(RTRIM(LTRIM(dar.numeroContaExpedidor)), '') AS "numeroContaExpedidor", 
						NULLIF(RTRIM(LTRIM(dar.numeroContaDestinatario)), '') AS "numeroContaDestinatario", 
						NULLIF(RTRIM(LTRIM(dar.nomeOriginalDestinatario)), '') AS "nomeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dar.moradaOriginalDestinatario)), '') AS "moradaOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dar.localidadeOriginalDestinatario)), '') AS "localidadeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dar.codPostalOriginalDestinatario)), '') AS "codigoPostalOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dar.locPostalOriginalDestinatario)), '') AS "localidadePostalOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dar.referenciaExterna1)), '') AS "referenciaExterna1", 
						NULLIF(RTRIM(LTRIM(dar.referenciaExterna2)), '') AS "referenciaExterna2", 
						NULLIF(RTRIM(LTRIM(dar.shipID)), '') AS "shipID"
					FOR XML PATH('dadosEntidades'), TYPE), 
					(SELECT
						NULLIF(RTRIM(LTRIM(dar.dutyType)), '') AS "dutyType", 
						dar.payment AS "payment", 
						(CONVERT(varchar(10), dar.dataDocumentoTransporte, 127) + 'Z') AS "dataDocumentoTransporte", 
						NULLIF(RTRIM(LTRIM(dar.numeroRequerimento)), '') AS "numeroRequerimento", 
						NULLIF(RTRIM(LTRIM(dar.numeroDURetorno)), '') AS "numeroDURetorno", 
						NULLIF(RTRIM(LTRIM(dar.numeroT1Retorno)), '') AS "numeroT1Retorno"
					FOR XML PATH('outrosDados'), TYPE), 
					(SELECT
						ISNULL(ndu.FUP_CODI, fup.FUP_CODI) AS "codigoFollowUp", 
						uno.UTI_UTIL AS "utilizadorNomeado"
					HAVING ISNULL(ndu.FUP_CODI, fup.FUP_CODI) IS NOT NULL
					FOR XML PATH('followUp'), TYPE), 										
					(SELECT TOP 1
						(SELECT 
							ddo.tipo AS "tipoDocumento", 
							doc.DOC_CODI AS "codigoDocumento",
							ddo.numero AS "numeroDocumento"
						FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) 
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY							
						WHERE ddo.id_declaracaoDAR = dar.id AND ddo.origem IN (0, 4) -- 0: Manual; 4: Importação XML
						FOR XML PATH('documento'), TYPE)
					FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) 
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY							
					WHERE ddo.id_declaracaoDAR = dar.id AND ddo.origem IN (0, 4) -- 0: Manual; 4: Importação XML
					GROUP BY ddo.id_declaracaoDAR
					FOR XML PATH('documentosECertificados'), TYPE),
					(SELECT TOP 1
						(SELECT 							
							doc.DOC_CODI AS "codigoDocumento",
							dpr.numero AS "numeroDocumento"
						FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) 
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY							
						WHERE dpr.id_declaracaoDAR = dar.id AND doc.DOC_CA40 = 1
						FOR XML PATH('documentoPrecedente'), TYPE)
					FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) 
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY							
					WHERE dpr.id_declaracaoDAR = dar.id AND doc.DOC_CA40 = 1
					GROUP BY dpr.id_declaracaoDAR
					FOR XML PATH('documentosPrecedentes'), TYPE),					
					(SELECT
						(SELECT 
							adi.numeroAdicao AS "numeroAdicao", 
							art.APA_CPAU AS "codigoPautal", 							
							SUBSTRING(RTRIM(LTRIM(adi.designacao)), 1, 150) AS "designacao", 	
							adi.regimeAdicional AS "regimeAdicional", 							
							por.PAI_CODI AS "paisOrigem",		
							(CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE 1 END) AS "metodoAvaliacao", 
							CAST(ROUND((adi.massaBruta * 95 / 100), 3) AS decimal(18, 6)) AS "massaLiquida", 					
							CAST(adi.massaBruta AS decimal(18, 6)) AS "massaBruta",	
							CAST((CASE alf.ALF_CODI WHEN 'PT000236' THEN 0 ELSE adi.unidades END) AS decimal(18, 6)) AS "unidades", 																				
							CAST(adi.montante AS decimal(18, 3)) AS "montanteAd", 																																				
							CAST(adi.custosTransporte AS decimal(18, 3)) AS "valorFrete", 							
							(SELECT TOP 1
								(SELECT 
									(CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE 'CT' END) AS "unidadeMedida", 
									dar.totalVolumes AS "volumes", 
									(CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE 'S/M' END) AS "marcas", 	
									NULLIF(RTRIM(LTRIM(adi.numeroObjetoCTT)), '') AS "numeroObjeto", 
									NULLIF(RTRIM(LTRIM(adi.codigoBarrasCTT)), '') AS "codigoBarras", 								
									(CASE WHEN dar.totalAdicoes > 1 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "parte"																		
								FOR XML PATH('marcaEVolume'), TYPE)	
							HAVING adi.numeroAdicao = 1
							FOR XML PATH('marcasEVolumes'), TYPE) 							
						FROM tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) 
							INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON adi.id_artigo = art.APA_IDTY
							LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON adi.id_paisOrigem = por.PAI_IDTY
						WHERE adi.id_declaracaoDAR = dar.id
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE),
					(SELECT	TOP 1
						(SELECT 
							ISNULL(CAST(sti.SIN_CODI AS varchar(8)), csc.COS_CODE) AS "codigoIncidencia", 
							(CONVERT(varchar(23), din.dataInicio, 127) + 'Z') AS "dataInicio", 
							(CONVERT(varchar(23), din.dataFim, 127) + 'Z') AS "dataFim", 
							NULLIF(din.observacoes, '') AS "observacoes", 
							NULLIF(din.releaseHold, '') AS "tipoIncidencia"
						FROM tb_DeclaracoesDARIncidencias AS din WITH(NOLOCK) 
							LEFT OUTER JOIN TAB_SINC AS sti WITH(NOLOCK) ON din.id_statusIncidencia = sti.SIN_IDTY
							LEFT OUTER JOIN TAB_COSM AS csc WITH(NOLOCK) ON din.id_statusIncidencia = csc.COS_IDTY
						WHERE din.id_declaracaoDAR = dar.id
						FOR XML PATH('incidencia'), TYPE)
					FROM tb_DeclaracoesDARIncidencias WITH(NOLOCK) 
					WHERE id_declaracaoDAR = dar.id
					GROUP BY id_declaracaoDAR
					FOR XML PATH('incidencias'), TYPE), 
					(SELECT	TOP 1
						(SELECT 
							fup.FUP_CODI AS "codigoFollowUp", 
							uti.UTI_UTIL AS "utilizador", 
							(CONVERT(varchar(23), dfu.dataFollowUp, 127) + 'Z') AS "dataHora"
						FROM tb_DeclaracoesDARFollowUps AS dfu WITH(NOLOCK) 
							INNER JOIN GIDWIN.dbo.FAP_FWUP AS fup WITH(NOLOCK) ON dfu.id_followUp = fup.FUP_IDTY
							INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON dfu.id_utilizadorFollowUp = uti.UTI_IDTY							
						WHERE dfu.id_declaracaoDAR = dar.id
						FOR XML PATH('followUpData'), TYPE)
					FROM tb_DeclaracoesDARFollowUps AS dfu WITH(NOLOCK) 
						INNER JOIN GIDWIN.dbo.FAP_FWUP AS fup WITH(NOLOCK) ON dfu.id_followUp = fup.FUP_IDTY
						INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON dfu.id_utilizadorFollowUp = uti.UTI_IDTY
					WHERE dfu.id_declaracaoDAR = dar.id
					GROUP BY dfu.id_declaracaoDAR
					FOR XML PATH('followUps'), TYPE), 
					(SELECT	TOP 1
						(SELECT 
							dco.descricao AS "descricaoContacto", 
							uti.UTI_UTIL AS "utilizador", 
							(CONVERT(varchar(23), dco.dataContacto, 127) + 'Z') AS "dataHora"
						FROM tb_DeclaracoesDARContactos AS dco WITH(NOLOCK) 						
							INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON dco.id_utilizadorContacto = uti.UTI_IDTY
						WHERE dco.id_declaracaoDAR = dar.id
						FOR XML PATH('contacto'), TYPE)
					FROM tb_DeclaracoesDARContactos AS dco WITH(NOLOCK) 						
						INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON dco.id_utilizadorContacto = uti.UTI_IDTY
					WHERE dco.id_declaracaoDAR = dar.id
					GROUP BY dco.id_declaracaoDAR
					FOR XML PATH('contactos'), TYPE), 
					(SELECT	TOP 1
						(SELECT 
							dma.tipoManifesto AS "tipoManifesto", 
							pai.PAI_CODI AS "paisManifesto",
							NULLIF(SUBSTRING(RTRIM(LTRIM(dma.descricao)), 1, 104), '') AS "descricao",	
							dma.valor AS "valor", 						
							pmo.PAI_CODI AS "paisMoeda",							
							dma.totalFatura AS "totalFatura",
							RTRIM(LTRIM(dma.documentoTransporte)) AS "numeroCPA", 
							dma.massaBruta AS "pesoBruto"
						FROM tb_DeclaracoesDARManifestos AS dma WITH(NOLOCK) 
							LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dma.id_pais = pai.PAI_IDTY
							LEFT OUTER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dma.id_paisMoeda = pmo.PAI_IDTY
						WHERE dma.id_declaracaoDAR = dar.id AND ISNULL(RTRIM(LTRIM(dma.documentoTransporte)), '') <> ''
						FOR XML PATH('manifesto'), TYPE)
					FROM tb_DeclaracoesDARManifestos WITH(NOLOCK)
					WHERE id_declaracaoDAR = dar.id AND ISNULL(RTRIM(LTRIM(documentoTransporte)), '') <> ''
					GROUP BY id_declaracaoDAR
					FOR XML PATH('manifestos'), TYPE)					
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
					INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON dar.id_fornecedor = frn.FOR_IDTY
					INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
					INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dar.id_declarante = dcl.DEC_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pfr WITH(NOLOCK) ON dar.id_paisFornecedor = pfr.PAI_IDTY
					INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
					LEFT OUTER JOIN TAB_ALFA AS ame WITH(NOLOCK) ON dar.id_estanciaMercadorias = ame.ALF_IDTY
					LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dar.id_localAutorizado = lme.LME_IDTY
					INNER JOIN TAB_PAIS AS pmt WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmt.PAI_IDTY
					INNER JOIN TAB_PAIS AS pct WITH(NOLOCK) ON dar.id_paisMoedaCustosTransporte = pct.PAI_IDTY
					INNER JOIN TAB_NDES AS ndu WITH(NOLOCK) ON nat.NDE_CODI2 = ndu.NDE_CODI
					LEFT OUTER JOIN GIDWIN.dbo.FAP_FWUP AS fup WITH(NOLOCK) ON dar.id_followUp = fup.FUP_IDTY
					LEFT OUTER JOIN GIDWIN.dbo.FAP_UTIL AS uno WITH(NOLOCK) ON dar.id_utilizadorNomeado = uno.UTI_IDTY
					LEFT OUTER JOIN TAB_CENT AS cen WITH(NOLOCK) ON dar.id_condicaoEntrega = cen.CEN_IDTY
					LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dar.id_meioTransporte = mtr.MTR_IDTY
				WHERE dar.id = @Id
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da declaração IMP-CAU
		SET @Erro = ''
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracaoIMPCAU, @IdUtilizador, @Erro OUTPUT		
-- senão houver erros na geração, efetua processamentos finais
		IF @NumErro = 0
		BEGIN
			SET @AnoDeclaracaoIMPCAU = NULL
			SET @NumDeclaracaoIMPCAU = NULL
			SET @IdDeclaracaoIMPCAU = NULL
-- obtem o id da declaração IMP-CAU gerada
			SELECT @AnoDeclaracaoIMPCAU = DUC_EANO, @NumDeclaracaoIMPCAU = DUC_PNUM, @IdDeclaracaoIMPCAU = DUC_IDTY
			FROM PRO_DUCG WITH(NOLOCK)
			WHERE DUC_EANO = YEAR(@DataAtual) AND DUC_CPRT = (SELECT SUBSTRING(documentoTransporte, 1, 18) FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE id = @Id)
-- verifica se a declaração IMP-CAU foi corretamente gerada
			IF @IdDeclaracaoIMPCAU IS NULL
				RAISERROR('Declaração IMP-CAU não foi gerada.', 16, 1)
-- atualiza o número dos documento automáticos de origem da alfândega
			UPDATE tb_IMP_DeclaracoesDocumentos SET numero = ddd.numero
			FROM tb_IMP_DeclaracoesDocumentos AS did WITH(NOLOCK) 				
				INNER JOIN tb_DeclaracoesDARDocumentos AS ddd WITH(NOLOCK) ON ddd.id_declaracaoDAR = @Id AND ddd.origem = 1 AND did.id_documento = ddd.id_documento
			WHERE did.id_declaracaoIMP = @IdDeclaracaoIMPCAU AND did.origem = 6 AND ISNULL(did.numero, '') <> ddd.numero			
-- remove o primeiro registo de follow-up criado pelo automatismo existente nos dados gerais das declarações IMP-CAU p/ evitar duplicação
			DELETE FROM PRO_DUFW
			WHERE DUC_EANO = @AnoDeclaracaoIMPCAU AND DUC_PNUM = @NumDeclaracaoIMPCAU AND DFW_CODI = (SELECT MIN(DFW_CODI) 
																									FROM PRO_DUFW WITH(NOLOCK) 
																									WHERE DUC_EANO = @AnoDeclaracaoIMPCAU AND DUC_PNUM = @NumDeclaracaoIMPCAU)
-- remove a declaração DAR se for possível; caso contrário coloca a declaração DAR no status de "Anulado"
			BEGIN TRY
				DELETE FROM tb_DeclaracoesDAR 
				WHERE id = @Id
			END TRY
			BEGIN CATCH
				UPDATE tb_DeclaracoesDAR SET documentoTransporte = (documentoTransporte + '_ANULADO'), status = 4 --Anulado
				WHERE id = @Id
			END CATCH
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ConverteRegistoParaIMPCAU] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ConverteRegistoParaIMPCAU] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_DescodificaTexto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_DescodificaTexto] @Id int, @Texto varchar(MAX) OUTPUT AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @SQLAExecutar nvarchar(MAX), @LstVarSQL nvarchar(1000), @Valor varchar(MAX), @IdxInicio int, @IdxFim int, @NomeCampo varchar(100), @NomeCampoComLimitadores varchar(100)
-- verifica a existência de limitadores para proceder à respetiva substituição
	IF (CHARINDEX('[<', @Texto) > 0) AND (CHARINDEX('>]', @Texto) > 0)
	BEGIN
-- obtem posições dos limitadores
		SET @IdxInicio = CHARINDEX('[<', @Texto) + 2
		SET @IdxFim = CHARINDEX('>]', @Texto)
-- obtem campo através da sua extração dos limitadores	
		SET @NomeCampo = SUBSTRING(@Texto, @IdxInicio, (@IdxFim - @IdxInicio))
		SET @NomeCampoComLimitadores = '[<' + @NomeCampo + '>]'
-- obtem valor do campo (se coluna existir na tabela)
		IF EXISTS(SELECT object_id FROM sys.columns WHERE name = @NomeCampo AND object_id = Object_ID(N'tb_DeclaracoesDAR'))
		BEGIN
			SET @LstVarSQL = N'@OUTValor varchar(MAX) OUTPUT, @INId int'
			SET @SQLAExecutar = N'SELECT @OUTVALOR = (CASE WHEN ISDATE(' + @NomeCampo + ') = 1 THEN CONVERT(varchar(10), ' + @NomeCampo + ', 105) ELSE CAST(' + @NomeCampo + ' AS varchar(MAX)) END) FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE id = @INId'
			EXEC sp_executesql @SQLAExecutar, @LstVarSQL, @OUTValor = @Valor OUTPUT, @INId = @Id	
		END
		ELSE
			SET @Valor = '????????'
-- substitui a variável ao campo pelo respetivo valor		
		SET @Texto = REPLACE(@Texto, @NomeCampoComLimitadores, @Valor)
-- verifica se ainda existe variaveis a substituir no texto
		EXEC sp_DeclaracoesDAR_DescodificaTexto @Id, @Texto OUTPUT
	END
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_DescodificaTexto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_DescodificaTexto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_DuplicaRegisto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_DuplicaRegisto] @Id int, @NovoNumero int, @IdUtilizador int, @NovoId int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @Ano smallint, @TaxaIVANormal decimal(8, 2), @Numero int, @IdAdicao bigint, @NovoIdAdicao bigint
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- obtem dados da declaração de origem
	SELECT @Ano = ano
	FROM tb_DeclaracoesDAR WITH(NOLOCK)
	WHERE id = @Id
-- calcula o ano da nova declaração
	IF (@Ano < YEAR(@DataAtual)) AND (EXISTS(SELECT EMP_CODI FROM GIDWIN.dbo.FAP_EANO WITH(NOLOCK) WHERE EMP_CODI = DB_NAME() and EAN_ANO = YEAR(@DataAtual)))		
		SET @Ano = YEAR(@DataAtual)
-- inicia transacção para inserção dados da declaração
	BEGIN TRANSACTION	
	BEGIN TRY	
		SET @NumErro = 0
-- ontem a taxa IVA normal configurada
		SELECT @TaxaIVANormal = PAP_TXNR
		FROM TAB_PAPL WITH(NOLOCK)
-- obtem o número para a nova declaração
		SELECT @Numero = (CASE proximoNumero WHEN 0 THEN ISNULL(@NovoNumero, 0) ELSE proximoNumero END)
		FROM tb_ConfiguracoesDARNumeradores
		WHERE ano = @Ano
-- verifica se o número é válido
		IF @Numero = 0
			RAISERROR('Número da declaração não foi especificado.', 16, 1)			
-- insere nova declaração
		ALTER TABLE tb_DeclaracoesDAR DISABLE TRIGGER tr_DeclaracoesDAR_Regras_IU
		INSERT INTO tb_DeclaracoesDAR(ano, numero, data, numeroReferenciaLocal, documentoTransporte, dataVoo, id_natureza, regimeIVA, regimeAdicional, tipoDeclaracao, 
			numeroNRUR, numeroVossaReferencia, id_estancia, totalAdicoes, totalVolumes, totalMassaBruta, id_fornecedor, nomeFornecedor, id_paisFornecedor, moradaFornecedor, 
			localidadeFornecedor, codPostalFornecedor, locPostalFornecedor, id_cliente, nomeCliente, id_paisCliente, nifCliente, moradaCliente, localidadeCliente, 
			codPostalCliente, locPostalCliente, tipoContaCliente, id_declarante, nomeDeclarante, id_paisDeclarante, nifDeclarante, moradaDeclarante, localidadeDeclarante, 
			codPostalDeclarante, locPostalDeclarante, estatutoDeclarante, nifRepresentante, caucao, funcaoRegimeIOSS, numeroIdentificacaoIVA, id_paisMoedaCustosTransporte, 
			cambioCustosTransporte, totalCustosTransporte, localizacaoMercadorias, qualificador, id_estanciaMercadorias, id_localAutorizado, id_paisMoedaMontante, 
			cambioMontante, totalMontante, totalMontanteEUR, totalIVA, numeroRequerimento, numeroDURetorno, numeroT1Retorno, payment, miniCPA, tipoCarga, dutyType, 
			numeroContaExpedidor, numeroContaDestinatario, nomeOriginalDestinatario, moradaOriginalDestinatario, localidadeOriginalDestinatario, codPostalOriginalDestinatario, 
			locPostalOriginalDestinatario, aeroportoOrigem, numeroVoo, referenciaExterna1, referenciaExterna2, shipID, tracking, posicaoAviao, nivelServico, condicaoEntregaUPS, 
			freteOriginal, moedaFreteOriginal, gatewayFEDEX, locIDFEDEX, portesAccFEDEX, portesFEDEX, despachoAccFEDEX, despesasDHL, origem, id_declaracaoDAR, 
			id_utilizadorControlo, dataControlo, id_tipoDocumentoConta, taxaIVAMaxima, beneficiarioIVACliente, tipoCaucao, posicaoArmazem, id_condicaoEntrega, 
			id_meioTransporte, totalOptativas)	
		OUTPUT inserted.id INTO @TblID
		SELECT @Ano, @Numero, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), 
			(SUBSTRING(STR(@Ano, 4), 3, 2) + 'PT' + REPLICATE('0', 9 - LEN(dar.nifDeclarante)) + dar.nifDeclarante + REPLICATE('0', 9 - LEN(LTRIM(STR(@Numero, 9)))) + LTRIM(STR(@Numero, 9))), 
			dar.documentoTransporte, (CASE WHEN dar.dataVoo IS NULL THEN NULL ELSE CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime) END), 
			dar.id_natureza, dar.regimeIVA, dar.regimeAdicional, dar.tipoDeclaracao, 
			dar.numeroNRUR, dar.numeroVossaReferencia, dar.id_estancia, dar.totalAdicoes, dar.totalVolumes, dar.totalMassaBruta, dar.id_fornecedor, dar.nomeFornecedor, dar.id_paisFornecedor, dar.moradaFornecedor, 
			dar.localidadeFornecedor, dar.codPostalFornecedor, dar.locPostalFornecedor, dar.id_cliente, dar.nomeCliente, dar.id_paisCliente, dar.nifCliente, dar.moradaCliente, dar.localidadeCliente, 
			dar.codPostalCliente, dar.locPostalCliente, dar.tipoContaCliente, dar.id_declarante, dar.nomeDeclarante, dar.id_paisDeclarante, dar.nifDeclarante, dar.moradaDeclarante, dar.localidadeDeclarante, 
			dar.codPostalDeclarante, dar.locPostalDeclarante, dar.estatutoDeclarante, dar.nifRepresentante, 
			(CASE WHEN (dar.regimeIVA = 3) AND (cli.CLI_BIVA = 1) AND (CAST(CONVERT(varchar(10), cli.CLI_DIBI, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)) THEN NULL ELSE dar.caucao END), 
			dar.funcaoRegimeIOSS, dar.numeroIdentificacaoIVA, dar.id_paisMoedaCustosTransporte, 
			dar.cambioCustosTransporte, dar.totalCustosTransporte, dar.localizacaoMercadorias, dar.qualificador, dar.id_estanciaMercadorias, dar.id_localAutorizado, dar.id_paisMoedaMontante, 
			dar.cambioMontante, dar.totalMontante, dar.totalMontanteEUR, dar.totalIVA, dar.numeroRequerimento, dar.numeroDURetorno, dar.numeroT1Retorno, dar.payment, dar.miniCPA, dar.tipoCarga, dar.dutyType, 
			dar.numeroContaExpedidor, dar.numeroContaDestinatario, dar.nomeOriginalDestinatario, dar.moradaOriginalDestinatario, dar.localidadeOriginalDestinatario, dar.codPostalOriginalDestinatario, 
			dar.locPostalOriginalDestinatario, dar.aeroportoOrigem, dar.numeroVoo, dar.referenciaExterna1, dar.referenciaExterna2, dar.shipID, dar.tracking, dar.posicaoAviao, dar.nivelServico, dar.condicaoEntregaUPS, 
			dar.freteOriginal, dar.moedaFreteOriginal, dar.gatewayFEDEX, dar.locIDFEDEX, dar.portesAccFEDEX, dar.portesFEDEX, dar.despachoAccFEDEX, dar.despesasDHL, 1, dar.id, 
			@IdUtilizador, @DataAtual, dar.id_tipoDocumentoConta, @TaxaIVANormal, 
			(CASE WHEN (cli.CLI_BIVA = 1) AND (CAST(CONVERT(varchar(10), cli.CLI_DIBI, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)) THEN 1 ELSE 0 END), 
			(CASE WHEN (dar.regimeIVA = 3) AND (cli.CLI_BIVA = 1) AND (CAST(CONVERT(varchar(10), cli.CLI_DIBI, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)) THEN NULL ELSE dar.tipoCaucao END), 
			dar.posicaoArmazem, dar.id_condicaoEntrega, 
			dar.id_meioTransporte, dar.totalOptativas
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
		WHERE dar.id = @Id
		ALTER TABLE tb_DeclaracoesDAR ENABLE TRIGGER tr_DeclaracoesDAR_Regras_IU
-- obtem o ID da nova declaração
		SELECT @NovoId = ID 
		FROM @TblID
-- insere o detalhe de documentos na nova declaracao
		INSERT INTO tb_DeclaracoesDARDocumentos(id_declaracaoDAR, id_documento, numero, tipo, origem, id_utilizadorControlo, dataControlo)
		SELECT @NovoId, id_documento, numero, tipo, origem, @IdUtilizador, @DataAtual
		FROM tb_DeclaracoesDARDocumentos WITH(NOLOCK)
		WHERE id_declaracaoDAR = @Id
-- insere o detalhe de menções na nova declaracao
		INSERT INTO tb_DeclaracoesDARMencoes(id_declaracaoDAR, id_mencao, texto, origem, id_utilizadorControlo, dataControlo)
		SELECT @NovoId, id_mencao, texto, origem, @IdUtilizador, @DataAtual
		FROM tb_DeclaracoesDARMencoes WITH(NOLOCK)
		WHERE id_declaracaoDAR = @Id
-- insere o detalhe de precedentes na nova declaracao
		INSERT INTO tb_DeclaracoesDARPrecedentes(id_declaracaoDAR, id_documento, numero, id_utilizadorControlo, dataControlo)
		SELECT @NovoId, id_documento, numero, @IdUtilizador, @DataAtual
		FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK)
		WHERE id_declaracaoDAR = @Id
-- obtem o detalhe de adições na declaracao de origem
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT id
			FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK)
			WHERE id_declaracaoDAR = @Id
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o ID existente
			DELETE FROM @TblID
-- insere a adição na nova declaracao
			ALTER TABLE tb_DeclaracoesDARAdicoes DISABLE TRIGGER tr_DeclaracoesDARAdicoes_Atualizacoes_IU
			ALTER TABLE tb_DeclaracoesDARAdicoes DISABLE TRIGGER tr_DeclaracoesDARAdicoes_Regras_IU
			INSERT INTO tb_DeclaracoesDARAdicoes(id_declaracaoDAR, numeroAdicao, id_artigo, codigoPautal, codigoNC, codigoTARIC, adicionalTARIC1, adicionalTARIC2, 
				adicionalTARIC3, adicionalNacional1, adicionalNacional2, adicionalNacional3, designacao, numeroNRUR, metodoPagamento, id_paisOrigem, regimeAdicional, unidades, 
				massaBruta, volumes, id_paisMoedaMontante, cambioMontante, montante, montanteEUR, baseTributacaoIVA, taxaIVA, valorIVA, id_paisMoedaCustosTransporte, 
				cambioCustosTransporte, custosTransporte, custosTransporteEUR, id_fornecedor, nomeFornecedor, id_paisFornecedor, moradaFornecedor, localidadeFornecedor, 
				codPostalFornecedor, locPostalFornecedor, codigoBarrasCTT, numeroObjetoCTT, id_utilizadorControlo, dataControlo, optativas)
			OUTPUT inserted.id INTO @TblID
			SELECT @NovoId, numeroAdicao, id_artigo, codigoPautal, codigoNC, codigoTARIC, adicionalTARIC1, adicionalTARIC2, 
				adicionalTARIC3, adicionalNacional1, adicionalNacional2, adicionalNacional3, designacao, numeroNRUR, metodoPagamento, id_paisOrigem, regimeAdicional, unidades, 
				massaBruta, volumes, id_paisMoedaMontante, cambioMontante, montante, montanteEUR, baseTributacaoIVA, taxaIVA, valorIVA, id_paisMoedaCustosTransporte, 
				cambioCustosTransporte, custosTransporte, custosTransporteEUR, id_fornecedor, nomeFornecedor, id_paisFornecedor, moradaFornecedor, localidadeFornecedor, 
				codPostalFornecedor, locPostalFornecedor, codigoBarrasCTT, numeroObjetoCTT, @IdUtilizador, @DataAtual, optativas
			FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK)
			WHERE id = @IdAdicao
			ALTER TABLE tb_DeclaracoesDARAdicoes ENABLE TRIGGER tr_DeclaracoesDARAdicoes_Atualizacoes_IU
			ALTER TABLE tb_DeclaracoesDARAdicoes ENABLE TRIGGER tr_DeclaracoesDARAdicoes_Regras_IU
-- obtem o ID da nova adição
			SELECT @NovoIdAdicao = ID 
			FROM @TblID
-- insere o detalhe de documentos na nova adição
			ALTER TABLE tb_DeclaracoesDARAdicoesDocumentos DISABLE TRIGGER tr_DeclaracoesDARAdicoesDocumentos_Regras_IU
			INSERT INTO tb_DeclaracoesDARAdicoesDocumentos(id_adicao, id_documento, numero, tipo, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoIdAdicao, id_documento, numero, tipo, origem, @IdUtilizador, @DataAtual
			FROM tb_DeclaracoesDARAdicoesDocumentos WITH(NOLOCK)
			WHERE id_adicao = @IdAdicao
			ALTER TABLE tb_DeclaracoesDARAdicoesDocumentos ENABLE TRIGGER tr_DeclaracoesDARAdicoesDocumentos_Regras_IU
-- insere o detalhe de menções na nova adição
			INSERT INTO tb_DeclaracoesDARAdicoesMencoes(id_adicao, id_mencao, texto, origem, id_adicaoDocumento, id_utilizadorControlo, dataControlo)
			SELECT @NovoIdAdicao, ome.id_mencao, ome.texto, ome.origem, ddo.id, @IdUtilizador, @DataAtual
			FROM tb_DeclaracoesDARAdicoesMencoes AS ome WITH(NOLOCK) 
				LEFT OUTER JOIN tb_DeclaracoesDARAdicoesDocumentos AS odo WITH(NOLOCK) ON ome.id_adicaoDocumento = odo.id
				LEFT OUTER JOIN tb_DeclaracoesDARAdicoesDocumentos AS ddo WITH(NOLOCK) ON ddo.id_adicao = @NovoIdAdicao AND odo.id_documento = ddo.id_documento AND odo.numero = ddo.numero AND odo.tipo = ddo.tipo AND odo.origem = ddo.origem
			WHERE ome.id_adicao = @IdAdicao
-- insere o detalhe de precedentes na nova adição
			INSERT INTO tb_DeclaracoesDARAdicoesPrecedentes(id_adicao, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoIdAdicao, id_documento, numero, origem, @IdUtilizador, @DataAtual
			FROM tb_DeclaracoesDARAdicoesPrecedentes WITH(NOLOCK)
			WHERE id_adicao = @IdAdicao
			FETCH NEXT FROM Adicoes INTO @IdAdicao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- processa reset ao valor de optativas se o n.º dias free/ADT está configurado e a declaração tem "Meio Transporte" definido com total optativas atribuído
		IF EXISTS(SELECT id FROM tb_ConfiguracoesDAR WITH(NOLOCK) WHERE diasFreeADT > 0)
		BEGIN
			UPDATE tb_DeclaracoesDAR SET totalOptativas = 0
			WHERE id = @NovoId AND id_meioTransporte IS NOT NULL AND totalOptativas <> 0
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_DuplicaRegisto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_DuplicaRegisto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ExportaFicheiroDARP]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ExportaFicheiroDARP] @Id int, @FicheiroXML xml(XMLSC_DeclaracoesImpToDARP) OUTPUT, @LinhaXMLEncoding varchar(200) OUTPUT AS
BEGIN
	SET DATEFORMAT DMY
-- atribui linha de encoding (definido no schema) para depois ser incluída no ficheiro XML a gerar
	SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="UTF-8"?>'	
-- constroi XML para ficheiro DARP
	SET @FicheiroXML = 				
		(SELECT 
			(SELECT (CASE WHEN dar.status = 4 THEN 'D' WHEN dar.revisao > 0 THEN 'U' ELSE 'I' END) AS "accao", 
				uco.UTI_UTIL AS "utilizadorCriacao", 
				(SELECT 
					(SELECT NULLIF(numeroObjetoCTT, '') AS "objecto"
					FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK)
					WHERE id_declaracaoDAR = dar.id
					FOR XML PATH(''), TYPE)
				FOR XML PATH('numeroLocalObjecto'), TYPE),
				(SELECT TOP 1 id FROM tb_DeclaracoesDARArquivos WHERE id_declaracaoDAR = dar.id AND tipo IN (4, 9) ORDER BY id DESC) AS "nomePDF",
				dar.numeroReferenciaLocal AS "numeroReferenciaLocal",
				NULLIF(dar.numeroRegistoLiquidacao, '') AS "numeroRegistoLiquidacao",
				NULLIF(dar.numeroNRM, '') AS "numeroOrdem",
				(CONVERT(varchar(10), dar.dataNRM, 120) + 'Z') AS "dataNumeroOrdem", 
				(CONVERT(varchar(10), dar.dataAutorizacaoSaida, 120) + 'Z') AS "dataAutorizacaoSaida", 
				nat.NDE_CODI AS "natureza",
				dar.totalAdicoes AS "numeroTotalAdicoes", 
				dar.totalVolumes AS "numeroTotalVolumes", 				 
				CAST(ROUND(dar.totalCustosTransporte / dar.cambioCustosTransporte, 2) AS numeric(28, 2)) AS "totalDespesas", 
				CAST(0 AS numeric(28, 2)) AS "totalVDA", 				
				CAST(dar.totalIVA AS numeric(28, 2)) AS "totalRecapitulativo", 
				(SELECT pmo.PAI_CODI AS "codigoMoedaFacturacao", 
					CAST(dar.totalMontante AS numeric(28, 3)) AS "montanteTotalFacturado", 
					CAST(dar.cambioMontante AS numeric(28, 6)) AS "taxaCambio"
				FOR XML PATH('montante'), TYPE),
				(CASE dar.totalCustosTransporte WHEN 0 THEN NULL ELSE pct.PAI_CODI END) AS "frete/codigoMoedaFrete", 
				(CASE dar.totalCustosTransporte WHEN 0 THEN NULL ELSE CAST(dar.totalCustosTransporte AS numeric(28, 3)) END) AS "frete/montanteFrete", 
				(CASE dar.totalCustosTransporte WHEN 0 THEN NULL ELSE CAST(dar.cambioCustosTransporte AS numeric(28, 6)) END) AS "frete/taxaCambio", 				
				(pcl.PAI_CODI + dar.nifCliente) AS "destinatario/numeroIdentificacao"				
			FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN GIDWIN.dbo.FAP_UTIL AS uco WITH(NOLOCK) ON dar.id_utilizadorControlo = uco.UTI_IDTY
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmo.PAI_IDTY
				INNER JOIN TAB_PAIS AS pct WITH(NOLOCK) ON dar.id_paisMoedaCustosTransporte = pct.PAI_IDTY
				INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
			WHERE dar.id = @Id
			FOR XML PATH('cabecalho'), TYPE),
			(SELECT 
				(SELECT dad.numeroAdicao AS "numeroAdicao", 
					dad.codigoPautal AS "codigoMercadorias", 
					dad.designacao AS "designacaoMercadorias",
					'000' AS "preferencia", 
					por.PAI_CODI AS "codigoPaisOrigem", 
					(SELECT 'CART.POSTAL' AS "marca", 
						NULLIF(dad.numeroObjetoCTT, '') AS "numeros", 
						NULLIF(dad.codigoBarrasCTT, '') AS "Loptica", 
						'CT' AS "naturezaVolumes", 
						dad.volumes AS "quantidadeMercadoria"					
					FOR XML PATH('volume'), TYPE), 
					(SELECT 
						(SELECT 'VDA' AS "codigoMencao", 								
							CAST(0 AS numeric(28, 2)) AS "montanteVDA"						
						FOR XML PATH('mencaoEspecial'), TYPE)
					FOR XML PATH('documentosCertificados'), TYPE), 
					(SELECT 
						(SELECT (CASE dad.taxaIVA WHEN PAP_TXIS THEN RRE_CDIS WHEN PAP_TXRD THEN RRE_CDRD WHEN PAP_TXIN THEN RRE_CDIN ELSE RRE_CDNR END) AS "rubricaReceita", 								
							(SELECT RRE_NOME FROM TAB_RREC WITH(NOLOCK) WHERE RRE_CODI = (CASE dad.taxaIVA WHEN PAP_TXIS THEN RRE_CDIS WHEN PAP_TXRD THEN RRE_CDRD WHEN PAP_TXIN THEN RRE_CDIN ELSE RRE_CDNR END)) AS "descricaoRubrica", 
							'B00' AS "tipoImposicao", 
							CAST(dad.baseTributacaoIVA AS numeric(28, 3)) AS "baseTributacao",
							CAST(dad.taxaIVA AS numeric(28, 4)) AS "taxaImposicao", 
							CAST(dad.valorIVA AS numeric(28, 2)) AS "montanteImposicao"
						FROM TAB_PAPL WITH(NOLOCK)						
						FOR XML PATH('imposicoes'), TYPE)
					FOR XML PATH('liquidacaoDefinitiva'), TYPE)
				FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON dad.id_paisOrigem = por.PAI_IDTY
				WHERE id_declaracaoDAR = @Id
				FOR XML PATH('adicao'), TYPE)
			FOR XML PATH('adicoes'), TYPE)
		FOR XML PATH('DARP'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ExportaFicheiroDARP] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ExportaFicheiroDARP] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ExportaFicheiroXMLMensagens]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ExportaFicheiroXMLMensagens] @DataReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @DataAtual datetime, @DirGeracaoFicheiro nvarchar(500), @Id bigint, @EstadoOperacao varchar(3), @Numero int, @FicheiroXML xml, @PathFicheiroTmpXML nvarchar(4000)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem a diretoria p/ geração do ficheiro XML
	SELECT @DirGeracaoFicheiro = PFC_PEPA 
	FROM TAB_PFCT WITH(NOLOCK)
-- obtem a lista de mensagens de "Resposta" existentes e ainda não exportadas
	DECLARE Respostas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT msg.id, msg.estadoOperacao, dar.numero
		FROM tb_DeclaracoesDARMensagens AS msg WITH(NOLOCK) INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON msg.id_declaracaoDAR = dar.id
		WHERE msg.fluxo = 0 AND msg.sucesso = 1 AND msg.exportado = 0 AND CAST(CONVERT(varchar(10), msg.dataMensagem, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, msg.dataMensagem), 105) AS datetime)
	OPEN Respostas
	FETCH NEXT FROM Respostas INTO @Id, @EstadoOperacao, @Numero
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro de dados da mensagem de resposta
		SET @FicheiroXML = 				
			(SELECT 
				1 AS 'TAG',
				NULL AS 'PARENT', 
				NULLIF(adi.numeroObjetoCTT, '') AS "INCIDENCIA!1!numeroLocalObjecto!element", 
				NULLIF(dar.documentoTransporte, '') AS "INCIDENCIA!1!numeroOrigemObjecto!element", 			
				NULLIF(dar.numeroNRM, '') AS "INCIDENCIA!1!numeroOrdem!element",
				NULLIF(msg.estadoOperacao, '') AS "INCIDENCIA!1!incidencia!element",
				(CASE WHEN msg.estadoOperacao IN ('RE', 'AP', 'ALT') THEN CAST(msg.resposta AS nvarchar(MAX)) ELSE NULL END) AS "INCIDENCIA!1!descricaoIncidencia!cdata",
				CONVERT(varchar(19), msg.dataMensagem, 120) as "INCIDENCIA!1!dataIncidencia!element"
			FROM tb_DeclaracoesDARMensagens AS msg WITH(NOLOCK) INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON msg.id_declaracaoDAR = dar.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON dar.id = adi.id_declaracaoDAR AND adi.numeroAdicao = 1			
			WHERE msg.id = @Id
			FOR XML EXPLICIT)		
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirGeracaoFicheiro + '\' + CAST(@Numero AS varchar(20)) + '_' + @EstadoOperacao + '_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML c/ encoding UTF-8
		EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroTmpXML					
-- atualiza mensagem de resposta p/ sinalizar como já exportada
		UPDATE tb_DeclaracoesDARMensagens SET exportado = 1
		WHERE id = @Id			
		FETCH NEXT FROM Respostas INTO @Id, @EstadoOperacao, @Numero
	END
	CLOSE Respostas
	DEALLOCATE Respostas	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ExportaFicheiroXMLMensagens] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ExportaFicheiroXMLMensagens] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_GeraDocumentoConta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_GeraDocumentoConta] @Id int, @IdTipoDoc int, @TipoCliente varchar(3), @IdUtilizador int, @Origem int, @IdDocConta int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @Utilizador varchar(30), @CfgBloqueiaEdicao int, @CfgPercRetencaoFonte numeric(38, 6), @CodTipoDocConta varchar(4), 
		@TipoContaTipoDoc int, @AnoDocConta int, @IdenDocConta int, @StatusDocConta int, @TotalAdicoesDeclaracao int, @TotalIVABeneficiarioDeclaracao decimal(18, 2), 
		@CodClienteDeclaracao varchar(18), @NIFClienteColetivoDeclaracao bit, @CodClienteCCDeclaracao varchar(18), @CodNaturezaDeclaracao varchar(3), 
		@TxIVANatureza numeric(38, 6), @IDTarifaNatureza int, @LigacaoASNatureza bit, @NumMascaras int, @TipoMascara int, @CodMascara int, @Observacoes varchar(MAX), 
		@ValorReferenciaTarifa numeric(38, 6), @CodRubCaucaoTarifa int, @CodRubMultiClassTarifa int, @NumAdicoesMultiClassTarifa int, 
		@ValorPorAdicaoMultiClassTarifa numeric(38, 6), @OUTValorNumerico numeric(38, 6), @TotalHonorariosDocConta numeric(38, 6), @TotalDocumentadasDocConta numeric(38, 6), 
		@TotalInerentesDocConta numeric(38, 6), @TotalInerentesIsentasIVADocConta numeric(38, 6), @TotalRetencaoDocConta numeric(38, 6), @TotalIVADocConta numeric(38, 6), 
		@i int,	@PosicaoDespesa int, @CodDespesa int, @NomeDespesa varchar(70), @CalcTrafegoDespesa bit, @FormulaDespesa varchar(4000), @CampoRecapitulativoDespesa int, 
		@CodChargeCodeDespesa varchar(4), @ValorDespesa numeric(38, 6), @IsentaIVADespesa bit, @CodIsencaoIVADespesa varchar(3), @MencaoIsencaoIVADespesa varchar(100), 
		@AutorizacaoSaida bit
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- obtem o ID do utilizador
	SELECT @Utilizador = UTI_UTIL
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações nos Parâmetros de Despacho
	SELECT @CfgBloqueiaEdicao = PDE_BCNR
	FROM TAB_PDES WITH(NOLOCK)
-- obtem configurações nos Parâmetros de Faturação
	SELECT @CfgPercRetencaoFonte = ISNULL(PFC_RFNT, 0)
	FROM TAB_PFCT WITH(NOLOCK)
-- inicia transacção para inserção dados da declaração
	BEGIN TRANSACTION	
	BEGIN TRY	
		SET @NumErro = 0
-- obtem dados do tipo de documento
		SELECT @CodTipoDocConta = TDO_DOCU, @TipoContaTipoDoc = ISNULL(TDO_TCNT, 0)
		FROM TAB_TDOC WITH(NOLOCK)
		WHERE TDO_TDOC = 0 AND ((TDO_DCON = 1 AND TDO_EXSF = 1 AND TDO_TDSF IN ('FT', 'OR')) OR (TDO_DCON = 0)) AND TDO_IDTY = @IdTipoDoc
-- verifica se o tipo documento é válido
		IF ISNULL(@CodTipoDocConta, '') = ''
			RAISERROR('Tipo de documento "%d" inválido.', 16, 1, @IdTipoDoc)	
-- obtem dados do documento de Conta associada à declaração DAR
		SELECT @IdDocConta = dar.id_conta, 
			@NIFClienteColetivoDeclaracao = (CASE 
				WHEN (SUBSTRING(dar.nifCliente, 1, 1) IN ('1', '2', '3')) OR (dar.nifCliente = '999999990') THEN 0 
				ELSE 1 
			END), 
			@TotalAdicoesDeclaracao = dar.totalAdicoes, 			
			@TotalIVABeneficiarioDeclaracao = (CASE 
				WHEN (dar.regimeIVA = 3) AND (dar.beneficiarioIVACliente = 1) THEN 0
				ELSE dar.totalIVA
			END), 
			@AutorizacaoSaida = dar.autorizacaoSaida, 
			@CodNaturezaDeclaracao = nat.NDE_CODI, 
			@TxIVANatureza = nat.NDE_TIVA, 
			@IDTarifaNatureza = nat.CBT_IDEN, 
			@LigacaoASNatureza = (CASE 
				WHEN ISNULL(nat.NDE_TLCV, -1) = 0 THEN 1 
				ELSE 0 
			END), 
			@CodClienteDeclaracao = cli.CLI_CODI, 
			@CodClienteCCDeclaracao = ISNULL(cli.CLI_CCOR, cli.CLI_CODI), 
			@AnoDocConta = ISNULL(cnt.CDO_EANO, YEAR(@DataAtual)), 
			@CodTipoDocConta = ISNULL(cnt.CDO_TDOC, @CodTipoDocConta), 
			@IdenDocConta = cnt.CDO_IDEN, 
			@StatusDocConta = cnt.CDO_STAT,
			@ValorReferenciaTarifa = (CASE 
				WHEN (SUBSTRING(dar.nifCliente, 1, 1) IN ('1', '2', '3')) OR (dar.nifCliente = '999999990') THEN (CASE cbt.CBT_VRFP 
						WHEN 0 THEN (CASE dar.tipoShipment WHEN 1 THEN (dar.totalMontanteEURParte + ROUND((dar.totalCustosTransporteParte / dar.cambioCustosTransporte), 2)) ELSE (dar.totalMontanteEUR + ROUND((dar.totalCustosTransporte / dar.cambioCustosTransporte), 2)) END) 
						WHEN 1 THEN ((CASE dar.tipoShipment WHEN 1 THEN dar.totalMontanteEURParte ELSE dar.totalMontanteEUR END) - ROUND((dar.despesasDHL / dar.cambioMontante), 2)) 
						WHEN 2 THEN (CASE WHEN (dar.regimeIVA = 3) AND (dar.beneficiarioIVACliente = 1) THEN 0 ELSE (CASE dar.tipoShipment WHEN 1 THEN dar.totalIVAParte ELSE dar.totalIVA END) END) 
						ELSE 0 
					END)				 
				ELSE 
					(CASE cbt.CBT_VREF 
						WHEN 0 THEN (CASE dar.tipoShipment WHEN 1 THEN (dar.totalMontanteEURParte + ROUND((dar.totalCustosTransporteParte / dar.cambioCustosTransporte), 2)) ELSE (dar.totalMontanteEUR + ROUND((dar.totalCustosTransporte / dar.cambioCustosTransporte), 2)) END)				
						WHEN 1 THEN ((CASE dar.tipoShipment WHEN 1 THEN dar.totalMontanteEURParte ELSE dar.totalMontanteEUR END) - ROUND((dar.despesasDHL / dar.cambioMontante), 2)) 
						WHEN 2 THEN (CASE WHEN (dar.regimeIVA = 3) AND (dar.beneficiarioIVACliente = 1) THEN 0 ELSE (CASE dar.tipoShipment WHEN 1 THEN dar.totalIVAParte ELSE dar.totalIVA END) END) 
						ELSE 0 
					END)
			END)
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY				
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
			LEFT OUTER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON dar.id_conta = cnt.CDO_IDTY
			LEFT OUTER JOIN TAB_PCBT as cbt WITH(NOLOCK) ON nat.CBT_IDEN = cbt.CBT_IDEN			
		WHERE dar.id = @Id
-- obtem a máscara a utilizar (cliente (1) ou natureza (2) ou nenhuma (0))
		EXEC SP_ObtemMascaraFacturacao @CodClienteDeclaracao, @CodNaturezaDeclaracao, @NumMascaras OUTPUT, @TipoMascara OUTPUT, @CodMascara OUTPUT
-- calcula as observações (definidas na máscara do cliente ou na natureza ou nos parâmetros de faturação)
		EXEC SP_ObtemObservacoesParaConta @CodMascara, -1, @Id, @CodClienteDeclaracao, @CodNaturezaDeclaracao, '', @Observacoes OUTPUT
-- obtem a despesa de honorários
		IF @IDTarifaNatureza IS NULL
		BEGIN
			SELECT @CodDespesa = DIN_CODI, @FormulaDespesa = ISNULL(DIN_FCLC, '')
			FROM TAB_DINE WITH(NOLOCK) 
			WHERE DIN_CODI = 13
		END
		ELSE
		BEGIN
			SELECT @CodDespesa = cbi.DIN_CODI1, @CodRubCaucaoTarifa = cbi.DIN_CODI3, @CodRubMultiClassTarifa = cbi.DIN_CODI2, @NumAdicoesMultiClassTarifa = cbi.CBI_NADF, @ValorPorAdicaoMultiClassTarifa = cbi.CBI_VLAD
			FROM TAB_PCBT AS cbt WITH(NOLOCK) INNER JOIN TAB_PCBI AS cbi WITH(NOLOCK) ON cbt.CBI_IDEN = cbi.CBI_IDEN 
			WHERE cbt.CBT_IDEN = @IDTarifaNatureza 
		END
-- calcula total de honorários
		IF @CodDespesa IS NOT NULL
		BEGIN
			IF @IDTarifaNatureza IS NULL
			BEGIN				
				IF (@LigacaoASNatureza = 1) AND (@FormulaDespesa <> '')
				BEGIN
					SET @OUTValorNumerico = 0
					EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaDespesa, @OUTValorNumerico OUTPUT, @Id, -1					
					SET @TotalHonorariosDocConta = @OUTValorNumerico
				END
				ELSE
				IF @TipoMascara = 1 
				BEGIN
					SELECT @TotalHonorariosDocConta = ISNULL(MCF_VALO, 0) 
					FROM TAB_MCFT WITH(NOLOCK) 
					WHERE CLI_CODI = @CodClienteCCDeclaracao AND NDE_CODI = @CodNaturezaDeclaracao AND MCF_CODI = @CodMascara
				END
				ELSE
				IF @TipoMascara = 2
				BEGIN
					SELECT @TotalHonorariosDocConta = ISNULL(MNF_VALO, 0) 
					FROM TAB_MNFT WITH(NOLOCK) 
					WHERE NDE_CODI = @CodNaturezaDeclaracao AND MNF_CODI = @CodMascara
				END
				ELSE
					SET @TotalHonorariosDocConta = 0
			END
			ELSE
			IF @CodTipoDocConta <> 'CEXB'
				SET @TotalHonorariosDocConta = dbo.FNT_CustomsBilling_CalculaValorTarifa(@IDTarifaNatureza, @ValorReferenciaTarifa, @ValorReferenciaTarifa, @TotalIVABeneficiarioDeclaracao, 1, @CodClienteDeclaracao, @NIFClienteColetivoDeclaracao)			
			ELSE
				SET @TotalHonorariosDocConta = 0
		END
		ELSE
			SET @TotalHonorariosDocConta = 0
-- se documento de Conta não existe, processa a inserção
		IF @IdDocConta IS NULL
		BEGIN
-- obtem próximo ID para documento de Conta			
			SELECT @IdenDocConta = ISNULL((MAX(CDO_IDEN) + 1), 1)
  			FROM FAC_CDOC
			WHERE CDO_TDOC = @CodTipoDocConta AND CDO_EANO = @AnoDocConta	
-- insere documento de Conta
			INSERT INTO FAC_CDOC(CDO_EANO, 
				CDO_TDOC, 
				CDO_IDEN, 
				NDE_CODI, 
				CDO_NPRO, 
				CDO_PANO, 
				CDO_TCNT, 
				DEC_CODI, 
				ALF_CODI, 
				CDO_NORD, 
				CDO_DTAC, 
				CDO_STAT, 
				CDO_DTAB, 
				CDO_DTIN, 
				CLI_DESP, 
				CLI_CCOR, 
				CLI_ENDC, 
				DIN_HONO, 
				CDO_AGRA, 
				CDO_DESA, 
				CDO_TTDC, 
				CDO_TTIN, 
				CDO_TTHO, 
				CDO_TTRF, 
				CDO_BIVA, 
				CDO_IVA, 
				CDO_TXIV, 
				CDO_RTFO, 
				CDO_TTPR, 
				CDO_ISIV, 
				CDO_QUNT, 
				CDO_QUAL, 
				CDO_DESC, 
				CDO_PBRT, 
				CDO_PLIQ, 
				CDO_VADU, 
				CDO_CTMR, 
				CDO_VREF, 
				CDO_UCRI, 
				CDO_DTCR, 
				CDO_UALT, 
				CDO_DTAL, 
				CDO_OBSR, 
				CDO_IN01, 
				CDO_IN02, 
				CDO_IN03, 
				CDO_IN04, 
				CDO_VI01, 
				CDO_VI02, 
				CDO_VI03, 
				CDO_VI04, 
				CDO_REGL, 
				CDO_DTRL, 
				CDO_MPAG, 
				CDO_CTIP, 
				CDO_CPRT, 
				CDO_CNOM, 
				CDO_CMOR, 
				CDO_CLOC, 
				CDO_CCPO, 
				CDO_CLPO, 
				CDO_CNIF, 
				CDO_CPAI, 
				CDO_CEAN, 
				IIV_CODI, 
				FOR_CODI, 
				FOR_NOME, 
				CDO_IVAA, 
				CCO_CODI, 
				CDO_ORIG, 
				CDO_CPAG,
				id_declaracaoDAR)
			OUTPUT inserted.CDO_IDTY INTO @TblID
			SELECT @AnoDocConta, 
				@CodTipoDocConta, 
				@IdenDocConta, 
				nat.NDE_CODI, 
				dar.numero, 
				dar.ano, 
				(CASE @TipoContaTipoDoc WHEN 0 THEN 0 ELSE 1 END), 
				dcl.DEC_CODI, 
				alf.ALF_CODI, 
				dar.numeroNRM, 
				dar.dataNRM, 
				0, 
				CAST(CONVERT(varchar(10), dar.data, 105) AS datetime), 
				CAST(CONVERT(varchar(10), dar.data, 105) AS datetime), 
				cli.CLI_CODI, 
				ISNULL(cli.CLI_CCOR, cli.CLI_CODI), 
				ISNULL(cli.CLI_ECON, cli.CLI_CODI), 
				@CodDespesa, 
				0, 
				0,  
				0, 
				0, 
				@TotalHonorariosDocConta, 
				0, 
				0, 
				0, 
				nat.NDE_TIVA, 
				@CfgPercRetencaoFonte, 
				0, 
				(SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = nat.IIV_CODI), 
				(CASE dar.tipoShipment WHEN 1 THEN dar.volumesDirty ELSE dar.totalVolumes END), 
				'VOLUMES', 
				(SELECT SUBSTRING(designacao, 1, 40) FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id AND numeroAdicao = 1), 
				(CASE dar.tipoShipment WHEN 1 THEN dar.totalMassaBrutaParte ELSE dar.totalMassaBruta END), 
				0, 
				(CASE dar.tipoShipment WHEN 1 THEN (dar.totalMontanteEURParte + ROUND((dar.totalCustosTransporteParte / dar.cambioCustosTransporte), 2)) ELSE (dar.totalMontanteEUR + ROUND((dar.totalCustosTransporte / dar.cambioCustosTransporte), 2)) END), 
				dbo.fn_DeclaracoesDAR_ObtemContramarca(dar.id), 
				dar.numeroVossaReferencia,  
				@Utilizador, 
				@DataAtual, 
				@Utilizador, 
				@DataAtual, 
				@Observacoes, 
				0, 
				0, 
				0, 
				0, 
				0, 
				0, 
				0, 
				0, 
				dar.numeroRegistoLiquidacao, 
				dar.dataRegistoLiquidacao, 
				cli.CLI_MPAG, 
				@TipoCliente, 
				dar.documentoTransporte, 
				dar.nomeCliente, 
				dar.moradaCliente, 
				dar.localidadeCliente, 
				SUBSTRING(dar.codPostalCliente, 1, 12), 
				dar.locPostalCliente, 
				dar.nifCliente, 
				pcl.PAI_CODI, 
				cli.CLI_CEAN, 
				nat.IIV_CODI, 
				frn.FOR_CODI, 
				dar.nomeFornecedor, 
				(CASE dar.tipoShipment WHEN 1 THEN dar.totalIVAParte ELSE dar.totalIVA END), 
				nat.CCO_CODI, 
				@Origem, 
				cli.CLI_CPAG,
				@Id 
			FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
				LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON dar.id_fornecedor = frn.FOR_IDTY
				LEFT OUTER JOIN TAB_PAIS AS pfo WITH(NOLOCK) ON dar.id_paisFornecedor = pfo.PAI_IDTY
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
				INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dar.id_declarante = dcl.DEC_IDTY								
			WHERE dar.id = @Id
-- obtem o ID do novo documento de conta
			SELECT @IdDocConta = ID 
			FROM @TblID
-- associa o documento de conta à declaração DAR
			UPDATE tb_DeclaracoesDAR SET id_conta = @IdDocConta
			WHERE id = @Id
		END
		ELSE
-- se documento de Conta existe, processa a edição se configuração de bloquear a retificação não ativa e o proprio documento de Conta ainda estiver no status de "Em Curso"
			IF ((@CfgBloqueiaEdicao = 0) OR ((@CfgBloqueiaEdicao = 2) AND (@AutorizacaoSaida = 0))) AND (@StatusDocConta = 0)
			BEGIN
				UPDATE FAC_CDOC SET NDE_CODI = nat.NDE_CODI, 
					CDO_NPRO = dar.numero, 
					CDO_PANO = dar.ano, 				
					DEC_CODI = dcl.DEC_CODI, 
					ALF_CODI = alf.ALF_CODI, 
					CDO_NORD = dar.numeroNRM, 
					CDO_DTAC = dar.dataNRM, 				
					CDO_DTAB = CAST(CONVERT(varchar(10), dar.data, 105) AS datetime), 				
					CLI_DESP = cli.CLI_CODI, 
					CLI_CCOR = ISNULL(cli.CLI_CCOR, cli.CLI_CODI), 
					CLI_ENDC = ISNULL(cli.CLI_ECON, cli.CLI_CODI), 
					DIN_HONO = @CodDespesa, 												
					CDO_TTHO = @TotalHonorariosDocConta, 												
					CDO_TXIV = nat.NDE_TIVA, 
					CDO_RTFO = @CfgPercRetencaoFonte, 				
					CDO_ISIV = (SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = nat.IIV_CODI), 
					CDO_QUNT = (CASE dar.tipoShipment WHEN 1 THEN dar.volumesDirty ELSE dar.totalVolumes END), 
					CDO_QUAL = 'VOLUMES', 
					CDO_DESC = (SELECT SUBSTRING(designacao, 1, 40) FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id AND numeroAdicao = 1), 
					CDO_PBRT = (CASE dar.tipoShipment WHEN 1 THEN dar.totalMassaBrutaParte ELSE dar.totalMassaBruta END), 					
					CDO_VADU = (CASE dar.tipoShipment WHEN 1 THEN (dar.totalMontanteEURParte + ROUND((dar.totalCustosTransporteParte / dar.cambioCustosTransporte), 2)) ELSE (dar.totalMontanteEUR + ROUND((dar.totalCustosTransporte / dar.cambioCustosTransporte), 2)) END), 
					CDO_CTMR = dbo.fn_DeclaracoesDAR_ObtemContramarca(dar.id), 
					CDO_VREF = dar.numeroVossaReferencia, 					
					CDO_UALT = @Utilizador, 
					CDO_DTAL = @DataAtual, 
					CDO_OBSR = @Observacoes, 					
					CDO_REGL = dar.numeroRegistoLiquidacao, 
					CDO_DTRL = dar.dataRegistoLiquidacao, 
					CDO_MPAG = cli.CLI_MPAG, 
					CDO_CTIP = @TipoCliente, 
					CDO_CPRT = dar.documentoTransporte, 
					CDO_CNOM = dar.nomeCliente, 
					CDO_CMOR = dar.moradaCliente, 
					CDO_CLOC = dar.localidadeCliente, 
					CDO_CCPO = SUBSTRING(dar.codPostalCliente, 1, 12), 
					CDO_CLPO = dar.locPostalCliente,  
					CDO_CNIF = dar.nifCliente, 
					CDO_CPAI = pcl.PAI_CODI, 
					CDO_CEAN = cli.CLI_CEAN, 
					IIV_CODI = nat.IIV_CODI, 
					FOR_CODI = frn.FOR_CODI, 
					FOR_NOME = dar.nomeFornecedor, 
					CDO_IVAA = (CASE dar.tipoShipment WHEN 1 THEN dar.totalIVAParte ELSE dar.totalIVA END), 
					CCO_CODI = nat.CCO_CODI, 
					CDO_ORIG = @Origem, 
					CDO_CPAG = cli.CLI_CPAG
				FROM FAC_CDOC AS cnt WITH(NOLOCK) INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON cnt.CDO_IDTY = dar.id_conta
					INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON dar.id_fornecedor = frn.FOR_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pfo WITH(NOLOCK) ON dar.id_paisFornecedor = pfo.PAI_IDTY
					INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
					INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
					INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dar.id_declarante = dcl.DEC_IDTY
				WHERE cnt.CDO_IDTY = @IdDocConta
			END
			ELSE
				RAISERROR('Conta bloqueada para edição.', 16, 2)
-- remove detalhes da conta		
		DELETE FROM FAC_DDCD 
		WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta 
			AND EXISTS(SELECT DCD_LINH FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = FAC_DDCD.CDO_EANO AND CDO_TDOC = FAC_DDCD.CDO_TDOC AND CDO_IDEN = FAC_DDCD.CDO_IDEN AND DCD_LINH = FAC_DDCD.DCD_LINH AND DCD_VFCX = 0)
		DELETE FROM FAC_DCDO 
		WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta AND DCD_VFCX = 0		
		DELETE FROM FAC_DICD 
		WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta
		DELETE FROM FAC_ICDO 
		WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta		
-- insere as linhas de despesas documentadas 
		SET @i = 1
		WHILE (@i < 10)
		BEGIN
			IF NOT EXISTS(SELECT DCD_LINH FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta AND DCD_LINH = @i)
			BEGIN
				INSERT INTO FAC_DCDO(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DCD_VTOT) 
				VALUES(@AnoDocConta, @CodTipoDocConta, @IdenDocConta, @i, 0)
			END
			SET @i = @i + 1
		END
-- insere as linhas de despesas inerentes
		SET @i = 1
		WHILE (@i < 13)
		BEGIN
			INSERT INTO FAC_ICDO(CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, ICD_VTOT) 
			VALUES(@AnoDocConta, @CodTipoDocConta, @IdenDocConta, @i, 0)
			SET @i = @i + 1
		END	
-- inicia total de documentadas
		SET @TotalDocumentadasDocConta = 0
-- insere detalhe de despesas documentadas de acordo c/ o tipo de máscara
		DECLARE DespDocumentadas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT DDO_PCDO, DDO_CODI, DDO_NOME, DDO_UCTE, ISNULL(DDO_FCLD, ''), DDO_CREC, CCO_CODI, 0
			FROM TAB_DDOC WITH(NOLOCK) 
			WHERE @TipoMascara = 0 AND DDO_CCDO = 1 AND NOT EXISTS(SELECT DCD_LINH FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta AND DCD_LINH = TAB_DDOC.DDO_PCDO AND DDO_CODI = TAB_DDOC.DDO_CODI AND DCD_VFCX = 1)
			UNION
			SELECT mas.MCD_POSI, mas.DDO_CODI, ddo.DDO_NOME, ddo.DDO_UCTE, ISNULL(ddo.DDO_FCLD, ''), ddo.DDO_CREC, ddo.CCO_CODI, ISNULL(mas.MCD_VALO, 0)
			FROM TAB_MCDO AS mas WITH(NOLOCK) INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON mas.DDO_CODI = ddo.DDO_CODI						
			WHERE @TipoMascara = 1 AND mas.CLI_CODI = @CodClienteCCDeclaracao AND mas.MCF_CODI = @CodMascara AND NOT EXISTS(SELECT DCD_LINH FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta AND DCD_LINH = mas.MCD_POSI AND DDO_CODI = mas.DDO_CODI AND DCD_VFCX = 1)
			UNION
			SELECT ROW_NUMBER() OVER(ORDER BY mas.DDO_CODI), mas.DDO_CODI, ddo.DDO_NOME, ddo.DDO_UCTE, ISNULL(ddo.DDO_FCLD, ''), ddo.DDO_CREC, ddo.CCO_CODI, ISNULL(mas.MND_VALO, 0)
			FROM TAB_MNDO AS mas WITH(NOLOCK) INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON mas.DDO_CODI = ddo.DDO_CODI						
			WHERE @TipoMascara = 2 AND mas.NDE_CODI = @CodNaturezaDeclaracao AND mas.MNF_CODI = @CodMascara AND NOT EXISTS(SELECT DCD_LINH FROM FAC_DCDO WITH(NOLOCK) WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta AND DDO_CODI = mas.DDO_CODI AND DCD_VFCX = 1)
		OPEN DespDocumentadas
		FETCH NEXT FROM DespDocumentadas INTO @PosicaoDespesa, @CodDespesa, @NomeDespesa, @CalcTrafegoDespesa, @FormulaDespesa, @CampoRecapitulativoDespesa, @CodChargeCodeDespesa, @ValorDespesa
		WHILE @@FETCH_STATUS = 0
		BEGIN						
-- obtem outro valor para a despesa documentada em função das suas configurações										
			IF @CampoRecapitulativoDespesa IS NOT NULL					
				SET @ValorDespesa = (CASE WHEN @CampoRecapitulativoDespesa IN (1, 3) THEN @TotalIVABeneficiarioDeclaracao ELSE 0 END)					
			ELSE			
				IF (@LigacaoASNatureza = 1) AND (@FormulaDespesa <> '')
				BEGIN
					SET @OUTValorNumerico = 0
					EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaDespesa, @OUTValorNumerico OUTPUT, @Id, -1
					SET @ValorDespesa = @OUTValorNumerico
				END						
-- atualiza a linha da despesa documentada			
			UPDATE FAC_DCDO SET DDO_CODI = @CodDespesa, DCD_DESC = @NomeDespesa, DCD_VTOT = @ValorDespesa, CCO_CODI = @CodChargeCodeDespesa
			WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta AND DCD_LINH = @PosicaoDespesa
-- incrementa o total de documentadas
			SET @TotalDocumentadasDocConta = @TotalDocumentadasDocConta + @ValorDespesa
			FETCH NEXT FROM DespDocumentadas INTO @PosicaoDespesa, @CodDespesa, @NomeDespesa, @CalcTrafegoDespesa, @FormulaDespesa, @CampoRecapitulativoDespesa, @CodChargeCodeDespesa, @ValorDespesa
		END
		CLOSE DespDocumentadas
		DEALLOCATE DespDocumentadas
-- inicia totais de inerentes
		SET @TotalInerentesDocConta = 0	
		SET @TotalInerentesIsentasIVADocConta = 0
-- insere detalhe de despesas inerentes de acordo c/ o tipo de máscara
		DECLARE DespInerentes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT DIN_PCDO, DIN_CODI, DIN_NOME, DIN_UCTE, ISNULL(DIN_FCLD, ''), CCO_CODI, DIN_ISEN, IIV_CODI, IIV_MENC, 0
			FROM TAB_DINE WITH(NOLOCK) 
			WHERE @TipoMascara = 0 AND DIN_CCDO = 1
			UNION
			SELECT mas.MCI_POSI, mas.DIN_CODI, din.DIN_NOME, din.DIN_UCTE, ISNULL(din.DIN_FCLD, ''), din.CCO_CODI, din.DIN_ISEN, din.IIV_CODI, din.IIV_MENC, mas.MCI_VALO
			FROM TAB_MCIN AS mas WITH(NOLOCK) INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON mas.DIN_CODI = din.DIN_CODI
			WHERE @TipoMascara = 1 AND mas.CLI_CODI = @CodClienteCCDeclaracao AND mas.MCF_CODI = @CodMascara
			UNION
			SELECT ROW_NUMBER() OVER(ORDER BY mas.DIN_CODI), mas.DIN_CODI, din.DIN_NOME, din.DIN_UCTE, ISNULL(din.DIN_FCLD, ''), din.CCO_CODI, din.DIN_ISEN, din.IIV_CODI, din.IIV_MENC, mas.MNI_VALO
			FROM TAB_MNIN AS mas WITH(NOLOCK) INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON mas.DIN_CODI = din.DIN_CODI
			WHERE @TipoMascara = 2 AND mas.NDE_CODI = @CodNaturezaDeclaracao AND mas.MNF_CODI = @CodMascara 
		OPEN DespInerentes
		FETCH NEXT FROM DespInerentes INTO @PosicaoDespesa, @CodDespesa, @NomeDespesa, @CalcTrafegoDespesa, @FormulaDespesa, @CodChargeCodeDespesa, @IsentaIVADespesa, @CodIsencaoIVADespesa, @MencaoIsencaoIVADespesa, 
			@ValorDespesa
		WHILE @@FETCH_STATUS = 0
		BEGIN						
			IF @CodDespesa = @CodRubCaucaoTarifa
				SET @ValorDespesa = dbo.FNT_CustomsBilling_CalculaValorTarifa(@IDTarifaNatureza, @ValorReferenciaTarifa, @TotalIVABeneficiarioDeclaracao, @TotalIVABeneficiarioDeclaracao, 2, @CodClienteDeclaracao, @NIFClienteColetivoDeclaracao)									
			ELSE
				IF @CodDespesa = @CodRubMultiClassTarifa
					SET @ValorDespesa = (CASE WHEN (@TotalAdicoesDeclaracao - @NumAdicoesMultiClassTarifa) < 0 THEN 0 ELSE (@TotalAdicoesDeclaracao - @NumAdicoesMultiClassTarifa) END) * @ValorPorAdicaoMultiClassTarifa
				ELSE				
					IF (@LigacaoASNatureza = 1) AND (@FormulaDespesa <> '')
					BEGIN
						SET @OUTValorNumerico = 0
						EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaDespesa, @OUTValorNumerico OUTPUT, @Id, -1
						SET @ValorDespesa = @OUTValorNumerico
					END						
-- atualiza a linha da despesa inerente
			UPDATE FAC_ICDO SET DIN_CODI = @CodDespesa, ICD_DESC = @NomeDespesa, ICD_VTOT = @ValorDespesa, CCO_CODI = @CodChargeCodeDespesa, ICD_ISEN = @IsentaIVADespesa, IIV_CODI = @CodIsencaoIVADespesa, 
				IIV_MENC = @MencaoIsencaoIVADespesa
			WHERE CDO_EANO = @AnoDocConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdenDocConta AND ICD_LINH = @PosicaoDespesa
-- incrementa os totais de inerentes
			IF @IsentaIVADespesa = 1
				SET @TotalInerentesIsentasIVADocConta = @TotalInerentesIsentasIVADocConta + @ValorDespesa
			SET @TotalInerentesDocConta = @TotalInerentesDocConta + @ValorDespesa			
			FETCH NEXT FROM DespInerentes INTO @PosicaoDespesa, @CodDespesa, @NomeDespesa, @CalcTrafegoDespesa, @FormulaDespesa, @CodChargeCodeDespesa, @IsentaIVADespesa, @CodIsencaoIVADespesa, @MencaoIsencaoIVADespesa, 
				@ValorDespesa
		END
		CLOSE DespInerentes
		DEALLOCATE DespInerentes	
-- calcula total da retenção na fonte
		SET @TotalRetencaoDocConta = ROUND((@TotalInerentesDocConta + @TotalHonorariosDocConta) * @CfgPercRetencaoFonte / 100, 2)
-- calculo total do IVA
		SET @TotalIVADocConta = ROUND((@TotalHonorariosDocConta + @TotalInerentesDocConta - @TotalInerentesIsentasIVADocConta) * @TxIVANatureza / 100, 2)
-- atualiza totais do documento de conta
		UPDATE FAC_CDOC SET CDO_TTDC = @TotalDocumentadasDocConta , 
			CDO_TTIN = @TotalInerentesDocConta, 
			CDO_TTRF = @TotalRetencaoDocConta, 
			CDO_IVA = @TotalIVADocConta, 
			CDO_TTPR = (@TotalDocumentadasDocConta + @TotalInerentesDocConta + @TotalHonorariosDocConta + @TotalIVADocConta), 
			CDO_IN01 = (@TotalDocumentadasDocConta + (CASE WHEN (CDO_TXIV = 0) THEN (@TotalInerentesDocConta + @TotalHonorariosDocConta) ELSE @TotalInerentesIsentasIVADocConta END)), 
			CDO_IN02 = 0, 
			CDO_IN03 = 0, 
			CDO_IN04 = (CASE WHEN (CDO_TXIV > 0) THEN (@TotalInerentesDocConta - @TotalInerentesIsentasIVADocConta + @TotalHonorariosDocConta) ELSE 0 END), 
			CDO_VI01 = 0, 
			CDO_VI02 = 0, 
			CDO_VI03 = 0, 
			CDO_VI04 = @TotalIVADocConta
		WHERE CDO_EANO = @AnoDocConta and CDO_TDOC = @CodTipoDocConta and CDO_IDEN = @IdenDocConta
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_GeraDocumentoConta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_GeraDocumentoConta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_GeraDocumentoVenda]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_GeraDocumentoVenda] @AnoDocVenda int, @Id int, @IdCliente int, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN
-- declaracao de variaveis
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @NumeroDocVnd int, @SerieDocVnd varchar(20), @DataDocVnd datetime, @AuxData datetime, 
		@CodClienteDocVnd varchar(18), @NomeClienteDocVnd varchar(70), @MoradaClienteDocVnd varchar(70), @LocalidadeClienteDocVnd varchar(35), @CodPostalClienteDocVnd varchar(12), 
		@LocPostalClienteDocVnd varchar(35), @NIFClienteDocVnd varchar(18), @PaisClienteDocVnd varchar(2), @ValorEspecialVDIN numeric(38, 6), 
		@AnoProcessoDocVnd int, @NumeroProcessoDocVnd int, @DocumentoTransporte varchar(18), @NumeroDocPrecedente varchar(70),
		@CodNaturezaDocVnd varchar(3), 		
		@TipoDocVnd varchar(4), @CtxDocVnd int, @ValidaDatasDocVnd bit, @TipoDocSAFT varchar(2), 
		@CodRubFactLinha int, @NomeRubFactLinha varchar(70), @ValorRubFactLinha numeric(38, 6), @TxIVARubFactLinha numeric(38, 6), @LancHonRubFactLinha bit, 
		@CodChargeCode varchar(4), @CodIsencaoIVA varchar(3), @MencaoIsencaoIVA varchar(100), 
		@ValorLiqDocVnd numeric(38, 6), @ValorIVADocVnd numeric(38, 6), @ValorTotalDocVnd numeric(38, 6), 
		@TxIVAIsenta numeric(38, 6), @TxIVAReduzida numeric(38, 6), @TxIVAIntermedia numeric(38, 6), @TxIVANormal numeric(38, 6), 
		@IncidenciaIVA1DocVnd numeric(38, 6), @IncidenciaIVA2DocVnd numeric(38, 6), @IncidenciaIVA3DocVnd numeric(38, 6), @IncidenciaIVA4DocVnd numeric(38, 6), 
		@ValorIVA1DocVnd numeric(38, 6), @ValorIVA2DocVnd numeric(38, 6), @ValorIVA3DocVnd numeric(38, 6), @ValorIVA4DocVnd numeric(38, 6) 
	SET DATEFORMAT DMY
-- inicia variaveis
	SET @IncidenciaIVA1DocVnd = 0
	SET @IncidenciaIVA2DocVnd = 0
	SET @IncidenciaIVA3DocVnd = 0
	SET @IncidenciaIVA4DocVnd = 0
	SET @ValorIVA1DocVnd = 0
	SET @ValorIVA2DocVnd = 0
	SET @ValorIVA3DocVnd = 0
	SET @ValorIVA4DocVnd = 0
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia transacção para inserção de documento de venda
	BEGIN TRANSACTION	
	BEGIN TRY	
		SET @NumErro = 0
-- obtem dados do utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem dados do cliente
		SELECT @CodClienteDocVnd = CLI_CODI, @NomeClienteDocVnd = CLI_NOME, @MoradaClienteDocVnd = CLI_MORA, @LocalidadeClienteDocVnd = CLI_LOCA, 
			@CodPostalClienteDocVnd = CLI_CPOS, @LocPostalClienteDocVnd = CLI_LPOS, @NIFClienteDocVnd = CLI_NIF, @PaisClienteDocVnd = PAI_CODI, @ValorEspecialVDIN = CLI_VEVD
		FROM TAB_CLIE WITH(NOLOCK)
		WHERE CLI_IDTY = @IdCliente
-- obtem dados da declaração 
		SELECT @AnoProcessoDocVnd = dar.ano, @NumeroProcessoDocVnd = dar.numero, @DocumentoTransporte = dar.documentoTransporte, 
			@CodNaturezaDocVnd = nat.NDE_CODI, @TipoDocVnd = nat.TDO_DOCU, @CodRubFactLinha = nat.RFC_CODI, 
			@CtxDocVnd = tdo.TDO_TDOC, @ValidaDatasDocVnd = tdo.TDO_VALI, @TipoDocSAFT = tdo.TDO_TDSF, 
			@NomeRubFactLinha = rft.RFC_NOME, @TxIVARubFactLinha = rft.RFC_IVA, @CodChargeCode = rft.CCO_CODI, 
			@CodIsencaoIVA = (CASE rft.RFC_IVA WHEN 0 THEN 'M04' ELSE NULL END), 
			@MencaoIsencaoIVA = (CASE rft.RFC_IVA WHEN 0 THEN (SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = 'M04') ELSE NULL END),
			@ValorRubFactLinha = (CASE WHEN (@NIFClienteDocVnd <> '999999990') AND (SUBSTRING(@NIFClienteDocVnd, 1, 1) IN ('5', '6', '9')) THEN rft.RFC_VLNC ELSE rft.RFC_VLNS END),
			@LancHonRubFactLinha = CAST((CASE rft.RFC_TIPO WHEN 2 THEN 1 ELSE 0 END) AS bit), 
			@NumeroDocPrecedente = (SELECT TOP 1 numero FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id) 
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON nat.TDO_DOCU = tdo.TDO_DOCU
			INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON nat.RFC_CODI = rft.RFC_CODI
		WHERE dar.id = @Id
-- verifica se existe valor especial VDIN para o cliente
		IF @ValorEspecialVDIN > 0
			SET @ValorRubFactLinha = @ValorEspecialVDIN
-- calcula valores totais p/ doc. venda
		SET @ValorLiqDocVnd = @ValorRubFactLinha
		SET @ValorIVADocVnd = ROUND((@ValorRubFactLinha * @TxIVARubFactLinha / 100), 2)
		SET @ValorTotalDocVnd = @ValorLiqDocVnd + @ValorIVADocVnd
-- obtem taxas de IVA configuradas na aplicação
		SELECT @TxIVAIsenta = PAP_TXIS, @TxIVAReduzida = PAP_TXRD, @TxIVAIntermedia = PAP_TXIN, @TxIVANormal = PAP_TXNR
		FROM TAB_PAPL WITH(NOLOCK)
-- calcula valores incidencia de IVA p/ doc. venda
		IF @TxIVARubFactLinha = @TxIVAIsenta
		BEGIN
			SET @IncidenciaIVA1DocVnd = @ValorLiqDocVnd
			SET @ValorIVA1DocVnd = @ValorIVADocVnd
		END
		ELSE
			IF @TxIVARubFactLinha = @TxIVAReduzida
			BEGIN
				SET @IncidenciaIVA2DocVnd = @ValorLiqDocVnd
				SET @ValorIVA2DocVnd = @ValorIVADocVnd
			END
			ELSE
				IF @TxIVARubFactLinha = @TxIVAIntermedia
				BEGIN
					SET @IncidenciaIVA3DocVnd = @ValorLiqDocVnd
					SET @ValorIVA3DocVnd = @ValorIVADocVnd
				END
				ELSE
					IF @TxIVARubFactLinha = @TxIVANormal
					BEGIN
						SET @IncidenciaIVA4DocVnd = @ValorLiqDocVnd
						SET @ValorIVA4DocVnd = @ValorIVADocVnd
					END
-- obtem a data p/ doc. venda em função do ano activo na aplicação e ano actual
		IF YEAR(@DataAtual) = @AnoDocVenda
			SET @DataDocVnd = CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)
		ELSE
		BEGIN
			SELECT @DataDocVnd = CAST(CONVERT(varchar(10), MAX(DVE_DATA), 105) AS datetime)
			FROM FAC_DVEN WITH(NOLOCK)
			WHERE DVE_EANO = @AnoDocVenda
		END
-- valida a data obtida p/ doc. venda se tipo documento configurado para tal
		IF @ValidaDatasDocVnd = 1
		BEGIN
			SELECT @AuxData = CAST(CONVERT(varchar(10), NUM_DATA, 105) AS datetime)
			FROM TAB_NUMD
			WHERE TDO_DOCU = @TipoDocVnd AND NUM_EANO = @AnoDocVenda
			IF @AuxData > @DataDocVnd
				SET @DataDocVnd = @AuxData
		END
-- obtem o numero do doc. venda da tabela de numeradores
		SELECT @NumeroDocVnd = isnull(NUM_NUME, 0) + 1, @SerieDocVnd = ISNULL(NULLIF(NUM_SERI, ''), '1')
		FROM TAB_NUMD 
		WHERE TDO_DOCU = @TipoDocVnd AND NUM_EANO = @AnoDocVenda
-- insere registo de cabeçalho do doc. venda
		INSERT INTO FAC_DVEN (DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_CTXT, DVE_DATA, CLI_CODI, DVE_CNOM, DVE_CMOR, DVE_CLOC, DVE_CCPO, DVE_CLPO, DVE_CNIF, PAI_CLIV, NDE_CODI, DVE_NPRO, 
			DVE_OBSV, DVE_UTIC, DVE_DTCR, DVE_UTIA, DVE_DTAL, DVE_IN01, DVE_IN02, DVE_IN03, DVE_IN04, DVE_VI01, DVE_VI02, DVE_VI03, DVE_VI04, DVE_VLIQ, DVE_VIVA, DVE_VTOT, 
			DVE_STAT, DVE_DIPS, DVE_DFPS, DVE_PANO, DVE_IMEX, TDO_TDSF, DVE_IDAR, DVE_CPRT, DVE_SERI)
		VALUES(@TipoDocVnd, @NumeroDocVnd, @AnoDocVenda, @CtxDocVnd, @DataDocVnd, @CodClienteDocVnd, @NomeClienteDocVnd, @MoradaClienteDocVnd, @LocalidadeClienteDocVnd, 
			@CodPostalClienteDocVnd, @LocPostalClienteDocVnd, @NIFClienteDocVnd, @PaisClienteDocVnd, @CodNaturezaDocVnd, @NumeroProcessoDocVnd,
			('CPA Nº.: ' + @DocumentoTransporte + CHAR(13) + CHAR(10) + 'NRM SDS:' + ISNULL(@NumeroDocPrecedente, '')), @CodUtilizador, @DataAtual, @CodUtilizador, @DataAtual, 
			@IncidenciaIVA1DocVnd, @IncidenciaIVA2DocVnd, @IncidenciaIVA3DocVnd, @IncidenciaIVA4DocVnd, @ValorIVA1DocVnd, @ValorIVA2DocVnd, @ValorIVA3DocVnd, @ValorIVA4DocVnd, 
			@ValorLiqDocVnd, @ValorIVADocVnd, @ValorTotalDocVnd, 1, @DataDocVnd, @DataDocVnd, @AnoProcessoDocVnd, 0, @TipoDocSAFT, @Id, @DocumentoTransporte, @SerieDocVnd)
-- actualiza dados da tabela de numeradores
		UPDATE TAB_NUMD SET NUM_NUME = @NumeroDocVnd, NUM_DATA = @DataDocVnd
		WHERE TDO_DOCU = @TipoDocVnd AND NUM_EANO = @AnoDocVenda
-- insere registo de detalhe do doc. venda
		INSERT INTO FAC_DVDT (DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_CTXT, DVD_LHON, IIV_CODI, IIV_MENC, CCO_CODI)
		VALUES (@TipoDocVnd, @NumeroDocVnd, @AnoDocVenda, 1, @CodRubFactLinha, @NomeRubFactLinha, 1, @ValorRubFactLinha, @TxIVARubFactLinha, 1, @CtxDocVnd, @LancHonRubFactLinha, 
			@CodIsencaoIVA, @MencaoIsencaoIVA, @CodChargeCode)
	END TRY
	BEGIN CATCH							
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' 
			+ CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) 
			+ CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) 
			+ CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() 
			+ CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE() + CHAR(13)
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION	
	END CATCH	
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_GeraDocumentoVenda] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_GeraDocumentoVenda] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaDeclaracoesTNT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaDeclaracoesTNT] @DirectoriaErros varchar(500), @IdUtilizador int AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin), @Erro varchar(MAX), @i int, @Erros varchar(MAX), @PathFicheiroErro varchar(500), 
		@Linha varchar(MAX)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
		SET @NumErro = 0		
-- constroi XML para as declarações DAR a partir do da tabela interna no formato TNT
		SET @XMLDeclaracaoDAR = 
			(SELECT
				(SELECT 'I' AS "@acao", 
					(CONVERT(varchar(10), GETDATE(), 127) + 'Z') AS "data",	
					(CASE ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_MCPA)), ''), '') 
						WHEN '' THEN 2 
						ELSE 1
					END) AS "regimeIVA",  		 
					(CASE 
						WHEN ROUND((dadosTNT.DU2_MT22 / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) 
																WHEN SUBSTRING(dadosTNT.DU2_PR22, 1, 2) THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
																ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
																	FROM TAB_CPAI WITH(NOLOCK)
																	WHERE PAI_CODI = SUBSTRING(dadosTNT.DU2_PR22, 1, 2) AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
																	ORDER BY CPA_DATA DESC) END), 1)), 2) > 45 THEN 'C07' 
						ELSE 'C08' 
					END) AS "adicionalRegime", 	
					(SELECT 
						(CASE 
							WHEN ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA17)), ''), '') <> 'PT' THEN 'FR1'			
							ELSE 'FR5' 
						END) AS "funcao", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_MCPA)), '') AS "numeroIdentificacaoIVA"
					HAVING ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_MCPA)), ''), '') <> ''
					FOR XML PATH('regimeIOSS'), TYPE),				
					'DAR' AS "natureza", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CPRT)), '') AS "documentoTransporte",
					(SELECT NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ENOM)), '') AS "nome", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_EMOR)), '') AS "morada", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ELOC)), '') AS "localidade", 
						ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ECPO)), ''), '0') AS "codigoPostal", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ELPO)), '') AS "localidadePostal", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA15)), '') AS "pais"		
					FOR XML PATH('exportador'), TYPE),
					(SELECT ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNIF)), ''), '999999990') AS "nif", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNOM)), '') AS "nome", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DMOR)), '') AS "morada", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLOC)), '') AS "localidade", 
						ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DCPO)), ''), '0') AS "codigoPostal", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLPO)), '') AS "localidadePostal", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA17)), '') AS "pais"
					FOR XML PATH('importador'), TYPE),
					'0691I8' AS "declarante/codigoDeclarante",				
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ALFA)), '') AS "estancia", 
					'A' AS "tipoDeclaracao", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_NVRF)), '') AS "vossaReferencia", 	
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CO20)), '') AS "condEntrega",
					(CASE WHEN NULLIF(RTRIM(LTRIM(dadosTNT.DU2_NVSR)), '') IN (9, 10, 12, 15) THEN '40' ELSE '30' END) AS "meioTransporte", 	
					(SELECT 'B' AS "tipoLocalizacao", 
						'Y' AS "qualificador", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CO30)), '') AS "armazemDTP"						
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					NULLIF(SUBSTRING(RTRIM(LTRIM(dadosTNT.DU2_PR22)), 1, 2), '') AS "paisMoedaFatura", 
					'EU' AS "paisMoedaCustosTransporte", 
					6 AS "followUp", 				
					(SELECT NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DELG)), '') AS "locID", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_GTWY)), '') AS "gateway", 	
						dadosTNT.DU2_NVSR AS "serviceLevel", 												
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_REF1)), '') AS "despachoAcc", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_AERD)), '') AS "nomeFicheiro"
					FOR XML PATH('dadosEspecificos'), TYPE),
					(SELECT NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNOM)), '') AS "nomeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DMOR)), '') AS "moradaOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLOC)), '') AS "localidadeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DCPO)), '') AS "codigoPostalOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLPO)), '') AS "localidadePostalOriginalDestinatario", 						
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_REF2)), '') AS "referenciaExterna2", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_SHIP)), '') AS "shipID"
					FOR XML PATH('dadosEntidades'), TYPE),
					(SELECT (CONVERT(varchar(10), dadosTNT.DU2_DTVO, 127) + 'Z') AS "dataVoo", 
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_AERO)), '') AS "aeroportoOrigem", 						
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_AERP)), '') AS "posicaoAviao", 						
						NULLIF(RTRIM(LTRIM(dadosTNT.DU2_TPCG)), '') AS "tipoCarga"
					FOR XML PATH('dadosAWB'), TYPE),		 
					(SELECT dadosTNT.DU2_PAYM AS "payment", 
						(CONVERT(varchar(10), dadosTNT.DU2_DTIN, 127) + 'Z') AS "dataDocumentoTransporte"			
					FOR XML PATH('outrosDados'), TYPE),		 																					
					(SELECT TOP 1
						(SELECT INF_CODI AS "codigoMencao"		
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_CODI = 'RBVDP'	
						FOR XML PATH('mencao'), TYPE)		
					FROM TAB_INFC WITH(NOLOCK)
					WHERE INF_CODI = 'RBVDP'
					FOR XML PATH('informacoesAdicionais'), TYPE), 											
					(SELECT
						(SELECT 1 AS "numeroAdicao", 
							ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CO33)), ''), '9999999999') AS "codigoPautal", 
							ISNULL(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DESG)), ''), 'NÃO CLASSIFICADO') AS "designacao", 								
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA16)), '') AS "paisOrigem",								
							CAST(dadosTNT.DU2_MBRT AS decimal(18, 6)) AS "massaBruta", 
							CAST(dadosTNT.DU2_US41 AS decimal(18, 6)) AS "unidades", 
							dadosTNT.DU2_TVL6 AS "volumes", 				
							NULLIF(SUBSTRING(RTRIM(LTRIM(dadosTNT.DU2_PR22)), 1, 2), '') AS "paisMoedaFatura", 
							CAST(dadosTNT.DU2_MT22 AS decimal(18, 2)) AS "montante", 
							'EU' AS "paisMoedaCustosTransporte", 				
							CAST(0.00 AS decimal(18, 2)) AS "custosTransporte"						
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE), 
					(SELECT
						(SELECT 'PAC' AS "codigoIncidencia", 
							(CONVERT(varchar(23), @DataAtual, 127) + 'Z') AS "dataInicio", 
							(CONVERT(varchar(23), @DataAtual, 127) + 'Z') AS "dataFim"
						FOR XML PATH('incidencia'), TYPE)
					FOR XML PATH('incidencias'), TYPE), 
					(SELECT 
						(SELECT 0 AS "tipoManifesto", 
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA16)), '') AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DESG)), '') AS "descricao", 
							CAST(0 AS decimal(18, 3)) AS "valor", 
							NULLIF(SUBSTRING(RTRIM(LTRIM(dadosTNT.DU2_PR22)), 1, 2), '') AS "paisMoedaManifesto", 
							CAST(dadosTNT.DU2_MT22 AS decimal(18, 3)) AS "totalFatura", 
							(NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CPRT)), '') 
							+ (CASE number 
								WHEN 1 THEN '' 
								ELSE ('_' + CAST((number - 1) AS varchar(10))) 
							END)) AS "numeroCPA", 
							CAST(dadosTNT.DU2_MBRT as numeric(18, 3)) AS "peso"	
						FROM master.dbo.spt_values 
						WHERE number >= 1 AND number <= dadosTNT.DU2_TVL6
						GROUP BY number
						FOR XML PATH('manifesto'), TYPE)							
					FOR XML PATH('manifestos'), TYPE)
				FROM IMP_DUI2 AS dadosTNT 
				WHERE dadosTNT.DU2_SINT = 0 AND ROUND((dadosTNT.DU2_MT22 / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN SUBSTRING(dadosTNT.DU2_PR22, 1, 2) THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
										ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
											FROM TAB_CPAI WITH(NOLOCK)
											WHERE PAI_CODI = SUBSTRING(dadosTNT.DU2_PR22, 1, 2) AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
											ORDER BY CPA_DATA DESC) END), 1)), 2) <= 150
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração das declarações DAR
		SET @Erro = ''
		EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @Erro OUTPUT			
-- actualiza as as declarações DAR processadas
		UPDATE IMP_DUI2 SET DU2_SINT = 1, DU2_DTEX = GETDATE()
		FROM tb_DeclaracoesDAR WITH(NOLOCK)
		WHERE IMP_DUI2.DU2_SINT = 0 AND ROUND((IMP_DUI2.DU2_MT22 / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN SUBSTRING(IMP_DUI2.DU2_PR22, 1, 2) THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
										ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
											FROM TAB_CPAI WITH(NOLOCK)
											WHERE PAI_CODI = SUBSTRING(IMP_DUI2.DU2_PR22, 1, 2) AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
											ORDER BY CPA_DATA DESC) END), 1)), 2) <= 150
			AND RTRIM(LTRIM(IMP_DUI2.DU2_CPRT)) = documentoTransporte AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_AERP)), '') = posicaoAviao AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_AERD)), '') = nomeFicheiroUPS 
			AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_TMAN)), '') = 'D' AND IMP_DUI2.DU2_DTVO = dataVoo							
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE() 			
	END CATCH	
-- se ocorreram erros no tratamento das declarações ou processamento das declarações, gera ficheiro de erros
	IF ISNULL(@Erro, '') <> ''
	BEGIN		
		SET @Erro = @Erro + CHAR(12)
		SET @PathFicheiroErro = @DirectoriaErros + '\' + REPLACE(CAST(CAST(GETDATE() as numeric(38,6)) as varchar(20)), '.', '_') + '.txt'															
		SET @i = CHARINDEX(CHAR(12), @Erro, 0)
		WHILE @i > 0
		BEGIN
			SET @Linha = SUBSTRING(@Erro, 1, @i - 1)
			EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
			SET @Erro = STUFF(@Erro, 1, @i, '')
			SET @i = CHARINDEX(CHAR(12), @Erro, 0)
		END					
	END			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaDeclaracoesTNT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaDeclaracoesTNT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaFicheiroCTT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaFicheiroCTT] @FicheiroXML xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
		SET @NumErro = 0
-- constroi XML para declaração DAR a partir do ficheiro XML no formato CTT
		SET @XMLDeclaracaoDAR = 
			(SELECT
				(SELECT XML_DECL.DCL_DATA.value('@Acao[1]', 'varchar(1)') AS "@acao", 
					(CONVERT(varchar(10), XML_DECL.DCL_DATA.value('Data[1]', 'datetime'), 127) + 'Z') AS "data",
					(CASE 
						WHEN ISNULL(XML_DECL.DCL_DATA.value('NumRequerimento[1]', 'varchar(30)'), '') <> '' THEN 1
						WHEN SUBSTRING(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('NIFDestinatario[1]', 'varchar(18)'), ''), '1'), 1, 1) IN ('1', '2', '3', '4') THEN 2
						ELSE 3 
					END) AS "regimeIVA", 
					NULLIF(XML_DECL.DCL_DATA.value('(Adicoes/Adicao/C37B)[1]', 'varchar(3)'), '') AS "adicionalRegime", 
					(SELECT 
						(CASE 							
							WHEN ISNULL(XML_DECL.DCL_DATA.value('CodPaisDestinatario[1]', 'varchar(2)'), '') <> 'PT' THEN 'FR1'			
							ELSE 'FR5' 
						END) AS "funcao", 
						NULLIF(XML_DECL.DCL_DATA.value('NumRequerimento[1]', 'varchar(30)'), '') AS "numeroIdentificacaoIVA"
					HAVING ISNULL(XML_DECL.DCL_DATA.value('NumRequerimento[1]', 'varchar(30)'), '') <> ''
					FOR XML PATH('regimeIOSS'), TYPE),	
					NULLIF(XML_DECL.DCL_DATA.value('CodNatureza[1]', 'varchar(3)'), '') AS "natureza", 
					NULLIF(XML_DECL.DCL_DATA.value('NumDocTransporte[1]', 'varchar(18)'), '') AS "documentoTransporte",
					(SELECT NULLIF(XML_DECL.DCL_DATA.value('NIFExpedidor[1]', 'varchar(18)'), '') AS "nif", 
						NULLIF(XML_DECL.DCL_DATA.value('NomeExpedidor[1]', 'varchar(70)'), '') AS "nome", 
						NULLIF(XML_DECL.DCL_DATA.value('MoradaExpedidor[1]', 'varchar(70)'), '') AS "morada", 
						NULLIF(XML_DECL.DCL_DATA.value('LocalidadeExpedidor[1]', 'varchar(35)'), '') AS "localidade", 
						NULLIF(XML_DECL.DCL_DATA.value('CodPostalExpedidor[1]', 'varchar(12)'), '') AS "codigoPostal", 
						NULLIF(XML_DECL.DCL_DATA.value('LocPostalExpedidor[1]', 'varchar(35)'), '') AS "localidadePostal", 
						NULLIF(XML_DECL.DCL_DATA.value('CodPaisExpedidor[1]', 'varchar(2)'), '') AS "pais"
					HAVING NULLIF(XML_DECL.DCL_DATA.value('NomeExpedidor[1]', 'varchar(70)'), '') <> ''
					FOR XML PATH('exportador'), TYPE),
					(SELECT ISNULL(NULLIF(XML_DECL.DCL_DATA.value('NIFDestinatario[1]', 'varchar(18)'), ''), '999999990') AS "nif", 
						NULLIF(XML_DECL.DCL_DATA.value('NomeDestinatario[1]', 'varchar(70)'), '') AS "nome", 
						NULLIF(XML_DECL.DCL_DATA.value('MoradaDestinatario[1]', 'varchar(70)'), '') AS "morada", 
						NULLIF(XML_DECL.DCL_DATA.value('LocalidadeDestinatario[1]', 'varchar(35)'), '') AS "localidade", 
						NULLIF(XML_DECL.DCL_DATA.value('CodPostalDestinatario[1]', 'varchar(12)'), '') AS "codigoPostal", 
						NULLIF(XML_DECL.DCL_DATA.value('LocalidadeDestinatario[1]', 'varchar(35)'), '') AS "localidadePostal", 
						NULLIF(XML_DECL.DCL_DATA.value('CodPaisDestinatario[1]', 'varchar(2)'), '') AS "pais" 			
					FOR XML PATH('importador'), TYPE),
					NULLIF(XML_DECL.DCL_DATA.value('CodDeclarante[1]', 'varchar(6)'), '') AS "declarante/codigoDeclarante",					
					NULLIF(XML_DECL.DCL_DATA.value('CodEstancia[1]', 'varchar(8)'), '') AS "estancia", 
					'A' AS "tipoDeclaracao", 						
					NULLIF(XML_DECL.DCL_DATA.value('CodCondEntrega[1]', 'varchar(3)'), '') AS "condEntrega",
					NULLIF(XML_DECL.DCL_DATA.value('CodMeioTransporte18[1]', 'varchar(2)'), '') AS "meioTransporte", 						
					(SELECT 'B' AS "tipoLocalizacao", 
						'Y' AS "qualificador", 
						'DTP00000969236PT' AS "armazemDTP"						
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					NULLIF(XML_DECL.DCL_DATA.value('CodPais22[1]', 'varchar(2)'), '') AS "paisMoedaFatura", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('MoedaFrete[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaCustosTransporte", 				
					(CONVERT(varchar(10), XML_DECL.DCL_DATA.value('DataPrevVoo[1]', 'datetime'), 127) + 'Z') AS "dadosAWB/dataVoo", 		 																
					(SELECT TOP 1
						(SELECT 0 AS "tipoDocumento", 
							NULLIF(XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)'), '') AS "codigoDocumento",
							NULLIF(XML_DOCS.DOC_DATA.value('NumeroReferencia[1]', 'varchar(35)'), '') AS "numeroDocumento"						
						FROM XML_DECL.DCL_DATA.nodes('Adicoes/Adicao/Documentos/Documento/.') AS XML_DOCS(DOC_DATA)
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI																	
						WHERE doc.DOC_DTRA = 0
						FOR XML PATH('documento'), TYPE)
					FROM XML_DECL.DCL_DATA.nodes('Adicoes/Adicao/Documentos/Documento/.') AS XML_DOCS(DOC_DATA)
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI																	
						WHERE doc.DOC_DTRA = 0		
					FOR XML PATH('documentosECertificados'), TYPE), 
					(SELECT
						(SELECT 'N750' AS "codigoDocumento", 
							NULLIF(XML_MVOL.MVL_DATA.value('Numero[1]', 'varchar(20)'), '') AS "numeroDocumento"			
						FROM XML_DECL.DCL_DATA.nodes('Adicoes/Adicao/MarcasEVolumes/MarcaEVolume/.') AS XML_MVOL(MVL_DATA)	
						WHERE XML_DECL.DCL_DATA.exist('Adicoes/Adicao/Documentos/Documento[CodDocumento=''N337'']') = 0		
						FOR XML PATH('documentoPrecedente'), TYPE),
						(SELECT NULLIF(XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)'), '') AS "codigoDocumento", 
							NULLIF(XML_DOCS.DOC_DATA.value('NumeroReferencia[1]', 'varchar(35)'), '') AS "numeroDocumento"			
						FROM XML_DECL.DCL_DATA.nodes('Adicoes/Adicao/Documentos/Documento/.') AS XML_DOCS(DOC_DATA)
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI																	
						WHERE doc.DOC_CA40 = 1 AND doc.DOC_CODI = 'N337'
						FOR XML PATH('documentoPrecedente'), TYPE)			
					FOR XML PATH('documentosPrecedentes'), TYPE), 											
					(SELECT
						(SELECT XML_ADIC.ADI_DATA.value('NumAdicao[1]', 'int') AS "numeroAdicao", 
							ISNULL((SELECT TOP 1 NULLIF(APA_CPAU, '') FROM TAB_APAU WITH(NOLOCK) WHERE APA_CODI = NULLIF(XML_ADIC.ADI_DATA.value('CodArtigoPautal[1]', 'varchar(22)'), '')), '9999999999') AS "codigoPautal", 
							ISNULL(NULLIF(XML_ADIC.ADI_DATA.value('Designacao[1]', 'varchar(150)'), ''), 'NÃO CLASSIFICADO') AS "designacao", 	
							NULLIF(XML_ADIC.ADI_DATA.value('RegimeB[1]', 'varchar(3)'), '') AS "adicionalRegimeB", 						
							NULLIF(XML_ADIC.ADI_DATA.value('CodPaisOrigem[1]', 'varchar(2)'), '') AS "paisOrigem",							
							CAST(XML_ADIC.ADI_DATA.value('MassaBruta[1]', 'decimal(28, 6)') AS decimal(18, 6)) AS "massaBruta",														
							CAST(ISNULL(XML_ADIC.ADI_DATA.value('QtdUnidades[1]', 'decimal(28, 6)'), 0) AS decimal(18, 6)) AS "unidades",							
							CAST(XML_ADIC.ADI_DATA.value('(MarcasEVolumes/MarcaEVolume/QtdVolumes)[1]', 'decimal(28, 6)') AS int) AS "volumes", 
							NULLIF(XML_DECL.DCL_DATA.value('CodPais22[1]', 'varchar(2)'), '') AS "paisMoedaFatura", 
							CAST(XML_ADIC.ADI_DATA.value('PrecoAdicao[1]', 'decimal(28, 6)') AS decimal(18, 2)) AS "montante", 
							ISNULL(NULLIF(XML_DECL.DCL_DATA.value('MoedaFrete[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaCustosTransporte", 
							CAST(ISNULL(XML_ADIC.ADI_DATA.value('ValorFrete[1]', 'decimal(28, 6)'), 0) AS decimal(18, 2)) AS "custosTransporte", 
							NULLIF(XML_ADIC.ADI_DATA.value('(MarcasEVolumes/MarcaEVolume/Loptica)[1]', 'varchar(30)'), '') AS "codigoBarras", 
							NULLIF(XML_ADIC.ADI_DATA.value('(MarcasEVolumes/MarcaEVolume/Numero)[1]', 'varchar(20)'), '') AS "numeroObjeto"
						FROM XML_DECL.DCL_DATA.nodes('Adicoes/Adicao/.') as XML_ADIC(ADI_DATA) 			
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE)
				FROM @FicheiroXML.nodes('DeclaracoesImpToGIDWin/Declaracao') AS XML_DECL(DCL_DATA)
				WHERE NOT EXISTS(SELECT id FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE (ano = YEAR(@DataAtual) OR ano = (YEAR(@DataAtual) - 1)) AND documentoTransporte = NULLIF(XML_DECL.DCL_DATA.value('NumDocTransporte[1]', 'varchar(18)'), ''))
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAR
		SET @Erro = ''
		EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @Erro OUTPUT						
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaFicheiroCTT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaFicheiroCTT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaFicheiroDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaFicheiroDHL] @FicheiroXML xml, @Gateway varchar(3), @MsgDate datetime, @XMLDadosRestricao xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin)
	DECLARE @TblAdicoes TABLE(
		id int NOT NULL IDENTITY(1, 1), 	
		documentoTransporte varchar(18) NOT NULL, 	
		totalAdicoes int NOT NULL,
		totalMassaBruta decimal(18, 6) NOT NULL,
		totalCustosTransporte decimal(18, 2) NOT NULL, 
		numeroAdicao int NOT NULL, 
		codigoPautal varchar(22) NULL, 
		designacao varchar(260) NULL, 
		codPaisOrigem varchar(2) NULL, 
		unidades decimal(18, 6) NOT NULL,
		massaBruta decimal(18, 6) NOT NULL, 
		montante decimal(18, 2) NOT NULL,
		custosTransporte decimal(18, 2) NOT NULL)									
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem as adições agrupadas por código pautal do ficheiro XML
		INSERT INTO @TblAdicoes(	
			documentoTransporte, 	
			totalAdicoes, 
			totalMassaBruta, 
			totalCustosTransporte, 	
			numeroAdicao, 
			codigoPautal, 
			designacao, 
			codPaisOrigem, 
			unidades,
			massaBruta, 
			montante,
			custosTransporte)
		SELECT 			
			t.documentoTransporte, 
			COUNT(*) OVER(PARTITION BY t.documentoTransporte), 
			ISNULL(t.totalMassaBruta, 0), 
			ISNULL(t.totalCustosTransporte, 0), 
			ROW_NUMBER() OVER(PARTITION BY t.documentoTransporte ORDER BY t.codigoPautal, t.designacao, t.codPaisOrigem), 
			NULLIF(t.codigoPautal, ''), 
			NULLIF(t.designacao, ''), 
			NULLIF(t.codPaisOrigem, ''), 
			SUM(ISNULL(t.unidades, 0)), 
			0, 
			SUM(ABS(ISNULL(t.montante, 0))),
			0
		FROM (SELECT 
				l.c.value('(../../HAWB)[1]', 'varchar(18)') AS documentoTransporte, 
				l.c.value('(../../GrossWgt)[1]', 'numeric(28, 6)') AS totalMassaBruta, 
				CAST(NULLIF(l.c.value('(../../CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHG"]/Val)[1]', 'varchar(255)'), '') AS decimal(18, 2)) AS totalCustosTransporte, 
				(CASE 
					WHEN r.c.value('numero[1]', 'int') IS NOT NULL THEN r.c.value('../artigoPautal[1]', 'varchar(22)')
					ELSE ISNULL(NULLIF(art.APA_CPAU, ''), '9999999999') 
				END) AS codigoPautal, 
				(CASE 
					WHEN r.c.value('numero[1]', 'int') IS NOT NULL THEN (NULLIF(r.c.value('../designacaoPautal[1]', 'varchar(150)'), '') + ' - ' + NULLIF(l.c.value('TariffCdNo[1]', 'varchar(18)'), ''))
					ELSE ISNULL(ISNULL(NULLIF(art.APA_DESG, ''), NULLIF(l.c.value('DescOfGoods[1]', 'varchar(260)'), '')), 'NÃO CLASSIFICADO') 
				END) AS designacao, 
				l.c.value('CtryOrgnCd[1]', 'varchar(2)') AS codPaisOrigem, 
				CAST(NULLIF(l.c.value('TariffQnty[1]', 'varchar(20)'), '') AS decimal(18, 6)) AS unidades, 
				l.c.value('InvLineVal[1]', 'decimal(18, 3)') AS montante				
			FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp/LineItems/LineItem') AS l(c)								 				
				LEFT OUTER JOIN @XMLDadosRestricao.nodes('DadosRestricao/AdicaoRestrita') AS r(c) ON l.c.value('GoodsItemNo[1]', 'int') = r.c.value('numero[1]', 'int')
				OUTER APPLY (SELECT TOP 1 APA_CPAU, APA_DESG FROM TAB_APAU WITH(NOLOCK) WHERE APA_CPAU = LEFT(NULLIF(l.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6)) AS art
			) AS t								
		GROUP BY t.documentoTransporte, t.totalMassaBruta, t.totalCustosTransporte, t.codigoPautal, t.designacao, t.codPaisOrigem
-- processa calculos para os campos de massa bruta e custos de transporte de cada adição em função do total de adições apurado
		UPDATE @TblAdicoes SET 			
			massaBruta = (ROUND((ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) / totalAdicoes), 3, 1) + (CASE 
																													WHEN (totalAdicoes > 1) AND (numeroAdicao = totalAdicoes) THEN (ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) - ROUND((ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) / totalAdicoes), 3, 1) * numeroAdicao)
																													ELSE 0
																												END)), 
			custosTransporte = (CASE 
									WHEN totalCustosTransporte >= 1 THEN (ROUND((totalCustosTransporte / totalAdicoes), 2) + (CASE 
																																WHEN (totalAdicoes > 1) AND (numeroAdicao = totalAdicoes) THEN (totalCustosTransporte - ROUND((totalCustosTransporte / totalAdicoes), 2) * numeroAdicao)
																																ELSE 0
																															END))
									ELSE 0
								END)				
-- constroi XML para declaração DAR a partir do ficheiro XML no formato DHL
		SET @XMLDeclaracaoDAR = 
			(SELECT
				(SELECT 'I' AS "@acao", 
					(CONVERT(varchar(10), GETDATE(), 127) + 'Z') AS "data",					
					(CASE 
						WHEN ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpExper/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), '')) <> '' THEN 1 
						WHEN SUBSTRING(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(25)'), ''), 1, 1) IN ('1', '2', '3', '4') THEN 2
						WHEN SUBSTRING(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(25)'), ''), 1, 1) NOT IN ('1', '2', '3', '4') THEN 3					
						WHEN NULLIF(XML_DECL.DCL_DATA.value('(DatElGrp[@Cd="ShpClss"]/DatEl[Cd="Clss"]/Val)[1]', 'varchar(255)'), '') IN ('B2B', 'B2BB', 'C2B') THEN 3
						ELSE 2
					END) AS "regimeIVA",  		 
					'C07' AS "adicionalRegime", 
					(SELECT 
						(CASE 
							WHEN ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), ''), '')) <> 'PT' THEN 'FR1'			
							ELSE 'FR5' 
						END) AS "funcao", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpExper/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), '')) AS "numeroIdentificacaoIVA"
					HAVING ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpExper/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), '')) <> ''
					FOR XML PATH('regimeIOSS'), TYPE),		
					(CASE 
						WHEN ISNULL(XML_REST.RES_DATA.value('natureza[1]', 'varchar(3)'), '') <> '' THEN XML_REST.RES_DATA.value('natureza[1]', 'varchar(3)')
						WHEN ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpExper/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), '')) <> '' THEN 'H7S'
						WHEN ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(LineItems/LineItem/TariffCdNo)[1]', 'varchar(18)'), ''), '') <> '' THEN 'H7C'			
						ELSE 'H7N' 
					END) AS "natureza", 
					NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') AS "documentoTransporte",
					(SELECT 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/CoName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCntctDtls/PreferredName)[1]', 'varchar(70)'), ''), '.')) AS "nome", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''), '.') AS "morada", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.') AS "localidade", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0') AS "codigoPostal", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.') AS "localidadePostal", 						
						(CASE ISNULL(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') WHEN 'IC' THEN 'ES' ELSE NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') END) AS "pais"		
					FOR XML PATH('exportador'), TYPE),
					(SELECT 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(18)'), ''), '999999990') AS "nif", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCntctDtls/PreferredName)[1]', 'varchar(70)'), ''), '.'))) AS "nome", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''),  ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''), '.')))) AS "morada", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.')) AS "localidade", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0')) AS "codigoPostal", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.')) AS "localidadePostal", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '')) AS "pais", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="TEL"]/DeviceDtls)[1]', 'varchar(15)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="TEL"]/DeviceDtls)[1]', 'varchar(15)'), '')) AS "telefone", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="EML"]/DeviceDtls)[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="EML"]/DeviceDtls)[1]', 'varchar(70)'), '')) AS "email"
					FOR XML PATH('importador'), TYPE),
					'00' AS "declarante/codigoDeclarante",				
					(CASE @Gateway WHEN 'LIS' THEN 'PT000015' ELSE 'PT000020' END) AS "estancia", 
					'A' AS "tipoDeclaracao", 					
					XML_DECL.DCL_DATA.value('Incoterms[1]', 'varchar(3)') AS "condEntrega",
					'40' AS "meioTransporte",		
					(SELECT 
						'B' AS "tipoLocalizacao", 
						'Y' AS "qualificador", 
						(CASE @Gateway WHEN 'LIS' THEN 'DTP00000487015PT' ELSE 'DTP00000473020PT' END) AS "armazemDTP"						
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaFatura", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHGCurCd"]/Val)[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaCustosTransporte", 				
					(SELECT 
						NULLIF(XML_DECL.DCL_DATA.value('(DatElGrp[@Cd="ShpClss"]/DatEl[Cd="Clss"]/Val)[1]', 'varchar(6)'), '') AS "locID", 
						@Gateway AS "gateway", 			
						CAST(NULLIF(XML_DECL.DCL_DATA.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHG"]/Val)[1]', 'varchar(255)'), '') AS decimal(18, 2)) AS "freteOriginal", 
						NULLIF(XML_DECL.DCL_DATA.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHGCurCd"]/Val)[1]', 'varchar(2)'), '') AS "moedafreteOriginal"			
					FOR XML PATH('dadosEspecificos'), TYPE),
					(SELECT 
						NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/DHLAcctNo)[1]', 'varchar(10)'), '') AS "numeroContaExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/DutyAcct)[1]', 'varchar(10)'), '') AS "numeroContaDestinatario", 			
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(70)'), '')) AS "nomeOriginalDestinatario", 
						ISNULL(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), '')), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''))) AS "moradaOriginalDestinatario", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) AS "localidadeOriginalDestinatario", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), '')) AS "codigoPostalOriginalDestinatario", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) AS "localidadePostalOriginalDestinatario", 
						ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(50)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(50)'), '')) AS "referenciaExterna1", 
						ISNULL(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(50)'), '')), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(50)'), ''))) AS "referenciaExterna2", 
						NULLIF(XML_DECL.DCL_DATA.value('ProdContentCd[1]', 'varchar(3)'), '') AS "shipID"
					FOR XML PATH('dadosEntidades'), TYPE),
					(SELECT 
						NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') AS "miniCPA", 
						NULLIF(XML_DECL.DCL_DATA.value('ShpOrgn[1]', 'varchar(6)'), '') AS "aeroportoOrigem"			
					FOR XML PATH('dadosAWB'), TYPE),		 
					(SELECT 
						(CONVERT(varchar(10), @MsgDate, 127) + 'Z') AS "dataDocumentoTransporte"			
					FOR XML PATH('outrosDados'), TYPE),		 																
					(SELECT TOP 1
						(SELECT 
							t.DocContext AS "tipoDocumento", 
							t.DocType AS "codigoDocumento",
							t.DocRefNo AS "numeroDocumento"						
						FROM (SELECT 2 AS DocContext, 
								(CASE NULLIF(XML_DOCS.DOC_DATA.value('DocType[1]', 'varchar(20)'), '')
									WHEN 'ATA' THEN 'N955'
									WHEN 'ATR' THEN 'N041'
									WHEN 'EU1' THEN 'N954'
									WHEN 'FMA' THEN 'N865'
									WHEN 'PHY' THEN 'N851'
									WHEN 'VET' THEN 'N853'
									ELSE NULL
								END) AS DocType, 
								ISNULL(NULLIF(XML_DOCS.DOC_DATA.value('DocRefNo[1]', 'varchar(70)'), ''), 'XXXXXXXXXX') AS DocRefNo
							FROM XML_DECL.DCL_DATA.nodes('LineItems/LineItem/AddDocInfo/.') AS XML_DOCS(DOC_DATA)
							WHERE XML_DOCS.DOC_DATA.value('(../GoodsItemNo)[1]', 'int') = 1 AND NULLIF(XML_DOCS.DOC_DATA.value('DocType[1]', 'varchar(20)'), '') IN ('ATA', 'ATR', 'EU1', 'FMA', 'PHY', 'VET')
							UNION
							SELECT 0 AS DocContext, 
								'N380' AS DocType, 
								ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(LineItems/LineItem/InvNo)[1]', 'varchar(35)'), ''), 'XXXXXXXXXX') AS DocRefNo
						) AS t INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON t.DocType = doc.DOC_CODI																	
						WHERE doc.DOC_DTRA = 0			
						FOR XML PATH('documento'), TYPE)
					FROM (SELECT 2 AS DocContext, 
								(CASE NULLIF(XML_DOCS.DOC_DATA.value('DocType[1]', 'varchar(20)'), '')
									WHEN 'ATA' THEN 'N955'
									WHEN 'ATR' THEN 'N041'
									WHEN 'EU1' THEN 'N954'
									WHEN 'FMA' THEN 'N865'
									WHEN 'PHY' THEN 'N851'
									WHEN 'VET' THEN 'N853'
									ELSE NULL
								END) AS DocType, 
								ISNULL(NULLIF(XML_DOCS.DOC_DATA.value('DocRefNo[1]', 'varchar(70)'), ''), 'XXXXXXXXXX') AS DocRefNo
						FROM XML_DECL.DCL_DATA.nodes('LineItems/LineItem/AddDocInfo/.') AS XML_DOCS(DOC_DATA)
						WHERE XML_DOCS.DOC_DATA.value('(../GoodsItemNo)[1]', 'int') = 1 AND NULLIF(XML_DOCS.DOC_DATA.value('DocType[1]', 'varchar(20)'), '')	IN ('ATA', 'ATR', 'EU1', 'FMA', 'PHY', 'VET')
						UNION
						SELECT 0 AS DocContext, 
							'N380' AS DocType, 
							ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(LineItems/LineItem/InvNo)[1]', 'varchar(35)'), ''), 'XXXXXXXXXX') AS DocRefNo
					) AS t INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON t.DocType = doc.DOC_CODI																	
					WHERE doc.DOC_DTRA = 0
					FOR XML PATH('documentosECertificados'), TYPE), 
					(SELECT TOP 1
						(SELECT INF_CODI AS "codigoMencao"		
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_CODI = 'RBVDP'	
						FOR XML PATH('mencao'), TYPE)		
					FROM TAB_INFC WITH(NOLOCK)
					WHERE INF_CODI = 'RBVDP'
					FOR XML PATH('informacoesAdicionais'), TYPE), 											
					(SELECT
						(SELECT 
							adi.numeroAdicao AS "numeroAdicao", 
							adi.codigoPautal AS "codigoPautal", 
							adi.designacao AS "designacao", 	
							(CASE 
								WHEN ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpExper/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="SDT"]/TraderRefId)[1]', 'varchar(35)'), '')) <> '' THEN 'F48' 
								WHEN SUBSTRING(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(25)'), ''), 1, 1) IN ('1', '2', '3') THEN 'F49'
								WHEN SUBSTRING(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(25)'), ''), 1, 1) NOT IN ('1', '2', '3') THEN NULL					
								WHEN NULLIF(XML_DECL.DCL_DATA.value('(DatElGrp[@Cd="ShpClss"]/DatEl[Cd="Clss"]/Val)[1]', 'varchar(255)'), '') IN ('B2B', 'B2BB', 'C2B') THEN NULL
								ELSE 'F49'
							END) AS "adicionalRegimeB", 													
							(CASE 
								WHEN ISNULL(adi.codPaisOrigem, '') IN ('DE', 'AT', 'BE', 'BG', 'CY', 'HR', 'DK', 'SK', 'SI', 'ES', 'EE', 'FI', 'FR', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'CZ', 'RO', 'SE') THEN 'EU' 
								WHEN ISNULL(adi.codPaisOrigem, '') = 'IC' THEN 'ES'
								ELSE adi.codPaisOrigem 
							END) AS "paisOrigem", 																																																					
							CAST(adi.massaBruta AS decimal(18, 6)) AS "massaBruta", 																																			
							CAST(adi.unidades AS decimal(18, 6)) AS "unidades", 
							(CASE adi.numeroAdicao WHEN 1 THEN XML_DECL.DCL_DATA.value('SDPieces[1]', 'int') ELSE 0 END) AS "volumes", 				
							ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaFatura", 
							CAST(adi.montante AS decimal(18, 2)) AS "montante", 
							ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHGCurCd"]/Val)[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaCustosTransporte", 
							CAST(adi.custosTransporte AS decimal(18, 2)) AS "custosTransporte"
						FROM @TblAdicoes AS adi 								
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE), 
					(SELECT TOP 1
						(SELECT 
							0 AS "tipoManifesto", 
							NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') AS "paisManifesto", 
							NULLIF(XML_DECL.DCL_DATA.value('(LineItems/LineItem/DescOfGoods)[1]', 'varchar(150)'), '') AS "descricao", 
							CAST(0 AS decimal(18, 3)) AS "valor", 
							ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaManifesto", 
							CAST(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtTINVA"]/Val)[1]', 'varchar(255)'), ''), 0) AS decimal(18, 3)) AS "totalFatura", 
							(NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') + (CASE number 
																								WHEN 1 THEN '' 
																								ELSE ('_' + CAST((number - 1) AS varchar(10))) 
																							END)) AS "numeroCPA", 
							CAST(ROUND(XML_DECL.DCL_DATA.value('GrossWgt[1]', 'decimal(28, 5)'), 6) AS numeric(18, 3)) AS "peso"	
						FROM master.dbo.spt_values 
						WHERE number >= 1 AND number <= XML_DECL.DCL_DATA.value('SDPieces[1]', 'int')
						GROUP BY number
						FOR XML PATH('manifesto'), TYPE)		
					FROM master.dbo.spt_values 
					WHERE number >= 1 AND number <= XML_DECL.DCL_DATA.value('SDPieces[1]', 'int')
					GROUP BY number		
					FOR XML PATH('manifestos'), TYPE)
				FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp') AS XML_DECL(DCL_DATA)
					OUTER APPLY @XMLDadosRestricao.nodes('DadosRestricao') AS XML_REST(RES_DATA)
				WHERE NOT EXISTS(SELECT id FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE ano = YEAR(@DataAtual) AND documentoTransporte = NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), ''))
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAR
		SET @Erro = ''
		EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @Erro OUTPUT						
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaFicheiroDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaFicheiroDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaFicheiroFEDEX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaFicheiroFEDEX] @FicheiroASCII varchar(MAX), @CodAlfandega varchar(8), @DataVoo datetime, @TipoManifesto int, @CodNatureza varchar(3), 
	@NumeroNRMMSTI varchar(70), @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON		
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @Delimiter CHAR(2), @NextPos int, @LastPos int, @Linha varchar(MAX), @TXTTipoLinha varchar(4), @TXTAcao varchar(1), 
		@TXTDocTransporte varchar(35), @TXTCodPaisMoeda varchar(2),  @TXTCodAlfandega varchar(8), @ValorEUR decimal(18, 3), @IdDeclaracao int, 
		@XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin), @ErroImportacao varchar(MAX)
	DECLARE @tmpTbFicheiro TABLE(ID int IDENTITY NOT NULL,							
							TipoLinha varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
							Acao varchar(1) COLLATE Latin1_General_CI_AI NOT NULL,
							DocTransporte varchar(35) COLLATE Latin1_General_CI_AI NOT NULL,
							CodPaisMoeda varchar(2) COLLATE Latin1_General_CI_AI NOT NULL,
							CodAlfandega varchar(8) COLLATE Latin1_General_CI_AI NOT NULL,
							DadosLinha varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL,
							ValorEUR decimal(18, 2) NOT NULL,
							IdDeclaracao int NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração das declarações DAR
	BEGIN TRY	
		SET @NumErro = 0
-- inicia variáveis
		SET @Delimiter = CHAR(13) + CHAR(10)
		SET @LastPos = 0
		SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, 1)
-- percorre as linhas do ficheiro e insere os respetivos dados na tabela tmp
		WHILE @NextPos > 0
		BEGIN
			SET @Linha = SUBSTRING(@FicheiroASCII, @LastPos, @NextPos - @LastPos)	
-- obtem o tipo de linha e número documento de transporte
			SET @TXTTipoLinha = LTRIM(RTRIM(SUBSTRING(@Linha, 1, 4)))	
-- se linha for "CGER", obtem número documento de transporte de nova declaração
			IF @TXTTipoLinha = 'CGER'
			BEGIN
				SET @TXTDocTransporte = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 8, 18))), '')
				SET @TXTCodPaisMoeda = (CASE NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 640, 2))), '')
											WHEN 'DH' THEN 'AE' 
											WHEN 'SF' THEN 'CH' 
											WHEN 'UK' THEN 'GB' 
											WHEN 'JY' THEN 'JP' 
											WHEN 'SI' THEN 'SG' 
											WHEN 'NT' THEN 'TW' 
											ELSE NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 640, 2))), '')
										END)
				SET @ValorEUR = ROUND((CAST(STUFF(RTRIM(LTRIM(SUBSTRING(@Linha, 642, 13))), 11, 0, '.') AS decimal(18, 3)) / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) 
											WHEN @TXTCodPaisMoeda THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
											ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
												FROM TAB_CPAI WITH(NOLOCK)
												WHERE PAI_CODI = @TXTCodPaisMoeda AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
												ORDER BY CPA_DATA DESC) 
											END), 1)), 2)	
				SET	@TXTCodAlfandega = (CASE @TipoManifesto 							
											WHEN 0 THEN (CASE 
															WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(@Linha, 1114, 3))), '') IN ('LIS', 'FNC', 'FAO', 'PXO') THEN 'PT000015' 
															ELSE 'PT000020' 
														END)
											ELSE @CodAlfandega 
										END)				
				IF (@TipoManifesto = 2) OR ((@TipoManifesto = 1) AND EXISTS(SELECT id 
																			FROM tb_DeclaracoesDAR WITH(NOLOCK) 
																			WHERE ano = YEAR(@DataAtual) AND documentoTransporte = @TXTDocTransporte AND dataVoo >= @DataVoo)) 
				BEGIN
					SET @TXTAcao = 'U'
					SET @IdDeclaracao = (SELECT TOP 1 id 
										FROM tb_DeclaracoesDAR WITH(NOLOCK) 
										WHERE ano = YEAR(@DataAtual) AND documentoTransporte = @TXTDocTransporte AND dataVoo >= @DataVoo
										ORDER BY id DESC)
				END
				ELSE 
				BEGIN
					SET @TXTAcao = 'I'							
					SET @IdDeclaracao = NULL
				END	
			END
-- insere dados da linha na tabela tmp
			INSERT INTO @tmpTbFicheiro (TipoLinha, Acao, DocTransporte, CodPaisMoeda, CodAlfandega, DadosLinha, ValorEUR, IdDeclaracao)
			VALUES (@TXTTipoLinha, @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @TXTCodAlfandega, @Linha, @ValorEUR, @IdDeclaracao)
-- incrementa variáveis
			SET @LastPos = @NextPos + 2
			SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, @NextPos + 1)			
		END
-- inicia variaveis
		SET @Erros = ''
-- obtem lista de declarações existentes dentro do ficheiro ASCII
		DECLARE DeclaracoesFEDEX CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
			SELECT Acao, DocTransporte, CodPaisMoeda, CodAlfandega, ValorEUR
			FROM @tmpTbFicheiro
			WHERE TipoLinha = 'CGER'	
		OPEN DeclaracoesFEDEX
		FETCH NEXT FROM DeclaracoesFEDEX INTO @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @TXTCodAlfandega, @ValorEUR
		WHILE @@FETCH_STATUS = 0
		BEGIN										
-- constroi XML para declaração DAR a partir do ficheiro ASCII no formato FEDEX
			SET @XMLDeclaracaoDAR = 
				(SELECT
					(SELECT @TXTAcao AS "@acao", 
						(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data",					
						(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1122, 20))), '') 
							WHEN '' THEN 2 
							ELSE 1
						END) AS "regimeIVA",  		 
						'C07' AS "adicionalRegime", 	
						(SELECT 
							(CASE 
								WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') <> 'PT' THEN 'FR1'			
								ELSE 'FR5' 
							END) AS "funcao", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1122, 20))), '') AS "numeroIdentificacaoIVA"
						HAVING ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1122, 20))), '') <> ''
						FOR XML PATH('regimeIOSS'), TYPE),	
						(CASE 
							WHEN ISNULL(@CodNatureza, '') <> '' THEN @CodNatureza
							WHEN @TXTAcao = 'U' THEN (CASE 
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.id = cge.IdDeclaracao AND dar.regimeIVA = 1 AND nat.NDE_CODI = '20') THEN '25'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.id = cge.IdDeclaracao AND SUBSTRING(dar.nifCliente, 1, 1) IN ('1', '2', '3') AND nat.NDE_CODI = '20') THEN '26'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.id = cge.IdDeclaracao AND SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9') AND dar.nifCliente <> '999999990' AND nat.NDE_CODI = '20') THEN '27'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.id = cge.IdDeclaracao AND dar.nifCliente = '999999990' AND nat.NDE_CODI = '96') THEN '89'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.id = cge.IdDeclaracao AND dar.nifCliente = '999999990' AND nat.NDE_CODI = '20') THEN '28'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.id = cge.IdDeclaracao AND nat.NDE_CODI = 'DAR') THEN '89'
									ELSE (SELECT TOP 1 nat.NDE_CODI FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.id = cge.IdDeclaracao)
								END)
							ELSE 'DAR'
						END) AS "natureza", 
						@TXTDocTransporte AS "documentoTransporte",
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 56, 70))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 126, 70))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidade", 
							'0' AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') AS "pais"		
						FOR XML PATH('exportador'), TYPE),
						(SELECT '999999990' AS "nif", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidade", 
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), ''), '0') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') AS "pais", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 268, 14))), '') AS "telefone"
						FOR XML PATH('importador'), TYPE),
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 547, 6))), '') AS "declarante/codigoDeclarante",				
						@TXTCodAlfandega AS "estancia", 
						'A' AS "tipoDeclaracao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1037, 50))), '') AS "vossaReferencia", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') AS "condEntrega",
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 553, 2))), '') AS "meioTransporte", 		
						(SELECT 'B' AS "tipoLocalizacao", 
							'Y' AS "qualificador", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 623, 16))), '') AS "armazemDTP"						
						FOR XML PATH('localizacaoMercadorias'), TYPE),
						@TXTCodPaisMoeda AS "paisMoedaFatura", 
						'EU' AS "paisMoedaCustosTransporte", 
						6 AS "followUp", 				
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1114, 3))), '') AS "locID", 
							(CASE 
								WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1114, 3))), '') IN ('LIS', 'FNC', 'FAO', 'PXO') THEN 'LIS' 
								ELSE 'OPO' 
							END) AS "gateway", 
							CAST(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1120, 2))), '') AS int) AS "serviceLevel", 								
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 690, 10))), '') AS "portesAcc", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 954, 13))), '') AS "portes",
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 801, 50))), '') AS "despachoAcc"							
						FOR XML PATH('dadosEspecificos'), TYPE),
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 690, 10))), '') AS "numeroContaDestinatario", 			
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nomeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "moradaOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidadeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), '') AS "codigoPostalOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostalOriginalDestinatario", 						
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 801, 50))), '') AS "referenciaExterna1", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 851, 50))), '') AS "referenciaExterna2"
						FOR XML PATH('dadosEntidades'), TYPE),
						(SELECT (CONVERT(varchar(10), @DataVoo, 127) + 'Z') AS "dataVoo", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 700, 80))), '') AS "aeroportoOrigem", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 782, 8))), '') AS "numeroVoo", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 954, 13))), '') AS "posicaoAviao", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 912, 35))), '') AS "tracking", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 949, 2))), '') AS "tipoCarga"
						FOR XML PATH('dadosAWB'), TYPE),		 
						(SELECT (CASE NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 947, 2))), '') 
									WHEN '03' THEN '03' 
									ELSE (CASE 
											WHEN ROUND((@ValorEUR * ISNULL((SELECT TOP 1 ISNULL(CPA_VEND, 1) 
												FROM TAB_CPAI WITH(NOLOCK)
												WHERE PAI_CODI = 'US' AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
												ORDER BY CPA_DATA DESC), 1)), 2) >= 750 THEN '01' 
											ELSE '02' 
										END) 
								END) AS "dutyType", 
							 CAST(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 679, 1))), '') AS int) AS "payment"			
						FOR XML PATH('outrosDados'), TYPE),	
						(SELECT TOP 1
							(SELECT 0 AS "tipoDocumento",
								DOC_CODI AS "codigoDocumento", 
								@NumeroNRMMSTI AS "numeroDocumento"
							FROM TAB_DOCU WITH(NOLOCK)
							WHERE DOC_DESP = 1 AND DOC_DTRA = 0 AND DOC_CODI = 'N821' AND ISNULL(@NumeroNRMMSTI, '') <> ''
							FOR XML PATH('documento'), TYPE)
						FROM TAB_DOCU WITH(NOLOCK)
						WHERE DOC_DESP = 1 AND DOC_DTRA = 0 AND DOC_CODI = 'N821' AND ISNULL(@NumeroNRMMSTI, '') <> ''
						FOR XML PATH('documentosECertificados'), TYPE), 	 																					
						(SELECT TOP 1
							(SELECT INF_CODI AS "codigoMencao"		
							FROM TAB_INFC WITH(NOLOCK)
							WHERE INF_CODI = 'RBVDP'	
							FOR XML PATH('mencao'), TYPE)		
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_CODI = 'RBVDP'
						FOR XML PATH('informacoesAdicionais'), TYPE), 											
						(SELECT
							(SELECT 1 AS "numeroAdicao", 
								'9999999999' AS "codigoPautal",								
								ISNULL((SELECT TOP 1 NULLIF(RTRIM(LTRIM(SUBSTRING(DadosLinha, 7, 104))), '') FROM @tmpTbFicheiro WHERE TipoLinha = 'OUTD' AND DocTransporte = adi.DocTransporte), 'NÃO CLASSIFICADO') AS "designacao", 													
								NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 27, 2))), '') AS "paisOrigem",																			     
								CAST(ABS(CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 29, 13))), 11, 0, '.') AS decimal(18, 6)) - ISNULL((SELECT SUM(massaBruta) FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK) WHERE @TXTAcao = 'U' AND id_declaracaoDAR = cge.IdDeclaracao AND numeroAdicao > 1), 0)) AS decimal(18, 6)) AS "massaBruta", 
								CAST(0 AS decimal(18, 6)) AS "unidades", 
								CAST(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 99, 10))) AS int) AS "volumes", 				
								@TXTCodPaisMoeda AS "paisMoedaFatura", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 65, 13))), 11, 0, '.') AS decimal(18, 2)) AS "montante",
								'EU' AS "paisMoedaCustosTransporte", 				
								CAST(0 AS decimal(18, 2)) AS "custosTransporte"	
							FROM @tmpTbFicheiro AS adi
							WHERE adi.TipoLinha = 'ADIC' AND adi.DocTransporte = cge.DocTransporte					
							FOR XML PATH('adicao'), TYPE), 
							(SELECT adi.numeroAdicao AS "numeroAdicao", 
								(adi.codigoPautal + ISNULL(adi.codigoNC, '') + ISNULL(adi.codigoTARIC, '') + ISNULL(adi.adicionalTARIC1, '') + ISNULL(adi.adicionalTARIC2, '') + ISNULL(adi.adicionalTARIC3, '')) AS "codigoPautal",								
								adi.designacao AS "designacao", 													
								por.PAI_CODI AS "paisOrigem",											
								CAST(adi.massaBruta AS decimal(18, 6)) AS "massaBruta", 
								CAST(adi.unidades AS decimal(18, 6)) AS "unidades", 
								adi.volumes AS "volumes", 				
								pmo.PAI_CODI AS "paisMoedaFatura", 
								CAST(adi.montante AS decimal(18, 2)) AS "montante",
								pct.PAI_CODI AS "paisMoedaCustosTransporte", 				
								CAST(adi.custosTransporte AS decimal(18, 2)) AS "custosTransporte"	
							FROM tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) 
								LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON adi.id_paisOrigem = por.PAI_IDTY
								INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON adi.id_paisMoedaMontante = pmo.PAI_IDTY
								INNER JOIN TAB_PAIS AS pct WITH(NOLOCK) ON adi.id_paisMoedaCustosTransporte = pct.PAI_IDTY
							WHERE @TXTAcao = 'U' AND adi.id_declaracaoDAR = cge.IdDeclaracao AND adi.numeroAdicao > 1					
							FOR XML PATH('adicao'), TYPE)
						FOR XML PATH('adicoes'), TYPE), 
						(SELECT 							
							(SELECT @TipoManifesto AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								(CASE NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '')
									WHEN 'DH' THEN 'AE' 
									WHEN 'SF' THEN 'CH' 
									WHEN 'UK' THEN 'GB' 
									WHEN 'JY' THEN 'JP' 
									WHEN 'SI' THEN 'SG' 
									WHEN 'NT' THEN 'TW' 
									ELSE NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '')
								END) AS "paisMoedaManifesto", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "peso"
							FROM @tmpTbFicheiro AS otd
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte							
							FOR XML PATH('manifesto'), TYPE)															
						FOR XML PATH('manifestos'), TYPE)
					FROM @tmpTbFicheiro AS cge
					WHERE cge.TipoLinha = 'CGER' AND cge.DocTransporte = @TXTDocTransporte 					
					FOR XML PATH('declaracao'), TYPE)
				FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAR
			SET @ErroImportacao = ''
			EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @ErroImportacao OUTPUT									
			IF @NumErro <> 0
				SET @Erros = @Erros + 'Erro na importação da declaração DAR "' + @TXTDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)												
			FETCH NEXT FROM DeclaracoesFEDEX INTO @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @TXTCodAlfandega, @ValorEUR
		END
		CLOSE DeclaracoesFEDEX
		DEALLOCATE DeclaracoesFEDEX	
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
		IF ISNULL(@Erros, '') <> ''
			RAISERROR ('%s', 16, 3, @Erros)		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erros = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaFicheiroFEDEX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaFicheiroFEDEX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaFicheiroPortalDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaFicheiroPortalDHL] @FicheiroXML xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin)
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para declaração DAR a partir do ficheiro XML no formato portal DHL
		SET @XMLDeclaracaoDAR = 
			(SELECT
				(SELECT 'U' AS "@acao", 
					(CONVERT(varchar(10), dar.data, 127) + 'Z') AS "data",					
					dar.regimeIVA AS "regimeIVA",  		 
					dar.regimeAdicional AS "adicionalRegime", 
					(SELECT 
						dar.funcaoRegimeIOSS AS "funcao", 
						dar.numeroIdentificacaoIVA AS "numeroIdentificacaoIVA"
					HAVING ISNULL(dar.numeroIdentificacaoIVA, '') <> ''
					FOR XML PATH('regimeIOSS'), TYPE),		
					NULLIF(t.c.value('natureza[1]', 'varchar(3)'), '') AS "natureza", 
					NULLIF(t.c.value('documentoTransporte[1]', 'varchar(35)'), '') AS "documentoTransporte",					
					(SELECT 
						ISNULL(NULLIF(cli.CLI_NIF, ''), dar.nifCliente) AS "nif", 
						ISNULL(NULLIF(cli.CLI_NOME, ''), dar.nomeCliente) AS "nome", 
						ISNULL(NULLIF(cli.CLI_MORA, ''), dar.moradaCliente) AS "morada", 
						ISNULL(NULLIF(cli.CLI_LOCA, ''), dar.localidadeCliente) AS "localidade", 
						ISNULL(NULLIF(cli.CLI_CPOS, ''), dar.codPostalCliente) AS "codigoPostal", 
						ISNULL(NULLIF(cli.CLI_LPOS, ''), dar.locPostalCliente) AS "localidadePostal", 
						ISNULL(NULLIF(cli.PAI_CODI, ''), pim.PAI_CODI) AS "pais", 
						ISNULL(NULLIF(cli.CLI_TELF, ''), dar.telefoneCliente) AS "telefone", 
						ISNULL(NULLIF(cli.CLI_EMAI, ''), dar.emailCliente) AS "email"
					FOR XML PATH('importador'), TYPE),
					dcl.DEC_CODI AS "declarante/codigoDeclarante",				
					alf.ALF_CODI AS "estancia", 
					dar.tipoDeclaracao AS "tipoDeclaracao", 					
					cen.CEN_CODI AS "condEntrega",
					mtr.MTR_CODI AS "meioTransporte",		
					(SELECT 
						dar.localizacaoMercadorias AS "tipoLocalizacao", 
						dar.qualificador AS "qualificador", 
						lme.LME_CODI AS "armazemDTP", 
						alm.ALF_CODI AS "estancia"
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					ISNULL(NULLIF(t.c.value('paisMoedaFatura[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaFatura", 
					ISNULL(NULLIF(t.c.value('paisMoedaCustosTransporte[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaCustosTransporte", 									
					(SELECT 						
						'PORTAL-DHL' AS "despachoAcc"			
					FOR XML PATH('dadosEspecificos'), TYPE),		 																
					(SELECT TOP 1
						(SELECT 
							0 AS "tipoDocumento", 
							NULLIF(d.c.value('codigoDocumento[1]', 'varchar(5)'), '') AS "codigoDocumento",
							NULLIF(d.c.value('numeroDocumento[1]', 'varchar(70)'), '') AS "numeroDocumento"						
						FROM t.c.nodes('documentos/documento/.') AS d(c)
						FOR XML PATH('documento'), TYPE)
					FROM t.c.nodes('documentos/documento/.') AS d(c)
					FOR XML PATH('documentosECertificados'), TYPE), 					
					(SELECT
						(SELECT 
							a.c.value('numeroAdicao[1]', 'int') AS "numeroAdicao", 
							ISNULL(apa.APA_CPAU, '9999999999') AS "codigoPautal", 
							ISNULL(NULLIF(apa.APA_DESG, ''), 'NÃO CLASSIFICADO') AS "designacao", 
							pex.PAI_CODI AS "paisOrigem", 																											
							CAST(ISNULL(a.c.value('massaBruta[1]', 'decimal(18, 6)'), 0) AS decimal(18, 6)) AS "massaBruta", 																																			
							CAST(ISNULL(a.c.value('unidades[1]', 'decimal(18, 6)'), 0) AS decimal(18, 6)) AS "unidades", 
							(CASE a.c.value('numeroAdicao[1]', 'int') WHEN 1 THEN dar.totalVolumes ELSE 0 END) AS "volumes", 				
							ISNULL(NULLIF(t.c.value('paisMoedaFatura[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaFatura", 
							CAST(ISNULL(a.c.value('montante[1]', 'decimal(18, 2)'), 0) AS decimal(18, 2)) AS "montante", 
							ISNULL(NULLIF(t.c.value('paisMoedaCustosTransporte[1]', 'varchar(2)'), ''), 'EU') AS "paisMoedaCustosTransporte", 
							CAST(ISNULL(a.c.value('custosTransporte[1]', 'decimal(18, 2)'), 0) AS decimal(18, 2)) AS "custosTransporte"
						FROM t.c.nodes('adicoes/adicao/.') AS a(c) 		
							LEFT OUTER JOIN TAB_APAU AS apa WITH(NOLOCK) ON apa.APA_CODI = NULLIF(a.c.value('codigoArtigo[1]', 'varchar(22)'), '')
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE)
				FROM @FicheiroXML.nodes('DeclaracoesDARPortalDHLToGIDWin/declaracao') AS t(c)
					INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON ano = YEAR(@DataAtual) AND documentoTransporte = NULLIF(t.c.value('documentoTransporte[1]', 'varchar(35)'), '')					
					LEFT OUTER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON NULLIF(t.c.value('nifImportador[1]', 'varchar(18)'), '') = cli.CLI_NIF
					INNER JOIN TAB_PAIS AS pim WITH(NOLOCK) ON dar.id_paisCliente = pim.PAI_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pex WITH(NOLOCK) ON dar.id_paisFornecedor = pex.PAI_IDTY
					INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dar.id_declarante = dcl.DEC_IDTY
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					LEFT OUTER JOIN TAB_CENT AS cen WITH(NOLOCK) ON dar.id_condicaoEntrega = cen.CEN_IDTY
					LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dar.id_meioTransporte = mtr.MTR_IDTY
					LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dar.id_localAutorizado = lme.LME_IDTY
					LEFT OUTER JOIN TAB_ALFA AS alm WITH(NOLOCK) ON dar.id_estanciaMercadorias = alm.ALF_IDTY					
				WHERE dar.dataEnvio IS NULL
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAR
		SET @Erro = ''
		EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @Erro OUTPUT	
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaFicheiroPortalDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaFicheiroPortalDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaFicheiroScanDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaFicheiroScanDHL] @FicheiroASCII varchar(MAX), @TipoManifesto int, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON		
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @Delimiter CHAR(2), @NextPos int, @LastPos int, @Linha varchar(MAX), @TXTTipoLinha varchar(4), @TXTAcao varchar(1), 
		@TXTDocTransporte varchar(35), @TXTCodPaisMoeda varchar(2), @ValorEUR decimal(18, 4), @IdDeclaracao int, @TotalVolumes int, @i int, 
		@XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin), @ErroImportacao varchar(MAX)
	DECLARE @tmpTbFicheiro TABLE(ID int IDENTITY NOT NULL,							
							TipoLinha varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
							Acao varchar(1) COLLATE Latin1_General_CI_AI NOT NULL,
							DocTransporte varchar(35) COLLATE Latin1_General_CI_AI NOT NULL,
							CodPaisMoeda varchar(2) COLLATE Latin1_General_CI_AI NOT NULL,							
							DadosLinha varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL,
							ValorEUR decimal(18, 2) NOT NULL,
							IdDeclaracao int NULL)
	DECLARE @tmpTbManifesto TABLE(ID int IDENTITY NOT NULL,														
							DocTransporte varchar(35) COLLATE Latin1_General_CI_AI NOT NULL,
							Numero int NOT NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração das declarações DAR
	BEGIN TRY	
		SET @NumErro = 0
-- inicia variáveis
		SET @Delimiter = CHAR(13) + CHAR(10)
		SET @LastPos = 0
		SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, 1)
-- percorre as linhas do ficheiro e insere os respetivos dados na tabela tmp
		WHILE @NextPos > 0
		BEGIN			
			SET @Linha = SUBSTRING(@FicheiroASCII, @LastPos, @NextPos - @LastPos)	
-- obtem o tipo de linha e número documento de transporte
			SET @TXTTipoLinha = LTRIM(RTRIM(SUBSTRING(@Linha, 1, 4)))	
-- se linha for "CGER", obtem número documento de transporte de nova declaração
			IF @TXTTipoLinha = 'CGER'
			BEGIN
				SET @TXTDocTransporte = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 8, 18))), '')				
				SET @TXTCodPaisMoeda = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 640, 2))), '')										
				SET @ValorEUR = ROUND((CAST(STUFF(RTRIM(LTRIM(SUBSTRING(@Linha, 642, 14))), 11, 0, '.') AS decimal(18, 4)) / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) 
											WHEN @TXTCodPaisMoeda THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
											ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
												FROM TAB_CPAI WITH(NOLOCK)
												WHERE PAI_CODI = @TXTCodPaisMoeda AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
												ORDER BY CPA_DATA DESC) 
											END), 1)), 2)
				SET @IdDeclaracao = (SELECT TOP 1 id 
									FROM tb_DeclaracoesDAR WITH(NOLOCK) 
									WHERE ano = YEAR(@DataAtual) AND documentoTransporte = @TXTDocTransporte
									ORDER BY id DESC)
				IF @IdDeclaracao IS NULL
					SET @TXTAcao = 'I'
				ELSE
				IF EXISTS(SELECT din.id 
						FROM tb_DeclaracoesDARIncidencias AS din WITH(NOLOCK) 
							LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON din.id_statusIncidencia = inc.SIN_IDTY 
							LEFT OUTER JOIN TAB_COSM AS cco WITH(NOLOCK) ON din.id_statusIncidencia = cco.COS_IDTY 
						WHERE din.id_declaracaoDAR = @IdDeclaracao AND (inc.SIN_CODI IN ('A99', 'A00') OR cco.COS_CODE IN ('A99', 'A00')))
					SET @TXTAcao = 'I'
				ELSE 
					SET @TXTAcao = 'U' 									
			END
			ELSE
			IF @TXTTipoLinha = 'ADIC'
			BEGIN
				SET @TotalVolumes = CAST(RTRIM(LTRIM(SUBSTRING(@Linha, 99, 10))) AS int)
				SET @i = 1
				WHILE @i <= @TotalVolumes
				BEGIN
					INSERT INTO @tmpTbManifesto(DocTransporte, Numero)
					VALUES (@TXTDocTransporte, @i) 
					SET @i = @i + 1
				END
			END			
-- insere dados da linha na tabela tmp
			INSERT INTO @tmpTbFicheiro (TipoLinha, Acao, DocTransporte, CodPaisMoeda, DadosLinha, ValorEUR, IdDeclaracao)
			VALUES (@TXTTipoLinha, @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @Linha, @ValorEUR, @IdDeclaracao)
-- incrementa variáveis
			SET @LastPos = @NextPos + 2
			SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, @NextPos + 1)			
		END
-- inicia variaveis
		SET @Erros = ''
-- obtem lista de declarações existentes dentro do ficheiro ASCII
		DECLARE DeclaracoesDHL CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
			SELECT Acao, DocTransporte, CodPaisMoeda, ValorEUR
			FROM @tmpTbFicheiro
			WHERE TipoLinha = 'CGER'	
		OPEN DeclaracoesDHL
		FETCH NEXT FROM DeclaracoesDHL INTO @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @ValorEUR
		WHILE @@FETCH_STATUS = 0
		BEGIN						
-- constroi XML para declaração DAR a partir do ficheiro ASCII no formato DHL
			SET @XMLDeclaracaoDAR = 
				(SELECT
					(SELECT @TXTAcao AS "@acao", 
						(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data",					
						(CASE 
							WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1383, 17))), '') <> '' THEN 1
							WHEN SUBSTRING(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 233, 18))), ''), 1, 1) NOT IN ('1', '2', '3', '4') THEN 3
							ELSE 2
						END) AS "regimeIVA", 
						(CASE 
							WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1383, 17))), '') <> '' THEN 'C07'
							WHEN SUBSTRING(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 233, 18))), ''), 1, 1) NOT IN ('1', '2', '3', '4') THEN 'C07'
							WHEN @ValorEUR > 45 THEN 'C07' 
							ELSE 'C08' 
						END) AS "adicionalRegime", 	
						(SELECT 
							(CASE 
								WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') <> 'PT' THEN 'FR1'			
								ELSE 'FR5' 
							END) AS "funcao", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1383, 17))), '') AS "numeroIdentificacaoIVA"
						HAVING ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1383, 17))), '') <> ''
						FOR XML PATH('regimeIOSS'), TYPE),	
						(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1383, 17))), '') 
							WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 5, 3))), '') 
							ELSE (CASE 
									WHEN (@TXTAcao = 'U') AND EXISTS(SELECT id 
																	FROM tb_DeclaracoesDAR WITH(NOLOCK) 
																	WHERE id = cge.IdDeclaracao AND regimeIVA <> 1) THEN 'OSS' 
									ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 5, 3))), '')
								END)
						END) AS "natureza", 
						@TXTDocTransporte AS "documentoTransporte",
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 38, 18))), '') AS "nif", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 56, 70))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 126, 70))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidade", 
							'0' AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') AS "pais"		
						FOR XML PATH('exportador'), TYPE),
						(SELECT ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 233, 18))), ''), '999999990') AS "nif", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidade", 
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), ''), '0') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') AS "pais", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1350, 20))), '') AS "telefone", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1290, 50))), '') AS "email"
						FOR XML PATH('importador'), TYPE),
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 547, 6))), '') AS "declarante/codigoDeclarante",				
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 30, 8))), '') AS "estancia", 
						'A' AS "tipoDeclaracao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 780, 2))), '') AS "vossaReferencia", 						
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') AS "condEntrega",
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 553, 2))), '') AS "meioTransporte", 										
						(SELECT 'B' AS "tipoLocalizacao", 
							'Y' AS "qualificador", 
							 NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 623, 17))), '') AS "armazemDTP"						
						FOR XML PATH('localizacaoMercadorias'), TYPE),
						@TXTCodPaisMoeda AS "paisMoedaFatura", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 669, 2))), '') AS "paisMoedaCustosTransporte", 								
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 805, 6))), '') AS "nomeFicheiro"							
						FOR XML PATH('dadosEspecificos'), TYPE),
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 10))), '') AS "numeroContaExpedidor",
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 233, 10))), '') AS "numeroContaDestinatario", 			
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nomeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "moradaOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidadeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), '') AS "codigoPostalOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostalOriginalDestinatario", 						
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 50))), '') AS "referenciaExterna1", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 50))), '') AS "referenciaExterna2",
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 905, 11))), '') AS "shipID"
						FOR XML PATH('dadosEntidades'), TYPE),
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 790, 11))), '') AS "miniCPA", 
							(CONVERT(varchar(10), CONVERT(datetime, NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 671, 8))), ''), 112), 127) + 'Z') AS "dataVoo", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 80))), '') AS "aeroportoOrigem", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 782, 8))), '') AS "numeroVoo", 						 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 916, 35))), '') AS "tracking", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 953, 5))), '') AS "tipoCarga"
						FOR XML PATH('dadosAWB'), TYPE),		 
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 951, 2))), '') AS "dutyType", 
							 CAST(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 679, 1))), '') AS int) AS "payment",
							 (CONVERT(varchar(10), CONVERT(datetime, NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1271, 10))), ''), 127), 127) + 'Z') AS "dataDocumentoTransporte"
						FOR XML PATH('outrosDados'), TYPE),		 																					
						(SELECT TOP 1
							(SELECT INF_CODI AS "codigoMencao"		
							FROM TAB_INFC WITH(NOLOCK)
							WHERE INF_CODI = 'RBVDP'	
							FOR XML PATH('mencao'), TYPE)		
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_CODI = 'RBVDP'
						FOR XML PATH('informacoesAdicionais'), TYPE), 											
						(SELECT
							(SELECT 1 AS "numeroAdicao", 
								'9999999999' AS "codigoPautal",								
								ISNULL((SELECT TOP 1 NULLIF(RTRIM(LTRIM(SUBSTRING(DadosLinha, 7, 104))), '') FROM @tmpTbFicheiro WHERE TipoLinha = 'OUTD' AND DocTransporte = adi.DocTransporte), 'NÃO CLASSIFICADO') AS "designacao", 													
								NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 27, 2))), '') AS "paisOrigem",											
								CAST(ABS(CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 29, 13))), 11, 0, '.') AS decimal(18, 6)) - ISNULL((SELECT SUM(massaBruta) FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK) WHERE @TXTAcao = 'U' AND id_declaracaoDAR = cge.IdDeclaracao AND numeroAdicao > 1), 0)) AS decimal(18, 6)) AS "massaBruta", 
								CAST(0 AS decimal(18, 6)) AS "unidades", 
								CAST(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 99, 10))) AS int) AS "volumes", 				
								@TXTCodPaisMoeda AS "paisMoedaFatura", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 65, 13))), 11, 0, '.') AS decimal(18, 2)) AS "montante",
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 669, 2))), '') AS "paisMoedaCustosTransporte", 				
								CAST(0 AS decimal(18, 2)) AS "custosTransporte"	
							FROM @tmpTbFicheiro AS adi
							WHERE adi.TipoLinha = 'ADIC' AND adi.DocTransporte = cge.DocTransporte					
							FOR XML PATH('adicao'), TYPE), 
							(SELECT adi.numeroAdicao AS "numeroAdicao", 
								(adi.codigoPautal + ISNULL(adi.codigoNC, '') + ISNULL(adi.codigoTARIC, '') + ISNULL(adi.adicionalTARIC1, '') + ISNULL(adi.adicionalTARIC2, '') + ISNULL(adi.adicionalTARIC3, '')) AS "codigoPautal",								
								adi.designacao AS "designacao", 													
								por.PAI_CODI AS "paisOrigem",											
								CAST(adi.massaBruta AS decimal(18, 6)) AS "massaBruta", 
								CAST(adi.unidades AS decimal(18, 6)) AS "unidades", 
								adi.volumes AS "volumes", 				
								pmo.PAI_CODI AS "paisMoedaFatura", 
								CAST(adi.montante AS decimal(18, 2)) AS "montante",
								pct.PAI_CODI AS "paisMoedaCustosTransporte", 				
								CAST(adi.custosTransporte AS decimal(18, 2)) AS "custosTransporte"	
							FROM tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) 
								LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON adi.id_paisOrigem = por.PAI_IDTY
								INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON adi.id_paisMoedaMontante = pmo.PAI_IDTY
								INNER JOIN TAB_PAIS AS pct WITH(NOLOCK) ON adi.id_paisMoedaCustosTransporte = pct.PAI_IDTY
							WHERE @TXTAcao = 'U' AND adi.id_declaracaoDAR = cge.IdDeclaracao AND adi.numeroAdicao > 1					
							FOR XML PATH('adicao'), TYPE)
						FOR XML PATH('adicoes'), TYPE), 
						(SELECT 							
							(SELECT 0 AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoedaManifesto", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "peso"
							FROM @tmpTbFicheiro AS otd
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte AND @TXTAcao = 'I'						
							FOR XML PATH('manifesto'), TYPE),									
							(SELECT 1 AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoedaManifesto", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "peso"
							FROM @tmpTbManifesto AS man INNER JOIN (SELECT TOP 1 TipoLinha, DocTransporte, DadosLinha 
																	FROM @tmpTbFicheiro 
																	WHERE TipoLinha = 'OUTD' AND DocTransporte = cge.DocTransporte) AS otd ON man.DocTransporte = otd.DocTransporte 
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte AND @TipoManifesto = 0		
							FOR XML PATH('manifesto'), TYPE),	
							(SELECT 2 AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoedaManifesto", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "peso"
							FROM @tmpTbManifesto AS man INNER JOIN (SELECT TOP 1 TipoLinha, DocTransporte, DadosLinha 
																	FROM @tmpTbFicheiro 
																	WHERE TipoLinha = 'OUTD' AND DocTransporte = cge.DocTransporte) AS otd ON man.DocTransporte = otd.DocTransporte 
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte							
							FOR XML PATH('manifesto'), TYPE)				
						FOR XML PATH('manifestos'), TYPE)
					FROM @tmpTbFicheiro AS cge
					WHERE cge.TipoLinha = 'CGER' AND cge.DocTransporte = @TXTDocTransporte 					
					FOR XML PATH('declaracao'), TYPE)
				FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAR
			SET @ErroImportacao = ''
			EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @ErroImportacao OUTPUT									
			IF @NumErro <> 0
				SET @Erros = @Erros + 'Erro na importação da declaração DAR "' + @TXTDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)										
			FETCH NEXT FROM DeclaracoesDHL INTO @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @ValorEUR
		END
		CLOSE DeclaracoesDHL
		DEALLOCATE DeclaracoesDHL	
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
		IF ISNULL(@Erros, '') <> ''
			RAISERROR ('%s', 16, 3, @Erros)		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erros = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaFicheiroScanDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaFicheiroScanDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaFicheiroTNT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaFicheiroTNT] @FicheiroASCII varchar(MAX), @TipoManifesto int, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON		
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @Delimiter CHAR(2), @NextPos int, @LastPos int, @Linha varchar(MAX), @TXTTipoLinha varchar(4), @TXTAcao varchar(4), @TXTDocTransporte varchar(35), 
		@TXTCodPaisMoeda varchar(2),  @ValorEUR decimal(18, 3), @XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin), @ErroImportacao varchar(MAX)
	DECLARE @tmpTbFicheiro TABLE(ID int IDENTITY NOT NULL,							
							TipoLinha varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
							Acao varchar(1) COLLATE Latin1_General_CI_AI NOT NULL,
							DocTransporte varchar(35) COLLATE Latin1_General_CI_AI NOT NULL,
							CodPaisMoeda varchar(2) COLLATE Latin1_General_CI_AI NOT NULL,							
							DadosLinha varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL,
							ValorEUR decimal(18, 2) NOT NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração das declarações DAR
	BEGIN TRY	
		SET @NumErro = 0
-- inicia variáveis
		SET @Delimiter = CHAR(13) + CHAR(10)
		SET @LastPos = 0
		SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, 1)
-- percorre as linhas do ficheiro e insere os respetivos dados na tabela tmp
		WHILE @NextPos > 0
		BEGIN
			SET @Linha = SUBSTRING(@FicheiroASCII, @LastPos, @NextPos - @LastPos)	
-- obtem o tipo de linha e número documento de transporte
			SET @TXTTipoLinha = LTRIM(RTRIM(SUBSTRING(@Linha, 1, 4)))	
-- se linha for "CGER", obtem número documento de transporte de nova declaração
			IF @TXTTipoLinha = 'CGER'
			BEGIN
				SET @TXTDocTransporte = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 8, 18))), '')
				IF NOT EXISTS(SELECT id 
							FROM tb_DeclaracoesDAR WITH(NOLOCK) 
							WHERE ano = YEAR(@DataAtual) AND documentoTransporte = @TXTDocTransporte)
					SET @TXTAcao = 'I'
				ELSE
				IF EXISTS(SELECT din.id 
						FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
							INNER JOIN tb_DeclaracoesDARIncidencias AS din WITH(NOLOCK) ON dar.id = din.id_declaracaoDAR 
							LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON din.id_statusIncidencia = inc.SIN_IDTY 
							LEFT OUTER JOIN TAB_COSM AS cco WITH(NOLOCK) ON din.id_statusIncidencia = cco.COS_IDTY 
						WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte AND (inc.SIN_CODI IN ('A99', 'A00') OR cco.COS_CODE IN ('A99', 'A00') OR din.releaseHold = 'R'))
					SET @TXTAcao = 'I'
				ELSE
				IF NOT EXISTS(SELECT din.id 
							FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
								INNER JOIN tb_DeclaracoesDARIncidencias AS din WITH(NOLOCK) ON dar.id = din.id_declaracaoDAR 
								LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON din.id_statusIncidencia = inc.SIN_IDTY 
								LEFT OUTER JOIN TAB_COSM AS cco WITH(NOLOCK) ON din.id_statusIncidencia = cco.COS_IDTY 
							WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte AND (inc.SIN_CODI IN ('B6', 'NY', 'SY', 'ER') OR cco.COS_CODE IN ('B6', 'NY', 'SY', 'ER')))
					SET @TXTAcao = 'U'
				ELSE 
					SET @TXTAcao = 'I'
				SET @TXTCodPaisMoeda = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 640, 2))), '')						
				SET @ValorEUR = ROUND((CAST(STUFF(RTRIM(LTRIM(SUBSTRING(@Linha, 642, 14))), 12, 0, '.') AS decimal(18, 3)) / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) 
											WHEN @TXTCodPaisMoeda THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
											ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
												FROM TAB_CPAI WITH(NOLOCK)
												WHERE PAI_CODI = @TXTCodPaisMoeda AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
												ORDER BY CPA_DATA DESC) 
											END), 1)), 2)					
			END
-- insere dados da linha na tabela tmp
			INSERT INTO @tmpTbFicheiro (TipoLinha, Acao, DocTransporte, CodPaisMoeda, DadosLinha, ValorEUR)
			VALUES (@TXTTipoLinha, @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @Linha, @ValorEUR)
-- incrementa variáveis
			SET @LastPos = @NextPos + 2
			SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, @NextPos + 1)			
		END
-- inicia variaveis
		SET @Erros = ''
-- obtem lista de declarações existentes dentro do ficheiro ASCII
		DECLARE DeclaracoesFEDEX CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
			SELECT Acao, DocTransporte, CodPaisMoeda, ValorEUR
			FROM @tmpTbFicheiro
			WHERE TipoLinha = 'CGER'	
		OPEN DeclaracoesFEDEX
		FETCH NEXT FROM DeclaracoesFEDEX INTO @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @ValorEUR
		WHILE @@FETCH_STATUS = 0
		BEGIN										
-- constroi XML para declaração DAR a partir do ficheiro ASCII no formato FEDEX
			SET @XMLDeclaracaoDAR = 
				(SELECT
					(SELECT @TXTAcao AS "@acao", 
						(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data",					
						(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1217, 20))), '') 
							WHEN '' THEN 2 
							ELSE 1
						END) AS "regimeIVA",  		 
						(CASE 						
							WHEN @ValorEUR > 45 THEN 'C07' 
							ELSE 'C08' 
						END) AS "adicionalRegime", 	
						(SELECT 
							(CASE 
								WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') <> 'PT' THEN 'FR1'			
								ELSE 'FR5' 
							END) AS "funcao", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1217, 20))), '') AS "numeroIdentificacaoIVA"
						HAVING ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1217, 20))), '') <> ''
						FOR XML PATH('regimeIOSS'), TYPE),	
						(CASE 
							WHEN (@TipoManifesto = 1) AND EXISTS(SELECT id FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE ano = YEAR(@DataAtual) AND documentoTransporte = @TXTDocTransporte) THEN (CASE 
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte AND dar.regimeIVA = 1 AND nat.NDE_CODI = '20') THEN '25'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte AND SUBSTRING(dar.nifCliente, 1, 1) IN ('1', '2', '3') AND nat.NDE_CODI = '20') THEN '26'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte AND SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8') AND nat.NDE_CODI = '20') THEN '27'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte AND dar.nifCliente = '999999990' AND nat.NDE_CODI = '20') THEN '28'
									WHEN EXISTS(SELECT dar.id FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte AND nat.NDE_CODI IN ('86', 'DAR')) THEN '89'
									ELSE (SELECT TOP 1 nat.NDE_CODI FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY WHERE dar.ano = YEAR(@DataAtual) AND dar.documentoTransporte = @TXTDocTransporte)
								END)
							ELSE 'DAR'
						END) AS "natureza", 
						@TXTDocTransporte AS "documentoTransporte",
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 38, 18))), '') AS "nif", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 56, 70))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 126, 70))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidade", 
							'0' AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') AS "pais"		
						FOR XML PATH('exportador'), TYPE),
						(SELECT ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 233, 18))), ''), '999999990') AS "nif", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidade", 
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), ''), '0') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') AS "pais", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 477, 10))), '') AS "telefone",
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 497, 50))), '') AS "email"
						FOR XML PATH('importador'), TYPE),
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 547, 6))), '') AS "declarante/codigoDeclarante",				
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 30, 8))), '') AS "estancia", 
						'A' AS "tipoDeclaracao", 						
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') AS "condEntrega",
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 553, 2))), '') AS "meioTransporte", 												
						(SELECT 'B' AS "tipoLocalizacao", 
							'Y' AS "qualificador", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 623, 17))), '') AS "armazemDTP"						
						FOR XML PATH('localizacaoMercadorias'), TYPE),
						@TXTCodPaisMoeda AS "paisMoedaFatura", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 669, 2))), '') AS "paisMoedaCustosTransporte", 
						6 AS "followUp", 				
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 690, 10))), '') AS "portesAcc", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 954, 13))), '') AS "portes",
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 801, 50))), '') AS "despachoAcc", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 967, 6))), '') AS "nomeFicheiro"						
						FOR XML PATH('dadosEspecificos'), TYPE),
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 680, 10))), '') AS "numeroContaExpedidor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 690, 10))), '') AS "numeroContaDestinatario", 			
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nomeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "moradaOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidadeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), '') AS "codigoPostalOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostalOriginalDestinatario", 						
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 801, 50))), '') AS "referenciaExterna1", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 851, 20))), '') AS "referenciaExterna2", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 901, 11))), '') AS "shipID"
						FOR XML PATH('dadosEntidades'), TYPE),
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 790, 11))), '') AS "miniCPA",
							(CONVERT(varchar(10), CONVERT(datetime, NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 671, 8))), ''), 112), 127) + 'Z') AS "dataVoo", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 700, 80))), '') AS "aeroportoOrigem", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 782, 8))), '') AS "numeroVoo", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 954, 13))), '') AS "posicaoAviao", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 912, 35))), '') AS "tracking", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 872, 5))), '') AS "tipoCarga"
						FOR XML PATH('dadosAWB'), TYPE),		 
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 947, 2))), '') AS "dutyType", 
							 CAST(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 679, 1))), '') AS int) AS "payment"			
						FOR XML PATH('outrosDados'), TYPE),		 																					
						(SELECT TOP 1
							(SELECT INF_CODI AS "codigoMencao"		
							FROM TAB_INFC WITH(NOLOCK)
							WHERE INF_CODI = 'RBVDP'	
							FOR XML PATH('mencao'), TYPE)		
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_CODI = 'RBVDP'
						FOR XML PATH('informacoesAdicionais'), TYPE), 											
						(SELECT
							(SELECT 1 AS "numeroAdicao", 
								ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 5, 22))), ''), '9999999999') AS "codigoPautal",								
								ISNULL((SELECT TOP 1 NULLIF(RTRIM(LTRIM(SUBSTRING(DadosLinha, 7, 104))), '') FROM @tmpTbFicheiro WHERE TipoLinha = 'OUTD' AND DocTransporte = adi.DocTransporte), 'NÃO CLASSIFICADO') AS "designacao", 													
								NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 27, 2))), '') AS "paisOrigem",											
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 29, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaBruta", 
								CAST(0 AS decimal(18, 6)) AS "unidades", 
								CAST(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 99, 10))) AS int) AS "volumes", 				
								@TXTCodPaisMoeda AS "paisMoedaFatura", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 65, 13))), 11, 0, '.') AS decimal(18, 2)) AS "montante",
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 669, 2))), '') AS "paisMoedaCustosTransporte", 				
								CAST(0 AS decimal(18, 2)) AS "custosTransporte"	
							FROM @tmpTbFicheiro AS adi
							WHERE adi.TipoLinha = 'ADIC' AND adi.DocTransporte = cge.DocTransporte					
							FOR XML PATH('adicao'), TYPE)
						FOR XML PATH('adicoes'), TYPE), 
						(SELECT 							
							(SELECT @TipoManifesto AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoedaManifesto", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "peso"
							FROM @tmpTbFicheiro AS otd
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte							
							FOR XML PATH('manifesto'), TYPE),
							(SELECT 2 AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoedaManifesto", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "peso"
							FROM @tmpTbFicheiro AS otd
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte AND @TipoManifesto = 1
							FOR XML PATH('manifesto'), TYPE)								
						FOR XML PATH('manifestos'), TYPE)
					FROM @tmpTbFicheiro AS cge
					WHERE cge.TipoLinha = 'CGER' AND cge.DocTransporte = @TXTDocTransporte 					
					FOR XML PATH('declaracao'), TYPE)
				FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAR
			SET @ErroImportacao = ''
			EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @ErroImportacao OUTPUT									
			IF @NumErro <> 0
				SET @Erros = @Erros + 'Erro na importação da declaração DAR "' + @TXTDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)												
			FETCH NEXT FROM DeclaracoesFEDEX INTO @TXTAcao, @TXTDocTransporte, @TXTCodPaisMoeda, @ValorEUR
		END
		CLOSE DeclaracoesFEDEX
		DEALLOCATE DeclaracoesFEDEX	
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
		IF ISNULL(@Erros, '') <> ''
			RAISERROR ('%s', 16, 3, @Erros)		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erros = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaFicheiroTNT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaFicheiroTNT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaFicheiroUPS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaFicheiroUPS] @FicheiroXML xml, @TipoManifesto int, @DataVoo datetime, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON		
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @TXTDocTransporte varchar(35), @TXTDataVoo varchar(6), @AcaoDeclaracao varchar(1), @IdDeclaracao int, 
		@XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin)
-- inicia variaveis
	SET @NumErro = 0
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem do ficheiro XML no formato UPS o "Doc. Transporte" e a "Data de Voo" da declaração DAR
		SELECT @TXTDocTransporte = RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), 
			@TXTDataVoo = RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 13, 6)))
		FROM @FicheiroXML.nodes('declaracaoUPS') AS t(c)
-- obtem ação e ID da declaração DAR conforme o tipo de manifesto
		IF @TipoManifesto = 0 
		BEGIN
			IF EXISTS(SELECT id FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE documentoTransporte = NULLIF(@TXTDocTransporte, '') AND CAST(CONVERT(varchar(10), dataVoo, 127) AS datetime) = ISNULL(@DataVoo, CAST(@TXTDataVoo AS datetime))) 
			BEGIN
				SET @AcaoDeclaracao = 'U' 
				SET @IdDeclaracao = (SELECT TOP 1 id 
									FROM tb_DeclaracoesDAR WITH(NOLOCK) 
									WHERE documentoTransporte = NULLIF(@TXTDocTransporte, '') AND CAST(CONVERT(varchar(10), dataVoo, 127) AS datetime) = ISNULL(@DataVoo, CAST(@TXTDataVoo AS datetime)) 
									ORDER BY id DESC)
			END
			ELSE 
			BEGIN
				SET @AcaoDeclaracao = 'I' 
				SET @IdDeclaracao = NULL
			END
		END
		ELSE
			IF EXISTS(SELECT id FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE ano = YEAR(@DataAtual) AND documentoTransporte = NULLIF(@TXTDocTransporte, '') AND ISNULL(dbo.fn_DeclaracoesDAR_ObtemContramarca(id), '') = '') 
			BEGIN
				SET @AcaoDeclaracao = 'U'
				SET @IdDeclaracao = (SELECT TOP 1 id 
									FROM tb_DeclaracoesDAR WITH(NOLOCK) 
									WHERE ano = YEAR(@DataAtual) AND documentoTransporte = NULLIF(@TXTDocTransporte, '') AND ISNULL(dbo.fn_DeclaracoesDAR_ObtemContramarca(id), '') = ''
									ORDER BY id DESC)
			END
			ELSE
			BEGIN
				SET @AcaoDeclaracao = 'I'										
				SET @IdDeclaracao = NULL
			END
-- constroi XML para declaração DAR a partir do ficheiro XML no formato UPS
		SET @XMLDeclaracaoDAR = 
			(SELECT
				(SELECT @AcaoDeclaracao AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data",					
					(CASE 
						WHEN (RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER') AND (ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 105, 12))), '') <> '') THEN 1
						WHEN (RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER') AND (ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 105, 12))), '') <> '') THEN 1 						
						ELSE 2
					END) AS "regimeIVA",  		 
					(CASE 						
						WHEN ROUND((ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS numeric(38, 6)) / 100.00), 0), 0.01) / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) 
										WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 176, 2))), '') THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
										ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
											FROM TAB_CPAI WITH(NOLOCK)
											WHERE PAI_CODI = NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 176, 2))), '') AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataAtual, 127) + ' 23:58:58' AS datetime)
											ORDER BY CPA_DATA DESC) 
										END), 1)), 2) > 45 THEN 'C07' 
						ELSE 'C08' 
					END) AS "adicionalRegime", 	
					(SELECT 
						(CASE 							
							WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') <> 'PT' THEN 'FR1'			
							ELSE 'FR5' 
						END) AS "funcao", 
						(CASE 
							WHEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 105, 12))), '')
							WHEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 105, 12))), '')
							ELSE NULL
						END) AS "numeroIdentificacaoIVA"
					HAVING ((RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER') AND (ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 105, 12))), '') <> '')) OR ((RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER') AND (ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 105, 12))), '') <> ''))
					FOR XML PATH('regimeIOSS'), TYPE),					
					'DAR' AS "natureza", 
					NULLIF(@TXTDocTransporte, '') AS "documentoTransporte",
					(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "nome", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 104, 35))), '') AS "morada", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') AS "localidade", 
						ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 9))), ''), '0') AS "codigoPostal", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') AS "localidadePostal", 
						(CASE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
							WHEN 'GB' THEN (CASE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 2))) 
												WHEN 'BT' THEN 'XI' 
												ELSE 'XU' 
											END) 
							ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '') 
						END) AS "pais"		
					FOR XML PATH('exportador'), TYPE),
					(SELECT ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9))), ''), '999999990') AS "nif", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "nome", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '') AS "morada", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidade", 
						ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), ''), '0') AS "codigoPostal", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidadePostal", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') AS "pais", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 268, 14))), '') AS "telefone"
					FOR XML PATH('importador'), TYPE),
					'0137I4' AS "declarante/codigoDeclarante",				
					'PT000020' AS "estancia", 
					'A' AS "tipoDeclaracao", 						
					'FCA' AS "condEntrega",
					(CASE 
						WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN '30' 
						ELSE '40' 
					END) AS "meioTransporte", 						
					(SELECT 'B' AS "tipoLocalizacao", 
						'Y' AS "qualificador", 
						'DTP00000117020PT' AS "armazemDTP"						
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 176, 2))), '') AS "paisMoedaFatura", 
					'EU' AS "paisMoedaCustosTransporte", 
					0 AS "followUp", 			
					(SELECT CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 137, 2))) AS int) AS "serviceLevel", 								
						(CASE @TipoManifesto 
							WHEN 1 THEN NULL 
							ELSE CAST(((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 207, 9))), ''), 0) AS decimal(18, 2)) / 100) - (CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 119, 13))), ''), 0) AS decimal(18, 2)) / 100)) AS decimal(18, 2)) 
						END) AS "freteOriginal", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 216, 3))), '') AS "moedafreteOriginal",
						NULLIF(SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '/', ''), 1, 2), '') AS "condicaoEntrega", 
						NULLIF(XML_DECL.DCL_DATA.value('nomeFicheiro[1]', 'varchar(500)'), '') AS "nomeFicheiro"
					FOR XML PATH('dadosEspecificos'), TYPE),
					(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') AS "numeroContaExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') AS "numeroContaDestinatario", 			
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "nomeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '') AS "moradaOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidadeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') AS "codigoPostalOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidadePostalOriginalDestinatario", 						
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 296, 12))), '') AS "referenciaExterna2", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 51, 11))), '') AS "shipID"
					FOR XML PATH('dadosEntidades'), TYPE),
					(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 34, 11))), '') AS "miniCPA", 
						(CONVERT(varchar(10), ISNULL(@DataVoo, CAST(@TXTDataVoo AS datetime)), 127) + 'Z') AS "dataVoo", 
						NULLIF(ISNULL((SELECT PAE_CODI FROM TAB_IATA WITH(NOLOCK) WHERE IAT_CODI = RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 3, 4)))), RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 3, 4)))), '') AS "aeroportoOrigem", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))), '') AS "numeroVoo", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') AS "posicaoAviao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 35))), '') AS "tracking", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 260, 5))), '') AS "tipoCarga"
					FOR XML PATH('dadosAWB'), TYPE),		 
					(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 133, 2))), '') AS "dutyType", 
						(CONVERT(varchar(10), CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 192, 9))) AS datetime), 127) + 'Z') AS "dataDocumentoTransporte"			
					FOR XML PATH('outrosDados'), TYPE),		 																					
					(SELECT TOP 1
						(SELECT INF_CODI AS "codigoMencao"		
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_CODI = 'RBVDP'	
						FOR XML PATH('mencao'), TYPE)		
					FROM TAB_INFC WITH(NOLOCK)
					WHERE INF_CODI = 'RBVDP'
					FOR XML PATH('informacoesAdicionais'), TYPE), 											
					(SELECT
						(SELECT 1 AS "numeroAdicao", 
							'9999999999' AS "codigoPautal", 
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), ''), 'NÃO CLASSIFICADO') AS "designacao", 													
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))), '') 
							END) AS "paisOrigem",																		 
							CAST(ABS(CAST((CASE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))) 
									WHEN 'LBS' THEN ROUND((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(18, 6)) * 0.4536), 3) 
									ELSE (CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(18, 6)) / 10.00) 
								END) AS decimal(18, 6)) - ISNULL((SELECT SUM(massaBruta) FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK) WHERE @AcaoDeclaracao = 'U' AND id_declaracaoDAR = @IdDeclaracao AND numeroAdicao > 1), 0)) AS decimal(18, 6)) AS "massaBruta", 
							CAST(0 AS decimal(18, 6)) AS "unidades", 
							CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 100, 3))) AS int) AS "volumes", 				
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 176, 2))), '') AS "paisMoedaFatura", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 2)) / 100.00), 0), 0.01) AS decimal(18, 2)) AS "montante", 
							'EU' AS "paisMoedaCustosTransporte", 				
							CAST(0 AS decimal(18, 2)) AS "custosTransporte"						
						FOR XML PATH('adicao'), TYPE), 
						(SELECT adi.numeroAdicao AS "numeroAdicao", 
							(adi.codigoPautal + ISNULL(adi.codigoNC, '') + ISNULL(adi.codigoTARIC, '') + ISNULL(adi.adicionalTARIC1, '') + ISNULL(adi.adicionalTARIC2, '') + ISNULL(adi.adicionalTARIC3, '')) AS "codigoPautal",								
							adi.designacao AS "designacao", 													
							por.PAI_CODI AS "paisOrigem",											
							CAST(adi.massaBruta AS decimal(18, 6)) AS "massaBruta", 
							CAST(adi.unidades AS decimal(18, 6)) AS "unidades", 
							adi.volumes AS "volumes", 				
							pmo.PAI_CODI AS "paisMoedaFatura", 
							CAST(adi.montante AS decimal(18, 2)) AS "montante",
							pct.PAI_CODI AS "paisMoedaCustosTransporte", 				
							CAST(adi.custosTransporte AS decimal(18, 2)) AS "custosTransporte"	
						FROM tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) 
							LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON adi.id_paisOrigem = por.PAI_IDTY
							INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON adi.id_paisMoedaMontante = pmo.PAI_IDTY
							INNER JOIN TAB_PAIS AS pct WITH(NOLOCK) ON adi.id_paisMoedaCustosTransporte = pct.PAI_IDTY
						WHERE @AcaoDeclaracao = 'U' AND adi.id_declaracaoDAR = @IdDeclaracao AND adi.numeroAdicao > 1					
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE), 
					(SELECT 
						(SELECT @TipoManifesto AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoedaManifesto", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(@TXTDocTransporte, '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(18, 3)) / 10.00) as decimal(18, 3)) AS "peso"						
						FOR XML PATH('manifesto'), TYPE), 
						(SELECT @TipoManifesto AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoedaManifesto", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_MANI.MAN_DATA.value('linha[1]', 'varchar(MAX)'), 167, 35))), '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_MANI.MAN_DATA.value('linha[1]', 'varchar(MAX)'), 66, 3))), ''), 0) AS decimal(18, 3)) / 10.00) as decimal(18, 3)) AS "peso"
						FROM XML_DECL.DCL_DATA.nodes('b600xxx/.') AS XML_MANI(MAN_DATA)							
						FOR XML PATH('manifesto'), TYPE),
						(SELECT 2 AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoedaManifesto", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(@TXTDocTransporte, '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(18, 3)) / 10.00) as decimal(18, 3)) AS "peso"	
						HAVING @TipoManifesto = 1					
						FOR XML PATH('manifesto'), TYPE), 
						(SELECT 2 AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoedaManifesto", 
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_MANI.MAN_DATA.value('linha[1]', 'varchar(MAX)'), 167, 35))), '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_MANI.MAN_DATA.value('linha[1]', 'varchar(MAX)'), 66, 3))), ''), 0) AS decimal(18, 3)) / 10.00) as decimal(18, 3)) AS "peso"
						FROM XML_DECL.DCL_DATA.nodes('b600xxx/.') AS XML_MANI(MAN_DATA)		
						WHERE @TipoManifesto = 1					
						FOR XML PATH('manifesto'), TYPE)
					FOR XML PATH('manifestos'), TYPE)
				FROM @FicheiroXML.nodes('declaracaoUPS') AS XML_DECL(DCL_DATA)
				WHERE NOT EXISTS(SELECT id 
								FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
									INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON dar.id_natureza = nde.NDE_IDTY 
								WHERE dar.id = @IdDeclaracao AND nde.NDE_CODI <> 'DAR' AND @TipoManifesto = 0)
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAR
		SET @Erro = ''
		EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @Erro OUTPUT						
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaFicheiroUPS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaFicheiroUPS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ImportaRegistosDeXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_DeclaracoesDAR_ImportaRegistosDeXML] @XMLDeclaracoes xml(XMLSC_DeclaracoesDARToGIDWin), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis	
	DECLARE @acao varchar(1), @data datetime, @regimeIVA int, @adicionalRegime varchar(3), @funcaoregimeIOSS varchar(3), @numeroIdentificacaoIVA varchar(17), @natureza varchar(3), 
		@documentoTransporte varchar(35), @nifExportador varchar(18), @nomeExportador varchar(70), @moradaExportador varchar(70), @localidadeExportador varchar(35), 
		@codigoPostalExportador varchar(20), @localidadePostalExportador varchar(35), @paisExportador varchar(2), @nifImportador varchar(18), @nomeImportador varchar(70), 
		@moradaImportador varchar(70), @localidadeImportador varchar(35), @codigoPostalImportador varchar(20), @localidadePostalImportador varchar(35), @paisImportador varchar(2), 
		@telefoneImportador varchar(15), @emailImportador varchar(70), @codigoDeclarante varchar(6), @estatutoDeclarante int, @estancia varchar(8), @tipoDeclaracao varchar(1), 
		@vossaReferencia varchar(50), @condEntrega varchar(3), @meioTransporte varchar(2), @tipoLocalizacaoMercadorias varchar(1), @qualificadorLocalizacaoMercadorias varchar(1), 
		@armazemDTPLocalizacaoMercadorias varchar(17), @estanciaLocalizacaoMercadorias varchar(8), @paisMoedaFatura varchar(2), @paisMoedaCustosTransporte varchar(2), @followUp int, 
		@utilizadorNomeado varchar(30), @numeroPDDT int, @numeroPDDTDEV int, @numeroTD int, @numeroACTM int, @numeroSequencia int, @locID varchar(6), @gateway varchar(6), @serviceLevel int, 
		@portesAcc varchar(10), @portes varchar(13), @despachoAcc varchar(50), @freteOriginal decimal(18, 2), @moedafreteOriginal varchar(3), @despesas decimal(18, 3), 
		@condicaoEntrega varchar(2), @nomeFicheiro varchar(100), @numeroContaExpedidor varchar(10), @numeroContaDestinatario varchar(10), @nomeOriginalDestinatario varchar(70), 
		@moradaOriginalDestinatario varchar(70), @localidadeOriginalDestinatario varchar(35), @codigoPostalOriginalDestinatario varchar(12), 
		@localidadePostalOriginalDestinatario varchar(35), @referenciaExterna1 varchar(50), @referenciaExterna2 varchar(50), @shipID varchar(11), @miniCPA varchar(20), 
		@dataVoo datetime,  @aeroportoOrigem varchar(80), @numeroVoo varchar(20), @posicaoAviao varchar(13), @tracking varchar(35), @tipoCarga varchar(5), @dutyType varchar(2), 
		@payment int, @dataDocumentoTransporte datetime, @XMLDocumentosECertificados xml, @XMLInformacoesAdicionais xml, @XMLDocumentosPrecedentes xml, @XMLAdicoes xml, 
		@XMLIncidencias xml, @XMLManifestos xml, @XMLFollowUps xml, @XMLContactos xml, @XMLSomaMassaBrutaAdicoes decimal(18, 6), @XMLSomaMontanteEURAdicoes decimal(18, 2)
	DECLARE @tipoDocumento int, @codigoDocumento varchar(5), @numeroDocumento varchar(70), @IdDetDocumento bigint
	DECLARE @codigoMencao varchar(8), @texto varchar(512)
	DECLARE @codigoIncidencia varchar(8), @dataInicio datetime, @dataFim datetime, @observacoes varchar(500), @tipoIncidencia varchar(1)
	DECLARE @tipoManifesto int, @paisManifesto varchar(2), @descricao varchar(150), @valor decimal(18, 3), @paisMoedaManifesto varchar(2), @totalFatura decimal(18, 3), 
		@numeroCPA varchar(35), @peso decimal(18, 3)
	DECLARE @codigoFollowUp int, @utilizadorFollowUp varchar(30), @dataFollowUp datetime
	DECLARE @descricaoContacto varchar(200), @utilizadorContacto varchar(30), @dataContacto datetime
	DECLARE @numeroAdicao int, @codigoPautal varchar(22), @designacao varchar(260), @adicionalRegimeB varchar(3), @paisOrigem varchar(2), @metodoPagamento varchar(1), 
		@massaBruta decimal(18, 6), @unidades decimal(18, 6), @volumes int, @montante decimal(18, 2), @custosTransporte decimal(18, 2), @codigoBarras varchar(30), 
		@numeroObjeto varchar(20), @Optativas decimal(18, 2)
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @TaxaIVANormal decimal(8, 2), @CamposAdicionais int, @DataAtual datetime, @Ano smallint, @Numero int, @IdNatureza int, @IdAlfandega int, 
		@IdPaisExportador int, @IdFornecedor int, @ExportadorDefinido bit, @IdPaisImportador int, @IdCliente int, @TipoContaCliente varchar(3), @BeneficiarioIVACliente bit, 
		@CaucaoCliente varchar(24), @IdDeclarante int, @NomeDeclarante varchar(70), @IdPaisDeclarante int, @NIFDeclarante varchar(18), @MoradaDeclarante varchar(70), 
		@LocalidadeDeclarante varchar(35), @CodPostalDeclarante varchar(20), @LocPostalDeclarante varchar(35), @CaucaoDeclarante varchar(24), @IdLocalizacaoMercadorias int, 
		@IdAlfandegaLocalizacaoMercadorias int, @IdPaisMoedaMontante int, @IdPaisMoedaCustosTransporte int, @IdFollowUp int, @IdUtilizadorNomeado int, 
		@CambioMoedaCustosTransporte decimal(12, 6), @CambioMoedaMontante decimal(12, 6), @IdDeclaracao int, @IdDocumento int, @IdMencao int, @IdStatusIncidencia int, 
		@IdPaisManifesto int, @IdPaisMoedaManifesto int, @IdAdicao bigint, @IdArtigo int, @AdicionalIC1 varchar(4), @AdicionalIC2 varchar(4), @AdicionalIC3 varchar(4), 
		@IdPaisOrigem int, @MontanteEUR decimal(18, 2), @CustosTransporteEUR decimal(18, 2), @BaseTributacaoIVA decimal(18, 2), @TaxaIVA decimal(8, 2), @ValorIVA decimal(18, 2), 
		@TipoEntCaucao tinyint, @NumeroCaucao varchar(24), @IdManifesto bigint, @GestaoCEeVDA tinyint, @DiasFreeADT tinyint, @IdCondicaoEntrega int, @IdMeioTransporte int, 
		@TotalOptativas decimal(18, 2), @MeioTransportePorVolume bit, @IdUtilizadorXML int, @OperacaoManifesto int
	DECLARE @TotalMontante decimal(18, 2), @TotalCustosTransporte decimal(18, 2), @TotalMassaBruta decimal(18, 6), @TotalVolumesDirty int, @TotalVolumesClean int, @TotalVolumesScan int, 
		@TotalAdicoes smallint, @TotalVolumes int, @TotalIVA decimal(18, 2)
-- inicia variaveis 
	SET @NumErro = 0
	SET @Erro = ''
-- obtem a taxa IVA normal configurada
	SELECT @TaxaIVANormal = PAP_TXNR
	FROM TAB_PAPL WITH(NOLOCK)
-- obtem nos campos adicionais qual o tipo de empresa configurada
	SELECT @CamposAdicionais = PDE_CADI
	FROM TAB_PDES WITH(NOLOCK)
-- obtem o tipo de gestão CE/VDA configurada
	SELECT @GestaoCEeVDA = gestaoCEeVDA, @DiasFreeADT = diasFreeADT
	FROM tb_ConfiguracoesDAR WITH(NOLOCK)
-- carrega declaracoes DAR do XML p/ INSERT
	DECLARE DeclaracoesDAR CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT XML_DDAR.DAR_DATA.value('@acao[1]', 'varchar(1)'), 
			XML_DDAR.DAR_DATA.value('data[1]', 'datetime'), 
			XML_DDAR.DAR_DATA.value('regimeIVA[1]', 'int'), 			
			XML_DDAR.DAR_DATA.value('adicionalRegime[1]', 'varchar(3)'), 
			XML_DDAR.DAR_DATA.value('(regimeIOSS/funcao)[1]', 'varchar(3)'), 
			XML_DDAR.DAR_DATA.value('(regimeIOSS/numeroIdentificacaoIVA)[1]', 'varchar(17)'), 
			XML_DDAR.DAR_DATA.value('natureza[1]', 'varchar(3)'), 
			XML_DDAR.DAR_DATA.value('documentoTransporte[1]', 'varchar(35)'), 
			NULLIF(XML_DDAR.DAR_DATA.value('(exportador/nif)[1]', 'varchar(18)'), ''), 
			XML_DDAR.DAR_DATA.value('(exportador/nome)[1]', 'varchar(70)'), 
			XML_DDAR.DAR_DATA.value('(exportador/morada)[1]', 'varchar(70)'), 
			XML_DDAR.DAR_DATA.value('(exportador/localidade)[1]', 'varchar(35)'), 
			XML_DDAR.DAR_DATA.value('(exportador/codigoPostal)[1]', 'varchar(20)'), 
			XML_DDAR.DAR_DATA.value('(exportador/localidadePostal)[1]', 'varchar(35)'), 
			XML_DDAR.DAR_DATA.value('(exportador/pais)[1]', 'varchar(2)'), 
			XML_DDAR.DAR_DATA.value('(importador/nif)[1]', 'varchar(18)'), 
			XML_DDAR.DAR_DATA.value('(importador/nome)[1]', 'varchar(70)'), 
			XML_DDAR.DAR_DATA.value('(importador/morada)[1]', 'varchar(70)'), 
			XML_DDAR.DAR_DATA.value('(importador/localidade)[1]', 'varchar(35)'), 
			XML_DDAR.DAR_DATA.value('(importador/codigoPostal)[1]', 'varchar(20)'), 
			XML_DDAR.DAR_DATA.value('(importador/localidadePostal)[1]', 'varchar(35)'), 
			XML_DDAR.DAR_DATA.value('(importador/pais)[1]', 'varchar(2)'), 
			NULLIF(XML_DDAR.DAR_DATA.value('(importador/telefone)[1]', 'varchar(15)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(importador/email)[1]', 'varchar(70)'), ''), 
			XML_DDAR.DAR_DATA.value('(declarante/codigoDeclarante)[1]', 'varchar(6)'), 
			XML_DDAR.DAR_DATA.value('(declarante/estatuto)[1]', 'int'), 
			XML_DDAR.DAR_DATA.value('estancia[1]', 'varchar(8)'), 
			XML_DDAR.DAR_DATA.value('tipoDeclaracao[1]', 'varchar(1)'), 
			NULLIF(XML_DDAR.DAR_DATA.value('vossaReferencia[1]', 'varchar(50)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('condEntrega[1]', 'varchar(3)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('meioTransporte[1]', 'varchar(2)'), ''), 
			XML_DDAR.DAR_DATA.value('(localizacaoMercadorias/tipoLocalizacao)[1]', 'varchar(1)'), 
			XML_DDAR.DAR_DATA.value('(localizacaoMercadorias/qualificador)[1]', 'varchar(1)'), 
			XML_DDAR.DAR_DATA.value('(localizacaoMercadorias/armazemDTP)[1]', 'varchar(17)'), 
			XML_DDAR.DAR_DATA.value('(localizacaoMercadorias/estancia)[1]', 'varchar(8)'), 
			XML_DDAR.DAR_DATA.value('paisMoedaFatura[1]', 'varchar(2)'), 
			XML_DDAR.DAR_DATA.value('paisMoedaCustosTransporte[1]', 'varchar(2)'), 
			XML_DDAR.DAR_DATA.value('followUp[1]', 'int'),
			NULLIF(XML_DDAR.DAR_DATA.value('utilizadorNomeado[1]', 'varchar(30)'), ''), 
			XML_DDAR.DAR_DATA.value('(depositoTemporario/numeroPDDT)[1]', 'int'), 
			XML_DDAR.DAR_DATA.value('(depositoTemporario/numeroPDDTDEV)[1]', 'int'), 
			XML_DDAR.DAR_DATA.value('(depositoTemporario/numeroTD)[1]', 'int'), 
			XML_DDAR.DAR_DATA.value('(depositoTemporario/numeroACTM)[1]', 'int'), 
			XML_DDAR.DAR_DATA.value('(depositoTemporario/numeroSequencia)[1]', 'int'), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/locID)[1]', 'varchar(6)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/gateway)[1]', 'varchar(6)'), ''), 
			XML_DDAR.DAR_DATA.value('(dadosEspecificos/serviceLevel)[1]', 'int'), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/portesAcc)[1]', 'varchar(10)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/portes)[1]', 'varchar(13)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/despachoAcc)[1]', 'varchar(50)'), ''), 
			ISNULL(XML_DDAR.DAR_DATA.value('(dadosEspecificos/freteOriginal)[1]', 'decimal(18, 2)'), 0), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/moedafreteOriginal)[1]', 'varchar(3)'), ''), 
			ISNULL(XML_DDAR.DAR_DATA.value('(dadosEspecificos/despesas)[1]', 'decimal(18, 3)'), 0), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/condicaoEntrega)[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEspecificos/nomeFicheiro)[1]', 'varchar(100)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/numeroContaExpedidor)[1]', 'varchar(10)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/numeroContaDestinatario)[1]', 'varchar(10)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/nomeOriginalDestinatario)[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/moradaOriginalDestinatario)[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/localidadeOriginalDestinatario)[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/codigoPostalOriginalDestinatario)[1]', 'varchar(12)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/localidadePostalOriginalDestinatario)[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/referenciaExterna1)[1]', 'varchar(50)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/referenciaExterna2)[1]', 'varchar(50)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosEntidades/shipID)[1]', 'varchar(11)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosAWB/miniCPA)[1]', 'varchar(20)'), ''), 
			XML_DDAR.DAR_DATA.value('(dadosAWB/dataVoo)[1]', 'datetime'),  
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosAWB/aeroportoOrigem)[1]', 'varchar(80)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosAWB/numeroVoo)[1]', 'varchar(20)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosAWB/posicaoAviao)[1]', 'varchar(13)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosAWB/tracking)[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(dadosAWB/tipoCarga)[1]', 'varchar(5)'), ''), 
			NULLIF(XML_DDAR.DAR_DATA.value('(outrosDados/dutyType)[1]', 'varchar(2)'), ''), 
			XML_DDAR.DAR_DATA.value('(outrosDados/payment)[1]', 'int'), 
			XML_DDAR.DAR_DATA.value('(outrosDados/dataDocumentoTransporte)[1]', 'datetime'), 
			XML_DDAR.DAR_DATA.query('documentosECertificados'), 
			XML_DDAR.DAR_DATA.query('informacoesAdicionais'), 
			XML_DDAR.DAR_DATA.query('documentosPrecedentes'), 
			XML_DDAR.DAR_DATA.query('adicoes'), 
			XML_DDAR.DAR_DATA.query('incidencias'), 
			XML_DDAR.DAR_DATA.query('manifestos'),
			XML_DDAR.DAR_DATA.query('followUps'),
			XML_DDAR.DAR_DATA.query('contactos')
		FROM @XMLDeclaracoes.nodes('declaracoesDARToGIDWin/declaracao') as XML_DDAR(DAR_DATA)			
	OPEN DeclaracoesDAR
	FETCH NEXT FROM DeclaracoesDAR INTO @acao, @data, @regimeIVA, @adicionalRegime, @funcaoregimeIOSS, @numeroIdentificacaoIVA, @natureza, @documentoTransporte, @nifExportador, 
		@nomeExportador, @moradaExportador, @localidadeExportador, @codigoPostalExportador, @localidadePostalExportador, @paisExportador, @nifImportador, @nomeImportador, 
		@moradaImportador, @localidadeImportador, @codigoPostalImportador, @localidadePostalImportador, @paisImportador, @telefoneImportador, @emailImportador, @codigoDeclarante, 
		@estatutoDeclarante, @estancia, @tipoDeclaracao, @vossaReferencia, @condEntrega, @meioTransporte, @tipoLocalizacaoMercadorias, @qualificadorLocalizacaoMercadorias, 
		@armazemDTPLocalizacaoMercadorias, @estanciaLocalizacaoMercadorias, @paisMoedaFatura, @paisMoedaCustosTransporte, @followUp, @utilizadorNomeado, @numeroPDDT, @numeroPDDTDEV, @numeroTD, 
		@numeroACTM, @numeroSequencia, @locID, @gateway, @serviceLevel, @portesAcc, @portes, @despachoAcc, @freteOriginal, @moedafreteOriginal, @despesas, @condicaoEntrega, @nomeFicheiro, 
		@numeroContaExpedidor, @numeroContaDestinatario, @nomeOriginalDestinatario, @moradaOriginalDestinatario, @localidadeOriginalDestinatario, @codigoPostalOriginalDestinatario, 
		@localidadePostalOriginalDestinatario, @referenciaExterna1, @referenciaExterna2, @shipID, @miniCPA, @dataVoo, @aeroportoOrigem, @numeroVoo, @posicaoAviao, @tracking, 
		@tipoCarga, @dutyType, @payment, @dataDocumentoTransporte, @XMLDocumentosECertificados, @XMLInformacoesAdicionais, @XMLDocumentosPrecedentes, @XMLAdicoes, @XMLIncidencias, 
		@XMLManifestos, @XMLFollowUps, @XMLContactos
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- inicia transacção para inserção dados da declaração DAR
		BEGIN TRANSACTION	
		BEGIN TRY							
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
			SET @Ano = YEAR(@data)
			SET @IdNatureza = NULL
			SET @IdPaisExportador = NULL
			SET @IdFornecedor = NULL			
			SET @IdPaisImportador = NULL
			SET @IdCliente = NULL 
			SET @IdDeclarante = NULL
			SET @IdAlfandega = NULL
			SET @IdCondicaoEntrega = NULL
			SET @IdMeioTransporte = NULL
			SET @TotalOptativas = 0
			SET @MeioTransportePorVolume = 0
			SET @IdLocalizacaoMercadorias = NULL
			SET @IdAlfandegaLocalizacaoMercadorias = NULL
			SET @IdPaisMoedaMontante = NULL 
			SET @IdPaisMoedaCustosTransporte = NULL
			SET @OperacaoManifesto = NULL			
-- inicia totais
			SET @TotalVolumesDirty = 0
			SET @TotalVolumesClean = 0
			SET @TotalVolumesScan = 0		
			SET @TotalAdicoes = 0
			SET @TotalVolumes = 0
			SET @TotalIVA = 0
			SET @TotalMontante = 0
			SET @TotalCustosTransporte = 0
			SET @TotalMassaBruta = 0
-- verifica se dados regime IOSS são válidos
			IF (@regimeIVA = 1) AND ((ISNULL(@funcaoregimeIOSS, '') = '') OR (ISNULL(@numeroIdentificacaoIVA, '') = ''))
				RAISERROR('Dados do regime IOSS inválidos.', 16, 1)		
			ELSE
				IF (@regimeIVA = 2) AND ((ISNULL(@funcaoregimeIOSS, '') <> '') OR (ISNULL(@numeroIdentificacaoIVA, '') <> ''))
					RAISERROR('Dados do regime IOSS não podem ser especificados.', 16, 2)
-- obtem dados da natureza de despacho
			SELECT @IdNatureza = NDE_IDTY
			FROM TAB_NDES WITH(NOLOCK)
			WHERE NDE_PART = 0 AND NDE_CODI = @natureza
-- verifica se a natureza é válida
			IF @IdNatureza IS NULL
				RAISERROR('Natureza "%s" inválida.', 16, 3, @natureza)		
-- obtem dados do país do fornecedor (exportador)
			SELECT @IdPaisExportador = PAI_IDTY
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisExportador
-- obtem dados do fornecedor (exportador)
			SELECT TOP 1 @IdFornecedor = frn.FOR_IDTY, 
				@nomeExportador = ISNULL(frn.FOR_NOME, @nomeExportador), 
				@IdPaisExportador = ISNULL(pai.PAI_IDTY, @IdPaisExportador), 
				@moradaExportador = ISNULL(frn.FOR_MORA, @moradaExportador), 
				@localidadeExportador = ISNULL(frn.FOR_LOCA, @localidadeExportador), 
				@codigoPostalExportador = ISNULL(frn.FOR_CPOS, @codigoPostalExportador), 
				@localidadePostalExportador = ISNULL(frn.FOR_LPOS, @localidadePostalExportador)
			FROM TAB_FORN AS frn WITH(NOLOCK) INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON frn.PAI_CODI = pai.PAI_CODI
			WHERE frn.FOR_INAC = 0 AND frn.FOR_DESP = 1 AND frn.FOR_NIF = @nifExportador
-- verifica se o país do fornecedor (exportador) é válido
			IF (ISNULL(@nomeExportador, '') <> '') AND (@IdPaisExportador IS NULL)
				RAISERROR('País "%s" do exportador inválido.', 16, 4, @paisExportador)
-- obtem se exportador está definido
			IF ISNULL(@nomeExportador, '') <> ''
				SET @ExportadorDefinido = 1
			ELSE 
				SET @ExportadorDefinido = 0
-- obtem dados do país do cliente (importador)
			SELECT @IdPaisImportador = PAI_IDTY
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisImportador
-- verifica se o país do cliente (importador) é válido
			IF @IdPaisImportador IS NULL
				RAISERROR('País "%s" do importador inválido.', 16, 5, @paisImportador)	
-- obtem dados do cliente (importador)
			SELECT TOP 1 @IdCliente = cli.CLI_IDTY, 
				@nomeImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @nomeImportador 
						ELSE ISNULL(cli.CLI_NOME, @nomeImportador) 
					END), 
				@IdPaisImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @IdPaisImportador 
						ELSE ISNULL(pai.PAI_IDTY, @IdPaisImportador)
					END), 				
				@moradaImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @moradaImportador 
						ELSE ISNULL(cli.CLI_MORA, @moradaImportador) 
					END), 
				@localidadeImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @localidadeImportador 
						ELSE ISNULL(cli.CLI_LOCA, @localidadeImportador) 
					END), 
				@codigoPostalImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @codigoPostalImportador 
						ELSE ISNULL(cli.CLI_CPOS, @codigoPostalImportador)
					END), 
				@localidadePostalImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @localidadePostalImportador 
						ELSE ISNULL(cli.CLI_LPOS, @localidadePostalImportador) 
					END), 
				@telefoneImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @telefoneImportador 
						ELSE ISNULL(cli.CLI_TELF, @telefoneImportador)
					END), 
				@emailImportador = (CASE 
						WHEN cli.CLI_NIF = '999999990' THEN @emailImportador 
						ELSE ISNULL(cli.CLI_EMAI, @emailImportador) 
					END), 
				@TipoContaCliente = (CASE 
					WHEN cli.CLI_CODC = 1 THEN 'COD' 
					WHEN cli.CLI_CACC = 1 THEN 'ACC' 
					WHEN cli.CLI_CEXB = 1 THEN 'EXB' 
					WHEN cli.CLI_CDAS = 1 THEN 'DAS' 
					ELSE NULL 
				END), 
				@BeneficiarioIVACliente = (CASE
					WHEN  (cli.CLI_BIVA = 1) AND (cli.CLI_DIBI <= @data) THEN 1 
					ELSE 0
				END), 
				@CaucaoCliente = (CASE 
					WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN (ISNULL(RIGHT(CLI_ANO1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(CLI_NCA1))) + CLI_NCA1)					
					WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN (ISNULL(RIGHT(CLI_ANO2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(CLI_NCA2))) + CLI_NCA2)
					WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN (ISNULL(RIGHT(CLI_ANO3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(CLI_NCA3))) + CLI_NCA3)
					WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN (ISNULL(RIGHT(CLI_ANO4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(CLI_NCA4))) + CLI_NCA4)
					WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN (ISNULL(RIGHT(CLI_ANO5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(CLI_NCA5))) + CLI_NCA5)
					ELSE NULL 
				END)
			FROM TAB_CLIE AS cli WITH(NOLOCK) INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON cli.PAI_CODI = pai.PAI_CODI
			WHERE cli.CLI_INAC = 0 AND cli.CLI_DESP = 1 AND cli.CLI_NIF = @nifImportador
-- se cliente (importador) não existir, assume como cliente "Consumidor Final"
			IF @IdCliente IS NULL
			BEGIN
				SELECT TOP 1 @IdCliente = CLI_IDTY, 
					@TipoContaCliente = (CASE 
						WHEN CLI_CODC = 1 THEN 'COD' 
						WHEN CLI_CACC = 1 THEN 'ACC' 
						WHEN CLI_CEXB = 1 THEN 'EXB' 
						WHEN CLI_CDAS = 1 THEN 'DAS' 
						ELSE NULL 
					END), 
					@BeneficiarioIVACliente = (CASE
						WHEN  (CLI_BIVA = 1) AND (CLI_DIBI <= @data) THEN 1 
						ELSE 0
					END), 
					@CaucaoCliente = (CASE 
						WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN (ISNULL(RIGHT(CLI_ANO1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(CLI_NCA1))) + CLI_NCA1)
						WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN (ISNULL(RIGHT(CLI_ANO2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(CLI_NCA2))) + CLI_NCA2)
						WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN (ISNULL(RIGHT(CLI_ANO3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(CLI_NCA3))) + CLI_NCA3)
						WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN (ISNULL(RIGHT(CLI_ANO4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(CLI_NCA4))) + CLI_NCA4)
						WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN (ISNULL(RIGHT(CLI_ANO5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(CLI_NCA5))) + CLI_NCA5)
						ELSE NULL 
					END)
				FROM TAB_CLIE WITH(NOLOCK) 
				WHERE CLI_INAC = 0 AND CLI_DESP = 1 AND CLI_NIF = '999999990'
			END
-- verifica se o cliente (importador) é válido
			IF @IdCliente IS NULL
				RAISERROR('Cliente importador "%s" inválido.', 16, 6, @nifImportador)	
-- obtem dados do declarante
			SELECT @IdDeclarante = dcl.DEC_IDTY, 
				@NomeDeclarante = dcl.DEC_NOME, 
				@IdPaisDeclarante = pai.PAI_IDTY, 
				@NIFDeclarante = dcl.DEC_NIF, 
				@MoradaDeclarante = dcl.DEC_MORA, 
				@LocalidadeDeclarante = dcl.DEC_LOCA, 
				@CodPostalDeclarante = dcl.DEC_CPOS, 
				@LocPostalDeclarante = dcl.DEC_LPOS,
				@CaucaoDeclarante = (CASE 
					WHEN (ISNULL(DEC_NCA1, '') <> '') AND (DEC_INA1 = 0) THEN (ISNULL(RIGHT(DEC_ACA1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(DEC_NCA1))) + DEC_NCA1)
					WHEN (ISNULL(DEC_NCA2, '') <> '') AND (DEC_INA2 = 0) THEN (ISNULL(RIGHT(DEC_ACA2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(DEC_NCA2))) + DEC_NCA2)
					WHEN (ISNULL(DEC_NCA3, '') <> '') AND (DEC_INA3 = 0) THEN (ISNULL(RIGHT(DEC_ACA3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(DEC_NCA3))) + DEC_NCA3)
					WHEN (ISNULL(DEC_NCA4, '') <> '') AND (DEC_INA4 = 0) THEN (ISNULL(RIGHT(DEC_ACA4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(DEC_NCA4))) + DEC_NCA4)
					WHEN (ISNULL(DEC_NCA5, '') <> '') AND (DEC_INA5 = 0) THEN (ISNULL(RIGHT(DEC_ACA5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(DEC_NCA5))) + DEC_NCA5)
					ELSE NULL 
				END)
			FROM TAB_DECL AS dcl WITH(NOLOCK) INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dcl.PAI_CODI = pai.PAI_CODI
			WHERE dcl.DEC_INAC = 0 AND dcl.DEC_CODI = @codigoDeclarante
-- verifica se o declarante é válido
			IF @IdDeclarante IS NULL
				RAISERROR('Declarante "%s" inválido.', 16, 7, @codigoDeclarante)	
-- obtem dados da alfândega
			SELECT @IdAlfandega = ALF_IDTY
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE SUBSTRING(ALF_CODI, 1, 2) = 'PT' AND LEN(ALF_CODI) = 8 AND ALF_CODI = @estancia
-- verifica se a alfândega é válida
			IF @IdAlfandega IS NULL
				RAISERROR('Alfândega "%s" inválida.', 16, 8, @estancia)
-- obtem dados da condição de entrega se regime IVA diferente de IOSS e gestão CE ativa
			IF (@regimeIVA <> 1) AND (@GestaoCEeVDA IN (1, 3))
			BEGIN
				SELECT @IdCondicaoEntrega = CEN_IDTY
				FROM TAB_CENT WITH(NOLOCK)
				WHERE CEN_CODI = @condEntrega
-- verifica se a condição de entrega é válida
				IF @IdCondicaoEntrega IS NULL 
					RAISERROR('Condição de Entrega "%s" inválida.', 16, 9, @condEntrega)				
			END
-- obtem a soma da massa bruta e do montante das adições p/ calculo das optativas apenas se regime IVA diferente de IOSS e gestão VDA ativa
			IF (@regimeIVA <> 1) AND (@GestaoCEeVDA IN (2, 3))
			BEGIN
				SELECT @XMLSomaMassaBrutaAdicoes = SUM(XML_ADIC.ADI_DATA.value('massaBruta[1]', 'decimal(18, 6)')), 
					@XMLSomaMontanteEURAdicoes = SUM(ROUND(XML_ADIC.ADI_DATA.value('montante[1]', 'decimal(18, 2)') / dbo.FNT_Geral_ObtemCambio(0, XML_ADIC.ADI_DATA.value('paisMoedaFatura[1]', 'varchar(2)'), @Data), 2))
				FROM @XMLAdicoes.nodes('adicoes/adicao') AS XML_ADIC(ADI_DATA)				
			END
			ELSE
			BEGIN
				SET @XMLSomaMassaBrutaAdicoes = 0
				SET @XMLSomaMontanteEURAdicoes = 0
			END
-- obtem dados do meio de transporte se regime IVA diferente de IOSS e gestão VDA ativa
			IF (@regimeIVA <> 1) AND (@GestaoCEeVDA IN (2, 3))
			BEGIN
				SELECT @IdMeioTransporte = mtr.MTR_IDTY, @MeioTransportePorVolume = (CASE ISNULL(mtr.MTR_VPVL, 0) WHEN 2 THEN 1 ELSE 0 END), 
					@TotalOptativas = (CASE @DiasFreeADT 
											WHEN 0 THEN (CASE mtr.MTR_OPAU 
															WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
																				FROM TAB_MTRO WITH(NOLOCK) 
																				WHERE MTR_IDTY = mtr.MTR_IDTY 
																					AND @XMLSomaMassaBrutaAdicoes BETWEEN MTO_LMNP AND MTO_LMXP 
																					AND @XMLSomaMontanteEURAdicoes BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
															ELSE ISNULL(mtr.MTR_VOP1, 0) 
														END) 
											ELSE 0 
										END)					
				FROM TAB_MTRA AS mtr WITH(NOLOCK)
				WHERE mtr.MTR_CODI = @meioTransporte
-- verifica se o meio de transporte é válido
				IF @IdMeioTransporte IS NULL 
					RAISERROR('Meio de Transporte "%s" inválido.', 16, 10, @meioTransporte)				
			END
-- obtem dados da localização de mercadorias
			SELECT @IdLocalizacaoMercadorias = LME_IDTY
			FROM TAB_LMER WITH(NOLOCK)
			WHERE LME_FLUX = 1 AND LEFT(RIGHT(LME_CODI, 5), 3) = RIGHT(@estancia, 3) AND LME_CODI = @armazemDTPLocalizacaoMercadorias
-- verifica se a localização das mercadorias é válida
			IF (@qualificadorLocalizacaoMercadorias IN ('U', 'Y')) AND (@IdLocalizacaoMercadorias IS NULL)
				RAISERROR('Armazém DTP "%s" da localização das mercadorias inválida.', 16, 11, @armazemDTPLocalizacaoMercadorias)
-- obtem dados da alfândega das mercadorias
			SELECT @IdAlfandegaLocalizacaoMercadorias = ALF_IDTY
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE SUBSTRING(ALF_CODI, 1, 2) = 'PT' AND LEN(ALF_CODI) = 8 AND ALF_CODI = @estanciaLocalizacaoMercadorias
-- verifica se a alfândega é válida
			IF (@qualificadorLocalizacaoMercadorias = 'V') AND (@IdAlfandegaLocalizacaoMercadorias IS NULL)
				RAISERROR('Alfândega "%s" da localização das mercadorias inválida.', 16, 12, @estanciaLocalizacaoMercadorias)
-- obtem dados do país da moeda do montante
			SELECT @IdPaisMoedaMontante = PAI_IDTY
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisMoedaFatura
-- verifica se o país da moeda do montante é válido
			IF @IdPaisMoedaMontante IS NULL
				RAISERROR('País "%s" da moeda da fatura inválido.', 16, 13, @paisMoedaFatura)
-- obtem câmbio da moeda do montante (no caso de ser DHL e atualização do portal, considera a data atual)
			IF (@acao = 'U') AND (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') = 'PORTAL-DHL')
				SET @CambioMoedaMontante = dbo.FNT_Geral_ObtemCambio(0, @paisMoedaFatura, @DataAtual)
			ELSE
				SET @CambioMoedaMontante = dbo.FNT_Geral_ObtemCambio(0, @paisMoedaFatura, @Data)				
-- obtem dados do país da moeda dos custos de transporte
			SELECT @IdPaisMoedaCustosTransporte = PAI_IDTY
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisMoedaCustosTransporte
-- verifica se o país da moeda dos custos de transporte é válido
			IF @IdPaisMoedaMontante IS NULL
				RAISERROR('País "%s" da moeda dos custos de transporte inválido.', 16, 14, @paisMoedaCustosTransporte)
-- obtem câmbio da moeda dos custos de transporte (no caso de ser DHL e atualização do portal, considera a data atual)
			IF (@acao = 'U') AND (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') = 'PORTAL-DHL')
				SET @CambioMoedaCustosTransporte = dbo.FNT_Geral_ObtemCambio(0, @paisMoedaCustosTransporte, @DataAtual)
			ELSE
				SET @CambioMoedaCustosTransporte = dbo.FNT_Geral_ObtemCambio(0, @paisMoedaCustosTransporte, @Data) 
-- obtem dados do follow-up
			SELECT @IdFollowUp = FUP_IDTY
			FROM GIDWIN.dbo.FAP_FWUP WITH(NOLOCK)
			WHERE FUP_CODI = @followUp
-- verifica se o follow-up é válido
			IF (@followUp IS NOT NULL) AND (@IdFollowUp IS NULL)
				RAISERROR('Follow-up "%d" inválido.', 16, 15, @followUp)
-- obtem dados do utilizador nomeado
			SELECT @IdUtilizadorNomeado = UTI_IDTY
			FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
			WHERE UTI_UTIL = @utilizadorNomeado
-- verifica se o utilizador nomeado é válido
			IF (ISNULL(@utilizadorNomeado, '') <> '') AND (@IdUtilizadorNomeado IS NULL)
				RAISERROR('Utilizador nomeado "%s" inválido.', 16, 16, @utilizadorNomeado)
-- obtem a caução (garantia) apenas quando o regime IVA é "Geral" e cliente não é "Beneficiário IVA"
			IF (@regimeIVA = 3) AND (@BeneficiarioIVACliente = 0) AND ISNULL(@CaucaoCliente, '') <> ''
			BEGIN
				SET @TipoEntCaucao = 2
				SET @NumeroCaucao = @CaucaoCliente
			END
			ELSE
				IF (@regimeIVA = 3) AND (@BeneficiarioIVACliente = 0) AND ISNULL(@CaucaoDeclarante, '') <> ''
				BEGIN
					SET @TipoEntCaucao = 1
					SET @NumeroCaucao = @CaucaoDeclarante
				END
				ELSE
				BEGIN
					SET @TipoEntCaucao = NULL
					SET @NumeroCaucao = NULL
				END			
-- processa a inserção ou edição da declaração conforme a ação
			IF @Acao = 'I'
			BEGIN			
-- obtem o número para a nova declaração
				SELECT @Numero = proximoNumero
				FROM tb_ConfiguracoesDARNumeradores
				WHERE ano = @Ano
-- verifica se o número é válido
				IF @Numero = 0
					RAISERROR('Número da declaração não foi especificado.', 17, 15)			
-- insere nova declaração		
				INSERT INTO tb_DeclaracoesDAR(ano, 
					numero, 
					data, 
					numeroReferenciaLocal, 
					documentoTransporte, 
					dataVoo, 
					id_natureza, 
					regimeIVA, 
					regimeAdicional, 
					tipoDeclaracao, 
					numeroNRUR, 
					numeroVossaReferencia, 
					id_estancia, 
					id_fornecedor, 
					nomeFornecedor, 
					id_paisFornecedor, 
					moradaFornecedor, 
					localidadeFornecedor, 
					codPostalFornecedor, 
					locPostalFornecedor, 
					id_cliente, 
					nomeCliente, 
					id_paisCliente, 
					nifCliente, 
					moradaCliente, 
					localidadeCliente, 
					codPostalCliente, 
					locPostalCliente, 
					tipoContaCliente, 
					telefoneCliente, 
					emailCliente, 
					id_declarante, 
					nomeDeclarante, 
					id_paisDeclarante, 
					nifDeclarante, 
					moradaDeclarante, 
					localidadeDeclarante, 
					codPostalDeclarante, 
					locPostalDeclarante, 
					estatutoDeclarante, 
					nifRepresentante, 
					caucao, 
					funcaoRegimeIOSS, 
					numeroIdentificacaoIVA, 
					id_paisMoedaCustosTransporte, 
					cambioCustosTransporte, 
					localizacaoMercadorias, 
					qualificador, 
					id_estanciaMercadorias, 
					id_localAutorizado, 
					id_paisMoedaMontante, 
					cambioMontante, 
					payment, 
					numeroPDDT, 
					numeroPDDTDEV, 
					numeroTD, 
					numeroACTM, 
					miniCPA, 
					tipoCarga, 
					dutyType, 
					numeroContaExpedidor, 
					numeroContaDestinatario, 
					nomeOriginalDestinatario, 
					moradaOriginalDestinatario, 
					localidadeOriginalDestinatario, 
					codPostalOriginalDestinatario, 
					locPostalOriginalDestinatario, 
					aeroportoOrigem, 
					numeroVoo, 
					referenciaExterna1, 
					referenciaExterna2, 
					shipID, 
					tracking, 
					posicaoAviao, 
					nivelServico, 
					nomeFicheiroUPS, 
					condicaoEntregaUPS, 
					freteOriginal, 
					moedaFreteOriginal, 
					gatewayFEDEX, 
					locIDFEDEX, 
					portesAccFEDEX, 
					portesFEDEX, 
					despachoAccFEDEX, 
					despesasDHL, 
					dataDocumentoTransporte, 
					origem, 
					id_utilizadorControlo, 
					dataControlo,
					id_followUp,
					id_utilizadorNomeado,
					numeroSequencia,
					taxaIVAMaxima,
					beneficiarioIVACliente, 
					tipoCaucao,
					posicaoArmazem,
					id_condicaoEntrega,
					id_meioTransporte,
					totalOptativas)	
				OUTPUT inserted.id INTO @TblID
				VALUES (@Ano, 
					@Numero, 
					@data, 
					(SUBSTRING(STR(@Ano, 4), 3, 2) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 9 - LEN(LTRIM(STR(@Numero, 9)))) + LTRIM(STR(@Numero, 9))), 				
					@documentoTransporte, 
					@dataVoo, 
					@IdNatureza, 
					@regimeIVA, 
					@adicionalRegime, 
					@tipoDeclaracao, 
					(CASE @ExportadorDefinido WHEN 0 THEN NULL ELSE @documentoTransporte END), 
					@vossaReferencia, 
					@IdAlfandega, 
					@IdFornecedor, 
					@nomeExportador, 
					@IdPaisExportador, 
					@moradaExportador, 
					@localidadeExportador, 
					@codigoPostalExportador, 
					@localidadePostalExportador, 
					@IdCliente, 
					@nomeImportador, 
					@IdPaisImportador, 
					@nifImportador, 
					@moradaImportador, 
					@localidadeImportador, 
					@codigoPostalImportador, 
					@localidadePostalImportador, 
					@tipoContaCliente, 
					@telefoneImportador, 
					@emailImportador, 
					@IdDeclarante, 
					@NomeDeclarante, 
					@IdPaisDeclarante, 
					@NIFDeclarante, 
					@MoradaDeclarante, 
					@LocalidadeDeclarante, 
					@CodPostalDeclarante, 
					@LocPostalDeclarante, 
					@estatutoDeclarante, 
					(CASE WHEN @estatutoDeclarante IS NULL THEN NULL ELSE @NIFDeclarante END), 
					@NumeroCaucao, 
					@funcaoregimeIOSS, 
					@numeroIdentificacaoIVA, 
					@IdPaisMoedaCustosTransporte, 
					@CambioMoedaCustosTransporte, 
					@tipoLocalizacaoMercadorias, 
					@qualificadorLocalizacaoMercadorias, 
					@IdAlfandegaLocalizacaoMercadorias, 
					@IdLocalizacaoMercadorias, 
					@IdPaisMoedaMontante, 
					@CambioMoedaMontante, 
					@payment, 
					@numeroPDDT, 
					@numeroPDDTDEV, 
					@numeroTD, 
					@numeroACTM, 
					@miniCPA, 
					@tipoCarga, 
					@dutyType, 
					@numeroContaExpedidor, 
					@numeroContaDestinatario, 
					@nomeOriginalDestinatario, 
					@moradaOriginalDestinatario, 
					@localidadeOriginalDestinatario, 
					@codigoPostalOriginalDestinatario, 
					@localidadePostalOriginalDestinatario, 
					@aeroportoOrigem, 
					@numeroVoo, 
					@referenciaExterna1, 
					@referenciaExterna2, 
					@shipID, 
					@tracking, 
					@posicaoAviao, 
					@serviceLevel, 
					@nomeFicheiro, 
					@condicaoEntrega, 
					@freteOriginal, 
					@moedafreteOriginal, 
					@gateway, 
					@locID, 
					@portesAcc, 
					@portes, 
					@despachoAcc, 
					@despesas, 
					@dataDocumentoTransporte, 
					2, 
					@IdUtilizador, 
					@DataAtual, 
					@IdFollowUp,
					@IdUtilizadorNomeado,
					@numeroSequencia, 
					@TaxaIVANormal, 
					@BeneficiarioIVACliente, 
					@TipoEntCaucao,
					('C' + RIGHT(@documentoTransporte, 1)), 
					@IdCondicaoEntrega,
					@IdMeioTransporte,
					@TotalOptativas)		
-- obtem o ID da nova declaração
				SELECT @IdDeclaracao = ID 
				FROM @TblID				
-- remove ID da tabela
				DELETE FROM @TblID	
			END
			ELSE
			BEGIN
-- obtem o id da declaração (1ª porque pode haver com o mesmo documento de transporte mas c/ várias datas de voo)
				SELECT TOP 1 @IdDeclaracao = dar.id, @TotalVolumesDirty = dar.volumesDirty, @TotalVolumesClean = dar.volumesClean, @TotalVolumesScan = dar.volumesScan, 
					@IdMeioTransporte = mtr.MTR_IDTY,
					@ExportadorDefinido = (CASE ISNULL(dar.nomeFornecedor, '') WHEN '' THEN 0 ELSE 1 END),  
					@MeioTransportePorVolume = (CASE ISNULL(mtr.MTR_VPVL, 0) WHEN 2 THEN 1 ELSE 0 END), 
					@TotalOptativas = (CASE @DiasFreeADT 
											WHEN 0 THEN (CASE mtr.MTR_OPAU 
															WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
																				FROM TAB_MTRO WITH(NOLOCK) 
																				WHERE MTR_IDTY = mtr.MTR_IDTY 
																					AND (CASE WHEN (@CamposAdicionais IN (1, 4) OR (@CamposAdicionais = 2 AND @OperacaoManifesto = 0) OR (@CamposAdicionais = 3 AND ISNULL(@despachoAcc, '') <> 'PORTAL-DHL')) THEN @XMLSomaMassaBrutaAdicoes ELSE dar.totalMassaBruta END) BETWEEN MTO_LMNP AND MTO_LMXP 
																					AND (CASE WHEN ((@CamposAdicionais = 2 AND @OperacaoManifesto = 0) OR (@CamposAdicionais = 3 AND ISNULL(@despachoAcc, '') = 'PORTAL-DHL')) THEN @XMLSomaMontanteEURAdicoes ELSE dar.totalMontanteEUR END) BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
															ELSE ISNULL(mtr.MTR_VOP1, 0) 
														END) 
											ELSE 0 
										END)										
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
					LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON (CASE WHEN @CamposAdicionais IN (1, 4) THEN @IdMeioTransporte ELSE dar.id_meioTransporte END) = mtr.MTR_IDTY
				WHERE dar.ano = @ano AND dar.documentoTransporte = @documentoTransporte
				ORDER BY dar.id DESC
-- obtem o tipo de dados de manifesto				
				SELECT TOP 1 @OperacaoManifesto = t.c.value('tipoManifesto[1]', 'int') 
				FROM @XMLManifestos.nodes('manifestos/manifesto') AS t(c)
-- edita a declaração
				IF @CamposAdicionais = 1 --FEDEX/TNT
				BEGIN
					UPDATE tb_DeclaracoesDAR SET 
						id_natureza = @IdNatureza, 
						id_estancia = @IdAlfandega, 					
						id_localAutorizado = @IdLocalizacaoMercadorias, 
						dataVoo = @dataVoo, 
						id_meioTransporte = @IdMeioTransporte,
						totalOptativas = @TotalOptativas, 
						id_utilizadorControlo = @IdUtilizador, 
						dataControlo = @DataAtual
					WHERE id = @IdDeclaracao
				END
				ELSE				
				IF @CamposAdicionais = 2 --UPS
				BEGIN
					IF @OperacaoManifesto = 0 --Dirty
					BEGIN
						UPDATE tb_DeclaracoesDAR SET 
							nivelServico = @serviceLevel,
							nomeFicheiroUPS = @nomeFicheiro, 	
							freteOriginal = @freteOriginal, 
							moedaFreteOriginal = @moedafreteOriginal, 
							totalOptativas = @TotalOptativas, 						
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual
						WHERE id = @IdDeclaracao
					END
					ELSE
					BEGIN
						UPDATE tb_DeclaracoesDAR SET 
							dataVoo = @dataVoo, 						
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual
						WHERE id = @IdDeclaracao
					END
				END
				ELSE				
				IF @CamposAdicionais = 3 --DHL
				BEGIN
					IF ISNULL(@despachoAcc, '') = 'PORTAL-DHL'
					BEGIN
						UPDATE tb_DeclaracoesDAR SET 
							id_natureza = @IdNatureza, 	
							id_cliente = @IdCliente, 
							nomeCliente = @nomeImportador, 
							id_paisCliente = @IdPaisImportador, 
							nifCliente = @nifImportador, 
							moradaCliente = @moradaImportador, 
							localidadeCliente = @localidadeImportador, 
							codPostalCliente = @codigoPostalImportador, 
							locPostalCliente = @localidadePostalImportador, 
							tipoContaCliente = @tipoContaCliente, 
							telefoneCliente = @telefoneImportador, 
							emailCliente = @emailImportador,					
							id_paisMoedaMontante = @IdPaisMoedaMontante, 
							cambioMontante = @CambioMoedaMontante, 
							id_paisMoedaCustosTransporte = @IdPaisMoedaCustosTransporte, 
							cambioCustosTransporte = dbo.FNT_Geral_ObtemCambio(0, @paisMoedaCustosTransporte, @DataAtual), 
							totalOptativas = @TotalOptativas, 
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual
						WHERE id = @IdDeclaracao
					END
					ELSE
					BEGIN
						UPDATE tb_DeclaracoesDAR SET 
							id_natureza = @IdNatureza, 						
							dataVoo = @dataVoo, 	
							regimeIVA = (CASE WHEN (regimeIVA <> 1) AND (@regimeIVA = 1) THEN @regimeIVA ELSE regimeIVA END), 
							regimeAdicional = (CASE WHEN (regimeIVA <> 1) AND (@regimeIVA = 1) THEN @adicionalRegime ELSE regimeAdicional END),
							funcaoRegimeIOSS = (CASE WHEN (regimeIVA <> 1) AND (@regimeIVA = 1) THEN @funcaoregimeIOSS ELSE funcaoRegimeIOSS END), 
							numeroIdentificacaoIVA = (CASE WHEN (regimeIVA <> 1) AND (@regimeIVA = 1) THEN @numeroIdentificacaoIVA ELSE numeroIdentificacaoIVA END), 
							telefoneCliente = @telefoneImportador, 
							emailCliente = @emailImportador, 					
							dutyType = @dutyType, 						
							numeroContaDestinatario = @numeroContaDestinatario, 						
							numeroVoo = @numeroVoo, 						
							shipID = @shipID, 						
							dataDocumentoTransporte = @dataDocumentoTransporte, 
							totalOptativas = @TotalOptativas, 
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual
						WHERE id = @IdDeclaracao
					END
				END
				ELSE
				IF @CamposAdicionais = 4 --TNT
				BEGIN
					UPDATE tb_DeclaracoesDAR SET 
						id_natureza = @IdNatureza, 						
						dataVoo = @dataVoo, 
						id_meioTransporte = @IdMeioTransporte,
						totalOptativas = @TotalOptativas, 
						id_utilizadorControlo = @IdUtilizador, 
						dataControlo = @DataAtual
					WHERE id = @IdDeclaracao
				END
			END		
-- processa a inserção dos detalhes de anexos e incidências apenas quando a ação é inserção
			IF @Acao = 'I'
			BEGIN
-- obtem os documentos e certicados do XML
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_DOCS.DOC_DATA.value('tipoDocumento[1]', 'int'), 
						XML_DOCS.DOC_DATA.value('codigoDocumento[1]', 'varchar(5)'), 
						XML_DOCS.DOC_DATA.value('numeroDocumento[1]', 'varchar(70)') 
					FROM @XMLDocumentosECertificados.nodes('documentosECertificados/documento') as XML_DOCS(DOC_DATA)
				OPEN Documentos
				FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @IdDocumento = NULL
-- obtem dados do documento
					SELECT @IdDocumento = DOC_IDTY
					FROM TAB_DOCU WITH(NOLOCK)
					WHERE LEN(DOC_CODI) = 4 AND DOC_DESP = 1 AND DOC_DTRA = (CASE @tipoDocumento WHEN 1 THEN 1 ELSE 0 END) AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
					IF @IdDocumento IS NULL
						RAISERROR('Documento "%s" inválido.', 16, 18, @codigoDocumento)				
-- insere o documento na nova declaracao
					INSERT INTO tb_DeclaracoesDARDocumentos(id_declaracaoDAR, 
						id_documento, 
						numero, 
						tipo, 
						origem, 
						id_utilizadorControlo, 
						dataControlo)
					VALUES (@IdDeclaracao, 
						@IdDocumento, 
						@numeroDocumento, 
						@tipoDocumento, 
						4, 
						@IdUtilizador, 
						@DataAtual)		
					FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento
				END
				CLOSE Documentos
				DEALLOCATE Documentos
-- obtem as informações adicionais do XML
				DECLARE Mencoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_MENC.MEN_DATA.value('codigoMencao[1]', 'varchar(8)'), 
						NULLIF(XML_MENC.MEN_DATA.value('texto[1]', 'varchar(512)'), '')
					FROM @XMLInformacoesAdicionais.nodes('informacoesAdicionais/mencao') as XML_MENC(MEN_DATA)
				OPEN Mencoes
				FETCH NEXT FROM Mencoes INTO @codigoMencao, @texto
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @IdMencao = NULL
-- obtem dados da menção
					SELECT @IdMencao = INF_IDTY
					FROM TAB_INFC WITH(NOLOCK)
					WHERE INF_CODI = @codigoMencao
-- verifica se a menção é válida
					IF @IdMencao IS NULL
						RAISERROR('Menção "%s" inválida.', 16, 19, @codigoMencao)				
-- insere a menção na nova declaracao
					INSERT INTO tb_DeclaracoesDARMencoes(id_declaracaoDAR, 
						id_mencao, 
						texto, 
						origem, 
						id_utilizadorControlo, 
						dataControlo)
					VALUES (@IdDeclaracao, 
						@IdMencao, 
						@texto, 					
						3, 
						@IdUtilizador, 
						@DataAtual)		
					FETCH NEXT FROM Mencoes INTO @codigoMencao, @texto
				END
				CLOSE Mencoes
				DEALLOCATE Mencoes
-- obtem os documentos precedentes do XML
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_DOCS.DOC_DATA.value('codigoDocumento[1]', 'varchar(5)'), 
						XML_DOCS.DOC_DATA.value('numeroDocumento[1]', 'varchar(70)') 
					FROM @XMLDocumentosPrecedentes.nodes('documentosPrecedentes/documentoPrecedente') as XML_DOCS(DOC_DATA)
				OPEN Documentos
				FETCH NEXT FROM Documentos INTO @codigoDocumento, @numeroDocumento
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @IdDocumento = NULL
-- obtem dados do documento
					SELECT @IdDocumento = DOC_IDTY
					FROM TAB_DOCU WITH(NOLOCK)
					WHERE DOC_CA40 = 1 AND DOC_CODI IN ('N337', 'N355', 'N750') AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
					IF @IdDocumento IS NULL
						RAISERROR('Documento precedente "%s" inválido.', 16, 20, @codigoDocumento)				
-- insere o documento na nova declaracao
					INSERT INTO tb_DeclaracoesDARPrecedentes(id_declaracaoDAR, 
						id_documento, 
						numero, 
						id_utilizadorControlo, 
						dataControlo, 
						origem)
					VALUES (@IdDeclaracao, 
						@IdDocumento, 
						@numeroDocumento, 										
						@IdUtilizador, 
						@DataAtual, 
						1)		
					FETCH NEXT FROM Documentos INTO @codigoDocumento, @numeroDocumento
				END
				CLOSE Documentos
				DEALLOCATE Documentos
-- obtem as incidências do XML
				DECLARE Incidencias CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_INCS.INC_DATA.value('codigoIncidencia[1]', 'varchar(8)'), 
						XML_INCS.INC_DATA.value('dataInicio[1]', 'datetime'), 
						XML_INCS.INC_DATA.value('dataFim[1]', 'datetime'), 
						NULLIF(XML_INCS.INC_DATA.value('observacoes[1]', 'varchar(500)'), ''), 
						NULLIF(XML_INCS.INC_DATA.value('tipoIncidencia[1]', 'varchar(1)'), '')
					FROM @XMLIncidencias.nodes('incidencias/incidencia') as XML_INCS(INC_DATA)
				OPEN Incidencias
				FETCH NEXT FROM Incidencias INTO @codigoIncidencia, @dataInicio, @dataFim, @observacoes, @tipoIncidencia
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @IdStatusIncidencia = NULL
-- obtem dados da incidência
					SELECT @IdStatusIncidencia = t.SIN_IDTY, @tipoIncidencia = ISNULL(@tipoIncidencia, t.SIN_REHO)
					FROM (SELECT SIN_CODI, SIN_IDTY, NULL AS SIN_REHO
						FROM TAB_SINC WITH(NOLOCK)
						UNION ALL
						SELECT COS_CODE, COS_IDTY, (CASE WHEN COS_RELI = 1 THEN 'R' WHEN COS_HOLD = 1 THEN 'H' ELSE NULL END)
						FROM TAB_COSM WITH(NOLOCK)
					) AS t
					WHERE t.SIN_CODI = @codigoIncidencia				
-- verifica se a incidência é válida
					IF @IdStatusIncidencia IS NULL
						RAISERROR('Status de incidência "%s" inválida.', 16, 21, @codigoIncidencia)				
-- insere a incidência na nova declaracao
					INSERT INTO tb_DeclaracoesDARIncidencias(id_declaracaoDAR, 
						id_statusIncidencia, 
						dataInicio, 
						dataFim, 
						observacoes, 
						id_utilizadorCriacao, 
						dataCriacao, 
						id_utilizadorControlo, 
						dataControlo, 
						origem, 
						releaseHold)
					VALUES (@IdDeclaracao, 
						@IdStatusIncidencia, 
						@dataInicio, 
						@dataFim,
						@observacoes, 					
						@IdUtilizador, 
						@DataAtual, 				
						@IdUtilizador, 
						@DataAtual, 
						1, 
						@tipoIncidencia)		
					FETCH NEXT FROM Incidencias INTO @codigoIncidencia, @dataInicio, @dataFim, @observacoes, @tipoIncidencia
				END
				CLOSE Incidencias
				DEALLOCATE Incidencias
-- obtem os follow-ups do XML
				DECLARE FollowUps CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_FWUP.FUP_DATA.value('codigoFollowUp[1]', 'int'), 
						XML_FWUP.FUP_DATA.value('utilizadorFollowUp[1]', 'varchar(30)'), 
						XML_FWUP.FUP_DATA.value('dataFollowUp[1]', 'datetime')						
					FROM @XMLFollowUps.nodes('followUps/followUpData') as XML_FWUP(FUP_DATA)
				OPEN FollowUps
				FETCH NEXT FROM FollowUps INTO @codigoFollowUp, @utilizadorFollowUp, @dataFollowUp
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @IdFollowUp = NULL
					SET @IdUtilizadorXML = NULL
-- obtem dados do follow-up
					SELECT @IdFollowUp = FUP_IDTY
					FROM GIDWIN.dbo.FAP_FWUP WITH(NOLOCK)
					WHERE FUP_CODI = @codigoFollowUp
-- verifica se o follow-up é válido
					IF @IdFollowUp IS NULL
						RAISERROR('Follow-up "%d" inválido.', 16, 99, @codigoFollowUp)	
-- obtem dados do utilizador
					SELECT @IdUtilizadorXML = UTI_IDTY
					FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
					WHERE UTI_UTIL = @utilizadorFollowUp
-- verifica se o utilizador é válido
					IF @IdUtilizadorXML IS NULL
						RAISERROR('Utilizador "%s" inválido.', 16, 99, @utilizadorFollowUp)											
-- insere o follow-up na nova declaracao
					INSERT INTO tb_DeclaracoesDARFollowUps(id_declaracaoDAR, 
						id_followUp, 
						id_utilizadorFollowUp, 
						dataFollowUp, 
						id_utilizadorControlo, 
						dataControlo)
					VALUES (@IdDeclaracao, 
						@IdFollowUp, 
						@IdUtilizadorXML, 
						@dataFollowUp,						
						@IdUtilizador, 
						@DataAtual)		
					FETCH NEXT FROM FollowUps INTO @codigoFollowUp, @utilizadorFollowUp, @dataFollowUp
				END
				CLOSE FollowUps
				DEALLOCATE FollowUps
-- obtem os contactos do XML
				DECLARE Contactos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_CONT.CNT_DATA.value('descricaoContacto[1]', 'varchar(200)'), 
						XML_CONT.CNT_DATA.value('utilizadorContacto[1]', 'varchar(30)'), 
						XML_CONT.CNT_DATA.value('dataContacto[1]', 'datetime')						
					FROM @XMLContactos.nodes('contactos/contacto') as XML_CONT(CNT_DATA)
				OPEN Contactos
				FETCH NEXT FROM Contactos INTO @descricaoContacto, @utilizadorContacto, @dataContacto 
				WHILE @@FETCH_STATUS = 0
				BEGIN				
					SET @IdUtilizadorXML = NULL
-- obtem dados do utilizador
					SELECT @IdUtilizadorXML = UTI_IDTY
					FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
					WHERE UTI_UTIL = @utilizadorContacto
-- verifica se o utilizador é válido
					IF @IdUtilizadorXML IS NULL
						RAISERROR('Utilizador "%s" inválido.', 16, 99, @utilizadorContacto)								
-- insere o contacto na nova declaracao
					INSERT INTO tb_DeclaracoesDARContactos(id_declaracaoDAR, 
						descricao, 
						id_utilizadorContacto, 
						dataContacto, 
						id_utilizadorControlo, 
						dataControlo)
					VALUES (@IdDeclaracao, 
						@descricaoContacto, 
						@IdUtilizadorXML, 
						@dataContacto,						
						@IdUtilizador, 
						@DataAtual)		
					FETCH NEXT FROM Contactos INTO @descricaoContacto, @utilizadorContacto, @dataContacto
				END
				CLOSE Contactos
				DEALLOCATE Contactos
			END
			ELSE
			BEGIN			
-- obtem os documentos e certicados do XML
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_DOCS.DOC_DATA.value('tipoDocumento[1]', 'int'), 
						XML_DOCS.DOC_DATA.value('codigoDocumento[1]', 'varchar(5)'), 
						XML_DOCS.DOC_DATA.value('numeroDocumento[1]', 'varchar(70)') 
					FROM @XMLDocumentosECertificados.nodes('documentosECertificados/documento') as XML_DOCS(DOC_DATA)
				OPEN Documentos
				FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento
				WHILE @@FETCH_STATUS = 0
				BEGIN	
					SET @IdDetDocumento = NULL
-- obtem id do detalhe de documento
					SELECT @IdDetDocumento = ddo.id
					FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoDAR = @IdDeclaracao AND doc.DOC_CODI = @codigoDocumento AND ddo.tipo = @tipoDocumento 
-- altera o documento na declaracao se este já existir
					IF @IdDetDocumento IS NOT NULL
					BEGIN
						UPDATE tb_DeclaracoesDARDocumentos SET numero = @numeroDocumento, 
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual
						WHERE id = @IdDetDocumento		
					END
					ELSE
-- insere o documento na declaração se não existir e apenas quando é DHL e atualização do portal
						IF (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') = 'PORTAL-DHL')
						BEGIN
							SET @IdDocumento = NULL
-- obtem dados do documento
							SELECT @IdDocumento = DOC_IDTY
							FROM TAB_DOCU WITH(NOLOCK)
							WHERE LEN(DOC_CODI) = 4 AND DOC_DESP = 1 AND DOC_DTRA = (CASE @tipoDocumento WHEN 1 THEN 1 ELSE 0 END) AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
							IF @IdDocumento IS NULL
								RAISERROR('Documento "%s" inválido.', 16, 18, @codigoDocumento)				
-- insere o documento na declaracao
							INSERT INTO tb_DeclaracoesDARDocumentos(id_declaracaoDAR, 
								id_documento, 
								numero, 
								tipo, 
								origem, 
								id_utilizadorControlo, 
								dataControlo)
							VALUES (@IdDeclaracao, 
								@IdDocumento, 
								@numeroDocumento, 
								@tipoDocumento, 
								4, 
								@IdUtilizador, 
								@DataAtual)								
						END					
					FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento
				END
				CLOSE Documentos
				DEALLOCATE Documentos
-- remove dados de manifesto quando em edição (se "Clean" [1] remove também as linhas "Scan")
				IF @OperacaoManifesto = 1 
				BEGIN
					UPDATE tb_DeclaracoesDARManifestos SET triggerOff = 1
					WHERE id_declaracaoDAR = @IdDeclaracao AND tipoManifesto >= 1
					DELETE FROM tb_DeclaracoesDARManifestos
					WHERE id_declaracaoDAR = @IdDeclaracao AND tipoManifesto >= 1
-- inicia total de volumes clean e volumes scan
					SET @TotalVolumesClean = 0
					SET @TotalVolumesScan = 0
				END
				ELSE
				BEGIN
-- remove dados de manifesto do tipo dirty ou scan
					UPDATE tb_DeclaracoesDARManifestos SET triggerOff = 1
					WHERE id_declaracaoDAR = @IdDeclaracao AND tipoManifesto = @OperacaoManifesto
					DELETE FROM tb_DeclaracoesDARManifestos
					WHERE id_declaracaoDAR = @IdDeclaracao AND tipoManifesto = @OperacaoManifesto
-- inicia total de volumes clean ou volumes dirty
					IF @OperacaoManifesto = 0
						SET @TotalVolumesDirty = 0 
					ELSE
						IF @OperacaoManifesto = 2
							SET @TotalVolumesScan = 0					
				END	
			END
-- obtem os manifestos do XML
			DECLARE Manifestos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT XML_MANI.MAN_DATA.value('tipoManifesto[1]', 'int'), 
					NULLIF(XML_MANI.MAN_DATA.value('paisManifesto[1]', 'varchar(2)'), ''), 
					NULLIF(XML_MANI.MAN_DATA.value('descricao[1]', 'varchar(150)'), ''), 
					XML_MANI.MAN_DATA.value('valor[1]', 'decimal(18, 3)'), 
					NULLIF(XML_MANI.MAN_DATA.value('paisMoedaManifesto[1]', 'varchar(2)'), ''), 
					XML_MANI.MAN_DATA.value('totalFatura[1]', 'decimal(18, 3)'), 
					NULLIF(XML_MANI.MAN_DATA.value('numeroCPA[1]', 'varchar(35)'), ''), 
					XML_MANI.MAN_DATA.value('peso[1]', 'decimal(18, 3)')					
				FROM @XMLManifestos.nodes('manifestos/manifesto') as XML_MANI(MAN_DATA)
			OPEN Manifestos
			FETCH NEXT FROM Manifestos INTO @tipoManifesto, @paisManifesto, @descricao, @valor, @paisMoedaManifesto, @totalFatura, @numeroCPA, @peso
			WHILE @@FETCH_STATUS = 0
			BEGIN				
				SET @IdManifesto = NULL
				SET @IdPaisManifesto = NULL
				SET @IdPaisMoedaManifesto = NULL
-- obtem dados do país do manifesto
				SELECT @IdPaisManifesto = PAI_IDTY
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisManifesto
-- obtem dados do país da moeda do manifesto
				SELECT @IdPaisMoedaManifesto = PAI_IDTY
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisMoedaManifesto								
-- insere o manifesto na nova declaracao
				INSERT INTO tb_DeclaracoesDARManifestos(id_declaracaoDAR, 
					tipoManifesto, 
					documentoTransporte, 
					massaBruta, 
					descricao, 
					id_pais, 
					valor, 
					id_paisMoeda, 
					totalFatura, 
					id_utilizadorControlo, 
					dataControlo, 
					origem,
					triggerOff)
				OUTPUT inserted.id INTO @TblID
				VALUES (@IdDeclaracao, 
					@tipoManifesto, 
					@numeroCPA, 	
					@peso,
					@descricao,
					@IdPaisManifesto, 
					@valor, 
					@IdPaisMoedaManifesto, 
					@totalFatura, 									
					@IdUtilizador, 
					@DataAtual, 
					1,
					1)	
-- obtem o ID da nova linha de manifesto
				SELECT @IdManifesto = ID 
				FROM @TblID				
-- remove ID da tabela
				DELETE FROM @TblID	
-- efetua o reset da flag na nova linha de manifesto inserida
				UPDATE tb_DeclaracoesDARManifestos SET triggerOff = 0
				WHERE id = @IdManifesto
-- incrementa totais
				IF @tipoManifesto = 0 
					SET @TotalVolumesDirty = @TotalVolumesDirty + 1
				ELSE
					IF @tipoManifesto = 1
						SET @TotalVolumesClean = @TotalVolumesClean + 1
					ELSE
						IF @tipoManifesto = 2 
							SET @TotalVolumesScan = @TotalVolumesScan + 1												
				FETCH NEXT FROM Manifestos INTO @tipoManifesto, @paisManifesto, @descricao, @valor, @paisMoedaManifesto, @totalFatura, @numeroCPA, @peso
			END
			CLOSE Manifestos
			DEALLOCATE Manifestos
-- remove todas as adições da declaração
			IF (@acao = 'U') AND (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') = 'PORTAL-DHL') 
			AND (NOT EXISTS(SELECT 1 FROM @XMLAdicoes.nodes('adicoes/adicao') AS t(c) WHERE t.c.value('codigoPautal[1]', 'varchar(22)') = '9999999999'))
			BEGIN
				SET @acao = 'I'
				DELETE FROM tb_DeclaracoesDARAdicoes
				WHERE id_declaracaoDAR = @IdDeclaracao
			END
-- obtem as adições do XML
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT XML_ADIC.ADI_DATA.value('numeroAdicao[1]', 'int'), 
					XML_ADIC.ADI_DATA.value('codigoPautal[1]', 'varchar(22)'), 
					XML_ADIC.ADI_DATA.value('designacao[1]', 'varchar(260)'), 
					NULLIF(XML_ADIC.ADI_DATA.value('adicionalRegimeB[1]', 'varchar(3)'), ''), 
					NULLIF(XML_ADIC.ADI_DATA.value('paisOrigem[1]', 'varchar(2)'), ''), 
					NULLIF(XML_ADIC.ADI_DATA.value('metodoPagamento[1]', 'varchar(1)'), ''), 
					NULLIF(XML_ADIC.ADI_DATA.value('(exportador/nif)[1]', 'varchar(18)'), ''), 
					XML_ADIC.ADI_DATA.value('(exportador/nome)[1]', 'varchar(70)'), 
					XML_ADIC.ADI_DATA.value('(exportador/morada)[1]', 'varchar(70)'), 
					XML_ADIC.ADI_DATA.value('(exportador/localidade)[1]', 'varchar(35)'), 
					XML_ADIC.ADI_DATA.value('(exportador/codigoPostal)[1]', 'varchar(20)'), 
					XML_ADIC.ADI_DATA.value('(exportador/localidadePostal)[1]', 'varchar(35)'), 
					XML_ADIC.ADI_DATA.value('(exportador/pais)[1]', 'varchar(2)'), 
					XML_ADIC.ADI_DATA.value('massaBruta[1]', 'decimal(18, 6)'), 
					XML_ADIC.ADI_DATA.value('unidades[1]', 'decimal(18, 6)'), 
					XML_ADIC.ADI_DATA.value('volumes[1]', 'int'), 
					XML_ADIC.ADI_DATA.value('paisMoedaFatura[1]', 'varchar(2)'), 
					XML_ADIC.ADI_DATA.value('montante[1]', 'decimal(18, 2)'), 
					XML_ADIC.ADI_DATA.value('paisMoedaCustosTransporte[1]', 'varchar(2)'), 
					XML_ADIC.ADI_DATA.value('custosTransporte[1]', 'decimal(18, 2)'), 
					NULLIF(XML_ADIC.ADI_DATA.value('codigoBarras[1]', 'varchar(30)'), ''), 
					NULLIF(XML_ADIC.ADI_DATA.value('numeroObjeto[1]', 'varchar(20)'), ''), 
					XML_ADIC.ADI_DATA.query('documentosECertificados')					
				FROM @XMLAdicoes.nodes('adicoes/adicao') as XML_ADIC(ADI_DATA)
			OPEN Adicoes
			FETCH NEXT FROM Adicoes INTO @numeroAdicao, @codigoPautal, @designacao, @adicionalRegimeB, @paisOrigem, @metodoPagamento, @nifExportador, @nomeExportador, 
				@moradaExportador, @localidadeExportador, @codigoPostalExportador, @localidadePostalExportador, @paisExportador, @massaBruta, @unidades, @volumes, 
				@paisMoedaFatura, @montante, @paisMoedaCustosTransporte, @custosTransporte, @codigoBarras, @numeroObjeto, @XMLDocumentosECertificados
			WHILE @@FETCH_STATUS = 0
			BEGIN	
				SET @IdAdicao = NULL
				SET @IdArtigo = NULL
				SET @IdPaisExportador = NULL
				SET @IdFornecedor = NULL
				SET @IdPaisOrigem = NULL
				SET @IdPaisMoedaMontante = NULL
				SET @IdPaisMoedaCustosTransporte = NULL
-- obtem dados do artigo
				SELECT TOP 1 @IdArtigo = APA_IDTY,
					@unidades = (CASE 
						WHEN (@unidades > 0) AND (ISNULL(USU_CODI, '') = '') THEN 0 
						ELSE @unidades 
					END), 
					@AdicionalIC1 = NULLIF(APA_AIC1, ''), 
					@AdicionalIC2 = NULLIF(APA_AIC2, ''), 
					@AdicionalIC3 = NULLIF(APA_AIC3, ''),				  
					@designacao = (CASE 
						WHEN APA_CPAU IN ('9999999999', '9999999998', '9999999997', '9999999996') THEN @designacao --cóodigo de artigo genérico/códigos de artigo restritos e dumping
						ELSE ISNULL(APA_DESG, @designacao) 
					END), 
					@TaxaIVA = (CASE 
						WHEN (@regimeIVA = 1) OR (@adicionalRegime = 'C08') THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) 
						WHEN (@regimeIVA = 2) THEN (SELECT PAP_TXNR FROM TAB_PAPL WITH(NOLOCK)) 
						ELSE ISNULL(APA_TIVA, 0) 
					END)
				FROM TAB_APAU WITH(NOLOCK)
				WHERE APA_INAC = 0 AND APA_FLUX IN (0, 1) AND APA_EDAR = 0 AND APA_CPAU = @codigoPautal
-- se artigo não existir, assume como artigo "Artigo Genérico"
				IF @IdArtigo IS NULL
				BEGIN
					SELECT TOP 1 @IdArtigo = APA_IDTY, 
						@unidades = (CASE 
							WHEN (@unidades > 0) AND (ISNULL(USU_CODI, '') = '') THEN 0 
							ELSE @unidades 
						END),
						@AdicionalIC1 = NULLIF(APA_AIC1, ''), 
						@AdicionalIC2 = NULLIF(APA_AIC2, ''), 
						@AdicionalIC3 = NULLIF(APA_AIC3, ''),
						@TaxaIVA = (CASE 
							WHEN (@regimeIVA = 1) OR (@adicionalRegime = 'C08') THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) 
							WHEN (@regimeIVA = 2) THEN (SELECT PAP_TXNR FROM TAB_PAPL WITH(NOLOCK)) 
							ELSE ISNULL(APA_TIVA, 0) 
						END)
					FROM TAB_APAU WITH(NOLOCK) 
					WHERE APA_INAC = 0 AND APA_FLUX IN (0, 1) AND APA_EDAR = 0 AND APA_CPAU = '9999999999'
				END
-- verifica se o artigo é válido
				IF @IdArtigo IS NULL
					RAISERROR('Artigo "%s" inválido.', 16, 22, @codigoPautal)	
-- verifica se o adicional regime é válido
				IF (ISNULL(@adicionalRegimeB, '') <> '') AND (@adicionalRegimeB <> (CASE WHEN (@regimeIVA = 1) AND (@adicionalRegime = 'C07') THEN 'F48' WHEN (@regimeIVA = 2) AND (@adicionalRegime = 'C07') THEN 'F49' ELSE @adicionalRegimeB END))
					RAISERROR('Adicional regime B "%s" inválido.', 16, 23, @adicionalRegimeB)
				ELSE
					IF ISNULL(@adicionalRegimeB, '') = ''
						SET @adicionalRegimeB = (CASE WHEN (@regimeIVA = 1) AND (@adicionalRegime = 'C07') THEN 'F48' WHEN (@regimeIVA = 2) AND (@adicionalRegime = 'C07') THEN 'F49' ELSE NULL END)
-- verifica se o exportador está definido
				IF (@ExportadorDefinido = 1) AND ((ISNULL(@nifExportador, '') <> '') OR (ISNULL(@nomeExportador, '') <> ''))
					RAISERROR('Exportador não pode ser especificado nas adições.', 16, 24)
-- obtem dados do país do fornecedor (exportador)
				SELECT @IdPaisExportador = PAI_IDTY
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisExportador
-- obtem dados do fornecedor (exportador)
				SELECT TOP 1 @IdFornecedor = frn.FOR_IDTY, 
					@nomeExportador = ISNULL(frn.FOR_NOME, @nomeExportador), 
					@IdPaisExportador = ISNULL(pai.PAI_IDTY, @IdPaisExportador), 
					@moradaExportador = ISNULL(frn.FOR_MORA, @moradaExportador), 
					@localidadeExportador = ISNULL(frn.FOR_LOCA, @localidadeExportador), 
					@codigoPostalExportador = ISNULL(frn.FOR_CPOS, @codigoPostalExportador), 
					@localidadePostalExportador = ISNULL(frn.FOR_LPOS, @localidadePostalExportador)
				FROM TAB_FORN AS frn WITH(NOLOCK) INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON frn.PAI_CODI = pai.PAI_CODI
				WHERE frn.FOR_INAC = 0 AND frn.FOR_DESP = 1 AND frn.FOR_NIF = @nifExportador
-- verifica se o país do fornecedor (exportador) é válido
				IF (ISNULL(@nomeExportador, '') <> '') AND (@IdPaisExportador IS NULL)
					RAISERROR('País "%s" do exportador inválido.', 16, 25, @paisExportador)
-- obtem dados do país de origem
				SELECT @IdPaisOrigem = PAI_IDTY
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisOrigem	
-- obtem dados do país da moeda do montante
				SELECT @IdPaisMoedaMontante = PAI_IDTY
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisMoedaFatura
-- verifica se o país da moeda do montante é válido
				IF @IdPaisMoedaMontante IS NULL
					RAISERROR('País "%s" da moeda da fatura inválido.', 16, 26, @paisMoedaFatura)	
-- obtem câmbio da moeda do montante
				SET @CambioMoedaMontante = dbo.FNT_Geral_ObtemCambio(0, @paisMoedaFatura, @Data)				
-- obtem dados do país da moeda dos custos de transporte
				SELECT @IdPaisMoedaCustosTransporte = PAI_IDTY
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisMoedaCustosTransporte
-- verifica se o país da moeda dos custos de transporte é válido
				IF @IdPaisMoedaMontante IS NULL
					RAISERROR('País "%s" da moeda dos custos de transporte inválido.', 16, 27, @paisMoedaCustosTransporte)
-- obtem câmbio da moeda dos custos de transporte
				SET @CambioMoedaCustosTransporte = dbo.FNT_Geral_ObtemCambio(0, @paisMoedaCustosTransporte, @Data)				
-- calcula o valor de optativas
				IF @MeioTransportePorVolume = 1			
				BEGIN
					IF @numeroAdicao = 1
						SET @Optativas = ROUND((@volumes * @TotalOptativas), 2)
					ELSE
						SET @Optativas = 0
				END
				ELSE
					IF @XMLSomaMassaBrutaAdicoes > 0
						SET @Optativas = ROUND(((@TotalOptativas * CEILING(@XMLSomaMassaBrutaAdicoes / 100)) * @massaBruta / @XMLSomaMassaBrutaAdicoes), 2)	
					ELSE
						SET @Optativas = 0
-- calcula valores da adição
				SET @MontanteEUR = ROUND((@montante / @CambioMoedaMontante), 2)
				SET @CustosTransporteEUR = ROUND((@custosTransporte / @CambioMoedaCustosTransporte), 2)
				SET @BaseTributacaoIVA = (@MontanteEUR + @CustosTransporteEUR + @Optativas)	
				SET @ValorIVA = ROUND((@BaseTributacaoIVA * @TaxaIVA / 100), 2)	
-- processa a inserção ou edição da adição conforme a ação da declaração 
				IF @Acao = 'I'
				BEGIN
-- insere a adição na nova declaracao
					INSERT INTO tb_DeclaracoesDARAdicoes(id_declaracaoDAR, 
						numeroAdicao, 
						id_artigo, 
						codigoPautal, 
						codigoNC, 
						codigoTARIC, 
						adicionalTARIC1, 
						adicionalTARIC2, 
						adicionalTARIC3, 
						adicionalNacional1, 
						adicionalNacional2, 
						adicionalNacional3, 
						designacao, 
						numeroNRUR, 
						metodoPagamento, 
						id_paisOrigem, 
						regimeAdicional, 
						unidades, 
						massaBruta, 
						volumes, 
						id_paisMoedaMontante, 
						cambioMontante, 
						montante, 
						montanteEUR, 
						baseTributacaoIVA, 
						taxaIVA, 
						valorIVA, 
						id_paisMoedaCustosTransporte, 
						cambioCustosTransporte, 
						custosTransporte, 
						custosTransporteEUR, 
						id_fornecedor, 
						nomeFornecedor, 
						id_paisFornecedor, 
						moradaFornecedor, 
						localidadeFornecedor, 
						codPostalFornecedor, 
						locPostalFornecedor, 
						codigoBarrasCTT, 
						numeroObjetoCTT, 					
						id_utilizadorControlo, 
						dataControlo,
						origem,
						triggerOff,
						optativas)
					OUTPUT inserted.id INTO @TblID
					VALUES (@IdDeclaracao, 
						@numeroAdicao, 
						@IdArtigo, 
						SUBSTRING(@codigoPautal, 1, 6), 
						SUBSTRING(@codigoPautal, 7, 2), 
						SUBSTRING(@codigoPautal, 9, 2), 
						SUBSTRING(@codigoPautal, 11, 4), 
						SUBSTRING(@codigoPautal, 15, 4), 
						SUBSTRING(@codigoPautal, 19, 4), 
						@AdicionalIC1, 
						@AdicionalIC2, 
						@AdicionalIC3, 
						@designacao, 
						(CASE @ExportadorDefinido WHEN 1 THEN NULL ELSE @documentoTransporte END), 
						(CASE WHEN (@regimeIVA = 3) AND (@BeneficiarioIVACliente = 1) THEN 'G' WHEN (@regimeIVA = 3) AND (ISNULL(@NumeroCaucao, '') <> '') THEN 'T' WHEN (@regimeIVA = 3) AND (ISNULL(@NumeroCaucao, '') = '') THEN  ISNULL(@metodoPagamento, 'A') ELSE NULL END),  
						@IdPaisOrigem, 
						@adicionalRegimeB, 
						@unidades, 
						@massaBruta, 
						@volumes, 
						@IdPaisMoedaMontante, 
						@CambioMoedaMontante, 
						@montante, 
						@MontanteEUR, 
						@BaseTributacaoIVA, 
						@TaxaIVA, 
						@ValorIVA, 
						@IdPaisMoedaCustosTransporte, 
						@CambioMoedaCustosTransporte, 
						@custosTransporte, 
						@CustosTransporteEUR, 
						@IdFornecedor, 
						@nomeExportador, 
						@IdPaisExportador, 
						@moradaExportador, 
						@localidadeExportador, 
						@codigoPostalExportador, 
						@localidadePostalExportador, 
						@codigoBarras, 
						@numeroObjeto, 																				
						@IdUtilizador, 
						@DataAtual, 
						1,
						1,
						@Optativas)		
-- obtem o ID da nova adição
					SELECT @IdAdicao = ID 
					FROM @TblID				
-- remove ID da tabela
					DELETE FROM @TblID	
-- efetua o reset da flag na nova adição inserida
					UPDATE tb_DeclaracoesDARAdicoes SET triggerOff = 0
					WHERE id = @IdAdicao
				END
				ELSE
				BEGIN	
-- obtem o id da adição
					SELECT @IdAdicao = dad.id, @ValorIVA = dad.valorIVA, 
						@custosTransporte = (CASE  
							WHEN (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') = 'PORTAL-DHL') THEN @custosTransporte
							ELSE dad.custosTransporte 
						END), 
						@montante = (CASE  
							WHEN (@CamposAdicionais = 2) AND (@OperacaoManifesto = 0) THEN @montante
							WHEN (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') = 'PORTAL-DHL') THEN @montante
							ELSE dad.montante 
						END), 
						@massaBruta = (CASE 
							WHEN (@CamposAdicionais IN (1, 4)) AND (@OperacaoManifesto <> 2) THEN @massaBruta 
							WHEN (@CamposAdicionais = 2) AND (@OperacaoManifesto = 0) THEN @massaBruta 
							WHEN @CamposAdicionais = 3 THEN (CASE 
																WHEN (dar.totalAdicoes = 1 AND ABS(dad.massaBruta - @massaBruta) < 0.500) THEN @massaBruta 
																ELSE dad.massaBruta 
															END)
							ELSE dad.massaBruta 
						END), 
						@volumes = (CASE  
							WHEN (@CamposAdicionais = 2) AND (@OperacaoManifesto <> 0) THEN dad.volumes
							ELSE @volumes
						END),
						@XMLSomaMassaBrutaAdicoes = (CASE  
							WHEN (@CamposAdicionais IN (1, 4)) AND (@OperacaoManifesto = 2) THEN dar.totalMassaBruta 
							WHEN (@CamposAdicionais = 2) AND (@OperacaoManifesto <> 0) THEN dar.totalMassaBruta
							WHEN (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') <> 'PORTAL-DHL') AND ((dar.totalAdicoes <> 1 OR ABS(dad.massaBruta - @massaBruta) >= 0.500)) THEN dar.totalMassaBruta															
							WHEN (@CamposAdicionais = 3) AND (ISNULL(@despachoAcc, '') = 'PORTAL-DHL') THEN dar.totalMassaBruta
							ELSE @XMLSomaMassaBrutaAdicoes 
						END)
					FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) 
						INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON dad.id_declaracaoDAR = dar.id
					WHERE dad.id_declaracaoDAR = @IdDeclaracao AND dad.numeroAdicao = @numeroAdicao
-- edita a adição
					IF @CamposAdicionais IN (1, 4) --FEDEX/TNT | TNT
					BEGIN
						UPDATE tb_DeclaracoesDARAdicoes SET 
							massaBruta = @massaBruta, 					
							volumes = @volumes, 						
							@Optativas = optativas = (CASE @MeioTransportePorVolume 
														WHEN 1 THEN (CASE numeroAdicao WHEN 1 THEN ROUND((@volumes * @TotalOptativas), 2) ELSE 0 END)
														ELSE (CASE WHEN @XMLSomaMassaBrutaAdicoes > 0 THEN ROUND(((@TotalOptativas * CEILING(@XMLSomaMassaBrutaAdicoes / 100)) * @massaBruta / @XMLSomaMassaBrutaAdicoes), 2) ELSE 0 END)
													END), 
							@BaseTributacaoIVA = baseTributacaoIVA = ROUND((montanteEUR + custosTransporteEUR + @Optativas), 2), 
							valorIVA = ROUND((@BaseTributacaoIVA * taxaIVA / 100), 2), 
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual,
							triggerOff = 1
						WHERE id = @IdAdicao
					END
					ELSE					
					IF (@CamposAdicionais = 2) AND (@OperacaoManifesto = 0) --UPS
					BEGIN
						UPDATE tb_DeclaracoesDARAdicoes SET 
							massaBruta = @massaBruta, 
							volumes = @volumes, 	
							montante = @montante, 
							@MontanteEUR = montanteEUR = ROUND((@montante / cambioMontante), 2),	
							@Optativas = optativas = (CASE @MeioTransportePorVolume 
														WHEN 1 THEN (CASE numeroAdicao WHEN 1 THEN ROUND((@volumes * @TotalOptativas), 2) ELSE 0 END)
														ELSE (CASE WHEN @XMLSomaMassaBrutaAdicoes > 0 THEN ROUND(((@TotalOptativas * CEILING(@XMLSomaMassaBrutaAdicoes / 100)) * @massaBruta / @XMLSomaMassaBrutaAdicoes), 2) ELSE 0 END)
													END), 
							@BaseTributacaoIVA = baseTributacaoIVA = ROUND((@MontanteEUR + custosTransporteEUR + @Optativas), 2), 
							valorIVA = ROUND((@BaseTributacaoIVA * taxaIVA / 100), 2), 				
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual,
							triggerOff = 1
						WHERE id = @IdAdicao
					END
					ELSE
					IF @CamposAdicionais = 3 --DHL
					BEGIN
						IF ISNULL(@despachoAcc, '') = 'PORTAL-DHL'
						BEGIN
							UPDATE tb_DeclaracoesDARAdicoes SET 								
								montante = @montante, 
								@MontanteEUR = montanteEUR = ROUND((@montante / cambioMontante), 2),								
								custosTransporte = @custosTransporte,
								@CustosTransporteEUR = custosTransporteEUR = ROUND((@custosTransporte / cambioCustosTransporte), 2),	
								@Optativas = optativas = (CASE @MeioTransportePorVolume 
														WHEN 1 THEN (CASE numeroAdicao WHEN 1 THEN ROUND((@volumes * @TotalOptativas), 2) ELSE 0 END)
														ELSE (CASE WHEN @XMLSomaMassaBrutaAdicoes > 0 THEN ROUND(((@TotalOptativas * CEILING(@XMLSomaMassaBrutaAdicoes / 100)) * @massaBruta / @XMLSomaMassaBrutaAdicoes), 2) ELSE 0 END)
													END), 
								@BaseTributacaoIVA = baseTributacaoIVA = ROUND((@MontanteEUR + @CustosTransporteEUR + @Optativas), 2), 
								valorIVA = ROUND((@BaseTributacaoIVA * taxaIVA / 100), 2), 					
								id_utilizadorControlo = @IdUtilizador, 
								dataControlo = @DataAtual, 
								triggerOff = 1
							WHERE id = @IdAdicao
						END
						ELSE
						BEGIN
							UPDATE tb_DeclaracoesDARAdicoes SET 
								massaBruta = @massaBruta, 
								volumes = @volumes, 	
								@Optativas = optativas = (CASE @MeioTransportePorVolume 
															WHEN 1 THEN (CASE numeroAdicao WHEN 1 THEN ROUND((@volumes * @TotalOptativas), 2) ELSE 0 END)
															ELSE (CASE 
																	WHEN massaBruta <> @massaBruta THEN (CASE WHEN @XMLSomaMassaBrutaAdicoes > 0 THEN ROUND(((@TotalOptativas * CEILING(@XMLSomaMassaBrutaAdicoes / 100)) * @massaBruta / @XMLSomaMassaBrutaAdicoes), 2) ELSE 0 END)
																	ELSE optativas
																END)
														END), 
								@BaseTributacaoIVA = baseTributacaoIVA = ROUND((montanteEUR + custosTransporteEUR + @Optativas), 2), 
								valorIVA = ROUND((@BaseTributacaoIVA * taxaIVA / 100), 2), 					
								id_utilizadorControlo = @IdUtilizador, 
								dataControlo = @DataAtual, 
								triggerOff = 1
							WHERE id = @IdAdicao
						END
					END					
-- efetua o reset da flag na nova adição inserida
					UPDATE tb_DeclaracoesDARAdicoes SET triggerOff = 0
					WHERE id = @IdAdicao
				END
-- incrementa totais
				SET @TotalAdicoes = @TotalAdicoes + 1
				SET @TotalVolumes = @TotalVolumes + @volumes
				SET @TotalIVA = @TotalIVA + @ValorIVA
				SET @TotalMontante = @TotalMontante + @montante
				SET @TotalCustosTransporte = @TotalCustosTransporte + @custosTransporte
				SET @TotalMassaBruta = @TotalMassaBruta + @massaBruta
-- processa a inserção dos detalhes de anexos apenas quando a ação da declaração é inserção
				IF @Acao = 'I'
				BEGIN
-- obtem os documentos e certicados da adição do XML
					DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
						SELECT XML_DOCS.DOC_DATA.value('tipoDocumento[1]', 'int'), 
							XML_DOCS.DOC_DATA.value('codigoDocumento[1]', 'varchar(5)'), 
							XML_DOCS.DOC_DATA.value('numeroDocumento[1]', 'varchar(70)') 
						FROM @XMLDocumentosECertificados.nodes('documentosECertificados/documento') as XML_DOCS(DOC_DATA)
					OPEN Documentos
					FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento
					WHILE @@FETCH_STATUS = 0
					BEGIN		
						SET @IdDocumento = NULL
-- obtem dados do documento
						SELECT @IdDocumento = DOC_IDTY
						FROM TAB_DOCU WITH(NOLOCK)
						WHERE LEN(DOC_CODI) = 4 AND DOC_DESP = 1 AND DOC_DTRA = (CASE @tipoDocumento WHEN 1 THEN 1 ELSE 0 END) AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
						IF @IdDocumento IS NULL
							RAISERROR('Documento "%s" inválido.', 16, 28, @codigoDocumento)				
-- insere o documento na nova adição
						INSERT INTO tb_DeclaracoesDARAdicoesDocumentos(id_adicao, 
							id_documento, 
							numero, 
							tipo, 
							origem, 
							id_utilizadorControlo, 
							dataControlo)
						VALUES (@IdAdicao, 
							@IdDocumento, 
							@numeroDocumento, 
							@tipoDocumento, 
							2, 
							@IdUtilizador, 
							@DataAtual)		
						FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento
					END
					CLOSE Documentos
					DEALLOCATE Documentos
				END
				FETCH NEXT FROM Adicoes INTO @numeroAdicao, @codigoPautal, @designacao, @adicionalRegimeB, @paisOrigem, @metodoPagamento, @nifExportador, @nomeExportador, 
					@moradaExportador, @localidadeExportador, @codigoPostalExportador, @localidadePostalExportador, @paisExportador, @massaBruta, @unidades, @volumes, 
					@paisMoedaFatura, @montante, @paisMoedaCustosTransporte, @custosTransporte, @codigoBarras, @numeroObjeto, @XMLDocumentosECertificados
			END
			CLOSE Adicoes
			DEALLOCATE Adicoes
-- atualiza totais na declaração
			SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de UPDATE não ser processado
			UPDATE tb_DeclaracoesDAR SET 
				totalAdicoes = @TotalAdicoes, 
				totalVolumes = @TotalVolumes, 
				totalIVA = @TotalIVA, 
				totalMontante = @TotalMontante,
				totalMontanteEUR = ROUND((@TotalMontante / cambioMontante), 2),
				totalCustosTransporte = @TotalCustosTransporte,
				totalMassaBruta = @TotalMassaBruta,
				volumesDirty = @TotalVolumesDirty,
				volumesClean = @TotalVolumesClean,
				volumesScan = @TotalVolumesScan
			WHERE id = @IdDeclaracao
			SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
		END TRY
		BEGIN CATCH							
-- constroi mensagem de erro detalhada
			SET @NumErro = 1 
			SET @Erro = @Erro + 'Doc. Transporte N.º: ' + @documentoTransporte 
				+ CHAR(13) + 'Detalhes do Erro: ' 
				+ CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) 
				+ CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
				+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) 
				+ CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() 
				+ CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
				+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE() + CHAR(13)
-- em caso de erro faz rollback da transacção iniciada						           
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION	
		END CATCH	
-- se sucesso faz commit da transacção iniciada
		IF @@TRANCOUNT > 0
			COMMIT TRANSACTION			
		FETCH NEXT FROM DeclaracoesDAR INTO @acao, @data, @regimeIVA, @adicionalRegime, @funcaoregimeIOSS, @numeroIdentificacaoIVA, @natureza, @documentoTransporte, @nifExportador, 
			@nomeExportador, @moradaExportador, @localidadeExportador, @codigoPostalExportador, @localidadePostalExportador, @paisExportador, @nifImportador, @nomeImportador, 
			@moradaImportador, @localidadeImportador, @codigoPostalImportador, @localidadePostalImportador, @paisImportador, @telefoneImportador, @emailImportador, @codigoDeclarante, 
			@estatutoDeclarante, @estancia, @tipoDeclaracao, @vossaReferencia, @condEntrega, @meioTransporte, @tipoLocalizacaoMercadorias, @qualificadorLocalizacaoMercadorias, 
			@armazemDTPLocalizacaoMercadorias, @estanciaLocalizacaoMercadorias, @paisMoedaFatura, @paisMoedaCustosTransporte, @followUp, @utilizadorNomeado, @numeroPDDT, @numeroPDDTDEV, @numeroTD, 
			@numeroACTM, @numeroSequencia, @locID, @gateway, @serviceLevel, @portesAcc, @portes, @despachoAcc, @freteOriginal, @moedafreteOriginal, @despesas, @condicaoEntrega, @nomeFicheiro, 
			@numeroContaExpedidor, @numeroContaDestinatario, @nomeOriginalDestinatario, @moradaOriginalDestinatario, @localidadeOriginalDestinatario, @codigoPostalOriginalDestinatario, 
			@localidadePostalOriginalDestinatario, @referenciaExterna1, @referenciaExterna2, @shipID, @miniCPA, @dataVoo, @aeroportoOrigem, @numeroVoo, @posicaoAviao, @tracking, 
			@tipoCarga, @dutyType, @payment, @dataDocumentoTransporte, @XMLDocumentosECertificados, @XMLInformacoesAdicionais, @XMLDocumentosPrecedentes, @XMLAdicoes, @XMLIncidencias, 
			@XMLManifestos, @XMLFollowUps, @XMLContactos
	END
	CLOSE DeclaracoesDAR
	DEALLOCATE DeclaracoesDAR
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ImportaRegistosDeXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ImportaRegistosDeXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ObtemRespostaRegisto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ObtemRespostaRegisto] @Ambito tinyint, @Tipo varchar(3), @Id int, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @PassPhrase varchar(50), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), @PathCertificado varchar(250), 
		@PwdCertificado varchar(100), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), @Resultado int, 
		@PublicKeyCertificadoAT nvarchar(4000), @PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), @RequestXML xml, 
		@ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX), @RespostasXML xml, @FicheirosXML xml, @MensagemXMLBase64 varchar(MAX), @MensagemXML xml, 
		@NomeFicheiro varchar(200), @FicheiroBinario varbinary(MAX), @NomeMensagem varchar(100), @IndiceInicial int, @IndiceFinal int, @XMLOperacao varchar(4), 
		@XMLEstadoOperacao varchar(3), @XMLNumeroNRM varchar(25), @XMLDataNRM datetime, @XMLVersao tinyint, @XMLNumeroProvisorio varchar(20), @XMLConferente varchar(80), 
		@XMLVerificador varchar(80), @XMLDataControlo datetime, @XMLNumeroLiquidacao varchar(20), @XMLDataLiquidacao datetime, @XMLDataPagamento datetime, 
		@XMLMontante decimal(18, 2)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
	SET @PassPhrase = '16345678901234567'
-- inicia processo de obtenção de respostas da declaração
	BEGIN TRY	
		SET @NumErro = 0
-- obtem configurações do Webservice e do Proxy Authentication
		SELECT @EnderecoWS = wsEndereco, @LoginWS = wsUtilizador, @PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPassword)), @PathCertificado = wsPathCertificado, 
			@PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPasswordCertificado)), @ProxyAuthentication = proxyAuthentication, @ProxyServer = ISNULL(proxyServer, ''), 
			@ProxyPort = ISNULL(proxyPort, 0), @ProxyUser = ISNULL(proxyUser, ''), @ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, proxyPassword)), '')
		FROM tb_ConfiguracoesDAR WITH(NOLOCK)	
-- obtem a chave pública do sistema de autenticação na AT para ambiente de produção
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT(0)
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- processa obtenção das mensagens de resposta
		IF @Ambito IN (0, 1)
		BEGIN
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- em função do âmbito constroi o respetivo request
			IF @Ambito = 0
			BEGIN
-- constroi estrutura XML com os dados do pedido ao metodo obterMensagensNaoEntregues a enviar à AT		
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
					'http://net.atos.at.impec.canalWS/' AS web, 
					'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
				SELECT @RequestXML = 
					(SELECT 
						(SELECT 
							(SELECT
								(SELECT 
									@LoginWS AS "wss:Username", 
									@PwdWSEncriptada AS "wss:Password",
									@ChvSimetricaEncriptada AS "wss:Nonce",
									@DataSistemaEncriptada AS "wss:Created"
								FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
							FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
						FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
						(SELECT
							(SELECT 
								(SELECT 
									(SELECT
										dar.numeroReferenciaLocal AS "numeroReferenciaLocal"
									FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK)
									WHERE id = @Id
									FOR XML PATH('listaNRLs'), TYPE),
									@Tipo AS "tipo"
								FOR XML PATH('obterMensagensNaoEntreguesInput'), TYPE)							
							FOR XML PATH('web:obterMensagensNaoEntregues'), TYPE)	
						FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Envelope'), ELEMENTS)	
			END
			ELSE
			BEGIN
-- constroi estrutura XML com os dados do pedido ao metodo obterMensagensEntregues a enviar à AT		
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
					'http://net.atos.at.impec.canalWS/' AS web, 
					'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
				SELECT @RequestXML = 
					(SELECT 
						(SELECT 
							(SELECT
								(SELECT 
									@LoginWS AS "wss:Username", 
									@PwdWSEncriptada AS "wss:Password",
									@ChvSimetricaEncriptada AS "wss:Nonce",
									@DataSistemaEncriptada AS "wss:Created"
								FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
							FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
						FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
						(SELECT
							(SELECT 
								(SELECT 
									(SELECT
										dar.numeroReferenciaLocal AS "numeroReferenciaLocal"
									FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK)
									WHERE id = @Id
									FOR XML PATH(''), TYPE),
									@Tipo AS "tipo"
								FOR XML PATH('obterMensagensEntreguesInput'), TYPE)							
							FOR XML PATH('web:obterMensagensEntregues'), TYPE)	
						FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Envelope'), ELEMENTS)	
			END
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, 'http://net.atos.at.impec.canalWS/STADAIMPCAUCanalWebService/obterMensagensNaoEntregues', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') as XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)					
-- em função do âmbito, obtem o resultado "OK"/"NOK" retornados do WS			
			IF @Ambito = 0
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impec.canalWS/' AS m)		
				SELECT 
					@FaultCode = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostasXML = XML_MSGR.MSG_DATA.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterMensagensNaoEntreguesResponse/return') as XML_MSGR(MSG_DATA)					
								
			END
			ELSE
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impec.canalWS/' AS m)		
				SELECT 
					@FaultCode = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostasXML = XML_MSGR.MSG_DATA.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterMensagensEntreguesResponse/return') as XML_MSGR(MSG_DATA)										
			END
			IF @FaultCode <> '0'
				RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 4, @FaultMessage)
-- obtem o resultado de sucesso de obtenção de resultados da declaração				
			SELECT 
				@FaultCode = XML_DECL.DEC_DATA.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_DECL.DEC_DATA.value('descricaoResultado[1]', 'nvarchar(MAX)'),
				@FicheirosXML = XML_DECL.DEC_DATA.query('ficheiroResposta')
			FROM @RespostasXML.nodes('declaracao') as XML_DECL(DEC_DATA)							
			IF (@FaultCode <> '100') AND (@FaultCode <> '101')
				RAISERROR('A declaração gerou o erro "%s".', 16, 5, @FaultMessage)	
-- obtem todos os ficheiros de resposta associados à declaração
			DECLARE FicheirosXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT XML_FICH.FIC_DATA.value('ficheiro[1]', 'varchar(MAX)')
				FROM @FicheirosXML.nodes('ficheiroResposta') as XML_FICH(FIC_DATA)
			OPEN FicheirosXML
			FETCH NEXT FROM FicheirosXML INTO @MensagemXMLBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN 
-- converte o Base64 para varbinary e depois para xml
				SET @MensagemXML = CAST('' AS XML).value('xs:base64Binary(sql:variable("@MensagemXMLBase64"))', 'varbinary(max)')					
-- obtem da mensagem xml o nome do elemento root como nome da mensagem obtida
				SELECT @NomeMensagem = XML_MENS.MEN_DATA.value('local-name(.)', 'varchar(100)')
				FROM @MensagemXML.nodes('*') AS XML_MENS(MEN_DATA)
-- atualiza declaração em função da mensagem de resposta obtida
				IF @NomeMensagem = 'mensagemICAUM002A'
				BEGIN
-- obtem dados da mensagem ICAUM002A
					SELECT @XMLOperacao = NULLIF(XML_MENS.MEN_DATA.value('(cabecalho/operacaoSolicitada)[1]', 'varchar(4)'), ''),
						@XMLEstadoOperacao = NULLIF(XML_MENS.MEN_DATA.value('(cabecalho/estadoOperacao)[1]', 'varchar(2)'), ''),
						@XMLNumeroNRM = NULLIF(XML_MENS.MEN_DATA.value('(numeracaoDefinitiva/numeroAceitacao)[1]', 'varchar(18)'), ''),
						@XMLDataNRM = XML_MENS.MEN_DATA.value('(numeracaoDefinitiva/dataAceitacao)[1]', 'datetime'),
						@XMLVersao = XML_MENS.MEN_DATA.value('(numeracaoDefinitiva/versaoNova)[1]', 'int'),
						@XMLNumeroProvisorio = NULLIF(XML_MENS.MEN_DATA.value('(numeracaoProvisoria/numeroProvisorio)[1]', 'varchar(19)'), '')
					FROM @MensagemXML.nodes('mensagemICAUM002A/mensagens/icaum002a') AS XML_MENS(MEN_DATA)
-- atualiza declaração DAR p/ alteração do status e utilizador/data
					UPDATE tb_DeclaracoesDAR SET [status] = (CASE 
																WHEN (@XMLOperacao = '0110') AND (@XMLEstadoOperacao = 'RE') THEN 0 
																WHEN (@XMLOperacao IN ('0270', '0710')) AND (@XMLEstadoOperacao = 'AP') THEN 4 
																ELSE 2 
															END), 
						estadoOperacao = @XMLEstadoOperacao, 
						versao = ISNULL(@XMLVersao, versao), 
						numeroProvisorio = ISNULL(@XMLNumeroProvisorio, numeroProvisorio), 
						numeroNRM = ISNULL(@XMLNumeroNRM, numeroNRM), 
						dataNRM = ISNULL(@XMLDataNRM, dataNRM), 
						id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual 
					WHERE id = @Id
-- insere no detalhe de mensagens os dados da obtenção da declaração DAR
					INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
					VALUES(@id, 0, ('ICAUM002A-' + @XMLOperacao), @IdUtilizador, @DataAtual, @RequestXML, @MensagemXML, 1, @XMLEstadoOperacao, @IdUtilizador, @DataAtual)
				END
				ELSE
				IF @NomeMensagem = 'mensagemICAUM003A'
				BEGIN
-- obtem dados da mensagem ICAUM003A
					SELECT @XMLEstadoOperacao = NULLIF(REPLACE(SUBSTRING(XML_MENS.MEN_DATA.value('(cabecalho/tipoControlo)[1]', 'varchar(35)'), 1, CHARINDEX('-', XML_MENS.MEN_DATA.value('(cabecalho/tipoControlo)[1]', 'varchar(35)')) - 1), '*', ''), ''),				
						@XMLConferente = NULLIF(XML_MENS.MEN_DATA.value('(cabecalho/conferente)[1]', 'varchar(80)'), ''),
						@XMLVerificador = NULLIF(XML_MENS.MEN_DATA.value('(cabecalho/verificador)[1]', 'varchar(80)'), ''),					
						@XMLDataControlo = CONVERT(datetime, XML_MENS.MEN_DATA.value('(cabecalho/realizacaoControlo/dataControlo)[1]', 'varchar(10)') + ' ' + XML_MENS.MEN_DATA.value('(cabecalho/realizacaoControlo/horaControlo)[1]', 'varchar(11)'), 127)
					FROM @MensagemXML.nodes('mensagemICAUM003A/mensagens/icaum003a') AS XML_MENS(MEN_DATA)
-- atualiza declaração DAR p/ alteração do status e utilizador/data
					UPDATE tb_DeclaracoesDAR SET [status] = 2, estadoOperacao = @XMLEstadoOperacao, 
						controloDocumental = (CASE @XMLEstadoOperacao WHEN 'CD' THEN 1 ELSE controloDocumental END), 
						dataControloDocumental = (CASE @XMLEstadoOperacao WHEN 'CD' THEN @XMLDataControlo ELSE dataControloDocumental END), 
						conferenteControloDocumental = (CASE @XMLEstadoOperacao WHEN 'CD' THEN @XMLConferente ELSE conferenteControloDocumental END), 
						verificadorControloDocumental = (CASE @XMLEstadoOperacao WHEN 'CD' THEN @XMLVerificador ELSE verificadorControloDocumental END), 
						controloFisico = (CASE WHEN @XMLEstadoOperacao IN ('CF', 'CFP', 'CFT') THEN 1 ELSE controloFisico END), 
						dataControloFisico = (CASE WHEN @XMLEstadoOperacao IN ('CF', 'CFP', 'CFT') THEN @XMLDataControlo ELSE dataControloFisico END), 
						conferenteControloFisico = (CASE WHEN @XMLEstadoOperacao IN ('CF', 'CFP', 'CFT') THEN @XMLConferente ELSE conferenteControloFisico END), 
						verificadorControloFisico = (CASE WHEN @XMLEstadoOperacao IN ('CF', 'CFP', 'CFT') THEN @XMLVerificador ELSE verificadorControloFisico END), 
						controloAduaneiro = (CASE @XMLEstadoOperacao WHEN 'CAP' THEN 1 ELSE controloAduaneiro END), 
						dataControloAduaneiro = (CASE @XMLEstadoOperacao WHEN 'CAP' THEN @XMLDataControlo ELSE dataControloAduaneiro END), 
						conferenteControloAduaneiro = (CASE @XMLEstadoOperacao WHEN 'CAP' THEN @XMLConferente ELSE conferenteControloAduaneiro END), 
						verificadorControloAduaneiro = (CASE @XMLEstadoOperacao WHEN 'CAP' THEN @XMLVerificador ELSE verificadorControloAduaneiro END), 
						id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual 
					WHERE id = @Id
-- insere no detalhe de mensagens os dados da obtenção da declaração DAR
					INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
					VALUES(@id, 0, 'ICAUM003A', @IdUtilizador, @DataAtual, @RequestXML, @MensagemXML, 1, @XMLEstadoOperacao, @IdUtilizador, @DataAtual)
-- processa o envio de emails de notificação de controlo para spool de acordo com as configurações
					EXEC sp_DeclaracoesDAR_ProcessaEnvioEmailNotificacaoControlo @id, @Erro OUTPUT
				END
				ELSE
				IF @NomeMensagem = 'mensagemICAUM004A'
				BEGIN
-- obtem dados da mensagem ICAUM004A
					SELECT @XMLEstadoOperacao = NULLIF(SUBSTRING(XML_MENS.MEN_DATA.value('(resultadoControlo/tipoControlo)[1]', 'varchar(35)'), 1, CHARINDEX('-', XML_MENS.MEN_DATA.value('(resultadoControlo/tipoControlo)[1]', 'varchar(35)')) - 1), ''),								
						@XMLDataControlo = XML_MENS.MEN_DATA.value('(resultadoControlo/dataControloDoc)[1]', 'datetime')
					FROM @MensagemXML.nodes('mensagemICAUM004A/mensagens/icaum004a') AS XML_MENS(MEN_DATA)
-- atualiza declaração DAR p/ alteração do status e utilizador/data
					UPDATE tb_DeclaracoesDAR SET [status] = 2, estadoOperacao = @XMLEstadoOperacao, 
						fechadoControloDocumental = (CASE @XMLEstadoOperacao WHEN 'CD' THEN 1 ELSE fechadoControloDocumental END), 
						dataFechoControloDocumental = (CASE @XMLEstadoOperacao WHEN 'CD' THEN @XMLDataControlo ELSE dataFechoControloDocumental END), 					
						fechadoControloFisico = (CASE WHEN @XMLEstadoOperacao IN ('CF', 'CFP', 'CFT') THEN 1 ELSE fechadoControloFisico END), 
						dataFechoControloFisico = (CASE WHEN @XMLEstadoOperacao IN ('CF', 'CFP', 'CFT') THEN @XMLDataControlo ELSE dataFechoControloFisico END), 					
						fechadoControloAduaneiro = (CASE @XMLEstadoOperacao WHEN 'CAP' THEN 1 ELSE fechadoControloAduaneiro END), 
						dataFechoControloAduaneiro = (CASE @XMLEstadoOperacao WHEN 'CAP' THEN @XMLDataControlo ELSE dataFechoControloAduaneiro END), 
						id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual 
					WHERE id = @Id
-- insere no detalhe de mensagens os dados da obtenção da declaração DAR
					INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
					VALUES(@id, 0, 'ICAUM004A', @IdUtilizador, @DataAtual, @RequestXML, @MensagemXML, 1, @XMLEstadoOperacao, @IdUtilizador, @DataAtual)
				END
				ELSE
				IF @NomeMensagem = 'mensagemICAUM005A'
				BEGIN
-- obtem dados da mensagem ICAUM005A
					SELECT @XMLEstadoOperacao = (CASE XML_MENS.MEN_DATA.value('(cabecalho/estadoOperacao)[1]', 'varchar(2)') 
													WHEN 'AP' THEN 'ND' 
													ELSE XML_MENS.MEN_DATA.value('(cabecalho/estadoOperacao)[1]', 'varchar(2)') 
												END),
						@XMLNumeroLiquidacao = NULLIF(XML_MENS.MEN_DATA.value('(dadosContabilisticos/registoLiquidacao/numeroRegistoLiquidacao)[1]', 'varchar(10)'), ''), 
						@XMLDataLiquidacao = XML_MENS.MEN_DATA.value('(dadosContabilisticos/registoLiquidacao/dataRegistoLiquidacao)[1]', 'datetime'),
						@XMLDataPagamento = XML_MENS.MEN_DATA.value('(dadosContabilisticos/registoLiquidacao/dataLimitePagamento)[1]', 'datetime'),
						@XMLMontante = XML_MENS.MEN_DATA.value('(dadosContabilisticos/registoLiquidacao/montante)[1]', 'decimal(18, 2)')
					FROM @MensagemXML.nodes('mensagemICAUM005A/mensagens/icaum005a') AS XML_MENS(MEN_DATA)
-- atualiza declaração DAR p/ alteração do status e utilizador/data
					UPDATE tb_DeclaracoesDAR SET [status] = (CASE @XMLEstadoOperacao WHEN 'RE' THEN 0 ELSE 2 END), estadoOperacao = @XMLEstadoOperacao, 
						numeroRegistoLiquidacao = ISNULL(@XMLNumeroLiquidacao, numeroRegistoLiquidacao), 
						dataRegistoLiquidacao = ISNULL(@XMLDataLiquidacao, dataRegistoLiquidacao), 
						dataLimitePagamento = ISNULL(@XMLDataPagamento, dataLimitePagamento), 
						totalIVA = ISNULL(@XMLMontante, totalIVA), 
						id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual 
					WHERE id = @Id
-- insere no detalhe de mensagens os dados da obtenção da declaração DAR
					INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
					VALUES(@id, 0, 'ICAUM005A', @IdUtilizador, @DataAtual, @RequestXML, @MensagemXML, 1, @XMLEstadoOperacao, @IdUtilizador, @DataAtual)
				END
				ELSE
				IF @NomeMensagem = 'mensagemICAUM006A'
				BEGIN
-- obtem dados da mensagem ICAUM006A
					SELECT @XMLEstadoOperacao = (CASE 
													WHEN (XML_MENS.MEN_DATA.value('(cabecalho/codigoOperacao)[1]', 'varchar(4)') = '0610') AND (XML_MENS.MEN_DATA.value('(autorizacaoSaida/data)[1]', 'datetime') IS NOT NULL) THEN 'AS' 
													WHEN (XML_MENS.MEN_DATA.value('(cabecalho/codigoOperacao)[1]', 'varchar(4)') = '0620') AND (XML_MENS.MEN_DATA.value('(autorizacaoSaida/data)[1]', 'datetime') IS NOT NULL) THEN 'SNA'
													ELSE NULL 
												END),
						@XMLDataControlo = XML_MENS.MEN_DATA.value('(autorizacaoSaida/data)[1]', 'datetime')
					FROM @MensagemXML.nodes('mensagemICAUM006A/mensagens/icaum006a') AS XML_MENS(MEN_DATA)
-- atualiza declaração DAR p/ alteração do status e utilizador/data
					UPDATE tb_DeclaracoesDAR SET [status] = 2, estadoOperacao = ISNULL(@XMLEstadoOperacao, estadoOperacao), 
						autorizacaoSaida = (CASE @XMLEstadoOperacao WHEN 'AS' THEN 1 WHEN 'SNA' THEN 0 ELSE autorizacaoSaida END), 
						dataAutorizacaoSaida = (CASE @XMLEstadoOperacao WHEN 'AS' THEN @XMLDataControlo WHEN 'SNA' THEN NULL ELSE autorizacaoSaida END), 
						envioEntregue = (CASE @XMLEstadoOperacao WHEN 'AS' THEN 1 WHEN 'SNA' THEN 0 ELSE envioEntregue END), 
						bloqueado = (CASE @XMLEstadoOperacao WHEN 'AS' THEN 1 WHEN 'SNA' THEN 0 ELSE bloqueado END), 
						id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual
					WHERE id = @Id
-- insere no detalhe de mensagens os dados da obtenção da declaração DAR
					INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
					VALUES(@id, 0, 'ICAUM006A', @IdUtilizador, @DataAtual, @RequestXML, @MensagemXML, 1, @XMLEstadoOperacao, @IdUtilizador, @DataAtual)
				END
				ELSE
				IF @NomeMensagem = 'mensagemICAUM008A'
				BEGIN
-- obtem dados da mensagem ICAUM008A
					SELECT @XMLEstadoOperacao = (CASE 
													WHEN XML_MENS.MEN_DATA.value('(cabecalho/dataAlteracao)[1]', 'datetime') IS NOT NULL THEN 'ALT' 
													ELSE NULL 
												END)					
					FROM @MensagemXML.nodes('mensagemICAUM008A/mensagens/icaum008a') AS XML_MENS(MEN_DATA)
-- atualiza declaração DAR p/ alteração do status e utilizador/data
					UPDATE tb_DeclaracoesDAR SET [status] = 2, estadoOperacao = ISNULL(@XMLEstadoOperacao, estadoOperacao), 					
						id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual 
					WHERE id = @Id
-- insere no detalhe de mensagens os dados da obtenção da declaração DAR
					INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
					VALUES(@id, 0, 'ICAUM008A', @IdUtilizador, @DataAtual, @RequestXML, @MensagemXML, 1, @XMLEstadoOperacao, @IdUtilizador, @DataAtual)
				END
				FETCH NEXT FROM FicheirosXML INTO @MensagemXMLBase64
			END
			CLOSE FicheirosXML
			DEALLOCATE FicheirosXML
		END
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- insere no detalhe de mensagens os dados da obtenção da declaração DAR
		IF (@RequestXML IS NOT NULL) AND (ISNULL(@RespostasXML, @ResponseXML) IS NOT NULL)
		BEGIN
			INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
			VALUES(@id, 0, 'ICAUM????', @IdUtilizador, @DataAtual, @RequestXML, ISNULL(@RespostasXML, @ResponseXML), 0, NULL, @IdUtilizador, @DataAtual)	
		END
	END CATCH	
-- processa obtenção dos documentos PDF
	IF @Ambito IN (0, 2)
	BEGIN
-- inicia processo de obtenção de PDFs da declaração
		BEGIN TRY	
			SET @FaultCode = NULL
			SET @FaultMessage = NULL
			SET @RespostasXML = NULL
			SET @FicheirosXML = NULL
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- em função do âmbito constroi o respetivo request
			IF @Ambito = 0
			BEGIN
-- constroi estrutura XML com os dados do pedido ao metodo obterDocumentosPDFNaoEntregues a enviar à AT		
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
					'http://net.atos.at.impec.canalWS/' AS web, 
					'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
				SELECT @RequestXML = 
					(SELECT 
						(SELECT 
							(SELECT
								(SELECT 
									@LoginWS AS "wss:Username", 
									@PwdWSEncriptada AS "wss:Password",
									@ChvSimetricaEncriptada AS "wss:Nonce",
									@DataSistemaEncriptada AS "wss:Created"
								FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
							FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
						FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
						(SELECT
							(SELECT 
								(SELECT 
									(SELECT
										dar.numeroReferenciaLocal AS "numeroReferenciaLocal"
									FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK)
									WHERE id = @Id
									FOR XML PATH('listaNRLs'), TYPE),
									@Tipo AS "tipo"
								FOR XML PATH('obterDocumentosPDFNaoEntreguesInput'), TYPE)
							FOR XML PATH('web:obterDocumentosPDFNaoEntregues'), TYPE)		
						FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Envelope'), ELEMENTS)	
			END
			ELSE
			BEGIN
-- constroi estrutura XML com os dados do pedido ao metodo obterDocumentosPDFEntregues a enviar à AT		
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
					'http://net.atos.at.impec.canalWS/' AS web, 
					'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
				SELECT @RequestXML = 
					(SELECT 
						(SELECT 
							(SELECT
								(SELECT 
									@LoginWS AS "wss:Username", 
									@PwdWSEncriptada AS "wss:Password",
									@ChvSimetricaEncriptada AS "wss:Nonce",
									@DataSistemaEncriptada AS "wss:Created"
								FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
							FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
						FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
						(SELECT
							(SELECT 
								(SELECT 
									(SELECT
										dar.numeroReferenciaLocal AS "numeroReferenciaLocal"
									FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK)
									WHERE id = @Id
									FOR XML PATH(''), TYPE),
									@Tipo AS "tipo"
								FOR XML PATH('obterDocumentosEntreguesInput'), TYPE)
							FOR XML PATH('web:obterDocumentosPDFEntregues'), TYPE)		
						FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Envelope'), ELEMENTS)
			END
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, 'http://net.atos.at.impec.canalWS/STADAIMPCAUCanalWebService/obterDocumentosPDFNaoEntregues', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 6, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') as XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 7, @FaultMessage)					
-- em função do âmbito, obtem o resultado "OK"/"NOK" retornados do WS			
			IF @Ambito = 0
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impec.canalWS/' AS m)		
				SELECT 
					@FaultCode = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostasXML = XML_MSGR.MSG_DATA.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterDocumentosPDFNaoEntreguesResponse/return') as XML_MSGR(MSG_DATA)					
			END
			ELSE
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impec.canalWS/' AS m)		
				SELECT 
					@FaultCode = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = XML_MSGR.MSG_DATA.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostasXML = XML_MSGR.MSG_DATA.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterDocumentosPDFEntreguesResponse/return') as XML_MSGR(MSG_DATA)					
			END
			IF @FaultCode <> '0'
				RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 8, @FaultMessage)			
-- obtem o resultado de sucesso de obtenção de resultados da declaração				
			SELECT 
				@FaultCode = XML_DECL.DEC_DATA.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_DECL.DEC_DATA.value('descricaoResultado[1]', 'nvarchar(MAX)'),
				@FicheirosXML = XML_DECL.DEC_DATA.query('ficheiroResposta')
			FROM @RespostasXML.nodes('declaracao') as XML_DECL(DEC_DATA)							
			IF (@FaultCode <> '100') AND (@FaultCode <> '101')
				RAISERROR('A declaração gerou o erro "%s".', 16, 9, @FaultMessage)		
-- obtem todos os ficheiros de resposta associados à declaração
			DECLARE FicheirosPDF CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT XML_FICH.FIC_DATA.value('nomeFicheiro[1]', 'varchar(200)'), 
					XML_FICH.FIC_DATA.value('ficheiro[1]', 'varchar(MAX)')
				FROM @FicheirosXML.nodes('ficheiroResposta') as XML_FICH(FIC_DATA)
			OPEN FicheirosPDF
			FETCH NEXT FROM FicheirosPDF INTO @NomeFicheiro, @MensagemXMLBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN 							
-- converte o Base64 para varbinary 
				SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@MensagemXMLBase64"))', 'varbinary(max)')
-- obtem do nome do ficheiro o tipo de mensagem
				IF CHARINDEX('.RLQ.', @NomeFicheiro) > 0
					SET @NomeMensagem = 'ICAUM005A'
				ELSE
					IF CHARINDEX('.AUT.', @NomeFicheiro) > 0
						SET @NomeMensagem = 'ICAUM006A'
					ELSE
					BEGIN
						SET @IndiceInicial = CHARINDEX('.ICAUM', @NomeFicheiro) + 1
						SET @IndiceFinal = CHARINDEX('A.', @NomeFicheiro, @IndiceInicial) + 1
						SET @NomeMensagem = SUBSTRING(@NomeFicheiro, @IndiceInicial, (@IndiceFinal - @IndiceInicial))
					END									
-- insere no detalhe de arquivos o ficheiro obtido da declaração DAR
				INSERT INTO tb_DeclaracoesDARArquivos(id_declaracaoDAR, descricao, tipo, nomeFicheiro, ficheiro, id_utilizadorArquivo, dataArquivo, origem, id_utilizadorControlo, dataControlo)
				VALUES(@id, @NomeMensagem, (CASE @NomeMensagem WHEN 'ICAUM002A' THEN 5 WHEN 'ICAUM003A' THEN 6 WHEN 'ICAUM004A' THEN 7 WHEN 'ICAUM005A' THEN 8 WHEN 'ICAUM006A' THEN 9 WHEN 'ICAUM008A' THEN 10 ELSE 4 END), 
					@NomeFicheiro, @FicheiroBinario, @IdUtilizador, @DataAtual, 1, @IdUtilizador, @DataAtual)
-- processa o envio de emails dos ficheiros das mensagens de Notificação de Dívida e Autorização de Saída para spool de acordo com as configurações
				IF (@NomeMensagem = 'ICAUM005A') OR (@NomeMensagem = 'ICAUM006A')
					EXEC sp_DeclaracoesDAR_ProcessaEnvioEmailArquivosResposta @id, @NomeMensagem, @NomeFicheiro, @FicheiroBinario, @Erro OUTPUT
				FETCH NEXT FROM FicheirosPDF INTO @NomeFicheiro, @MensagemXMLBase64
			END
			CLOSE FicheirosPDF
			DEALLOCATE FicheirosPDF
		END TRY
		BEGIN CATCH		
-- constroi mensagem de erro detalhada
			SET @NumErro = 1 
			SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
				+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
				+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
		END CATCH	
	END
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ObtemRespostaRegisto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ObtemRespostaRegisto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ObterDadosDMG]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ObterDadosDMG] @Operacao tinyint, @Id bigint, @IdDMG bigint, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @LstBasesDados varchar(250), @BaseDados varchar(100), @PassPhrase varchar(50), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), 
		@PathCertificado varchar(250), @PwdCertificado varchar(100), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), 
		@Resultado int, @PublicKeyCertificadoAT nvarchar(4000), @PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), @SoapAction varchar(200), 
		@RequestXML xml, @ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX), @EstadoDMG varchar(50), @ErrosDMG xml, @FicheiroPDFBase64 varchar(MAX), 
		@FicheiroBinario varbinary(MAX), @SQLString nvarchar(1000), @SQLParams nvarchar(500)
-- inicia outras variaveis
	SET @NumErro = 0
	SET @PassPhrase = '16345678901234567'
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de obtenção de respostas da declaração
	BEGIN TRY			
-- obtem a lista de outras bases de dados cujas declarações irão constar na DMG
		SELECT @LstBasesDados = baseDadosDMG 
		FROM tb_ConfiguracoesDAR
-- obtem configurações do Webservice e do Proxy Authentication
		SELECT @EnderecoWS = wsEnderecoDMG, @LoginWS = wsUtilizadorDMG, @PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPasswordDMG)), @PathCertificado = wsPathCertificado, 
			@PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPasswordCertificado)), @ProxyAuthentication = proxyAuthentication, @ProxyServer = ISNULL(proxyServer, ''), 
			@ProxyPort = ISNULL(proxyPort, 0), @ProxyUser = ISNULL(proxyUser, ''), @ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, proxyPassword)), '')
		FROM tb_ConfiguracoesDAR WITH(NOLOCK)	
-- obtem a chave pública do sistema de autenticação na AT para ambiente de produção
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT(0)
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
		EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi o request para a operação de consultar estados
		IF @Operacao = 0
		BEGIN
			SET @SoapAction = 'tns:consultarEstadoSubmissao'
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
				'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS dec, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 														
							@IdDMG AS "idDeclaracao"							
						FOR XML PATH('dec:consultarEstadoSubmissaoDMGIVARequest'), TYPE)	
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
		END
		ELSE
-- constroi o request para a operação de obter comprovativo
			IF @Operacao = 1
			BEGIN
				SET @SoapAction = 'tns:obterComprovativo'
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
					'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS dec, 
					'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
				SELECT @RequestXML = 
					(SELECT 
						(SELECT 
							(SELECT
								(SELECT 
									@LoginWS AS "wss:Username", 
									@PwdWSEncriptada AS "wss:Password",
									@ChvSimetricaEncriptada AS "wss:Nonce",
									@DataSistemaEncriptada AS "wss:Created"
								FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
							FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
						FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
						(SELECT
							(SELECT 														
								@IdDMG AS "idDeclaracao"							
							FOR XML PATH('dec:obterComprovativoDMGIVARequest'), TYPE)	
						FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
			END
			ELSE					
-- constroi o request para a operação de obter dados pagamento
				IF @Operacao = 2
				BEGIN
					SET @SoapAction = 'tns:obterDadosPagamento'
					;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
						'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS dec, 
						'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
					SELECT @RequestXML = 
						(SELECT 
							(SELECT 
								(SELECT
									(SELECT 
										@LoginWS AS "wss:Username", 
										@PwdWSEncriptada AS "wss:Password",
										@ChvSimetricaEncriptada AS "wss:Nonce",
										@DataSistemaEncriptada AS "wss:Created"
									FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
								FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
							FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
							(SELECT
								(SELECT 														
									@IdDMG AS "idDeclaracao"							
								FOR XML PATH('dec:obterDadosPagamentoDMGIVARequest'), TYPE)	
							FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
						FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
				END
-- processa envio do XML para o WebService da AT
		EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @SoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
		SELECT 
			@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
		SELECT 
			@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') as XML_MSGR(MSG_DATA)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)					
-- obtem dados do response para a operação de consultar estados			
		IF @Operacao = 0
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS ns0)		
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('codigo[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('mensagem[1]', 'nvarchar(MAX)'),
				@EstadoDMG = XML_MSGR.MSG_DATA.value('(dadosSubmissao/estado)[1]', 'nvarchar(50)'), 					
				@ErrosDMG = XML_MSGR.MSG_DATA.query('erros')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/ns0:consultarEstadoSubmissaoDMGIVAResponse') AS XML_MSGR(MSG_DATA)												
		END
		ELSE
-- obtem dados do response para a operação de obter comprovativo			
			IF @Operacao = 1
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS ns0)		
				SELECT 
					@FaultCode = XML_MSGR.MSG_DATA.value('codigo[1]', 'nvarchar(100)'), 
					@FaultMessage = XML_MSGR.MSG_DATA.value('mensagem[1]', 'nvarchar(MAX)'),
					@FicheiroPDFBase64 = XML_MSGR.MSG_DATA.value('comprovativo[1]', 'varchar(MAX)')						
				FROM @ResponseXML.nodes('env:Envelope/env:Body/ns0:obterComprovativoDMGIVAResponse') AS XML_MSGR(MSG_DATA)												
			END
			ELSE			
-- obtem dados do response para a operação de obter dados pagamento
				IF @Operacao = 2
				BEGIN
					;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS ns0)		
					SELECT 
						@FaultCode = XML_MSGR.MSG_DATA.value('codigo[1]', 'nvarchar(100)'), 
						@FaultMessage = XML_MSGR.MSG_DATA.value('mensagem[1]', 'nvarchar(MAX)'),
						@FicheiroPDFBase64 = XML_MSGR.MSG_DATA.value('documento[1]', 'varchar(MAX)')						
					FROM @ResponseXML.nodes('env:Envelope/env:Body/ns0:obterDadosPagamentoDMGIVAResponse') AS XML_MSGR(MSG_DATA)												
				END	
-- se resultado não for de sucesso, manda erro							
		IF @FaultCode <> '0'
			RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 4, @FaultMessage)
-- processa ação para a operação de consultar estados
		IF @Operacao = 0
		BEGIN
-- insere no histórico DMG nas várias base de dados o resultado da consulta do estado
			DECLARE BaseDados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT DB_NAME()
				UNION
				SELECT valor
				FROM FNT_Geral_SeparaTexto(@LstBasesDados, ';')
			OPEN BaseDados
			FETCH NEXT FROM BaseDados INTO @BaseDados
			WHILE @@FETCH_STATUS = 0
			BEGIN
				IF CHARINDEX('.', @BaseDados) = 0 -- não insere historico em linked servers devido à limitação dos mesmos com objetos do tipo xml
				BEGIN											
					SET @SQLString = N'INSERT INTO ' + @BaseDados + '.dbo.tb_HistoricoDMG(ano, mes, tipo, id_utilizadorSubmissao, dataSubmissao, pedido, resposta, idDMG, id_utilizadorControlo, dataControlo, estadoDMG, sucesso)
						SELECT ano, mes, 2, @INIdUtilizador, @INDataAtual, @INRequestXML, @INResponseXML, idDMG, @INIdUtilizador, @INDataAtual, @INEstadoDMG, 
							(CASE WHEN ISNULL(CAST(@INErrosDMG AS varchar(MAX)), '''') <> '''' THEN 0 ELSE 1 END)
						FROM ' + @BaseDados + '.dbo.tb_HistoricoDMG WITH(NOLOCK)
						WHERE id = @INId'
					SET @SQLParams = N'@INId bigint, @INIdUtilizador int, @INDataAtual datetime, @INRequestXML xml, @INResponseXML xml, @INEstadoDMG varchar(50), @INErrosDMG xml'
					EXECUTE sp_executesql @SQLString, @SQLParams, @INId = @Id, @INIdUtilizador = @IdUtilizador, @INDataAtual = @DataAtual, @INRequestXML = @RequestXML, @INResponseXML = @ResponseXML, @INEstadoDMG = @EstadoDMG, @INErrosDMG = @ErrosDMG
				END
				FETCH NEXT FROM BaseDados INTO @BaseDados
			END
			CLOSE BaseDados
			DEALLOCATE BaseDados												
-- se consulta de estado devolveu erros, manda erro
			IF ISNULL(CAST(@ErrosDMG AS varchar(MAX)), '') <> ''
				RAISERROR('O estado da DMG gerou o erro "%s".', 16, 5, @FaultMessage)			
		END
		ELSE
-- processa ação para a operação de obter comprovativo
			IF @Operacao = 1
			BEGIN
-- converte o Base64 para varbinary 
				SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@FicheiroPDFBase64"))', 'varbinary(max)')
-- atualiza no histórico DMG nas várias base de dados que o ficheiro de comprovativo
				DECLARE BaseDados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
					SELECT DB_NAME()
					UNION
					SELECT valor
					FROM FNT_Geral_SeparaTexto(@LstBasesDados, ';')
				OPEN BaseDados
				FETCH NEXT FROM BaseDados INTO @BaseDados
				WHILE @@FETCH_STATUS = 0
				BEGIN
					IF CHARINDEX('.', @BaseDados) = 0 -- não insere historico em linked servers devido à limitação dos mesmos com objetos do tipo xml
					BEGIN											
						SET @SQLString = N'UPDATE ' + @BaseDados + '.dbo.tb_HistoricoDMG SET ficheiroComprovativo = @INFicheiroBinario, id_utilizadorControlo = @INIdUtilizador, dataControlo = @INDataAtual
							WHERE id = @INId'
						SET @SQLParams = N'@INId bigint, @INIdUtilizador int, @INDataAtual datetime, @INFicheiroBinario varbinary(MAX)'
						EXECUTE sp_executesql @SQLString, @SQLParams, @INId = @Id, @INIdUtilizador = @IdUtilizador, @INDataAtual = @DataAtual, @INFicheiroBinario = @FicheiroBinario
					END
					FETCH NEXT FROM BaseDados INTO @BaseDados
				END
				CLOSE BaseDados
				DEALLOCATE BaseDados				
			END		
			ELSE
-- processa ação para a operação de obter dados pagamento
				IF @Operacao = 2
				BEGIN
-- converte o Base64 para varbinary 
					SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@FicheiroPDFBase64"))', 'varbinary(max)')
-- atualiza no histórico DMG nas várias base de dados que o ficheiro de comprovativo
					DECLARE BaseDados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
						SELECT DB_NAME()
						UNION
						SELECT valor
						FROM FNT_Geral_SeparaTexto(@LstBasesDados, ';')
					OPEN BaseDados
					FETCH NEXT FROM BaseDados INTO @BaseDados
					WHILE @@FETCH_STATUS = 0
					BEGIN
						IF CHARINDEX('.', @BaseDados) = 0 -- não insere historico em linked servers devido à limitação dos mesmos com objetos do tipo xml
						BEGIN											
							SET @SQLString = N'UPDATE ' + @BaseDados + '.dbo.tb_HistoricoDMG SET ficheiroPagamento = @INFicheiroBinario, id_utilizadorControlo = @INIdUtilizador, dataControlo = @INDataAtual
								WHERE id = @INId'
							SET @SQLParams = N'@INId bigint, @INIdUtilizador int, @INDataAtual datetime, @INFicheiroBinario varbinary(MAX)'
							EXECUTE sp_executesql @SQLString, @SQLParams, @INId = @Id, @INIdUtilizador = @IdUtilizador, @INDataAtual = @DataAtual, @INFicheiroBinario = @FicheiroBinario
						END
						FETCH NEXT FROM BaseDados INTO @BaseDados
					END
					CLOSE BaseDados
					DEALLOCATE BaseDados
				END		
	END TRY
	BEGIN CATCH				
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH		
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ObterDadosDMG] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ObterDadosDMG] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ProcessaEnvioEmailArquivosResposta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ProcessaEnvioEmailArquivosResposta] @IdDeclaracaoDAR int, @NomeMensagem varchar(50), @NomeFicheiro varchar(200), @FicheiroBinario varbinary(MAX), 
	@Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @EstadoOperacao varchar(3), @EmailDeclarante varchar(100), @EmailCliente varchar(250), @EmailCliente2 varchar(250), @Assunto varchar(250), 
		@Texto varchar(MAX)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de envio de email de notificação de controlo para spool
	BEGIN TRY	
		SET @NumErro = 0
-- obtem se ficheiro da mensagem já foi arquivado para definir tipo de ficheiro
		IF @NomeMensagem = 'ICAUM005A' 
		BEGIN
			IF EXISTS(SELECT id_declaracaoDAR FROM tb_DeclaracoesDARArquivos WITH(NOLOCK) WHERE id_declaracaoDAR = @IdDeclaracaoDAR AND nomeFicheiro LIKE '%.RLQ.%' AND origem = 1 GROUP BY id_declaracaoDAR HAVING COUNT(*) > 1)
				SET @NomeMensagem = @NomeMensagem + '.1'
			ELSE
				SET @NomeMensagem = @NomeMensagem + '.0'
		END
		ELSE
			IF @NomeMensagem = 'ICAUM006A' 
			BEGIN
				IF EXISTS(SELECT id_declaracaoDAR FROM tb_DeclaracoesDARArquivos WITH(NOLOCK) WHERE id_declaracaoDAR = @IdDeclaracaoDAR AND nomeFicheiro LIKE '%.AUT.%' AND origem = 1 GROUP BY id_declaracaoDAR HAVING COUNT(*) > 1)
					SET @NomeMensagem = @NomeMensagem + '.1'
				ELSE
					SET @NomeMensagem = @NomeMensagem + '.0'
			END
-- obtem os dados para envio na declaração
		SELECT @EmailDeclarante = dcl.DEC_EMAI, @Assunto = cer.assuntoEmail, @Texto = cer.textoEmail, @EmailCliente = cli.CLI_EMAI, @EmailCliente2 = cli.CLI_EMA2
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dar.id_declarante = dcl.DEC_IDTY
			INNER JOIN tb_ConfiguracoesDAREmailsResposta AS cer WITH(NOLOCK) ON cer.mensagem = @NomeMensagem AND cer.ativo = 1 AND SUBSTRING(cer.listaRegimesIVA, dar.regimeIVA, 1) = '1'
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
		WHERE dar.id = @IdDeclaracaoDAR AND ISNULL(dcl.DEC_EMAI, '') <> '' AND ISNULL(cli.CLI_EMAI, '') <> '' AND cli.CLI_IEDA = 0			
-- se configurações todas ativas, insere os dados do email do ficheiro da resposta no spool para o email configurado
		IF (ISNULL(@EmailDeclarante, '') <> '') AND (ISNULL(@Assunto, '') <> '') AND (ISNULL(@EmailCliente, '') <> '') 
		BEGIN
-- descodifica assunto e texto do email
			EXEC sp_DeclaracoesDAR_DescodificaTexto @IdDeclaracaoDAR, @Assunto OUTPUT
			EXEC sp_DeclaracoesDAR_DescodificaTexto @IdDeclaracaoDAR, @Texto OUTPUT
-- insere pedido de envio de email no spool
			INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_IMPR, IMF_STAT, IMF_DTST, IMF_FBIN, IMF_TIPO, IMF_FROM, IMF_PARA, IMF_ASSU, IMF_TEXT, IMF_NFIC, IMF_CCOP)
			VALUES(@DataAtual, 'SMTP', 0, @DataAtual, @FicheiroBinario, 1, @EmailDeclarante, @EmailCliente, @Assunto, @Texto, @NomeFicheiro, @EmailCliente2)
		END
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ProcessaEnvioEmailArquivosResposta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ProcessaEnvioEmailArquivosResposta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ProcessaEnvioEmailNotificacaoControlo]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ProcessaEnvioEmailNotificacaoControlo] @Id int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @EstadoOperacao varchar(3), @EmailDeclarante varchar(50), @Assunto varchar(250), @Texto varchar(MAX)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de envio de email de notificação de controlo para spool
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados para envio na declaração
		SELECT @EstadoOperacao = dar.estadoOperacao, @EmailDeclarante = dcl.DEC_EMAI, 
			@Assunto = 'Aviso de ' + (CASE dar.estadoOperacao 
										WHEN 'CF' THEN 'Controlo Físico' 
										WHEN 'CFP' THEN 'Controlo Físico Parcial' 
										WHEN 'CFT' THEN 'Controlo Físico Total' 
										WHEN 'CD' THEN 'Controlo Documental' 
										WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
										ELSE '?????' 
									END), 
			@Texto = 'Dados da declaração DAR:' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) +
			         '		.Declaração N.º....: ' + CAST(dar.numero AS varchar(10)) + CHAR(13) + CHAR(10) +
					 '		.NRL.....................: ' + dar.numeroReferenciaLocal + CHAR(13) + CHAR(10) +
					 '		.NRM....................: ' + ISNULL(dar.numeroNRM, '') + CHAR(13) + CHAR(10) +
					 '		.Cliente.................: ' + dar.nomeCliente + CHAR(13) + CHAR(10) +
					 '		.Doc. Transporte...: ' + dar.documentoTransporte + CHAR(13) + CHAR(10) +
					 '		.Tipo de Controlo..: ' + (CASE dar.estadoOperacao 
														WHEN 'CF' THEN 'Controlo Físico' 
														WHEN 'CFP' THEN 'Controlo Físico Parcial' 
														WHEN 'CFT' THEN 'Controlo Físico Total' 
														WHEN 'CD' THEN 'Controlo Documental' 
														WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
														ELSE '?????' 
													END) + CHAR(13) + CHAR(10) +
					 '		.Conferente...........: ' + (CASE dar.estadoOperacao 
														WHEN 'CF' THEN ISNULL(dar.conferenteControloFisico, '') 
														WHEN 'CFP' THEN ISNULL(dar.conferenteControloFisico, '')
														WHEN 'CFT' THEN ISNULL(dar.conferenteControloFisico, '')
														WHEN 'CD' THEN ISNULL(dar.conferenteControloDocumental, '') 
														WHEN 'CAP' THEN ISNULL(dar.conferenteControloAduaneiro, '') 
														ELSE '?????' 
													END) + CHAR(13) + CHAR(10) + 
					 '		.Verificador............: ' + (CASE dar.estadoOperacao 
														WHEN 'CF' THEN ISNULL(dar.verificadorControloFisico, '') 
														WHEN 'CFP' THEN ISNULL(dar.verificadorControloFisico, '') 
														WHEN 'CFT' THEN ISNULL(dar.verificadorControloFisico, '') 
														WHEN 'CD' THEN ISNULL(dar.verificadorControloDocumental, '') 
														WHEN 'CAP' THEN ISNULL(dar.verificadorControloAduaneiro, '') 
														ELSE '?????' 
													END) + CHAR(13) + CHAR(10)
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dar.id_declarante = dcl.DEC_IDTY
		WHERE dar.id = @Id
-- insere os dados do email de notificação de controlo no spool para os emails configurados
		INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_IMPR, IMF_STAT, IMF_DTST, IMF_TIPO, IMF_FROM, IMF_PARA, IMF_ASSU, IMF_TEXT)
		SELECT @DataAtual, 'SMTP', 0, @DataAtual, 1, @EmailDeclarante, enderecoEmail, @Assunto, @Texto
		FROM tb_ConfiguracoesDARNotificacoesControlo WITH(NOLOCK)
		WHERE (@EstadoOperacao = 'CAP' AND enviaEmailEmCAP = 1)
		OR (@EstadoOperacao = 'CD' AND enviaEmailEmCD = 1)
		OR (@EstadoOperacao IN ('CF', 'CFP', 'CFT') AND enviaEmailEmCF = 1)
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ProcessaEnvioEmailNotificacaoControlo] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ProcessaEnvioEmailNotificacaoControlo] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ProcessaListagem]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ProcessaListagem] @ModoMenu bit, @IDListagem tinyint, @Ano smallint, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @MesAtual tinyint
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
	SET @MesAtual = MONTH(@DataAtual)
	BEGIN TRY	
		SET @NumErro = 0
-- obtem as listagens a apresentar nas declarações DAR
		IF @ModoMenu = 1
		BEGIN
			SELECT 0 AS id, 'Standard (Mensal)' AS titulo, 'Vista Standard p/ Mês Atual' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 1 AS id, 'Standard (Global)' AS titulo, 'Vista Standard Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 2 AS id, 'Reduzida (Mensal)' AS titulo, 'Vista Reduzida p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 3 AS id, 'Reduzida (Global)' AS titulo, 'Vista Reduzida Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 4 AS id, 'Declaração Mensal IVA' AS titulo, 'Vista Declaração Mensal IVA' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 5 AS id, 'Detalhada (Mensal)' AS titulo, 'Vista Detalhada p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 6 AS id, 'Detalhada (Global)' AS titulo, 'Vista Detalhada Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			UNION
			SELECT 7 AS id, 'IOSS (Mensal)' AS titulo, 'Vista IOSS p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 8 AS id, 'IOSS (Global)' AS titulo, 'Vista IOSS Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			ORDER BY id, titulo
		END
		ELSE
		BEGIN
-- obtem as declarações DAR para as listagens "Standard (Mensal)" e "Standard (Global)"
			IF @IDListagem IN (0, 1)
			BEGIN
				SELECT dar.id, dar.numero AS "Número", dar.data AS "Data", 
					(CASE dar.regimeIVA WHEN 1 THEN 'IOSS' WHEN 2 THEN 'Especial' WHEN 3 THEN 'Geral' ELSE NULL END) AS "Regime IVA", 
					dar.regimeAdicional AS "Ad. Regime", nat.NDE_CODI AS "Natureza", nat.NDE_NOME AS "_Nome Natureza", dar.documentoTransporte AS "Documento Transporte", 
					(CASE dar.status WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Finalizado' WHEN 4 THEN 'Anulado' ELSE 'Por Enviar' END) AS "Status", 
					(CASE dar.estadoOperacao WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'AJ' THEN 'Operação Pendente' WHEN 'SC' THEN 'Sem Controlo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' WHEN 'CD' THEN 'Controlo Documental' WHEN 'CF' THEN 'Controlo Físico' WHEN 'CFP' THEN 'Controlo Físico Parcial' WHEN 'CFT' THEN 'Controlo Físico Total' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída Não Autorizada' ELSE NULL END) AS "Estado Operação", 
					dar.numeroNRM AS "Número NRM", dar.dataNRM AS "Data NRM", dar.nomeFornecedor AS "Exportador", dar.nomeCliente AS "Importador", dar.nifCliente AS "NIF Importador", 
					dar.beneficiarioIVACliente AS "B.IVA", 
					(CASE dar.estatutoDeclarante WHEN 1 THEN 'Representação Direta' ELSE NULL END) AS "Estatuto", 
					alf.ALF_CODI AS "Estância", alf.ALF_NOME AS "_Nome Estância", dar.numeroReferenciaLocal AS "N.º Referência Local", dar.totalMontante AS "Montante Total", pmo.PAI_CODI AS "Moeda", 
					dar.totalMontanteEUR AS "Total EUR", dar.totalCustosTransporte AS "Custos Transporte", dar.totalAdicoes AS "Total Adições", dar.totalVolumes AS "Total Volumes", 
					dar.totalMassaBruta AS "Total Massa Bruta", 
					ISNULL(NULLIF(cnt.CDO_INVN, ''), (cnt.CDO_TDOC + ' ?/?')) AS "N.º Conta", 
					dar.totalIVA AS "Dívida Aduaneira", dar.numeroRegistoLiquidacao	AS "N.º Liquidação", dar.dataLimitePagamento AS "Data Pagamento", dar.numeroTD AS "N.º TD"					
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmo.PAI_IDTY
					LEFT OUTER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON dar.id_conta = cnt.CDO_IDTY
				WHERE dar.ano = @Ano AND (CASE @IDListagem WHEN 0 THEN MONTH(dar.data) ELSE @MesAtual END) = @MesAtual
				ORDER BY dar.numero
			END
			ELSE
-- obtem as declarações DAR para as listagens "Reduzida (Mensal)" e "Reduzida (Global)"
			IF @IDListagem IN (2, 3)
			BEGIN
				SELECT dar.id, dar.numero AS "Número", dar.data AS "Data", 
					(CASE dar.regimeIVA WHEN 1 THEN 'IOSS' WHEN 2 THEN 'Especial' WHEN 3 THEN 'Geral' ELSE NULL END) AS "Regime IVA", 
					dar.regimeAdicional AS "Ad. Regime", nat.NDE_CODI AS "Natureza", nat.NDE_NOME AS "_Nome Natureza", dar.documentoTransporte AS "Documento Transporte", 
					(CASE dar.status WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Finalizado' WHEN 4 THEN 'Anulado' ELSE 'Por Enviar' END) AS "Status", 
					(CASE dar.estadoOperacao WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'AJ' THEN 'Operação Pendente' WHEN 'SC' THEN 'Sem Controlo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' WHEN 'CD' THEN 'Controlo Documental' WHEN 'CF' THEN 'Controlo Físico' WHEN 'CFP' THEN 'Controlo Físico Parcial' WHEN 'CFT' THEN 'Controlo Físico Total' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída Não Autorizada' ELSE NULL END) AS "Estado Operação", 
					dar.nomeFornecedor AS "_Exportador", dar.nomeCliente AS "_Importador", dar.nifCliente AS "NIF Importador", dar.beneficiarioIVACliente AS "B.IVA", 
					alf.ALF_CODI AS "Estância", alf.ALF_NOME AS "_Nome Estância", dar.numeroReferenciaLocal AS "N.º Referência Local", dar.totalMontante AS "_Montante Total", pmo.PAI_CODI AS "_Moeda", 
					dar.totalMontanteEUR AS "Total EUR", dar.totalCustosTransporte AS "_Custos Transporte", dar.totalAdicoes AS "Total Adições", dar.totalVolumes AS "Total Volumes", 
					dar.totalMassaBruta AS "Total Massa Bruta", 
					ISNULL(NULLIF(cnt.CDO_INVN, ''), (cnt.CDO_TDOC + ' ?/?')) AS "N.º Conta", 
					dar.totalIVA AS "Dívida Aduaneira"
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmo.PAI_IDTY
					LEFT OUTER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON dar.id_conta = cnt.CDO_IDTY
				WHERE dar.ano = @Ano AND (CASE @IDListagem WHEN 2 THEN MONTH(dar.data) ELSE @MesAtual END) = @MesAtual
				ORDER BY dar.numero
			END
			ELSE
-- obtem as declarações DAR para a listagem "Declaração Mensal IVA"
			IF @IDListagem = 4
			BEGIN
				SELECT dar.id, dar.numero AS "_Número", dar.data AS "_Data", dar.numeroNRM AS "Número NRM", dar.dataNRM AS "Data NRM", SUM(adi.baseTributacaoIVA) AS "Valor Tributável", dar.totalIVA AS "Valor IVA", 
					dar.totalMontante AS "_Montante Total", pmo.PAI_CODI AS "_Moeda", dar.totalMontanteEUR AS "_Total EUR", dar.totalCustosTransporte AS "_Custos Transporte", dar.nomeFornecedor AS "_Exportador", 
					dar.nomeCliente AS "_Importador", dar.nifCliente AS "NIF Importador", dar.numeroNRMExportacao AS "Declaração Exportação"	
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmo.PAI_IDTY
					INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON dar.id = adi.id_declaracaoDAR
				WHERE dar.ano = @Ano AND MONTH(dar.data) = @MesAtual AND dar.regimeIVA = 2 AND dar.status <> 4 AND dar.autorizacaoSaida = 1 AND dar.envioEntregue = 1 AND adi.taxaIVA > 0
				GROUP BY dar.id, dar.numero, dar.data, dar.numeroNRM, dar.dataNRM, dar.totalIVA, dar.totalMontante, pmo.PAI_CODI, dar.totalMontanteEUR, dar.totalCustosTransporte, dar.nomeFornecedor, 
					dar.nomeCliente, dar.nifCliente, dar.numeroNRMExportacao
				ORDER BY dar.numeroNRM
			END
			ELSE
-- obtem as declarações DAR para as listagens "Detalhada (Mensal)" e "Detalhada (Global)"
			IF @IDListagem IN (5, 6)
			BEGIN
				SELECT dar.id, dar.numero AS "Número", dar.data AS "Data", 
					(CASE dar.regimeIVA WHEN 1 THEN 'IOSS' WHEN 2 THEN 'Especial' WHEN 3 THEN 'Geral' ELSE NULL END) AS "Regime IVA", 
					dar.regimeAdicional AS "Ad. Regime", nat.NDE_CODI AS "Natureza", nat.NDE_NOME AS "_Nome Natureza", dar.documentoTransporte AS "Documento Transporte", 
					(CASE dar.status WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Finalizado' WHEN 4 THEN 'Anulado' ELSE 'Por Enviar' END) AS "Status", 
					(CASE dar.estadoOperacao WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'AJ' THEN 'Operação Pendente' WHEN 'SC' THEN 'Sem Controlo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' WHEN 'CD' THEN 'Controlo Documental' WHEN 'CF' THEN 'Controlo Físico' WHEN 'CFP' THEN 'Controlo Físico Parcial' WHEN 'CFT' THEN 'Controlo Físico Total' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída Não Autorizada' ELSE NULL END) AS "Estado Operação", 
					dar.nomeFornecedor AS "_Exportador", dar.nomeCliente AS "_Importador", dar.nifCliente AS "NIF Importador", dar.beneficiarioIVACliente AS "B.IVA", 
					alf.ALF_CODI AS "Estância", alf.ALF_NOME AS "_Nome Estância", dar.numeroReferenciaLocal AS "N.º Referência Local", dar.totalMontante AS "_Montante Total", pmo.PAI_CODI AS "_Moeda", 
					dar.totalMontanteEUR AS "Total EUR", dar.totalCustosTransporte AS "_Custos Transporte", dar.totalAdicoes AS "Total Adições", dar.totalVolumes AS "Total Volumes", 
					dar.totalMassaBruta AS "Total Massa Bruta", 
					ISNULL(NULLIF(cnt.CDO_INVN, ''), (cnt.CDO_TDOC + ' ?/?')) AS "N.º Conta", 
					dar.totalIVA AS "Dívida Aduaneira", 
					adi.numeroAdicao AS "N.º Adição", 
					(adi.codigoPautal + ISNULL(adi.codigoNC, '') + ISNULL(adi.codigoTARIC, '')) AS "Artigo Pautal", 
					adi.regimeAdicional AS "Ad.Regime", por.PAI_CODI AS "Pais Origem",  adi.massaBruta AS "Massa Bruta", adi.unidades AS "Unidades", adi.volumes AS "Volumes", 	adi.montanteEUR AS "Montante EUR", 
					adi.custosTransporteEUR AS "Custos EUR", adi.baseTributacaoIVA AS "Base Tributação", adi.taxaIVA AS "Taxa IVA", adi.valorIVA AS "Valor IVA"
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					INNER JOIN TAB_PAIS AS pmo WITH(NOLOCK) ON dar.id_paisMoedaMontante = pmo.PAI_IDTY
					LEFT OUTER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON dar.id_conta = cnt.CDO_IDTY
					LEFT OUTER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON dar.id = adi.id_declaracaoDAR
					LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON adi.id_paisOrigem = por.PAI_IDTY
				WHERE dar.ano = @Ano AND (CASE @IDListagem WHEN 5 THEN MONTH(dar.data) ELSE @MesAtual END) = @MesAtual
				ORDER BY dar.numero, adi.numeroAdicao
			END
			ELSE
-- obtem as declarações DAR para as listagens "IOSS (Mensal)" e "IOSS (Global)"
			IF @IDListagem IN (7, 8)
			BEGIN
				SELECT dar.id, dar.numero AS "Número", dar.data AS "Data", dar.documentoTransporte AS "Documento Transporte", dar.numeroNRM AS "Número NRM", dar.dataNRM AS "Data NRM", 					
					dar.nomeFornecedor AS "Exportador", dar.nomeCliente AS "_Importador", dar.nifCliente AS "NIF Importador", alf.ALF_CODI AS "Estância", alf.ALF_NOME AS "_Nome Estância", 
					dar.funcaoRegimeIOSS AS "Função IOSS", dar.numeroIdentificacaoIVA AS "N.º Identificação IVA", dar.taxaIVAMaxima AS "Taxa IVA", 					 
					SUM(ROUND((dad.baseTributacaoIVA * dar.taxaIVAMaxima / 100), 2)) AS "Dívida Aduaneira"
				FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
					INNER JOIN tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) ON dar.id = dad.id_declaracaoDAR
				WHERE dar.ano = @Ano and dar.regimeIVA = 1 AND ISNULL(dar.numeroNRM, '') <> '' AND dar.autorizacaoSaida = 1 AND (CASE @IDListagem WHEN 7 THEN MONTH(dar.data) ELSE @MesAtual END) = @MesAtual
				GROUP BY dar.id, dar.numero, dar.data, dar.documentoTransporte, dar.numeroNRM, dar.dataNRM, dar.nomeFornecedor, dar.nomeCliente, dar.nifCliente, alf.ALF_CODI, alf.ALF_NOME, dar.funcaoRegimeIOSS, 
					dar.numeroIdentificacaoIVA, dar.taxaIVAMaxima
				ORDER BY dar.numero
			END
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ProcessaListagem] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ProcessaListagem] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ProcessaObtencaoAutomatica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ProcessaObtencaoAutomatica] @Tipo tinyint, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE	@NumErro int, @CamposAdicionais int, @IdDeclaracao int, @NumeroDeclaracao int, @Erro varchar(MAX)
-- obtem nos campos adicionais qual o tipo de empresa configurada
	SELECT @CamposAdicionais = PDE_CADI
	FROM TAB_PDES WITH(NOLOCK)
-- inicia variáveis
	SET @Erros = ''
-- obtem declarações DAR em situação de obtenção de respostas do webservice 
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dar.id, dar.numero
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY		
		WHERE @Tipo = 0 AND (dar.status = 1 OR (dar.status = 2 AND dar.autorizacaoSaida = 0)) -- p/ mensagens 2A ou 6A		
			AND dar.totalAdicoes > 0 AND nat.NDE_FEDI = 1 	
			AND (CASE WHEN @CamposAdicionais IN (3, 5) THEN dar.totalVolumes ELSE dar.volumesClean END) = dar.totalVolumes
			AND EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
			AND NOT EXISTS(SELECT dad.id FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dad.id_artigo = art.APA_IDTY WHERE dad.id_declaracaoDAR = dar.id AND art.APA_CPAU = '9999999999')
		UNION
		SELECT dar.id, dar.numero
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY		
		WHERE @Tipo = 1 AND dar.status = 2 AND dar.autorizacaoSaida = 0 AND ISNULL(dar.estadoOperacao, '') <> 'SNA' AND ISNULL(dar.numeroRegistoLiquidacao, '') = '' -- p/ mensagens 5A
			AND dar.totalAdicoes > 0 AND nat.NDE_FEDI = 1 
			AND (CASE WHEN @CamposAdicionais IN (3, 5) THEN dar.totalVolumes ELSE dar.volumesClean END) = dar.totalVolumes
			AND EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
			AND NOT EXISTS(SELECT dad.id FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dad.id_artigo = art.APA_IDTY WHERE dad.id_declaracaoDAR = dar.id AND art.APA_CPAU = '9999999999')
		UNION
		SELECT dar.id, dar.numero
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY		
		WHERE @Tipo = 2 AND dar.status = 2 AND dar.autorizacaoSaida = 1 AND (dar.versao > 1 OR dar.revisao > 0) -- p/ restantes mensagens pós 6A
			AND dar.totalAdicoes > 0 AND nat.NDE_FEDI = 1 
			AND (CASE WHEN @CamposAdicionais IN (3, 5) THEN dar.totalVolumes ELSE dar.volumesClean END) = dar.totalVolumes
			AND EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
			AND NOT EXISTS(SELECT dad.id FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dad.id_artigo = art.APA_IDTY WHERE dad.id_declaracaoDAR = dar.id AND art.APA_CPAU = '9999999999')
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		SET @Erro = NULL
-- processa a obtenção das respostas da declaração DAR
		EXEC @NumErro = sp_DeclaracoesDAR_ObtemRespostaRegisto 0, '', @IdDeclaracao, @IdUtilizador, @Erro OUTPUT		
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A obtenção das respostas da declaração DAR N.º ' + CAST(@NumeroDeclaracao AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
-- devolve resultado (0: Sucesso; 1: Erro)
	IF @Erros = ''
		RETURN 0
	ELSE
		RETURN 1
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ProcessaObtencaoAutomatica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ProcessaObtencaoAutomatica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ProcessaObtencaoAutomaticaJaEntregues]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ProcessaObtencaoAutomaticaJaEntregues] @Tipo tinyint, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE	@NumErro int, @CamposAdicionais int, @IdDeclaracao int, @NumeroDeclaracao int, @Erro varchar(MAX)
-- obtem nos campos adicionais qual o tipo de empresa configurada
	SELECT @CamposAdicionais = PDE_CADI
	FROM TAB_PDES WITH(NOLOCK)
-- inicia variáveis
	SET @Erros = ''
-- obtem declarações DAR em situação de obtenção de respostas do webservice 
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dar.id, dar.numero
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY		
		WHERE @Tipo = 0 AND ((dar.status = 1 AND ISNULL(dar.numeroNRM, '') = '') OR (dar.status = 2 AND dar.autorizacaoSaida = 0)) -- p/ mensagens 2A ou 6A	
			AND dar.totalAdicoes > 0 AND nat.NDE_FEDI = 1 		
			AND (CASE @CamposAdicionais WHEN 5 THEN dar.totalVolumes ELSE dar.volumesClean END) = dar.totalVolumes
			AND EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
			AND NOT EXISTS(SELECT dad.id FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dad.id_artigo = art.APA_IDTY WHERE dad.id_declaracaoDAR = dar.id AND art.APA_CPAU = '9999999999')
		UNION
		SELECT dar.id, dar.numero
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY		
		WHERE @Tipo = 1 AND dar.status = 2 AND dar.autorizacaoSaida = 0 AND ISNULL(dar.estadoOperacao, '') <> 'SNA' AND ISNULL(dar.numeroRegistoLiquidacao, '') = '' -- p/ mensagens 5A
			AND dar.totalAdicoes > 0 AND nat.NDE_FEDI = 1 
			AND (CASE @CamposAdicionais WHEN 5 THEN dar.totalVolumes ELSE dar.volumesClean END) = dar.totalVolumes
			AND EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
			AND NOT EXISTS(SELECT dad.id FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dad.id_artigo = art.APA_IDTY WHERE dad.id_declaracaoDAR = dar.id AND art.APA_CPAU = '9999999999')
		UNION
		SELECT dar.id, dar.numero
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY		
		WHERE @Tipo = 2 AND dar.status = 2 AND dar.autorizacaoSaida = 1 AND (dar.versao > 1 OR dar.revisao > 0) -- p/ restantes mensagens pós 6A
			AND dar.totalAdicoes > 0 AND nat.NDE_FEDI = 1 
			AND (CASE @CamposAdicionais WHEN 5 THEN dar.totalVolumes ELSE dar.volumesClean END) = dar.totalVolumes
			AND EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
			AND NOT EXISTS(SELECT dad.id FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dad.id_artigo = art.APA_IDTY WHERE dad.id_declaracaoDAR = dar.id AND art.APA_CPAU = '9999999999')
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN			
-- processa a obtenção das respostas já entregues da declaração DAR
		SET @Erro = NULL
		EXEC @NumErro = sp_DeclaracoesDAR_ObtemRespostaRegisto 1, '', @IdDeclaracao, @IdUtilizador, @Erro OUTPUT		
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A obtenção das respostas já entregues da declaração DAR N.º ' + CAST(@NumeroDeclaracao AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
-- processa a obtenção dos ficheiros já entregues da declaração DAR
		SET @Erro = NULL
		EXEC @NumErro = sp_DeclaracoesDAR_ObtemRespostaRegisto 2, '', @IdDeclaracao, @IdUtilizador, @Erro OUTPUT		
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A obtenção dos ficheiros já entregues da declaração DAR N.º ' + CAST(@NumeroDeclaracao AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
-- devolve resultado (0: Sucesso; 1: Erro)
	IF @Erros = ''
		RETURN 0
	ELSE
		RETURN 1
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ProcessaObtencaoAutomaticaJaEntregues] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ProcessaObtencaoAutomaticaJaEntregues] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_ProcessaSubmissaoAutomatica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_ProcessaSubmissaoAutomatica] @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE	@NumErro int, @ValorMaxLiquidacao numeric(38, 6), @CamposAdicionais int, @IdDeclaracao int, @NumeroDeclaracao int, @Erro varchar(MAX)
-- obtem o valor máximo de liquidação configurado para o utilizador
	SELECT @ValorMaxLiquidacao = UTI_VMLD
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_IDTY = @IdUtilizador
-- obtem nos campos adicionais qual o tipo de empresa configurada
	SELECT @CamposAdicionais = PDE_CADI
	FROM TAB_PDES WITH(NOLOCK)
-- inicia variáveis
	SET @Erros = ''
-- obtem declarações DAR em situação de submissão ao webservice
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dar.id, dar.numero
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY		
		WHERE dar.status = 0 AND ISNULL(dar.estadoOperacao, '') <> 'RE' AND dar.totalAdicoes > 0 AND dar.totalIVA >= 0 AND dar.totalIVA <= 100 
			AND dar.totalIVA <= @ValorMaxLiquidacao AND nat.NDE_FEDI = 1 
			AND (CASE @CamposAdicionais WHEN 5 THEN dar.totalVolumes ELSE ISNULL(NULLIF(dar.volumesClean, 0), dar.volumesScan) END) = dar.totalVolumes
			AND EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
			AND NOT EXISTS(SELECT dad.id FROM tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dad.id_artigo = art.APA_IDTY WHERE dad.id_declaracaoDAR = dar.id AND art.APA_CPAU = '9999999999')
			AND dar.totalMontante = (SELECT SUM(montante) FROM tb_DeclaracoesDARAdicoes WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		SET @Erro = NULL
-- processa a submissão da declaração DAR
		EXEC @NumErro = sp_DeclaracoesDAR_SubmetePedidoRegisto '0110', @IdDeclaracao, NULL, NULL, NULL, NULL, @IdUtilizador, @Erro OUTPUT
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A submissão da declaração DAR N.º ' + CAST(@NumeroDeclaracao AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
-- devolve resultado (0: Sucesso; 1: Erro)
	IF @Erros = ''
		RETURN 0
	ELSE
		RETURN 1
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_ProcessaSubmissaoAutomatica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_ProcessaSubmissaoAutomatica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_SubmetePedidoRegisto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_SubmetePedidoRegisto] @TipoMensagem varchar(4), @Id int, @Motivo varchar(2000), @CodMotivoAnulacao varchar(4), @XMLMencoesAnulacao xml, @AcaoResposta int, 
	@IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @PassPhrase varchar(50), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), @PathCertificado varchar(250), 
		@PwdCertificado varchar(100), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), @DiasFreeADT tinyint, 
		@dataContramarca datetime, @Resultado int, @MensagemSoapAction varchar(250), @MensagemXML xml, @MensagemTXT varchar(MAX), @MensagemXMLBinario varbinary(MAX), 
		@MensagemXMLBase64 varchar(MAX), @PublicKeyCertificadoAT nvarchar(4000), @PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), 
		@RequestXML xml, @ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
	SET @PassPhrase = '16345678901234567'
-- inicia processo de submissão de pedido da declaração
	BEGIN TRY	
		SET @NumErro = 0
-- obtem configurações do Webservice e do Proxy Authentication
		SELECT @EnderecoWS = wsEndereco, @LoginWS = wsUtilizador, @PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPassword)), @PathCertificado = wsPathCertificado, 
			@PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPasswordCertificado)), @ProxyAuthentication = proxyAuthentication, @ProxyServer = ISNULL(proxyServer, ''), 
			@ProxyPort = ISNULL(proxyPort, 0), @ProxyUser = ISNULL(proxyUser, ''), @ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, proxyPassword)), ''),
			@DiasFreeADT = diasFreeADT
		FROM tb_ConfiguracoesDAR WITH(NOLOCK)	
-- obtem a chave pública do sistema de autenticação na AT para ambiente de produção
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT(0)
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- processa recalculo de optativas se o tipo de mensagem for submissão e o n.º dias free/ADT está configurado e a declaração tem status "Por Enviar" e tem "Meio Transporte" definido
		IF (@TipoMensagem = '0110') AND (@DiasFreeADT > 0) AND (EXISTS(SELECT id FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE id = @Id AND status = 0 AND id_meioTransporte IS NOT NULL))
		BEGIN
-- obtem data da contramarca da declaração
			SET @dataContramarca = ISNULL((SELECT TOP 1 dataContramarca 
										FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK) 
										WHERE id_declaracaoDAR = @Id), @dataAtual)
-- processa recalculo de optativas se diferença de dias uteis superior ao n.º dias free/ADT configurado
			IF dbo.FNT_CalculaDifDiasUteis(CAST(CONVERT(varchar(10), @dataContramarca, 105) AS datetime), CAST(CONVERT(varchar(10), @dataAtual, 105) AS datetime), 1, 1) > @DiasFreeADT
			BEGIN
				UPDATE tb_DeclaracoesDAR SET totalOptativas = dbo.fn_IMP_CalculaValorTotalOptativas(id_meioTransporte, NULL, totalMassaBruta, totalMontanteEUR)				
				WHERE id = @Id
			END
		END
-- constroi o XML de acordo com o tipo de mensagem
		IF @TipoMensagem = '0710'
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impec.canalWS/STADAIMPCAUCanalWebService/processaMensagemICAUM007A'
			SET @MensagemXML =
				(SELECT 
					1 AS "@versao", 
					(SELECT
						(SELECT
							(SELECT								
								dar.numeroReferenciaLocal AS "numeroReferenciaLocal", 
								NULLIF(dar.numeroProvisorio, '') AS "numeroProvisorio", 
								alf.ALF_CODI AS "codigoEstancia", 
								NULLIF(dar.numeroNRM, '') AS "numeroAceitacao", 
								dar.versao AS "numeroVersao", 								
								@TipoMensagem AS "codigoOperacao", 
								CONVERT(varchar(10), @DataAtual, 120) AS "dataAnulacao", 
								NULLIF(@CodMotivoAnulacao, '') AS "motivoAnulacao", 
								NULLIF(@Motivo, '') AS "justificacaoAnulacao", 
								(SELECT 
									NULLIF(XML_MENC.MEN_DATA.value('codigo[1]', 'varchar(6)'), '') AS "codigoMencao", 
									NULLIF(XML_MENC.MEN_DATA.value('numero[1]', 'varchar(35)'), '') AS "numeroMencao", 
									CONVERT(varchar(10), XML_MENC.MEN_DATA.value('data[1]', 'datetime'), 120) AS "dataDocumento"
								FROM @XMLMencoesAnulacao.nodes('mencoesAnulacao/mencao') AS XML_MENC(MEN_DATA)
								FOR XML PATH('mencoes'), TYPE)
							FOR XML PATH('cabecalho'), TYPE), 
							(SELECT 
								(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN NULL ELSE (pcl.PAI_CODI + dar.nifCliente) END) AS "numeroIdentificacao", 
								(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.nomeCliente) ELSE NULL END) AS "nome", 
								(SELECT 
									(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.moradaCliente) ELSE NULL END) AS "ruaNumero", 
									(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.localidadeCliente) ELSE NULL END) AS "localidade", 
									(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dar.codPostalCliente ELSE NULL END)AS "codigoPostal", 
									(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN pcl.PAI_CODI ELSE NULL END) AS "pais"
								HAVING (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9')))
								FOR XML PATH('endereco'), TYPE)
							FOR XML PATH('importador'), TYPE), 
							(SELECT 
								(pdc.PAI_CODI + dar.nifDeclarante) AS "numeroIdentificacao"
							FOR XML PATH('declarante'), TYPE), 
							(SELECT 
								(CASE dar.estatutoDeclarante WHEN 1 THEN 2 ELSE dar.estatutoDeclarante END) AS "estatuto", 
								NULLIF(dar.nifRepresentante, '') AS "numeroIdentificacao"
							HAVING dar.estatutoDeclarante IS NOT NULL
							FOR XML PATH('representante'), TYPE)				
						FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY							
							INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY	
							INNER JOIN TAB_PAIS AS pdc WITH(NOLOCK) ON dar.id_paisDeclarante = pdc.PAI_IDTY				
						WHERE id = @Id
						FOR XML PATH('icaum007a'), TYPE)
					FOR XML PATH('mensagens'), TYPE)
				FOR XML PATH('mensagemICAUM007A'), ELEMENTS)
		END
		ELSE
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impec.canalWS/STADAIMPCAUCanalWebService/processaMensagemICAUM001A'
			SET @MensagemXML =
				(SELECT 
					1 AS "@versao", 
					(SELECT
						(SELECT
							(SELECT
								dar.tipoDeclaracao AS "tipoDeclaracaoAdicional",
								NULLIF(dar.numeroNRUR, '') AS "numeroReferencia", 
								dar.numeroReferenciaLocal AS "numeroReferenciaLocal", 
								NULLIF(dar.numeroProvisorio, '') AS "numeroProvisorio", 
								alf.ALF_CODI AS "codigoEstancia", 
								NULLIF(dar.numeroNRM, '') AS "numeroAceitacao", 
								dar.versao AS "numeroVersao", 
								CONVERT(varchar(10), dar.dataNRM, 120) AS "dataAceitacao", 
								@TipoMensagem AS "codigoOperacao", 
								(CASE 
									WHEN @TipoMensagem IN ('0140', '0150') THEN CONVERT(varchar(10), @DataAtual, 120)
									ELSE NULL 
								END) AS "dataAlteracao", 
								(CASE 
									WHEN @TipoMensagem IN ('0140', '0150') THEN NULLIF(@Motivo, '')
									ELSE NULL 
								END) AS "motivoAlteracao", 
								(SELECT 
									@AcaoResposta AS "indicador", 
									NULLIF(@Motivo, '') AS "justificacao", 
									CONVERT(varchar(10), @DataAtual, 120) AS "data"
								HAVING @TipoMensagem IN ('0160', '0190')
								FOR XML PATH('resposta'), TYPE),								
								NULLIF(dar.caucao, '') AS "diferimentoPagamento", 
								dar.totalMassaBruta AS "massaBruta", 
								(SELECT 
									NULLIF(dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.nomeFornecedor), '') AS "nome",
									(SELECT
										NULLIF(dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.moradaFornecedor), '') AS "ruaNumero", 
										NULLIF(dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.localidadeFornecedor), '') AS "localidade", 
										NULLIF(dar.codPostalFornecedor, '') AS "codigoPostal", 
										pfr.PAI_CODI AS "pais"
									HAVING ISNULL(dar.moradaFornecedor, '') <> ''
									FOR XML PATH('endereco'), TYPE)
								HAVING ISNULL(dar.nomeFornecedor, '') <> ''
								FOR XML PATH('exportador'), TYPE),
								(SELECT 
									(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN NULL ELSE (pcl.PAI_CODI + dar.nifCliente) END) AS "numeroIdentificacao", 
									(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.nomeCliente) ELSE NULL END) AS "nome", 
									(SELECT 
										(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.moradaCliente) ELSE NULL END) AS "ruaNumero", 
										(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dar.localidadeCliente) ELSE NULL END) AS "localidade", 
										(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN dar.codPostalCliente ELSE NULL END)AS "codigoPostal", 
										(CASE WHEN (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9'))) THEN pcl.PAI_CODI ELSE NULL END) AS "pais"
									HAVING (dar.nifCliente = '999999990') OR ((dar.regimeIVA = 1) AND (SUBSTRING(dar.nifCliente, 1, 1) IN ('5', '6', '7', '8', '9')))
									FOR XML PATH('endereco'), TYPE)
								FOR XML PATH('importador'), TYPE), 
								(SELECT 
									(pdc.PAI_CODI + dar.nifDeclarante) AS "numeroIdentificacao"
								FOR XML PATH('declarante'), TYPE), 
								(SELECT 
									(CASE dar.estatutoDeclarante WHEN 1 THEN 2 ELSE dar.estatutoDeclarante END) AS "estatuto", 
									NULLIF(pdc.PAI_CODI + dar.nifRepresentante, '') AS "numeroIdentificacao"
								HAVING dar.estatutoDeclarante IS NOT NULL
								FOR XML PATH('representante'), TYPE), 
								(SELECT 
									(SELECT 
										NULLIF(dar.funcaoRegimeIOSS, '') AS "funcao", 									
										NULLIF(dar.numeroIdentificacaoIVA, '') AS "numeroIdentificacaoIva"
									HAVING dar.regimeIVA = 1
									FOR XML PATH('referenciaFiscalAdicional'), TYPE)
								HAVING dar.regimeIVA = 1
								FOR XML PATH('identificacaoRefFiscalAdicional'), TYPE), 
								(SELECT 
									 'EUR' AS "moeda", 
									 CAST((ROUND(dar.totalCustosTransporte / dar.cambioCustosTransporte, 2) + dar.totalOptativas) AS decimal(18, 2)) AS "montante"
								FOR XML PATH('custoTransporteDestino'), TYPE), 
								(SELECT TOP 1
									(SELECT 
										doc.DOC_CODI AS "tipo", 
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dpr.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
									WHERE dpr.id_declaracaoDAR = dar.id
									FOR XML PATH('documento'), TYPE)
								FROM tb_DeclaracoesDARPrecedentes WITH(NOLOCK)
								WHERE id_declaracaoDAR = dar.id
								FOR XML PATH('docPrecedente'), TYPE), 
								(SELECT TOP 1
									(SELECT 
										men.INF_CODI AS "codigo", 
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ISNULL(NULLIF(dme.texto, ''), NULLIF(men.INF_DESI, ''))) AS "texto"
									FROM tb_DeclaracoesDARMencoes AS dme WITH(NOLOCK) INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON dme.id_mencao = men.INF_IDTY
									WHERE dme.id_declaracaoDAR = dar.id
									FOR XML PATH('informacao'), TYPE)
								FROM tb_DeclaracoesDARMencoes WITH(NOLOCK)
								WHERE id_declaracaoDAR = dar.id
								FOR XML PATH('informacoesAdicionais'), TYPE), 
								(SELECT TOP 1
									(SELECT 
										doc.DOC_CODI AS "tipo",									
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ddo.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
									WHERE ddo.id_declaracaoDAR = dar.id AND ddo.tipo = 0
									FOR XML PATH('documentosSuporte'), TYPE),
									(SELECT 
										doc.DOC_CODI AS "tipo",									
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ddo.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
									WHERE ddo.id_declaracaoDAR = dar.id AND ddo.tipo = 2
									FOR XML PATH('referenciasAdicionais'), TYPE), 
									(SELECT 
										doc.DOC_CODI AS "tipo",									
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ddo.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
									WHERE ddo.id_declaracaoDAR = dar.id AND ddo.tipo = 1
									FOR XML PATH('documentoTransporte'), TYPE)
								FROM tb_DeclaracoesDARDocumentos WITH(NOLOCK)
								WHERE id_declaracaoDAR = dar.id
								FOR XML PATH('documentosCertificados'), TYPE), 
								(SELECT 
									dar.localizacaoMercadorias AS "tipoLocalizacao", 
									dar.qualificador AS "qualificadorIdentificacao", 
									ame.ALF_CODI AS "numeroReferencia", 
									lme.LME_CODI AS "numeroAutorizacao"
								FOR XML PATH('localizacaoMercadorias'), TYPE)
							FOR XML PATH('cabecalho'), TYPE), 
							(SELECT 
								adi.numeroAdicao AS "numeroAdicao", 
								NULLIF(adi.numeroNRUR, '') AS "numeroReferencia", 
								NULLIF(adi.metodoPagamento, '') AS "metodoPagamento", 
								NULLIF(adi.unidades, 0) AS "unidadesSuplementares", 								
								dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(adi.designacao) AS "descricaoMercadorias", 
								(CASE alf.ALF_CODI WHEN 'PT000236' THEN NULL ELSE adi.volumes END) AS "numeroVolumes", 
								adi.codigoPautal AS "codigoSubposicaoSistHarmonizado", 
								(SELECT 
									pmm.PAI_PREF AS "moeda", 
									adi.montante AS "montante"
								FOR XML PATH('valor'), TYPE), 
								(SELECT 
									(SELECT 
										dar.regimeAdicional AS "codigoRegimeAdicional"
									FOR XML PATH(''), TYPE), 
									(SELECT 
										NULLIF(adi.regimeAdicional, '') AS "codigoRegimeAdicional"	
									FOR XML PATH(''), TYPE)
								FOR XML PATH('regimeAdicional'), TYPE), 
								(SELECT 
									NULLIF(dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(adi.nomeFornecedor), '') AS "nome",
									(SELECT
										NULLIF(dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(adi.moradaFornecedor), '') AS "ruaNumero", 
										NULLIF(dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(adi.localidadeFornecedor), '') AS "localidade", 
										NULLIF(adi.codPostalFornecedor, '') AS "codigoPostal", 
										paf.PAI_CODI AS "pais"
									HAVING ISNULL(adi.moradaFornecedor, '') <> ''
									FOR XML PATH('endereco'), TYPE)
								HAVING ISNULL(adi.nomeFornecedor, '') <> ''
								FOR XML PATH('exportador'), TYPE), 
								(SELECT TOP 1
									(SELECT 
										doc.DOC_CODI AS "tipo", 
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(apr.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARAdicoesPrecedentes AS apr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON apr.id_documento = doc.DOC_IDTY
									WHERE apr.id_adicao = adi.id
									FOR XML PATH('documento'), TYPE)
								FROM tb_DeclaracoesDARAdicoesPrecedentes WITH(NOLOCK)
								WHERE id_adicao = adi.id
								FOR XML PATH('docPrecedente'), TYPE), 
								(SELECT TOP 1
									(SELECT 
										men.INF_CODI AS "codigo", 
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ISNULL(NULLIF(ame.texto, ''), NULLIF(men.INF_DESI, ''))) AS "texto"
									FROM tb_DeclaracoesDARAdicoesMencoes AS ame WITH(NOLOCK) INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON ame.id_mencao = men.INF_IDTY
									WHERE ame.id_adicao = adi.id
									FOR XML PATH('informacao'), TYPE)
								FROM tb_DeclaracoesDARAdicoesMencoes WITH(NOLOCK)
								WHERE id_adicao = adi.id
								FOR XML PATH('informacoesAdicionais'), TYPE), 
								(SELECT TOP 1
									(SELECT 
										doc.DOC_CODI AS "tipo",									
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ado.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARAdicoesDocumentos AS ado WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.id_documento = doc.DOC_IDTY
									WHERE ado.id_adicao = adi.id AND ado.tipo = 2
									FOR XML PATH('documentosSuporte'), TYPE),
									(SELECT 
										doc.DOC_CODI AS "tipo",									
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ado.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARAdicoesDocumentos AS ado WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.id_documento = doc.DOC_IDTY
									WHERE ado.id_adicao = adi.id AND ado.tipo = 0
									FOR XML PATH('referenciasAdicionais'), TYPE), 
									(SELECT 
										doc.DOC_CODI AS "tipo",									
										dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(ado.numero) AS "numeroReferencia"
									FROM tb_DeclaracoesDARAdicoesDocumentos AS ado WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.id_documento = doc.DOC_IDTY
									WHERE ado.id_adicao = dar.id AND ado.tipo = 1
									FOR XML PATH('documentoTransporte'), TYPE)
								FROM tb_DeclaracoesDARAdicoesDocumentos WITH(NOLOCK)
								WHERE id_adicao = adi.id
								FOR XML PATH('documentosCertificados'), TYPE), 								
								(SELECT 
									por.PAI_CODI AS "paisOrigem", 
									NULLIF(adi.codigoNC, '') AS "codigoNomenclaturaCombinada", 
									NULLIF(adi.codigoTARIC, '') AS "codigoTaric", 
									(SELECT 
										(SELECT 
											NULLIF(adi.adicionalNacional1, '') AS "codigoNacional"
										FOR XML PATH(''), TYPE), 
										(SELECT 
											NULLIF(adi.adicionalNacional2, '') AS "codigoNacional"	
										FOR XML PATH(''), TYPE), 
										(SELECT 
											NULLIF(adi.adicionalNacional3, '') AS "codigoNacional"	
										FOR XML PATH(''), TYPE)
									HAVING ISNULL(adi.adicionalNacional1, '') <> '' OR ISNULL(adi.adicionalNacional2, '') <> '' OR ISNULL(adi.adicionalNacional3, '') <> ''
									FOR XML PATH('codigosNacionaisAdicionais'), TYPE), 
									(SELECT 
										(SELECT 
											NULLIF(adi.adicionalTARIC1, '') AS "codigoAdicional"
										FOR XML PATH(''), TYPE), 
										(SELECT 
											NULLIF(adi.adicionalTARIC2, '') AS "codigoAdicional"	
										FOR XML PATH(''), TYPE), 
										(SELECT 
											NULLIF(adi.adicionalTARIC3, '') AS "codigoAdicional"	
										FOR XML PATH(''), TYPE)
									HAVING ISNULL(adi.adicionalTARIC1, '') <> '' OR ISNULL(adi.adicionalTARIC2, '') <> '' OR ISNULL(adi.adicionalTARIC3, '') <> ''
									FOR XML PATH('codigosAdicionaisTaric'), TYPE)
								FOR XML PATH('elementosTecnicos'), TYPE)
							FROM tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) INNER JOIN TAB_PAIS AS pmm WITH(NOLOCK) ON adi.id_paisMoedaMontante = pmm.PAI_IDTY
								LEFT OUTER JOIN TAB_PAIS AS paf WITH(NOLOCK) ON adi.id_paisFornecedor = paf.PAI_IDTY
								INNER JOIN TAB_PAIS AS pmc WITH(NOLOCK) ON adi.id_paisMoedaCustosTransporte = pmc.PAI_IDTY
								LEFT OUTER JOIN TAB_PAIS AS por WITH(NOLOCK) ON adi.id_paisOrigem = por.PAI_IDTY
							WHERE adi.id_declaracaoDAR = dar.id
							FOR XML PATH('adicao'), TYPE)
						FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
							LEFT OUTER JOIN TAB_PAIS AS pfr WITH(NOLOCK) ON dar.id_paisFornecedor = pfr.PAI_IDTY
							INNER JOIN TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY
							INNER JOIN TAB_PAIS AS pdc WITH(NOLOCK) ON dar.id_paisDeclarante = pdc.PAI_IDTY							
							LEFT OUTER JOIN TAB_ALFA AS ame WITH(NOLOCK) ON dar.id_estanciaMercadorias = ame.ALF_IDTY
							LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dar.id_localAutorizado = lme.LME_IDTY
						WHERE id = @Id
						FOR XML PATH('icaum001a'), TYPE)
					FOR XML PATH('mensagens'), TYPE)
				FOR XML PATH('mensagemICAUM001A'), ELEMENTS)
		END
-- converte o XML gerado para varbinary e depois para Base64
		SET @MensagemTXT = '<?xml version="1.0" encoding="UTF-8"?>' + CAST(@MensagemXML AS varchar(MAX))
		SET @MensagemXMLBinario = CONVERT(varbinary(MAX), @MensagemTXT) 
		SET @MensagemXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@MensagemXMLBinario"))', 'varchar(MAX)') 
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
		EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido ao metodo submitMessages a enviar à AT
		IF @TipoMensagem = '0710'
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
				'http://net.atos.at.impec.canalWS/' AS web, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							(SELECT @MensagemXMLBase64 AS "mensagem"
							FOR XML PATH('processaMensagemInput'), TYPE)
						FOR XML PATH('web:processaMensagemICAUM007A'), TYPE)						
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)
		END
		ELSE
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
				'http://net.atos.at.impec.canalWS/' AS web, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							(SELECT @MensagemXMLBase64 AS "mensagem"
							FOR XML PATH('processaMensagemInput'), TYPE)
						FOR XML PATH('web:processaMensagemICAUM001A'), TYPE)		
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
		END
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
		SELECT 
			@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS XML_MSGR(MSG_DATA)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
		SELECT 
			@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS XML_MSGR(MSG_DATA)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)				
-- obtem o resultado "OK"/"NOK" retornados do WS
		IF @TipoMensagem = '0710'
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impec.canalWS/' AS m)		
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:processaMensagemICAUM007AResponse/return/resultadoProcessamento') AS XML_MSGR(MSG_DATA)	
		END
		ELSE
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impec.canalWS/' AS m)		
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:processaMensagemICAUM001AResponse/return/resultadoProcessamento') AS XML_MSGR(MSG_DATA)			
		END
-- se resultado não for de sucesso, manda erro
		IF @FaultCode <> '0'
			RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 4, @FaultMessage)		
-- atualiza declaração DAR p/ alteração do status e utilizador/data
		UPDATE tb_DeclaracoesDAR SET [status] = 1, dataEnvio = @DataAtual, id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual 
		WHERE id = @Id
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH	
-- insere no detalhe de mensagens os dados da submissão da declaração DAR
	INSERT INTO tb_DeclaracoesDARMensagens(id_declaracaoDAR, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, id_utilizadorControlo, dataControlo)
	VALUES(@id, 1, (CASE WHEN @TipoMensagem IN ('0110', '0140', '0150', '0160', '0190') THEN ('ICAUM001A-' + @TipoMensagem) WHEN @TipoMensagem = '0710' THEN 'ICAUM007A-0710' ELSE NULL END), @IdUtilizador, @DataAtual, @MensagemXML, 
		@ResponseXML, (CASE @NumErro WHEN 1 THEN 0 ELSE 1 END), NULL, @IdUtilizador, @DataAtual)			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_SubmetePedidoRegisto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_SubmetePedidoRegisto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclaracoesDAR_SubmeterDMG]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclaracoesDAR_SubmeterDMG] @Webservice bit, @FormatoCTT bit, @Ano smallint, @Mes tinyint, @Prazo tinyint, @MotivoImpedimento tinyint, @DataImpedimento datetime, @IdUtilizador int, 
	@FicheiroXML xml OUTPUT, @LinhaXMLEncoding varchar(200) OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @TblDAR table (baseDados varchar(100) NOT NULL, 
			id int NOT NULL, 
			numeroNRM varchar(25) NOT NULL,
			documentoTransporte varchar(35) NOT NULL,
			dataNRM datetime NOT NULL,
			baseIVA decimal(18, 2) NOT NULL, 
			totalIVA decimal(18, 2) NOT NULL,
			numeroNRMExportacao varchar(25) NULL, 
			codigoPaisCliente varchar(2) NOT NULL,
			nifCliente varchar(18) NOT NULL)	
	DECLARE @NumErro int, @DataAtual datetime, @PassPhrase varchar(50), @NIFEmpresa varchar(18), @NIFContabilista varchar(9), @LstBasesDados varchar(250), @BaseDados varchar(100), @EnderecoWS varchar(250), 
		@LoginWS varchar(50), @PwdWS varchar(100), @PathCertificado varchar(250), @PwdCertificado varchar(100), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), 
		@ProxyPassword varchar(100), @Resultado int, @DeclaracaoDMGTXT varchar(MAX), @DeclaracaoDMGXMLBinario varbinary(MAX), @DeclaracaoDMGXMLBase64 varchar(MAX), @PublicKeyCertificadoAT nvarchar(4000), 
		@PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), @RequestXML xml, @ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX), 
		@IdDMG bigint, @EstadoDMG varchar(50), @ErrosDMG xml, @IdDAR int, @SQLString nvarchar(1000), @SQLParams nvarchar(500)
-- inicia outras variaveis
	SET @NumErro = 0
	SET @PassPhrase = '16345678901234567'
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
	BEGIN TRY			
-- obtem os dados da empresa
		SELECT @NIFEmpresa = EMP_NIF, @NIFContabilista = EMP_CNIF
		FROM GIDWIN.dbo.FAP_EMPR WITH(NOLOCK)
		WHERE EMP_CODI = DB_NAME()		
-- obtem a lista de outras bases de dados cujas declarações irão constar na DMG
		SELECT @LstBasesDados = baseDadosDMG 
		FROM tb_ConfiguracoesDAR
-- obtem as declarações nas várias base de dados que satisfaçam as condições para constar na DMG do ano/mês selecionado
		DECLARE BaseDados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT DB_NAME()
			UNION
			SELECT valor
			FROM FNT_Geral_SeparaTexto(@LstBasesDados, ';')
		OPEN BaseDados
		FETCH NEXT FROM BaseDados INTO @BaseDados
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO @TblDAR (baseDados, id, numeroNRM, documentoTransporte, dataNRM, baseIVA, totalIVA, numeroNRMExportacao, codigoPaisCliente, nifCliente)
			EXEC('SELECT ''' + @BaseDados + ''', dar.id, dar.numeroNRM, dar.documentoTransporte, dar.dataNRM, SUM(dad.baseTributacaoIVA), dar.totalIVA, dar.numeroNRMExportacao, pcl.PAI_CODI, dar.nifCliente
			FROM ' + @BaseDados + '.dbo.tb_DeclaracoesDAR AS dar WITH(NOLOCK) INNER JOIN ' + @BaseDados + '.dbo.tb_DeclaracoesDARAdicoes AS dad WITH(NOLOCK) ON dar.id = dad.id_declaracaoDAR
				INNER JOIN ' + @BaseDados + '.dbo.TAB_PAIS AS pcl WITH(NOLOCK) ON dar.id_paisCliente = pcl.PAI_IDTY	
			WHERE dar.ano = ' + @Ano + ' AND DATEPART(MONTH, dar.dataAutorizacaoSaida) = ' + @Mes + ' AND dar.regimeIVA = 2 AND dar.status <> 4 AND dar.autorizacaoSaida = 1 AND dar.envioEntregue = 1 AND dar.totalIVA > 0		
			GROUP BY dar.id, dar.numeroNRM, dar.documentoTransporte, dar.dataNRM, dar.nifCliente, pcl.PAI_CODI, dar.totalIVA, dar.numeroNRMExportacao
			ORDER BY dar.id')
			FETCH NEXT FROM BaseDados INTO @BaseDados
		END
		CLOSE BaseDados
		DEALLOCATE BaseDados
-- atribui linha de encoding (definido no schema) para depois ser incluída no ficheiro XML a gerar
		SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="UTF-8"?>'	
-- constroi XML para ficheiro DMG
		--;WITH XMLNAMESPACES (DEFAULT 'dmgiva')	
		SELECT @FicheiroXML = 			
			(SELECT 
				(SELECT 
					NULLIF(@NIFEmpresa, '') AS "Q01C1"
				FOR XML PATH('Quadro01'), TYPE),
				(SELECT 
					@Ano AS "Q02C1", 
					@Mes AS "Q02C2", 
					@Prazo AS "Q02Prazo"
				FOR XML PATH('Quadro02'), TYPE),
				(SELECT 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY baseDados, id) AS "Q03IdLinha",
						NULLIF(numeroNRM, '') AS "Q03C1", 
						CONVERT(varchar(10), dataNRM, 120) AS "Q03C2", 												
						CAST(baseIVA AS decimal(12, 2)) AS "Q03C3",
						CAST((CASE ISNULL(numeroNRMExportacao, '') WHEN '' THEN totalIVA ELSE 0 END) AS decimal(12, 2)) AS "Q03C4",
						(CASE ISNULL(numeroNRMExportacao, '') WHEN '' THEN NULL ELSE 2 END) AS "Q03C5",
						NULLIF(numeroNRMExportacao, '') AS "Q03C6", 
						(CASE nifCliente WHEN '999999990' THEN NULL ELSE codigoPaisCliente END) AS "Q03C7",									 
						(CASE nifCliente WHEN '999999990' THEN NULL ELSE nifCliente END) AS "Q03C8",
						(CASE @FormatoCTT WHEN 1 THEN documentoTransporte ELSE NULL END) AS "Q03NumeroObjeto"
					FROM @TblDAR					
					ORDER BY baseDados, id
					FOR XML PATH('Q03-Linha'), TYPE), 
					(SELECT CAST(SUM(totalIVA) AS decimal(12, 2)) FROM @TblDAR WHERE ISNULL(numeroNRMExportacao, '') = '') AS "Q03C9"
				FOR XML PATH('Quadro03'), TYPE),
				(SELECT 
					NULLIF(@NIFContabilista, '') AS "Q04C1", 
					@MotivoImpedimento AS "Q04C2", 
					(CONVERT(varchar(10), @DataImpedimento, 120) + 'Z') AS "Q04C3"
				FOR XML PATH('Quadro04'), TYPE)
			FOR XML PATH('DMGIVA'), ELEMENTS)	
-- adiciona namespace ao ficheiro xml
			SELECT @FicheiroXML = (
				SELECT 1 AS Tag,
					NULL AS Parent,
					@FicheiroXML AS [DMGIVA!1!!xmltext],
					'dmgiva' AS [DMGIVA!1!xmlns]
				FOR XML EXPLICIT)
-- processa a submissão do ficheiro XML via webservice
		IF @Webservice = 1
		BEGIN
-- obtem configurações do Webservice e do Proxy Authentication
			SELECT @EnderecoWS = wsEnderecoDMG, @LoginWS = wsUtilizadorDMG, @PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPasswordDMG)), @PathCertificado = wsPathCertificado, 
				@PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, wsPasswordCertificado)), @ProxyAuthentication = proxyAuthentication, @ProxyServer = ISNULL(proxyServer, ''), 
				@ProxyPort = ISNULL(proxyPort, 0), @ProxyUser = ISNULL(proxyUser, ''), @ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, proxyPassword)), '')
			FROM tb_ConfiguracoesDAR WITH(NOLOCK)	
-- obtem a chave pública do sistema de autenticação na AT para ambiente de produção
			SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT(0)
-- valida se o path p/ o certificado é válido
			EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
			IF @Resultado = 0
				RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)
-- converte o XML gerado para varbinary e depois para Base64
			SET @DeclaracaoDMGTXT = @LinhaXMLEncoding + CAST(@FicheiroXML AS varchar(MAX))
			SET @DeclaracaoDMGXMLBinario = CONVERT(varbinary(MAX), @DeclaracaoDMGTXT) 
			SET @DeclaracaoDMGXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@DeclaracaoDMGXMLBinario"))', 'varchar(MAX)') 
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido ao metodo submeterDeclaracao a enviar à AT
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 
				'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS dec, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							2021 AS "versaoDeclaracao", 
							@DeclaracaoDMGXMLBase64 AS "declaracao"							
						FOR XML PATH('dec:submeterDMGIVARequest'), TYPE)		
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)	
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, 'tns:submeterDeclaracao', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)	
-- obtem o resultado "OK"/"NOK" retornados do WS
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'https://servicos.portaldasfinancas.gov.pt/dmgivaws/DeclaracaoMensalGlobalIVAWebService' AS ns0)		
			SELECT 
				@FaultCode = XML_MSGR.MSG_DATA.value('codigo[1]', 'nvarchar(100)'), 
				@FaultMessage = XML_MSGR.MSG_DATA.value('mensagem[1]', 'nvarchar(MAX)'),
				@EstadoDMG = XML_MSGR.MSG_DATA.value('(dadosSubmissao/estado)[1]', 'nvarchar(50)'), 
				@IdDMG = XML_MSGR.MSG_DATA.value('(dadosSubmissao/idDeclaracao)[1]', 'bigint'), 
				@ErrosDMG = XML_MSGR.MSG_DATA.query('erros')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/ns0:submeterDMGIVAResponse') AS XML_MSGR(MSG_DATA)					
-- se resultado não for de sucesso, manda erro
			IF @FaultCode <> '0'
				RAISERROR('A submissão da DMG gerou o erro "%s".', 16, 4, @FaultMessage)									
-- se submissão recebeu ID, atualiza as declarações DAR obtidas nas bases de dados p/ alteração do status IVA e utilizador/data	
			IF @IdDMG IS NOT NULL
			BEGIN
				DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR					
					SELECT baseDados, id
					FROM @TblDAR
				OPEN Declaracoes
				FETCH NEXT FROM Declaracoes INTO @BaseDados, @IdDAR
				WHILE @@FETCH_STATUS = 0
				BEGIN								
					SET @SQLString = N'UPDATE ' + @BaseDados + '.dbo.tb_DeclaracoesDAR SET statusIVA = 1, id_utilizadorControlo = @INIdUtilizador, dataControlo = @INDataAtual WHERE id = @INId'
					SET @SQLParams = N'@INId int, @INIdUtilizador int, @INDataAtual datetime'
					EXECUTE sp_executesql @SQLString, @SQLParams, @INId = @IdDAR, @INIdUtilizador = @IdUtilizador, @INDataAtual = @DataAtual				
					FETCH NEXT FROM Declaracoes INTO @BaseDados, @IdDAR
				END
				CLOSE Declaracoes
				DEALLOCATE Declaracoes			
			END
			ELSE
-- se submissão gerou erros, manda erro
				IF @ErrosDMG IS NOT NULL
					RAISERROR('A submissão da DMG gerou o erro "%s".', 16, 5, @FaultMessage)					
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- insere no histórico da DMG se for via webservice
	IF @Webservice = 1
	BEGIN
		DECLARE BaseDados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR					
			SELECT baseDados
			FROM @TblDAR
			GROUP BY baseDados
		OPEN BaseDados
		FETCH NEXT FROM BaseDados INTO @BaseDados
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			IF CHARINDEX('.', @BaseDados) = 0 -- não insere historico em linked servers devido à limitação dos mesmos com objetos do tipo xml
			BEGIN											
				SET @SQLString = N'INSERT INTO ' + @BaseDados + '.dbo.tb_HistoricoDMG(ano, mes, tipo, id_utilizadorSubmissao, dataSubmissao, pedido, resposta, idDMG, id_utilizadorControlo, dataControlo, estadoDMG, sucesso)
					VALUES(@INAno, @INMes, (CASE WHEN EXISTS(SELECT id FROM ' + @BaseDados + '.dbo.tb_HistoricoDMG WITH(NOLOCK) WHERE ano = @INAno AND mes = @INMes AND tipo = 0 AND sucesso = 1) THEN 1 ELSE 0 END), 
						@INIdUtilizador, @INDataAtual, @INFicheiroXML, @INResponseXML, @INIdDMG, @INIdUtilizador, @INDataAtual, @INEstadoDMG, (CASE @INNumErro WHEN 1 THEN 0 ELSE 1 END))'
				SET @SQLParams = N'@INAno smallint, @INMes tinyint, @INIdUtilizador int, @INDataAtual datetime, @INFicheiroXML xml, @INResponseXML xml, @INIdDMG bigint, @INEstadoDMG varchar(50), @INNumErro int'
				EXECUTE sp_executesql @SQLString, @SQLParams, @INAno = @Ano, @INMes = @Mes, @INIdUtilizador = @IdUtilizador, @INDataAtual = @DataAtual, @INFicheiroXML = @FicheiroXML, @INResponseXML = @ResponseXML, @INIdDMG = @IdDMG, @INEstadoDMG = @EstadoDMG, @INNumErro = @NumErro
			END
			FETCH NEXT FROM BaseDados INTO @BaseDados
		END
		CLOSE BaseDados
		DEALLOCATE BaseDados			
	END
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclaracoesDAR_SubmeterDMG] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclaracoesDAR_SubmeterDMG] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_AdicoesGeraDeLinhasOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_DeclImportacao_AdicoesGeraDeLinhasOGMA] @Ano int, @Numero int, @ParteResto bit, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin)
	DECLARE @TblTmpLinhas TABLE(
		LIN_IDEN int NOT NULL IDENTITY(1, 1), 
		APA_CODI varchar(22) NOT NULL,
		APA_DESG varchar(150) NOT NULL, 
		PAI_CODI varchar(2) NULL,
		PRE_CODI varchar(3) NOT NULL, 
		LIN_MBRT decimal(28, 6) NOT NULL,
		LIN_MLIQ decimal(28, 6) NOT NULL,
		LIN_REGI varchar(4) NOT NULL,
		LIN_QUNI decimal(28, 6) NOT NULL,
		LIN_MONT decimal(28, 6) NOT NULL,
		UME_CODI varchar(2) NOT NULL,
		LIN_VOLS decimal(28, 6) NOT NULL)
	DECLARE @TblTmpPrecedentes TABLE(
		PRE_IDEN int NOT NULL IDENTITY(1, 1),	
		LIN_IDEN int NOT NULL, 
		PRE_NDOC varchar(20) NOT NULL,
		PRE_DDOC datetime NOT NULL)	
	DECLARE @IdLinha bigint, @TotalPrecedentes int, @NumPrecedentesIguais int, @CodArtigo varchar(22), @DesignacaoArtigo varchar(150), @CodPaisOrigem varchar(2), @CodPreferencia varchar(3), 
		@MassaBrt decimal(28, 6), @MassaLiq decimal(28, 6), @Regime varchar(4), @QtdUnidades decimal(28, 6), @Montante decimal(28, 6), @CodUnidMedida varchar(2), @Volumes decimal(28, 6), 
		@NumeroDocPrecedente varchar(20), @DataDocPrecedente datetime, @NumAdicao int, @TotalAdicoes int
-- inicia processo para geração de adições a partir de linhas OGMA
	BEGIN TRY	
		SET @NumErro = 0
		SET @TotalAdicoes = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem as linhas OGMA da declaração já associadas a artigo pautal para globalização
		DECLARE Linhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT apa.APA_CODI, apa.APA_DESG, pai.PAI_CODI, pre.PRE_CODI, lin.massaBruta, lin.massaLiquida, lin.observacoes, lin.unidades, lin.montante, ume.UME_CODI, lin.volumes, 
				lin.numeroOrdem, lin.dataOrdem
			FROM PRO_DUCG AS duc WITH(NOLOCK)
				INNER JOIN tb_TBL_LinhasOGMA AS lin WITH(NOLOCK) ON duc.DUC_IDTY = lin.id_declaracaoIMP
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON lin.id_artigo = apa.APA_IDTY
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON lin.id_paisOrigem = pai.PAI_IDTY
				INNER JOIN TAB_PREF AS pre WITH(NOLOCK) ON lin.id_preferencia = pre.PRE_IDTY
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON lin.id_unidadeMedida = ume.UME_IDTY
			WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero AND lin.id_artigo IS NOT NULL
			ORDER BY apa.APA_CODI, pai.PAI_CODI, pre.PRE_CODI, lin.observacoes, ume.UME_CODI
		OPEN Linhas
		FETCH NEXT FROM Linhas INTO @CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @CodPreferencia, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, @Volumes, 
			@NumeroDocPrecedente, @DataDocPrecedente
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @IdLinha = NULL
			SET @TotalPrecedentes = 0
			SET @NumPrecedentesIguais = 0			
-- obtem dados referente ao artigo/pais origem/preferência/regime/unidade medida para globalização
			SELECT @IdLinha = MAX(lin.LIN_IDEN), @TotalPrecedentes = COUNT(*), @NumPrecedentesIguais = COUNT((CASE WHEN (pre.PRE_NDOC = @NumeroDocPrecedente) AND (pre.PRE_DDOC = @DataDocPrecedente) THEN 1 ELSE NULL END))
			FROM @TblTmpLinhas AS lin
				LEFT OUTER JOIN @TblTmpPrecedentes AS pre ON lin.LIN_IDEN = pre.LIN_IDEN
			WHERE APA_CODI = @CodArtigo AND PAI_CODI = @CodPaisOrigem AND PRE_CODI = @CodPreferencia AND LIN_REGI = @Regime AND UME_CODI = @CodUnidMedida
			GROUP BY lin.LIN_IDEN		
-- se artigo/pais origem/preferência/regime/unidade medida ainda não existe ou já existe mas já tem 20 precedentes associados, insere nova linha
			IF (@IdLinha IS NULL) OR ((@TotalPrecedentes = 20) AND (@NumPrecedentesIguais = 0))
			BEGIN		
				INSERT INTO @TblTmpLinhas(APA_CODI, APA_DESG, PAI_CODI, PRE_CODI, LIN_MBRT, LIN_MLIQ, LIN_REGI, LIN_QUNI, LIN_MONT, UME_CODI, LIN_VOLS)		
				VALUES(@CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @CodPreferencia, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, @Volumes)	
				SET @IdLinha = SCOPE_IDENTITY()
			END
			ELSE
			BEGIN
				UPDATE @TblTmpLinhas SET 
					LIN_MBRT = LIN_MBRT + @MassaBrt, 
					LIN_MLIQ = LIN_MLIQ + @MassaLiq, 
					LIN_QUNI = LIN_QUNI + @QtdUnidades, 
					LIN_MONT = LIN_MONT + @Montante, 
					LIN_VOLS = LIN_VOLS + @Volumes
				WHERE LIN_IDEN = @IdLinha
			END	
-- insere precedente se este ainda não existe na linha
			IF NOT EXISTS(SELECT PRE_IDEN FROM @TblTmpPrecedentes WHERE LIN_IDEN = @IdLinha AND PRE_NDOC = @NumeroDocPrecedente AND PRE_DDOC = @DataDocPrecedente)
			BEGIN
				INSERT @TblTmpPrecedentes(LIN_IDEN, PRE_NDOC, PRE_DDOC)
				VALUES(@IdLinha, @NumeroDocPrecedente, @DataDocPrecedente)
			END
			FETCH NEXT FROM Linhas INTO @CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @CodPreferencia, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, @Volumes, 
				@NumeroDocPrecedente, @DataDocPrecedente
		END
		CLOSE Linhas
		DEALLOCATE Linhas
-- obtem o total de adições apuradas
		SELECT @TotalAdicoes = COUNT(*)
		FROM @TblTmpLinhas
-- constroi XML para edição da declaração DUI2 com adições sendo as linhas OGMA
		SELECT @DocumentoXML = 
			(SELECT
				(SELECT 'U' AS "@Acao",
					(CONVERT(varchar(10), duc.DUC_DATA, 127) + 'Z') AS "Data",	 
					duc.NDE_CODI AS "CodNatureza", 
					duc.TDE_CODI AS "CodTipoDeclaracao", 									
					duc.ALF_CODI AS "CodEstancia", 					
					NULLIF(duc.DEC_CO14, '') AS "CodDeclarante", 									
					duc.DUC_CT19 AS "TemContentores", 
					NULLIF(duc.CEN_CO20, '') AS "CodCondEntrega", 
					NULLIF(duc.ALF_CODI1, '') AS "CodEstanciaAduaneira", 
					NULLIF(duc.LME_CO30, '') AS "CodLocalAutorizado", 
					NULLIF(duc.PAI_PR22, '') AS "CodPais22", 
					duc.DUC_DUNO AS "EDeclaracaoImportacao", 					
					(SELECT 
						(SELECT 
							'DUC_PNUM' AS "CodigoCampoExtra", 
							duc.DUC_PNUM AS "ValorCampoExtra"
						FOR XML PATH('CampoExtra'), TYPE)
					FOR XML PATH('CamposExtra'), TYPE),
					(SELECT 'I' AS "@Acao",
						adi.LIN_NUME AS "NumAdicao", 
						adi.APA_CODI AS "CodArtigoPautal", 
						adi.APA_DESG AS "Designacao",
						adi.PAI_CODI AS "CodPaisOrigem",  
						adi.PRE_CODI AS "CodPreferencia", 																			
						CAST(adi.LIN_MBRT AS numeric(28, 6)) AS "MassaBruta", 
						CAST(adi.LIN_MLIQ AS numeric(28, 6)) AS "MassaLiquida",												
						CAST(adi.LIN_QUNI AS numeric(28, 6)) AS "QtdUnidades", 
						CAST(adi.LIN_MONT AS numeric(28, 6)) AS "PrecoAdicao", 													
						(SELECT 					
							CAST(adi.LIN_VOLS AS numeric(28, 6)) AS "QtdVolumes", 				
							ume.UME_CODI AS "CodUnidMedida", 													
							(CASE WHEN (@ParteResto = 1) AND (adi.LIN_NUME <> @TotalAdicoes) THEN 1 ELSE 0 END) AS "P", 						
							(CASE WHEN (@ParteResto = 1) AND (adi.LIN_NUME = @TotalAdicoes) THEN 1 ELSE 0 END) AS "R",
							CAST(0 AS bit) AS "C"								
						FROM TAB_UMED AS ume WITH(NOLOCK)
						WHERE ume.UME_CODI = adi.UME_CODI AND ume.UME_IMPT = 1	
						FOR XML PATH('MarcaEVolume'), ROOT('MarcasEVolumes'), TYPE), 
						(SELECT 									
							'Z' AS "Tipo", 
							doc.DOC_CODI AS "CodDocumento", 						
							pre.PRE_NDOC AS "NumeroDeclSumaria", 													
							(CONVERT(varchar(10), pre.PRE_DDOC, 127) + 'Z') AS "DataApresentacao"
						FROM @TblTmpPrecedentes AS pre
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'IM' AND doc.DOC_DESP = 1
						WHERE pre.LIN_IDEN = adi.LIN_IDEN
						FOR XML PATH('DeclaracaoSumaria'), ROOT('DeclaracoesSumaria'), TYPE), 																																	
						(SELECT 
							doc.DOC_CODI AS "CodDocumento",
							NULLIF(t.CLD_NDOC, '') AS "NumeroDocumento", 
							(CONVERT(varchar(10), t.CLD_DDOC, 127) + 'Z') AS "DataEmissao"
						FROM TAB_DOCU AS doc WITH(NOLOCK) 
							INNER JOIN (SELECT cdo.DOC_CODI, cdo.CLD_NDOC, cdo.CLD_DDOC
										FROM TAB_CLDO AS cdo WITH(NOLOCK) 
											INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cdo.DOC_CODI = doc.DOC_CODI
										WHERE cdo.CLD_UIMP = 1 AND cdo.CLI_CODI = duc.DUC_DST8 AND doc.DOC_DESP = 1 AND (adi.LIN_NUME = 1 OR doc.DOC_RSDA = 1)
										UNION ALL								
										SELECT DOC_CODI, NULLIF(duc.DUC_REF2, ''), NULL
										FROM TAB_DOCU WITH(NOLOCK) 
										WHERE DOC_DESP = 1 AND DOC_CODI = 'N380' AND adi.LIN_REGI IN ('4000', '4051', '4071', '5171') AND (adi.LIN_NUME = 1 OR DOC_RSDA = 1)
										UNION ALL
										SELECT DOC_CODI, NULLIF(duc.DUC_CPRT, ''), NULL
										FROM TAB_DOCU WITH(NOLOCK) 
										WHERE DOC_DESP = 1 AND DOC_CODI = (CASE WHEN adi.LIN_REGI IN ('4071', '5171') THEN 'N740' WHEN adi.LIN_REGI = '4000' THEN 'N741' WHEN adi.LIN_REGI = '7171' THEN 'N705' ELSE NULL END) 
											AND adi.LIN_REGI IN ('4000', '4071', '5171', '7171') AND (adi.LIN_NUME = 1 OR DOC_RSDA = 1)
										UNION ALL									
										SELECT DOC_CODI, NULL, NULL
										FROM TAB_DOCU WITH(NOLOCK) 
										WHERE DOC_DESP = 1 AND DOC_CODI = '9Z07' AND adi.LIN_REGI = '4000' AND (adi.LIN_NUME = 1 OR DOC_RSDA = 1)
										UNION ALL
										SELECT doc.DOC_CODI, NULLIF(pre.PRE_NDOC, ''), pre.PRE_DDOC
										FROM @TblTmpPrecedentes AS pre
											INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = '9D06' AND doc.DOC_DESP = 1
										WHERE pre.LIN_IDEN = adi.LIN_IDEN AND adi.LIN_REGI IN ('4051', '4071', '5171', '7171')
									) AS t ON doc.DOC_CODI = t.DOC_CODI
						WHERE doc.DOC_DESP = 1
						FOR XML PATH('Documento'), ROOT('Documentos'), TYPE)												
					FROM (SELECT ROW_NUMBER() OVER(ORDER BY LIN_IDEN) AS LIN_NUME, LIN_IDEN, APA_CODI, APA_DESG, PAI_CODI, PRE_CODI, LIN_MBRT, LIN_MLIQ, LIN_REGI, LIN_QUNI, LIN_MONT, LIN_VOLS, UME_CODI
						FROM @TblTmpLinhas) AS adi
					FOR XML PATH('Adicao'), ROOT('Adicoes'), TYPE)
				FROM PRO_DUCG AS duc WITH(NOLOCK) 
				WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero
				FOR XML PATH('Declaracao'), TYPE)
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)
-- processa a atualização da declaração para inserir as adições apuradas
		EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @CodUtilizador, @Erro OUTPUT
		IF @NumErro > 0
			RAISERROR ('Erro na inserção de adições na declaração: %s', 16, 1, @Erro)		
-- inicia o número da adição em todas as linhas OGMA
		UPDATE tb_TBL_LinhasOGMA SET numeroAdicao = NULL
		FROM tb_TBL_LinhasOGMA AS lin WITH(NOLOCK)
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON lin.id_declaracaoIMP = duc.DUC_IDTY
		WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero AND lin.numeroAdicao IS NOT NULL
-- atribui a todas as linhas OGMA o respetivo número de adição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dua.DUA_CODI, lin.id
			FROM PRO_DUCG AS duc WITH(NOLOCK)
				INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM
				INNER JOIN PRO_DURA AS ads WITH(NOLOCK) ON dua.DUC_EANO = ads.DUC_EANO AND dua.DUC_PNUM = ads.DUC_PNUM AND dua.DUA_CODI = ads.DUA_CODI
				INNER JOIN PRO_DU31 AS amv WITH(NOLOCK) ON dua.DUC_EANO = amv.DUC_EANO AND dua.DUC_PNUM = amv.DUC_PNUM AND dua.DUA_CODI = amv.DUA_CODI
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON dua.APA_CO33 = apa.APA_CODI
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dua.PAI_CO34 = pai.PAI_CODI
				INNER JOIN TAB_PREF AS pre WITH(NOLOCK) ON dua.PRE_CO36 = pre.PRE_CODI
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON amv.UME_CODI = ume.UME_CODI
				INNER JOIN tb_TBL_LinhasOGMA AS lin WITH(NOLOCK) ON duc.DUC_IDTY = lin.id_declaracaoIMP AND apa.APA_IDTY = lin.id_artigo AND pai.PAI_IDTY = lin.id_paisOrigem AND pre.PRE_IDTY = lin.id_preferencia AND dua.DUA_RG37 = lin.observacoes AND ume.UME_IDTY = lin.id_unidadeMedida AND ads.DRA_APC1 = lin.numeroOrdem				
			WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdLinha
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			UPDATE tb_TBL_LinhasOGMA SET numeroAdicao = @NumAdicao
			WHERE id = @IdLinha
			FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdLinha
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes					
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_AdicoesGeraDeLinhasOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_AdicoesGeraDeLinhasOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_AnexaDocumento]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_AnexaDocumento] @PathFicheiroAnexar varchar(500), @DirDestinoDocsImportacao varchar(250), @AnoProcesso int, @NumeroProcesso int, 
	@DescricaoFicheiroAnexar varchar(150), @NomeFicheiroAnexar varchar(100), @Utilizador varchar(30), @ImpressaoSerie bit, @TipoFicheiroAnexar varchar(8), @Origem int AS
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @ExtFicheiro varchar(10), @PathDestinoFicheiro varchar(500), @IDDocAnexo int, @PathDocAnexo varchar(500), @Erros varchar(MAX)
-- verfica se diretoria tem backslash no final	
	IF SUBSTRING(REVERSE(@DirDestinoDocsImportacao), 1, 1) <> '\'
		SET @DirDestinoDocsImportacao = @DirDestinoDocsImportacao + '\'		
-- obtem extensão do ficheiro a anexar
	SET @ExtFicheiro = REVERSE(SUBSTRING(REVERSE(@NomeFicheiroAnexar), 1, CHARINDEX('.', REVERSE(@NomeFicheiroAnexar))))
-- constroi path completa diretoria dos anexos da declaração de Importação
	SET @PathDestinoFicheiro = @DirDestinoDocsImportacao + CAST(@AnoProcesso AS varchar(4)) + '\DU' + REPLICATE('0', (8 - LEN(CAST(@NumeroProcesso AS varchar(8))))) + CAST(@NumeroProcesso AS varchar(8)) + '\'
-- processa a criação diretoria dos anexos da declaração de Importação
	EXEC GIDWIN..SP_Externo_CriaDiretoria @PathDestinoFicheiro, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
	BEGIN
		RAISERROR ('Não foi possível criar a diretoria "%s"! ERRO: "%s".', 16, 1, @PathDestinoFicheiro, @Erros)			
		RETURN
	END
-- constroi path completa c/ novo nome p/ ficheiro a anexar
	SET @PathDestinoFicheiro = @PathDestinoFicheiro + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(50), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121), '-', ''), ':', ''), '.', ''), ' ', '') + REPLICATE('0', (8 - LEN(CAST(@NumeroProcesso AS varchar(8))))) + CAST(@NumeroProcesso AS varchar(8)) + @ExtFicheiro
-- processa o mover do ficheiro a anexar (se este tiver sido especificado)
	IF ISNULL(@PathFicheiroAnexar, '') <> ''
	BEGIN
		EXEC GIDWIN..SP_Externo_MoveFicheiro @PathFicheiroAnexar, @PathDestinoFicheiro, @Erros OUTPUT
		IF ISNULL(@Erros, '') <> ''
		BEGIN
			RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 2, @PathFicheiroAnexar, @Erros)	
			RETURN
		END
	END
-- verifica se documento já está anexado na declaração de Importação
	SELECT @IDDocAnexo = DUC_IDEN, @PathDocAnexo = DUF_LINK 
	FROM PRO_DUFI 
	WHERE DUC_PNUM = @NumeroProcesso AND DUC_EANO = @AnoProcesso AND ISNULL(DUF_NOMF, '') = ISNULL(@NomeFicheiroAnexar, '') 
		AND ISNULL(DUF_TMSG, '') = ISNULL(@TipoFicheiroAnexar, '') AND DUF_ORIG = @Origem
-- se não existe ficheiro anexado, insere
	IF @IDDocAnexo IS NULL
	BEGIN							
-- procede à inserção do documento no detalhe de Arquivo da declaração de Importação
		INSERT INTO PRO_DUFI(DUC_PNUM, DUC_EANO, DUF_DESC, DUF_LINK, DUF_DATA, DUF_NOMF, DUF_UTIL, DUF_ISER, DUF_TMSG, DUF_ORIG)
		VALUES(@NumeroProcesso, @AnoProcesso, @DescricaoFicheiroAnexar, @PathDestinoFicheiro, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @NomeFicheiroAnexar, @Utilizador, 
			@ImpressaoSerie, @TipoFicheiroAnexar, @Origem)		
	END
	ELSE		
	BEGIN
-- constroi comando DOS para remover o ficheiro anexado
		EXEC GIDWIN..SP_Externo_RemoveFicheiro @PathDocAnexo, @Erros OUTPUT
		IF ISNULL(@Erros, '') <> ''
		BEGIN
			RAISERROR ('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 3, @PathDocAnexo, @Erros)
			RETURN
		END
-- procede à edição do documento no detalhe de Arquivo da declaração de Importação
		UPDATE PRO_DUFI SET DUF_LINK = @PathDestinoFicheiro, DUF_DATA = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), DUF_NOMF = @NomeFicheiroAnexar , DUF_UTIL = @Utilizador
		WHERE DUC_PNUM = @NumeroProcesso AND DUC_EANO = @AnoProcesso  and DUC_IDEN = @IDDocAnexo
	END	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_AnexaDocumento] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_AnexaDocumento] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_AtualizaDadosDeclaracao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_AtualizaDadosDeclaracao] @NumProcesso int, @AnoProcesso int, @NovaMassaBrtTotal numeric(38, 6) = NULL, @NovosVolumesTotal numeric(38, 6) = NULL, 
	@Utilizador varchar(30), @MensagemErro varchar(8000) OUTPUT, @NovoFreteTotal numeric(38, 6) = NULL, @CodPaisFrete varchar(2) = NULL, @RecalculoCambios bit = 0 AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Erro int, @DataAtual datetime, @TipoEmpresa int, @TotalAdicsDecl int, @TotalVolsDecl numeric(38, 6), @MassaBrtTotalDecl numeric(38, 6), @MontanteTotalDecl numeric(38, 6), 
		@ValorTotalEURDecl numeric(38, 6), @ValorOptativasDecl numeric(38, 6), @SomaFormulaDecl bit, @TxFDADecl numeric(38, 6), @CambioMoedaFreteDecl numeric(38, 6), 
		@CambioMoedaSeguroDecl numeric(38, 6), @VerbasAutoDecl bit, @MassaLiqTotalDecl numeric(38, 6), @ValorAduaneiroTotalDecl numeric(38, 6), @FreteTotalDecl numeric(38, 6), 
		@CodCondEntregaDecl varchar(3), @CodPais15Decl varchar(2), @TxCambioDecl numeric(38, 6), @CodMeioTransporte18 varchar(2), 
		@TotalLiquidacao numeric(38, 6), @TipoMeioTransporte18 int, @AbrPaisFrete varchar(3), 
		@NumAdicao int, @MassaBrtAd numeric(38, 6), @MassaLiqAd numeric(38, 6), @ValorOptativasAd numeric(38, 6), @BaseManualAd bit, @BaseTributacaoDireitosAd numeric(38, 6), 
		@BaseTribDireitosAd numeric(38, 6), @QtdUnidadesAd numeric(38, 6), @TipoTributacaoAd int, @ValorAd numeric(38, 6), @ValorEURAd numeric(38, 6), @DireitosAd numeric(38, 6), 
		@RoyaltiesAd numeric(38, 6), @ValorEstatisticoAd numeric(38, 6), @MatPrimasAd numeric(38, 6), @AjustamentoAd numeric(38, 6), @ValorFreteAd numeric(38, 6), @ValorSeguroAd numeric(38, 6), 
		@ETxCompostaAd bit, @MontanteTribDireitosAd numeric(38, 6), @TaxaValorAd numeric(38, 6), @BaseTribIVAAd numeric(38, 6), @VerbaTransAd numeric(38, 6), 
		@ValorISVAd numeric(38, 6), @AjusteBTIAd numeric(38, 6), @MontanteTribIVAAd numeric(38, 6), @TxIVAArtigoAd numeric(38, 6), @FatorUnidMedida numeric(38, 6), 
		@TotalIVAImposicoes numeric(38, 6), @AcertaFrete bit, @CambioMoedaOriginal numeric(38, 6), @MoedaFreteOriginal varchar(3)	
-- inicia transacção para atualização dos dados na Declarações de Importação
	BEGIN TRANSACTION		
	BEGIN TRY	
-- inicia variáveis
		SET @Erro = 0	
-- valida dados
		IF (@NovaMassaBrtTotal IS NULL) AND (@NovosVolumesTotal IS NULL) AND (@NovoFreteTotal IS NULL) AND (@RecalculoCambios = 0)
			RAISERROR('Novos valores da massa bruta total, total de volumes, frete e recalculo de câmbios não podem ser nulos em simultâneo!', 16, 1)	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()				
-- obtem tipo de empresa
		SELECT @TipoEmpresa = PDE_CADI
		FROM TAB_PDES WITH(NOLOCK)
-- se massa bruta total for p/ alterar, procede à obtenção do novo valor total de optativas se for caso disso
		IF @NovaMassaBrtTotal IS NOT NULL
		BEGIN	
-- obtem meio de transporte da declaração e respetivo novo valor total EUR a aplicar nas adições
			SELECT @CodMeioTransporte18 = duc.MTR_PT18, 
				@ValorTotalEURDecl = SUM((CASE 
						WHEN (@NovaMassaBrtTotal IS NOT NULL) AND (@NovosVolumesTotal IS NOT NULL) THEN ROUND(ROUND((@NovaMassaBrtTotal * ISNULL(dua.DUA_VAEU, 0) / ISNULL(duc.DUC_MBRT, 0)), 3) / ISNULL(duc.DUC_TX23, 1), 2)
						ELSE ISNULL(duc.DUC_VEUR, 0)
					END))
			FROM PRO_DUCG AS duc WITH(NOLOCK) 
				INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_PNUM = dua.DUC_PNUM AND duc.DUC_EANO = dua.DUC_EANO				
			WHERE duc.DUC_PNUM = @NumProcesso AND duc.DUC_EANO = @AnoProcesso AND dua.DUA_CODI = (CASE WHEN (@NovoFreteTotal IS NULL) AND (@RecalculoCambios = 0) THEN 1 ELSE dua.DUA_CODI END)
			GROUP BY duc.MTR_PT18
-- obtem novo valor total de optativas associado ao meio de transporte
			SELECT @ValorOptativasDecl = (CASE mtr.MTR_OPAU
											WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT
																FROM TAB_MTRO WITH(NOLOCK)
																WHERE MTR_IDTY = mtr.MTR_IDTY
																	AND @NovaMassaBrtTotal BETWEEN MTO_LMNP AND MTO_LMXP
																	AND @ValorTotalEURDecl BETWEEN MTO_LMNV AND MTO_LMXV), 0)
											ELSE NULL
										END)
			FROM TAB_MTRA AS mtr WITH(NOLOCK)
			WHERE mtr.MTR_CODI = @CodMeioTransporte18
		END
		ELSE
			SET @ValorOptativasDecl = NULL
-- inicia totais
		SELECT @MassaLiqTotalDecl = 0, @ValorAduaneiroTotalDecl = 0, @MontanteTotalDecl = 0, @ValorTotalEURDecl = 0	
-- obtem dados da declaração de importação e adição nº. "1"
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
			SELECT duc.DUC_ADI5, ISNULL(duc.DUC_TVL6, 0), ISNULL(duc.DUC_MBRT, 0), ISNULL(@ValorOptativasDecl, ISNULL(duc.DUC_OP18, 0)), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TX23, 1), 
				duc.DUC_VBAT, (CASE WHEN ISNULL(NULLIF(CHARINDEX('+', ISNULL(duc.DUC_FR20, '')), 0), 999999999) < ISNULL(NULLIF(CHARINDEX('-', ISNULL(duc.DUC_FR20, '')), 0), 999999999) THEN 1 ELSE 0 END), 
				ISNULL(duc.DUC_TXFR, 1), ISNULL(duc.DUC_TXSE, 1), ISNULL(duc.DUC_FRET, 0), duc.CEN_CO20, duc.PAI_PA15, 
				ISNULL(mtr.MTR_VPVL, 0), 
				dua.DUA_CODI, dua.DUA_MB35, dua.DUA_ML38, dua.DUA_BMAN, ISNULL(dua.DUA_US41, 0), ISNULL(dua.DUA_TRIB, 0), dua.DUA_VA42, ISNULL(dua.DUA_VAEU, 0), 
				ISNULL(dua.DUA_VDIR, 0), ISNULL(dua.DUA_VROY, 0), ISNULL(dua.DUA_MTPR, 0), ISNULL(dua.DUA_VFRE, 0), ISNULL(dua.DUA_VSEG, 0), ISNULL(dua.DUA_BTRI, 0), dua.DUA_TXCO, 
				ISNULL(dua.DUA_TXVL, 0), ISNULL(dua.DUA_VTRA, 0), ISNULL(dua.DUA_IVAV, 0), dua.DUA_ABTI, ISNULL(dua.DUA_TIVA, 0), 
				ISNULL(ume.UME_FACT, 0),
				ROUND(ISNULL((SELECT SUM(DUO_MONT) FROM PRO_DUOI WITH(NOLOCK) WHERE RRE_LIVA = 1 AND DUO_AUTO NOT IN (1, 2, 4, 5) AND DUA_CODI = dua.DUA_CODI AND DUC_EANO = dua.DUC_EANO AND DUC_PNUM = dua.DUC_PNUM), 0), 2), 
				(CASE @TipoEmpresa WHEN 3 THEN 
					(CASE WHEN (duc.CEN_CO20 IN ('FCA', 'EXW')) AND (dbo.FNT_DeclImportacao_CalculaFreteAcordado(duc.CEN_CO20, duc.PAI_PA15, ISNULL(duc.DUC_MBRT, 0), ISNULL(duc.DUC_FRET, 0)) = ISNULL(duc.DUC_FRET, 0)) THEN 1 
					ELSE 0 END)
				ELSE 1 END)
			FROM PRO_DUCG AS duc WITH(NOLOCK) 
				INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_PNUM = dua.DUC_PNUM AND duc.DUC_EANO = dua.DUC_EANO
				LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON duc.MTR_PT18 = mtr.MTR_CODI				
				LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON dua.UME_CODI = ume.UME_CODI
			WHERE duc.DUC_PNUM = @NumProcesso AND duc.DUC_EANO = @AnoProcesso AND dua.DUA_CODI = (CASE WHEN (@NovoFreteTotal IS NULL) AND (@RecalculoCambios = 0) THEN 1 ELSE dua.DUA_CODI END)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @TotalAdicsDecl, @TotalVolsDecl, @MassaBrtTotalDecl, @ValorOptativasDecl, @TxFDADecl, @TxCambioDecl, @VerbasAutoDecl, @SomaFormulaDecl, 
			@CambioMoedaFreteDecl, @CambioMoedaSeguroDecl, @FreteTotalDecl, @CodCondEntregaDecl, @CodPais15Decl, @TipoMeioTransporte18, @NumAdicao, @MassaBrtAd, @MassaLiqAd, 
			@BaseManualAd, @QtdUnidadesAd, @TipoTributacaoAd, @ValorAd, @ValorEURAd, @DireitosAd, @RoyaltiesAd, @MatPrimasAd, @ValorFreteAd, @ValorSeguroAd, @BaseTributacaoDireitosAd, 
			@ETxCompostaAd, @TaxaValorAd, @VerbaTransAd, @ValorISVAd, @AjusteBTIAd, @TxIVAArtigoAd, @FatorUnidMedida, @TotalIVAImposicoes, @AcertaFrete			
		WHILE @@FETCH_STATUS = 0
		BEGIN					
-- se massa bruta total e total volumes forem p/ alterar, procede à alteração do valor
			IF (@NovaMassaBrtTotal IS NOT NULL) AND (@NovosVolumesTotal IS NOT NULL)
			BEGIN
				SET @ValorAd = ROUND((@NovaMassaBrtTotal * @ValorAd / @MassaBrtTotalDecl), 3)
				SET @ValorEURAd = ROUND(@ValorAd / @TxCambioDecl, 2)
			END			
			ELSE
				IF @RecalculoCambios = 1
					SET @ValorEURAd = ROUND(@ValorAd / @TxCambioDecl, 2)
-- se massa bruta total for p/ alterar, procede à respetiva alteração na adição		
			IF @NovaMassaBrtTotal IS NOT NULL			
			BEGIN
				IF @AcertaFrete = 1
					SET @FreteTotalDecl = ROUND((@NovaMassaBrtTotal * @FreteTotalDecl / @MassaBrtTotalDecl), 3)
				SET @MassaBrtTotalDecl = @NovaMassaBrtTotal				
				SET @MassaBrtAd = @MassaBrtTotalDecl
				SET @MassaLiqAd = ROUND((@MassaBrtTotalDecl * 90 / 100), 3)
-- se declaração tiver verbas automáticas, altera valores de frete, seguro e verba transitário	
				IF (@VerbasAutoDecl = 1) AND (@AcertaFrete = 1)
					SET @ValorFreteAd = @FreteTotalDecl					
			END
-- se total volumes for p/ alterar, procede à respetiva alteração
			IF @NovosVolumesTotal IS NOT NULL
				SET @TotalVolsDecl = @NovosVolumesTotal	
-- se frete for p/ alterar, procede à respetiva alteração
			IF @NovoFreteTotal IS NOT NULL
			BEGIN
				SET @ValorFreteAd = ROUND((@MassaBrtAd * @NovoFreteTotal / @MassaBrtTotalDecl), 3)
				SET @FreteTotalDecl = @NovoFreteTotal
			END						
-- se país do frete for p/ alterar, obtem os respetivos dados
			IF ISNULL(@CodPaisFrete, '') <> ''
			BEGIN
				SELECT @AbrPaisFrete = PAI_PREF, @CambioMoedaFreteDecl = dbo.FNT_Geral_ObtemCambio(0, PAI_CODI, @DataAtual)
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @CodPaisFrete				 
			END
-- calcula valor de optativas da adição 
			IF @TipoMeioTransporte18 = 2 -- por volume
				SET @ValorOptativasAd = ROUND(@TotalVolsDecl * @ValorOptativasDecl, 2)			
			ELSE
				SET @ValorOptativasAd = ROUND(@MassaBrtAd * (@ValorOptativasDecl * CEILING(@MassaBrtTotalDecl / 100)) / @MassaBrtTotalDecl, 2)		
-- calcula valor do ajustamento da adição
			IF @TxFDADecl = 0		
			BEGIN
				IF @SomaFormulaDecl = 1
					SET @AjustamentoAd = ROUND(ROUND(@ValorFreteAd / @CambioMoedaFreteDecl, 2) + ROUND(@ValorSeguroAd / @CambioMoedaSeguroDecl, 2) + @RoyaltiesAd + @MatPrimasAd + @DireitosAd, 2)
				ELSE
					SET @AjustamentoAd = ROUND((ROUND(@ValorFreteAd / @CambioMoedaFreteDecl, 2) * -1) - ROUND(@ValorSeguroAd / @CambioMoedaSeguroDecl, 2) + @RoyaltiesAd + @MatPrimasAd - @DireitosAd, 2)
			END
			ELSE
			BEGIN
				IF @SomaFormulaDecl = 1
					SET @AjustamentoAd = ROUND(ROUND(@ValorFreteAd / @CambioMoedaFreteDecl * @TxFDADecl / 100, 2) + ROUND(@ValorSeguroAd / @CambioMoedaSeguroDecl, 2) + @RoyaltiesAd + @MatPrimasAd + @DireitosAd, 2)
				ELSE
					SET @AjustamentoAd = ROUND((ROUND(@ValorFreteAd / @CambioMoedaFreteDecl * @TxFDADecl / 100, 2) * -1) - ROUND(@ValorSeguroAd / @CambioMoedaSeguroDecl, 2) + @RoyaltiesAd + @MatPrimasAd - @DireitosAd, 2)
			END					
-- calcula valor estatistico da adição
			SET @ValorEstatisticoAd = @ValorEURAd + @AjustamentoAd - @MatPrimasAd						
-- calcula valor da base de tributação dos direitos da adição
			IF @BaseManualAd = 0
			BEGIN
				IF @TipoTributacaoAd = 0
					SET @BaseTribDireitosAd = ROUND(@QtdUnidadesAd / @FatorUnidMedida, 3)
				ELSE
					IF @TipoTributacaoAd = 1
						SET @BaseTribDireitosAd = ROUND(@MassaLiqAd / @FatorUnidMedida, 3)
					ELSE
						IF @TipoTributacaoAd = 3
						BEGIN
							IF @SomaFormulaDecl = 1
								SET @BaseTribDireitosAd = ROUND(@ValorEstatisticoAd - @DireitosAd, 3)
							ELSE
								SET @BaseTribDireitosAd = ROUND(@ValorEURAd - @DireitosAd + @RoyaltiesAd, 3)
						END
						ELSE
							SET @BaseTribDireitosAd = 0
			END
			ELSE	
				SET @BaseTribDireitosAd = @BaseTributacaoDireitosAd		
-- calcula montante de tributação dos direitos da adição 
			IF @ETxCompostaAd = 1
				SET @MontanteTribDireitosAd = ROUND(@BaseTribDireitosAd * @TaxaValorAd, 2)					
			ELSE
				SET @MontanteTribDireitosAd = ROUND(@BaseTribDireitosAd * @TaxaValorAd / 100, 2)			
-- calcula valor da base de tributação do IVA da adição
			IF @SomaFormulaDecl = 1
				SET @BaseTribIVAAd = ROUND(@ValorEURAd + ROUND(@ValorFreteAd / @CambioMoedaFreteDecl, 2) + ROUND(@ValorSeguroAd / @CambioMoedaSeguroDecl, 2) + @VerbaTransAd + @ValorOptativasAd + @MontanteTribDireitosAd + @ValorISVAd + @TotalIVAImposicoes + @RoyaltiesAd + @AjusteBTIAd, 2)
			ELSE
				IF @TxFDADecl = 0
					SET @BaseTribIVAAd = ROUND(@ValorEURAd + @VerbaTransAd + @ValorOptativasAd + @MontanteTribDireitosAd + @ValorISVAd + @TotalIVAImposicoes - @DireitosAd + @RoyaltiesAd + @AjusteBTIAd, 2)
				ELSE
					SET @BaseTribIVAAd = ROUND(@ValorEURAd + + ROUND(@ValorSeguroAd / @CambioMoedaSeguroDecl, 2) + @VerbaTransAd + @ValorOptativasAd + @MontanteTribDireitosAd + @ValorISVAd + @TotalIVAImposicoes - @DireitosAd + @RoyaltiesAd + @AjusteBTIAd, 2)																		
-- calcula montante de tributação do IVA da adição
			SET @MontanteTribIVAAd = ROUND(@BaseTribIVAAd * @TxIVAArtigoAd / 100, 2)					
-- atualiza adição da declaração de importação
			UPDATE PRO_DUAD SET DUA_MB35 = @MassaBrtAd, DUA_ML38 = @MassaLiqAd, DUA_VFRE = @ValorFreteAd, DUA_VA42 = @ValorAd, DUA_VAEU = @ValorEURAd, DUA_AJUS = @AjustamentoAd, 
				DUA_VEST = @ValorEstatisticoAd, DUA_VATO = @ValorEstatisticoAd, DUA_BTRI = @BaseTribDireitosAd, DUA_MTRI = @MontanteTribDireitosAd, DUA_BTIV = @BaseTribIVAAd, 
				DUA_VIVA = @MontanteTribIVAAd, DUA_VOPT = @ValorOptativasAd								
			WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso and DUA_CODI = @NumAdicao		
-- atualiza quantidade volumes do anexo de marcas e volumes da adição
			UPDATE PRO_DU31 SET D31_QNTD = @TotalVolsDecl
			WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso and DUA_CODI = @NumAdicao		
-- atualiza montante da menção "VDA" do anexo de documentos da adição
			UPDATE PRO_DDOC SET DDO_MONT = ROUND((CASE @TxFDADecl WHEN 0 THEN (@ValorOptativasAd + @VerbaTransAd) ELSE (CASE WHEN @AjustamentoAd >= 0 THEN (@ValorOptativasDecl + (@ValorFreteAd / @CambioMoedaFreteDecl / 100 * (100 - @TxFDADecl))) ELSE (@ValorOptativasDecl + (@ValorFreteAd / @CambioMoedaFreteDecl / 100 * @TxFDADecl)) END) END), 2)
			WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao AND DDO_AUTO = 5
-- atualiza base tributação e montante da imposição relativa aos dados da Tributação dos Direitos
			UPDATE PRO_DUOI SET DUO_BTRI = @BaseTribDireitosAd, DUO_MONT = @MontanteTribDireitosAd
			WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao AND DUO_AUTO = 1
-- atualiza base tributação e montante da imposição relativa aos dados da Tributação do IVA
			UPDATE PRO_DUOI SET DUO_BTRI = @BaseTribIVAAd, DUO_MONT = @MontanteTribIVAAd
			WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao AND DUO_AUTO = 2
-- atualiza base tributação e montante das imposições não automáticas e não c/ base manual e que não sejam as rubricas configuradas de Trafego CTT e DGA
			UPDATE PRO_DUOI SET DUO_BTRI = ROUND((CASE DUO_TIPO WHEN 1 THEN @BaseTribDireitosAd ELSE @MassaLiqAd END), 3), 
				DUO_MONT = ROUND((CASE DUO_TIPO WHEN 1 THEN (ROUND(@BaseTribDireitosAd, 3) * DUO_TXVL / 100) ELSE (ROUND(@MassaLiqAd, 3) * DUO_TXVL) END), 2)
			WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao AND DUO_AUTO = 0 AND DUO_BMAN = 0 
				AND RRE_CODI NOT IN (SELECT RRE_CDPT FROM TAB_PDES WITH(NOLOCK) UNION SELECT RRE_CDAL FROM TAB_PDES WITH(NOLOCK))
-- incrementa variaveis
			SELECT @MassaLiqTotalDecl = @MassaLiqTotalDecl + @MassaLiqAd, @ValorAduaneiroTotalDecl = @ValorAduaneiroTotalDecl + @ValorEstatisticoAd, 
				@MontanteTotalDecl = @MontanteTotalDecl + @ValorAd, @ValorTotalEURDecl = @ValorTotalEURDecl + @ValorEURAd
			FETCH NEXT FROM Adicoes INTO @TotalAdicsDecl, @TotalVolsDecl, @MassaBrtTotalDecl, @ValorOptativasDecl, @TxFDADecl, @TxCambioDecl, @VerbasAutoDecl, @SomaFormulaDecl, 
				@CambioMoedaFreteDecl, @CambioMoedaSeguroDecl, @FreteTotalDecl, @CodCondEntregaDecl, @CodPais15Decl, @TipoMeioTransporte18, @NumAdicao, @MassaBrtAd, @MassaLiqAd, 
				@BaseManualAd, @QtdUnidadesAd, @TipoTributacaoAd, @ValorAd, @ValorEURAd, @DireitosAd, @RoyaltiesAd, @MatPrimasAd, @ValorFreteAd, @ValorSeguroAd, @BaseTributacaoDireitosAd, 
				@ETxCompostaAd, @TaxaValorAd, @VerbaTransAd, @ValorISVAd, @AjusteBTIAd, @TxIVAArtigoAd, @FatorUnidMedida, @TotalIVAImposicoes, @AcertaFrete
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- atualiza montante do documento "N934" ou remove documento "N934" do anexo de documentos da 1ª adição
		IF EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE ISNULL(PDE_MDV1, 0) < @ValorAduaneiroTotalDecl)
		BEGIN
			UPDATE PRO_DDOC SET DDO_MONT = @ValorAduaneiroTotalDecl
			WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = 1 AND DDO_AUTO = 4		
		END
		ELSE
		BEGIN
			DELETE FROM PRO_DDOC
			WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = 1 AND DDO_AUTO = 4		
		END
-- remove detalhe da Liquidação da declaração de importação
		DELETE FROM PRO_DULR
		WHERE DUC_PNUM = @NumProcesso and DUC_EANO = @AnoProcesso
-- insere rubricas no detalhe da Liquidação da declaração de importação
		INSERT INTO PRO_DULR(DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, DUL_MONT, DUL_MTAG)
		SELECT DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, SUM((CASE DUO_DEST WHEN 0 THEN ISNULL(DUO_MONT, 0) ELSE 0 END)), SUM((CASE DUO_DEST WHEN 1 THEN DUO_MTAG ELSE 0 END))
		FROM PRO_DUOI WITH(NOLOCK) 
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso
		GROUP BY DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME
		ORDER BY RRE_CODI
-- obtem o valor total liquidação no detalhe da Liquidação da declaração de importação 
		SET @TotalLiquidacao = ISNULL((SELECT SUM(DUL_MONT) FROM PRO_DULR WITH(NOLOCK) WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso), 0)
-- calcula a moeda do frete original p/ "XXX" quando o país do frete não tem um último câmbio válido
		IF (ISNULL(@CodPaisFrete, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PAPL WITH(NOLOCK) WHERE PAI_CODI = @CodPaisFrete))
		BEGIN
			SET @CambioMoedaOriginal = 0			
			SELECT TOP 1 @CambioMoedaOriginal = ISNULL(CPA_VEND, 0) 
			FROM TAB_CPAI WITH(NOLOCK) 
			WHERE PAI_CODI = @CodPaisFrete AND CAST(CONVERT(varchar(10), CPA_DATA, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)
			ORDER BY CPA_DATA DESC
			IF @CambioMoedaOriginal = 0
				SET @MoedaFreteOriginal = 'XXX'
			ELSE
				SET @MoedaFreteOriginal = 'EUR'
		END
		ELSE
			SET @MoedaFreteOriginal = 'EUR'				
-- atualiza dados da declaração de importação				
		UPDATE PRO_DUCG SET DUC_TVL6 = @TotalVolsDecl, DUC_OP18 = @ValorOptativasDecl, DUC_FRET = @FreteTotalDecl, PAI_FRET = (CASE ISNULL(@CodPaisFrete, '') WHEN '' THEN PAI_FRET ELSE @CodPaisFrete END), 
			DUC_TXFR = (CASE ISNULL(@CodPaisFrete, '') WHEN '' THEN DUC_TXFR ELSE @CambioMoedaFreteDecl END), PAI_MOFT = (CASE ISNULL(@CodPaisFrete, '') WHEN '' THEN PAI_MOFT ELSE @AbrPaisFrete END),
			DUC_MLQT = @MassaLiqTotalDecl, DUC_MBRT = @MassaBrtTotalDecl, DUC_VATT = @ValorAduaneiroTotalDecl, DUC_TREM = @MassaBrtTotalDecl, DUC_VLRC = @TotalLiquidacao, 
			DUC_MT22 = @MontanteTotalDecl, DUC_VEUR = @ValorTotalEURDecl, DUC_VLRE = dbo.FNT_Extenso_ValorPorExtenso(@TotalLiquidacao, 'euros', 'cêntimos'), 
			DUC_VFRC = (CASE WHEN @NovoFreteTotal IS NULL THEN DUC_VFRC ELSE ROUND(@NovoFreteTotal / @CambioMoedaFreteDecl, 2) END), 
			DUC_MFRC = (CASE ISNULL(@CodPaisFrete, '') WHEN '' THEN DUC_MFRC ELSE @MoedaFreteOriginal END), 
			DUC_UALT = @Utilizador, DUC_DTAL = @DataAtual
		WHERE DUC_PNUM = @NumProcesso and DUC_EANO = @AnoProcesso		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) + ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_AtualizaDadosDeclaracao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_AtualizaDadosDeclaracao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ConverteRegistoParaDAR]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ConverteRegistoParaDAR] @Ano int, @Numero int, @IdUtilizador int, @IdDeclaracaoDAR int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
		SET @NumErro = 0
-- constroi XML para declaração DAR a partir da declaração DUI2
		SET @XMLDeclaracaoDAR = 
			(SELECT
				(SELECT 'I' AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data",
					(CASE duc.DUC_TPDS WHEN 0 THEN 3 ELSE 2 END) AS "regimeIVA",  
					'C07' AS "adicionalRegime", 
					NULLIF(nat.NDE_CODI3, '') AS "natureza", 
					NULLIF(duc.DUC_CPRT, '') AS "documentoTransporte",
					(SELECT NULLIF(duc.DUC_ENIF, '') AS "nif", 
						NULLIF(duc.DUC_ENOM, '') AS "nome", 
						NULLIF(duc.DUC_EMOR, '') AS "morada", 
						NULLIF(duc.DUC_ELOC, '') AS "localidade", 
						NULLIF(duc.DUC_ECPO, '') AS "codigoPostal", 
						NULLIF(duc.DUC_ELPO, '') AS "localidadePostal", 
						NULLIF(duc.PAI_ELIV, '') AS "pais"
					HAVING ISNULL(duc.DUC_ENOM, '') <> ''
					FOR XML PATH('exportador'), TYPE),
					(SELECT ISNULL(NULLIF(duc.DUC_DNIF, ''), '999999990') AS "nif", 
						NULLIF(duc.DUC_DNOM, '') AS "nome", 
						NULLIF(duc.DUC_DMOR, '') AS "morada", 
						NULLIF(duc.DUC_DLOC, '') AS "localidade", 
						NULLIF(duc.DUC_DCPO, '') AS "codigoPostal", 
						NULLIF(duc.DUC_DLPO, '') AS "localidadePostal", 
						NULLIF(duc.PAI_DLIV, '') AS "pais", 
						NULLIF(duc.DUC_DTEL, '') AS "telefone", 
						NULLIF(duc.DUC_DEMA, '') AS "email"					
					FOR XML PATH('importador'), TYPE),
					NULLIF(duc.DEC_CO14, '') AS "declarante/codigoDeclarante",					
					duc.ALF_CODI AS "estancia", 
					'A' AS "tipoDeclaracao", 
					NULLIF(duc.DUC_NVRF, '') AS "vossaReferencia", 
					NULLIF(duc.CEN_CO20, '') AS "condEntrega",
					NULLIF(duc.MTR_PT18, '') AS "meioTransporte", 
					(SELECT 'B' AS "tipoLocalizacao", 
						(CASE duc.DUC_TLOC WHEN 'EA' THEN 'V' ELSE 'Y' END) AS "qualificador", 
						(CASE duc.DUC_TLOC WHEN 'EA' THEN NULL ELSE NULLIF(duc.LME_CO30, '') END) AS "armazemDTP", 
						(CASE duc.DUC_TLOC WHEN 'EA' THEN NULLIF(duc.ALF_CODI1, '') ELSE NULL END) AS "estancia"			
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					NULLIF(duc.PAI_PR22, '') AS "paisMoedaFatura", 
					NULLIF(duc.PAI_FRET, '') AS "paisMoedaCustosTransporte", 	
					ISNULL(nda.FUP_CODI, duc.FUP_CODI) AS "followUp", 
					NULLIF(duc.DUC_UNMD, '') AS "utilizadorNomeado", 	
					duc.DUC_NPDT AS "depositoTemporario/numeroPDDT", 
					duc.DUC_NPDD AS "depositoTemporario/numeroPDDTDEV", 
					duc.DUC_NTDP AS "depositoTemporario/numeroTD", 
					duc.DUC_NACT AS "depositoTemporario/numeroACTM", 
					duc.DUC_NSEQ AS "depositoTemporario/numeroSequencia", 
					NULLIF(duc.DUC_DELG, '') AS "dadosEspecificos/locID", 
					NULLIF(duc.DUC_GTWY, '') AS "dadosEspecificos/gateway", 
					duc.DUC_NVSR AS "dadosEspecificos/serviceLevel", 
					NULLIF(duc.DUC_CIDE, '') AS "dadosEspecificos/portesAcc", 
					NULLIF(duc.DUC_POSA, '') AS "dadosEspecificos/portes", 
					NULLIF(duc.DUC_REF1, '') AS "dadosEspecificos/despachoAcc", 
					NULLIF(duc.DUC_VFRC, 0) AS "dadosEspecificos/freteOriginal", 
					NULLIF(duc.DUC_MFRC, '') AS "dadosEspecificos/moedafreteOriginal", 
					NULLIF(duc.DUC_VDES, 0) AS "dadosEspecificos/despesas", 
					NULLIF(duc.DUC_PPFC, '') AS "dadosEspecificos/condicaoEntrega", 
					NULLIF(duc.DUC_FUPS, '') AS "dadosEspecificos/nomeFicheiro", 
					NULLIF(duc.DUC_CIEX, '') AS "dadosEntidades/numeroContaExpedidor", 
					NULLIF(duc.DUC_CIDE, '') AS "dadosEntidades/numeroContaDestinatario", 
					NULLIF(duc.DUC_D2NO, '') AS "dadosEntidades/nomeOriginalDestinatario", 
					NULLIF(duc.DUC_D2MO, '') AS "dadosEntidades/moradaOriginalDestinatario", 
					NULLIF(duc.DUC_D2LO, '') AS "dadosEntidades/localidadeOriginalDestinatario", 
					NULLIF(duc.DUC_D2CP, '') AS "dadosEntidades/codigoPostalOriginalDestinatario", 
					NULLIF(duc.DUC_D2LP, '') AS "dadosEntidades/localidadePostalOriginalDestinatario", 
					NULLIF(duc.DUC_REF1, '') AS "dadosEntidades/referenciaExterna1", 
					NULLIF(duc.DUC_REF2, '') AS "dadosEntidades/referenciaExterna2", 
					NULLIF(duc.DUC_SHIP, '') AS "dadosEntidades/shipID", 
					NULLIF(duc.DUC_MCPA, '') AS "dadosAWB/miniCPA", 
					(CONVERT(varchar(10), duc.DUC_DTVO, 127) + 'Z') AS "dadosAWB/dataVoo", 
					NULLIF(duc.DUC_AERO, '') AS "dadosAWB/aeroportoOrigem", 
					NULLIF(duc.DUC_NVOO, '') AS "dadosAWB/numeroVoo", 
					NULLIF(duc.DUC_POSA, '') AS "dadosAWB/posicaoAviao", 
					NULLIF(duc.DUC_TRAC, '') AS "dadosAWB/tracking", 
					NULLIF(duc.DUC_TPCG, '') AS "dadosAWB/tipoCarga", 
					NULLIF(duc.DUC_DTYP, '') AS "outrosDados/dutyType", 
					NULLIF(duc.DUC_PAYM, '') AS "outrosDados/payment", 																
					(SELECT
						(SELECT 0 AS "tipoDocumento", 
							ddo.DOC_CODI AS "codigoDocumento",
							ddo.DDO_NUME AS "numeroDocumento"						
						FROM PRO_DUAD AS adi WITH(NOLOCK) INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON adi.APA_CO33 = apa.APA_CODI
							INNER JOIN PRO_DDOC AS ddo WITH(NOLOCK) ON adi.DUC_EANO = ddo.DUC_EANO AND adi.DUC_PNUM = ddo.DUC_PNUM AND adi.DUA_CODI = ddo.DUA_CODI
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.DOC_CODI = doc.DOC_CODI																	
						WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM AND adi.DUA_CODI = 1 AND ddo.DDO_TIPO = 0 AND ddo.DDO_AUTO = 0 AND doc.DOC_DTRA = 0
							AND NOT EXISTS(SELECT AFD_CODI FROM TAB_ALFD WITH(NOLOCK) WHERE ALF_CODI = duc.ALF_CODI AND DOC_CODI = ddo.DOC_CODI)
							AND NOT EXISTS(SELECT ADC_CODI FROM TAB_ADOC WITH(NOLOCK) WHERE APA_CHVE = apa.APA_CHVE AND DOC_CODI = ddo.DOC_CODI AND ADC_UIMP = 1)
						FOR XML PATH('documento'), TYPE)
					FROM PRO_DUAD AS adi WITH(NOLOCK) INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON adi.APA_CO33 = apa.APA_CODI
						INNER JOIN PRO_DDOC AS ddo WITH(NOLOCK) ON adi.DUC_EANO = ddo.DUC_EANO AND adi.DUC_PNUM = ddo.DUC_PNUM AND adi.DUA_CODI = ddo.DUA_CODI
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.DOC_CODI = doc.DOC_CODI																	
					WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM AND adi.DUA_CODI = 1 AND ddo.DDO_TIPO = 0 AND ddo.DDO_AUTO = 0 AND doc.DOC_DTRA = 0
						AND NOT EXISTS(SELECT AFD_CODI FROM TAB_ALFD WITH(NOLOCK) WHERE ALF_CODI = duc.ALF_CODI AND DOC_CODI = ddo.DOC_CODI)
						AND NOT EXISTS(SELECT ADC_CODI FROM TAB_ADOC WITH(NOLOCK) WHERE APA_CHVE = apa.APA_CHVE AND DOC_CODI = ddo.DOC_CODI AND ADC_UIMP = 1)
					GROUP BY ddo.DUC_EANO, ddo.DUC_PNUM
					FOR XML PATH('documentosECertificados'), TYPE), 
					(SELECT
						(SELECT men.INF_CODI AS "codigoMencao"					
						FROM TAB_INFC AS men WITH(NOLOCK) INNER JOIN PRO_DDOC AS ddo WITH(NOLOCK) ON ddo.DDO_TIPO = 1 AND ddo.DDO_AUTO = 0 AND ddo.DOC_CODI = 'PCEDP'
						WHERE men.INF_CODI = 'RBVDP' AND ddo.DUC_EANO = duc.DUC_EANO AND ddo.DUC_PNUM = duc.DUC_PNUM AND ddo.DUA_CODI = 1
						FOR XML PATH('mencao'), TYPE)
					FROM TAB_INFC AS men WITH(NOLOCK) INNER JOIN PRO_DDOC AS ddo WITH(NOLOCK) ON ddo.DDO_TIPO = 1 AND ddo.DDO_AUTO = 0 AND ddo.DOC_CODI = 'PCEDP'
					WHERE men.INF_CODI = 'RBVDP' AND ddo.DUC_EANO = duc.DUC_EANO AND ddo.DUC_PNUM = duc.DUC_PNUM AND ddo.DUA_CODI = 1
					GROUP BY ddo.DUC_EANO, ddo.DUC_PNUM
					FOR XML PATH('informacoesAdicionais'), TYPE),		
					(SELECT
						(SELECT doc.DOC_CODI AS "codigoDocumento", 
							(duc.ALF_CODI + SUBSTRING(ISNULL(duc.MTR_PT18, ''), 1, 1) + ISNULL(RTRIM(LTRIM(STR(dds.DRA_APAN, 4))), '') + dds.DRA_APC1) AS "numeroDocumento"			
						FROM TAB_DOCU AS doc WITH(NOLOCK) INNER JOIN PRO_DURA AS dds WITH(NOLOCK) ON dds.DRA_QUAL = 'X'
						WHERE doc.DOC_CODI = 'N337' AND doc.DOC_CA40 = 1 AND dds.DUC_EANO = duc.DUC_EANO AND dds.DUC_PNUM = duc.DUC_PNUM AND dds.DUA_CODI = 1
						FOR XML PATH('documentoPrecedente'), TYPE)
					FROM TAB_DOCU AS doc WITH(NOLOCK) INNER JOIN PRO_DURA AS dds WITH(NOLOCK) ON dds.DRA_QUAL = 'X'
					WHERE doc.DOC_CODI = 'N337' AND doc.DOC_CA40 = 1 AND dds.DUC_EANO = duc.DUC_EANO AND dds.DUC_PNUM = duc.DUC_PNUM AND dds.DUA_CODI = 1
					GROUP BY dds.DUC_EANO, dds.DUC_PNUM
					FOR XML PATH('documentosPrecedentes'), TYPE), 										
					(SELECT
						(SELECT adi.DUA_CODI AS "numeroAdicao", 
							NULLIF(adi.APA_CP33, '') AS "codigoPautal", 
							NULLIF(adi.DUA_DESG, '') AS "designacao", 							
							NULLIF(adi.PAI_CO34, '') AS "paisOrigem",							
							CAST(adi.DUA_MB35 AS decimal(18, 6)) AS "massaBruta",														
							CAST(ISNULL(adi.DUA_US41, 0) AS decimal(18, 6)) AS "unidades",							
							(CASE adi.DUA_CODI WHEN 1 THEN CAST(duc.DUC_TVL6 AS int) ELSE 0 END) AS "volumes", 
							NULLIF(duc.PAI_PR22, '') AS "paisMoedaFatura", 
							CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "montante", 
							NULLIF(duc.PAI_FRET, '') AS "paisMoedaCustosTransporte", 
							CAST(ISNULL(adi.DUA_VFRE, 0) AS decimal(18, 2)) AS "custosTransporte", 
							(SELECT TOP 1 ISNULL(D31_LOPT, '') FROM PRO_DU31 WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI) AS "codigoBarras", 
							(SELECT TOP 1 ISNULL(D31_NUME, '') FROM PRO_DU31 WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI) AS "numeroObjeto"
						FROM PRO_DUAD AS adi WITH(NOLOCK) 
						WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE),
					(SELECT			
						(SELECT 
							SIN_CODI AS "codigoIncidencia", 
							(CONVERT(varchar(23), CAST(CONVERT(varchar(10), DUI_DINI, 105) + ' ' + CONVERT(varchar(12), DUI_HINI, 114) AS datetime), 127) + 'Z') AS "dataInicio",
							(CONVERT(varchar(23), CAST(CONVERT(varchar(10), DUI_DFIM, 105) + ' ' + CONVERT(varchar(12), DUI_HFIM, 114) AS datetime), 127) + 'Z')AS "dataFim",	
							CAST(DUI_OBSR AS varchar(500)) AS "observacoes", 
							(CASE DUI_REHO WHEN 0 THEN 'R' WHEN 1 THEN 'H' ELSE NULL END) AS "tipoIncidencia"					
						FROM PRO_DUIN WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
						FOR XML PATH('incidencia'), TYPE)
					FROM PRO_DUIN WITH(NOLOCK)
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
					GROUP BY DUC_EANO, DUC_PNUM
					FOR XML PATH('incidencias'), TYPE),
					(SELECT			
						(SELECT DUO_TIPO AS "tipoManifesto", 
							NULLIF(PAI_CODI, '') AS "paisManifesto",
							NULLIF(RTRIM(LTRIM(DUO_DESC)), '') AS "descricao",	
							CAST(ISNULL(DUO_VALO, 0) AS decimal(18, 3)) AS "valor", 						
							SUBSTRING(NULLIF(DUO_MOED, ''), 1, 2) AS "paisMoedaManifesto",							
							CAST(ISNULL(DUO_TFAC, 0) AS decimal(18, 3)) AS "totalFatura",
							RTRIM(LTRIM(DUO_CPA2)) AS "numeroCPA", 
							CAST(ISNULL(DUO_PES2, 0) AS decimal(18, 3)) AS "peso"							
						FROM PRO_DUOD WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND ISNULL(RTRIM(LTRIM(DUO_CPA2)), '') <> ''
						FOR XML PATH('manifesto'), TYPE)
					FROM PRO_DUOD WITH(NOLOCK)
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND ISNULL(RTRIM(LTRIM(DUO_CPA2)), '') <> ''
					GROUP BY DUC_EANO, DUC_PNUM
					FOR XML PATH('manifestos'), TYPE)
				FROM PRO_DUCG AS duc WITH(NOLOCK) INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI	
					INNER JOIN TAB_NDES AS nda WITH(NOLOCK) ON nat.NDE_CODI3 = nda.NDE_CODI
				WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAT
		SET @Erro = ''
		EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @Erro OUTPUT				
-- senão houver erros na geração, efetua processamentos finais
		IF @NumErro = 0
		BEGIN
			SET @IdDeclaracaoDAR = NULL
-- obtem o id da declaração DAR gerada
			SELECT @IdDeclaracaoDAR = id
			FROM tb_DeclaracoesDAR WITH(NOLOCK)
			WHERE ano = YEAR(@DataAtual) AND documentoTransporte = (SELECT DUC_CPRT FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero)
-- verifica se a declaração DAR foi corretamente gerada
			IF @IdDeclaracaoDAR IS NULL
				RAISERROR('Declaração DAR não foi gerada.', 16, 1)
-- atualiza o número dos documento automáticos de origem da alfândega
			UPDATE tb_DeclaracoesDARDocumentos SET numero = ISNULL(did.DDO_NUME, '')
			FROM tb_DeclaracoesDARDocumentos AS ddd WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddd.id_documento = doc.DOC_IDTY
				INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND doc.DOC_CODI = did.DOC_CODI
			WHERE ddd.id_declaracaoDAR = @IdDeclaracaoDAR AND ddd.origem = 1 AND ddd.numero <> ISNULL(did.DDO_NUME, '')
-- remove a declaração DUI2 se for possível; caso contrário coloca a declaração DUI2 no status de "Anulado"
			BEGIN TRY
				DELETE FROM PRO_DUCG 
				WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero
			END TRY
			BEGIN CATCH
				UPDATE PRO_DUCG SET DUC_CPRT = (DUC_CPRT + '_ANULADO'), DUC_STAT = 3 --Anulado
				WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero
			END CATCH
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ConverteRegistoParaDAR] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ConverteRegistoParaDAR] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ConverteRegistoParaIMP]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ConverteRegistoParaIMP] @Ano int, @Numero int, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30)
	DECLARE @IdDeclaracao bigint, @CodDestinatario varchar(18), @CodDeclarante varchar(6), @CaucaoGlobal bit, @NumeroCaucao varchar(17), @AnoCaucao varchar(4), @TipoCaucao varchar(1), 
		@TipoEntidadeCaucao int, @NIFDeclarante varchar(17), @NumeroNRG varchar(24), @CodAlfandegaGarantia varchar(8), @CodigoAcessoGarantia varchar(4), @OutrasRefGarantia varchar(35), 
		@NIFREsponsavelGarantia varchar(17), @CodPaisCondEntrega varchar(2), @Regime varchar(4), @TipoMeioTransporte int, @Contentor varchar(17), @CodDocumentoArmazem varchar(5), 
		@NumeroRefArmazem varchar(35), @NumeroEORIArmazem varchar(17), @AlfandegaEncomendasPostais bit, @NumeroContramarca varchar(70), @DataContramarca datetime, @BeneficiarioIVA bit
	DECLARE @NumAdicao int, @NumRegisto int, @IdRegisto bigint
-- inicia transacção para a conversão para IMP-CAU
	BEGIN TRANSACTION TspIMPConverteIMPCAU
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem dados em falta 
		SELECT @IdDeclaracao = duc.DUC_IDTY, @CodDestinatario = duc.DUC_DST8, @CodDeclarante = duc.DEC_CO14, @CaucaoGlobal = duc.DUC_CGLB, @NumeroCaucao = duc.DUC_CAUC, @AnoCaucao = duc.DUC_CANO, 
			@TipoCaucao = duc.DUC_CTIP, @TipoEntidadeCaucao = duc.DUC_CENT, @BeneficiarioIVA = duc.DUC_BIVA, 
			@AlfandegaEncomendasPostais = (CASE duc.ALF_CODI WHEN 'PT000236' THEN 1 ELSE 0 END), 
			@NIFDeclarante = CAST(dcl.DEC_NIF AS varchar(17)),
			@NIFREsponsavelGarantia = (CASE duc.DUC_CENT WHEN 1 THEN cli.CLI_CNIF ELSE NULL END), 
			@CodPaisCondEntrega = (CASE cen.CEN_LOCT WHEN 1 THEN (CASE cen.CEN_LOCD WHEN 0 THEN duc.PAI_ELIV ELSE duc.PAI_DLIV END) ELSE (CASE WHEN ISNULL(NULLIF(CHARINDEX('+', ISNULL(duc.DUC_FR20, '')), 0), 999999) > ISNULL(NULLIF(CHARINDEX('-', ISNULL(duc.DUC_FR20, '')), 0), 999999) THEN duc.PAI_DLIV ELSE duc.PAI_ELIV END) END), 
			@TipoMeioTransporte = mtr.MTR_TIPO, 
			@Regime = ISNULL(ISNULL(NULLIF(adi.DUA_RG37, ''), NULLIF(tde.TDE_REGI, '')), '4000'), 
			@CodDocumentoArmazem = arm.DOC_CODI, @NumeroRefArmazem = arm.ARM_NAUT, @NumeroEORIArmazem = arm.ARM_EORI, 
			@Contentor = (CASE duc.DUC_ADI5 WHEN 1 THEN (SELECT MIN(DCO_CNUM) FROM PRO_DCON WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI GROUP BY DUC_EANO, DUC_PNUM, DUA_CODI HAVING COUNT(*) = 1) ELSE NULL END), 
			@NumeroContramarca = (ISNULL(duc.ALF_CODI, '') + LEFT(ISNULL(duc.MTR_PT18, ''), 1) + (SELECT TOP 1 (CAST(DRA_APAN AS varchar(10)) + DRA_APC1) FROM PRO_DURA WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DRA_QUAL = 'X')), 
			@DataContramarca = (SELECT TOP 1 DRA_APDT FROM PRO_DURA WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DRA_QUAL = 'X')
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
			INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON duc.TDE_CODI = tde.TDE_CODI
			LEFT OUTER JOIN TAB_CENT AS cen WITH(NOLOCK) ON duc.CEN_CO20 = cen.CEN_CODI
			LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON duc.MTR_PT18 = mtr.MTR_CODI
			LEFT OUTER JOIN TAB_ARMZ AS arm WITH(NOLOCK) ON duc.ARM_CODI = arm.ARM_CODI
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON duc.DUC_EANO = adi.DUC_EANO AND duc.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI = 1			
		WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero
-- obtem dados da garantia em falta
		IF (@CaucaoGlobal = 1) AND (ISNULL(@NumeroCaucao, '') <> '')
		BEGIN						
			IF @TipoEntidadeCaucao = 0
			BEGIN
				SELECT @NumeroNRG = (ISNULL(DEC_ACA1, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA1))) + DEC_NCA1 + '/' + ISNULL(DEC_TCA1, '')), @CodAlfandegaGarantia = ALF_CODI1, @CodigoAcessoGarantia = DEC_CCA1, @OutrasRefGarantia = DEC_OCA1
				FROM TAB_DECL WITH(NOLOCK)
				WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA1, '') = @NumeroCaucao AND ISNULL(DEC_ACA1, '') = @AnoCaucao AND ISNULL(DEC_TCA1, '') = @TipoCaucao
				IF ISNULL(@NumeroNRG, '') = ''
				BEGIN				
					SELECT @NumeroNRG = (ISNULL(DEC_ACA2, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA2))) + DEC_NCA2 + '/' + ISNULL(DEC_TCA2, '')), @CodAlfandegaGarantia = ALF_CODI2, @CodigoAcessoGarantia = DEC_CCA2, @OutrasRefGarantia = DEC_OCA2
					FROM TAB_DECL WITH(NOLOCK)
					WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA2, '') = @NumeroCaucao AND ISNULL(DEC_ACA2, '') = @AnoCaucao AND ISNULL(DEC_TCA2, '') = @TipoCaucao
					IF ISNULL(@NumeroNRG, '') = ''
					BEGIN				
						SELECT @NumeroNRG = (ISNULL(DEC_ACA3, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA3))) + DEC_NCA3 + '/' + ISNULL(DEC_TCA3, '')), @CodAlfandegaGarantia = ALF_CODI3, @CodigoAcessoGarantia = DEC_CCA3, @OutrasRefGarantia = DEC_OCA3
						FROM TAB_DECL WITH(NOLOCK)
						WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA3, '') = @NumeroCaucao AND ISNULL(DEC_ACA3, '') = @AnoCaucao AND ISNULL(DEC_TCA3, '') = @TipoCaucao
						IF ISNULL(@NumeroNRG, '') = ''
						BEGIN				
							SELECT @NumeroNRG = (ISNULL(DEC_ACA4, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA4))) + DEC_NCA4 + '/' + ISNULL(DEC_TCA4, '')), @CodAlfandegaGarantia = ALF_CODI4, @CodigoAcessoGarantia = DEC_CCA4, @OutrasRefGarantia = DEC_OCA4
							FROM TAB_DECL WITH(NOLOCK)
							WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA4, '') = @NumeroCaucao AND ISNULL(DEC_ACA4, '') = @AnoCaucao AND ISNULL(DEC_TCA4, '') = @TipoCaucao
							IF ISNULL(@NumeroNRG, '') = ''
							BEGIN				
								SELECT @NumeroNRG = (ISNULL(DEC_ACA5, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA5))) + DEC_NCA5 + '/' + ISNULL(DEC_TCA5, '')), @CodAlfandegaGarantia = ALF_CODI5, @CodigoAcessoGarantia = DEC_CCA5, @OutrasRefGarantia = DEC_OCA5
								FROM TAB_DECL WITH(NOLOCK)
								WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA5, '') = @NumeroCaucao AND ISNULL(DEC_ACA5, '') = @AnoCaucao AND ISNULL(DEC_TCA5, '') = @TipoCaucao
							END
						END
					END
				END
			END
			ELSE
			BEGIN
				SELECT @NumeroNRG = (ISNULL(CLI_ANO1, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA1))) + CLI_NCA1 + '/' + ISNULL(CLI_TCA1, '')), @CodAlfandegaGarantia = ALF_CODI1, @CodigoAcessoGarantia = CLI_CCA1, @OutrasRefGarantia = CLI_OCA1
				FROM TAB_CLIE WITH(NOLOCK)
				WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA1, '') = @NumeroCaucao AND ISNULL(CLI_ANO1, '') = @AnoCaucao AND ISNULL(CLI_TCA1, '') = @TipoCaucao
				IF ISNULL(@NumeroNRG, '') = ''
				BEGIN
					SELECT @NumeroNRG = (ISNULL(CLI_ANO2, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA2))) + CLI_NCA2 + '/' + ISNULL(CLI_TCA2, '')), @CodAlfandegaGarantia = ALF_CODI2, @CodigoAcessoGarantia = CLI_CCA2, @OutrasRefGarantia = CLI_OCA2
					FROM TAB_CLIE WITH(NOLOCK)
					WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA2, '') = @NumeroCaucao AND ISNULL(CLI_ANO2, '') = @AnoCaucao AND ISNULL(CLI_TCA2, '') = @TipoCaucao
					IF ISNULL(@NumeroNRG, '') = ''
					BEGIN
						SELECT @NumeroNRG = (ISNULL(CLI_ANO3, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA3))) + CLI_NCA3 + '/' + ISNULL(CLI_TCA3, '')), @CodAlfandegaGarantia = ALF_CODI3, @CodigoAcessoGarantia = CLI_CCA3, @OutrasRefGarantia = CLI_OCA3
						FROM TAB_CLIE WITH(NOLOCK)
						WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA3, '') = @NumeroCaucao AND ISNULL(CLI_ANO3, '') = @AnoCaucao AND ISNULL(CLI_TCA3, '') = @TipoCaucao
						IF ISNULL(@NumeroNRG, '') = ''
						BEGIN
							SELECT @NumeroNRG = (ISNULL(CLI_ANO4, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA4))) + CLI_NCA4 + '/' + ISNULL(CLI_TCA4, '')), @CodAlfandegaGarantia = ALF_CODI4, @CodigoAcessoGarantia = CLI_CCA4, @OutrasRefGarantia = CLI_OCA4
							FROM TAB_CLIE WITH(NOLOCK)
							WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA4, '') = @NumeroCaucao AND ISNULL(CLI_ANO4, '') = @AnoCaucao AND ISNULL(CLI_TCA4, '') = @TipoCaucao
							IF ISNULL(@NumeroNRG, '') = ''
							BEGIN
								SELECT @NumeroNRG = (ISNULL(CLI_ANO5, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA5))) + CLI_NCA5 + '/' + ISNULL(CLI_TCA5, '')), @CodAlfandegaGarantia = ALF_CODI5, @CodigoAcessoGarantia = CLI_CCA5, @OutrasRefGarantia = CLI_OCA5
								FROM TAB_CLIE WITH(NOLOCK)
								WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA5, '') = @NumeroCaucao AND ISNULL(CLI_ANO5, '') = @AnoCaucao AND ISNULL(CLI_TCA5, '') = @TipoCaucao
							END
						END
					END
				END
			END			
		END
		ELSE
		BEGIN
			SET @NumeroNRG = NULL 
			SET @CodAlfandegaGarantia = NULL  
			SET @CodigoAcessoGarantia = NULL  
			SET @OutrasRefGarantia = NULL 
		END
-- atualiza dados gerais da declaração p/ assumir valor de anexo B "dummy" de modo a que possa assumir os calculos automáticos dos TR associados ao anexo "H1" ou "H6"
		UPDATE PRO_DUCG SET 
			DUC_ANXB = '##'
		WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero
-- atualiza pedidos para atualização do campo da origem (necessário fazer este update primeiro que os dados gerais devido ao automatismo do TR)
		UPDATE PRO_DUPD SET 			
			DPD_ORIG = 1
		FROM PRO_DUPD AS dpd WITH(NOLOCK)
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dpd.DUC_EANO = duc.DUC_EANO AND dpd.DUC_PNUM = duc.DUC_PNUM 
			INNER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON duc.TDE_CODI = tdp.TDE_CODI AND dpd.TXM_CODI = tdp.TXM_CODI
		WHERE dpd.DUC_EANO = @Ano AND dpd.DUC_PNUM = @Numero AND dpd.DPD_ORIG = 0
-- atualiza imposições das adições para atualização do campo da origem (necessário fazer este update primeiro que os dados gerais devido ao automatismo do TR)		
		UPDATE PRO_DUOI SET 			
			DUO_AUTO = 6
		FROM PRO_DUOI AS dai WITH(NOLOCK) 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON dai.DUC_EANO = adi.DUC_EANO AND dai.DUC_PNUM = adi.DUC_PNUM AND dai.DUA_CODI = adi.DUA_CODI
			INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON adi.APA_CO33 = art.APA_CODI
			INNER JOIN TAB_APOI AS aoi WITH(NOLOCK) ON art.APA_CHVE = aoi.APA_CHVE AND dai.RRE_CODI = aoi.RRE_CODI
		WHERE dai.DUC_EANO = @Ano AND dai.DUC_PNUM = @Numero AND dai.DUO_AUTO = 0
-- altera dados gerais da declaração p/ assumir IMP-CAU
		UPDATE PRO_DUCG SET 
			DUC_DUNO = 2, 
			DUC_NRLO = (RIGHT(STR(DUC_EANO, 4), 2) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 9 - LEN(LTRIM(STR(DUC_PNUM, 9)))) + LTRIM(STR(DUC_PNUM, 9))), 
			PAI_PA10 = NULL,
			PAI_NO10 = NULL, 
			DUC_DST8 = DUC_DST8, 
			DEC_CO14 = DEC_CO14, 
			ALF_CODI = ALF_CODI, 
			TDE_CODI = TDE_CODI,
			DUC_VATT = DUC_VATT,
			DUC_VTRN = DUC_VTRN, 
			DUC_NTDP = DUC_NTDP, 
			PAI_PA15 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE PAI_PA15 END), 
			PAI_NO15 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE PAI_NO15 END), 
			PAI_P15A = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE PAI_P15A END), 
			DUC_DIRT = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN 0 ELSE DUC_DIRT END), 
			PAI_P17B = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE PAI_P17B END), 		 
			NTR_CO24 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE NTR_CO24 END), 
			NTR_NOME = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE NTR_NOME END), 
			MTR_FT21 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE MTR_FT21 END), 
			MTR_NO21 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE MTR_NO21 END), 
			PAI_PA21 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE PAI_PA21 END), 		
			DUC_TPDC = (CASE DUC_TPDC WHEN 2 THEN DUC_TPDC ELSE NULL END), 
			DUC_CAUC = @NumeroNRG, 
			DUC_REF7 = DUC_CPRT,
			DUC_ARTI = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE DUC_ARTI END),  
			DUC_DE20 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE DUC_DE20 END), 
			DUC_MT18 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE DUC_MT18 END), 
			DUC_CT19 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN 0 ELSE DUC_CT19 END), 
			DUC_TLOC = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE (CASE DUC_TLOC WHEN 'OL' THEN 'A' ELSE 'B' END) END), 
			LME_CO30 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE LME_CO30 END), 
			DUC_LC30 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE DUC_LC30 END), 
			ALF_CODI1 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE ALF_CODI1 END), 
			ALF_NOME1 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE ALF_NOME1 END), 
			DUC_LAMO = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE DUC_LAMO END), 
			DUC_LACP = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE DUC_LACP END), 
			DUC_LALO = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE DUC_LALO END), 
			ARM_CODI = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE ARM_CODI END), 
			ARM_NOME = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE ARM_NOME END), 
			TAR_CODI = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE TAR_CODI END), 
			TAR_DESC = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE TAR_DESC END), 
			DUC_ANXB = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN 'H6' ELSE 'H1' END), 
			DEC_NIF = @NIFDeclarante, 
			DUC_CNIR = @NIFREsponsavelGarantia, 
			ALF_CODI2 = @CodAlfandegaGarantia, 
			DUC_CCAC = @CodigoAcessoGarantia, 
			DUC_CORF = @OutrasRefGarantia, 
			PAI_CODI2 = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE @CodPaisCondEntrega END), 
			MTR_TIPO = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE @TipoMeioTransporte END), 
			DUC_CONT = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE @Contentor END), 
			DUC_QUAL = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE (CASE DUC_TLOC WHEN 'OL' THEN 'Z' WHEN 'LA' THEN 'Y' ELSE 'V' END) END), 
			DOC_CODI = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE @CodDocumentoArmazem END), 
			DUC_NRAU = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE @NumeroRefArmazem END), 
			DUC_EORI = (CASE @AlfandegaEncomendasPostais WHEN 1 THEN NULL ELSE @NumeroEORIArmazem END), 
			DUC_REGI = @Regime, 
			DUC_UALT = @CodUtilizador, 
			DUC_DTAL = @DataAtual
		WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero	
-- atualiza pedidos para atualização de campos de acordo com IMP-CAU 
		UPDATE PRO_DUPD SET 
			TXM_CODI = TXM_CODI, 
			DPD_DESC = SUBSTRING(DPD_DESC, 1, 512)
		WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero
-- atualiza manifestos para atualização de campos de acordo com IMP-CAU
		UPDATE PRO_DUOD SET 
			APA_CPAU = NULL, 
			PAI_IDTY = (SELECT PAI_IDTY FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = LEFT(DUO_MOED, 2))
		WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero
-- atualiza documento precedente afeto ao regime "N337"/"N960"
		UPDATE tb_IMP_DeclaracoesPrecedentes SET 
			numero = ISNULL(NULLIF(@NumeroContramarca, ''), numero), 
			dataContramarca = @DataContramarca,
			id_utilizadorControlo = @IdUtilizador, 
			dataControlo = @DataAtual
		WHERE id_declaracaoIMP = @IdDeclaracao AND origem = 1
-- remove todos os registos do sub-detalhe de declaração sumária
		DELETE FROM PRO_DURA
		WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero
-- remove os registos do sub-detalhe de menções exceto de origem do artigo
		DELETE FROM PRO_DDOC 
		FROM PRO_DDOC AS dam WITH(NOLOCK)
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON dam.DUC_EANO = adi.DUC_EANO AND dam.DUC_PNUM = adi.DUC_PNUM AND dam.DUA_CODI = adi.DUA_CODI
			INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON adi.APA_CO33 = art.APA_CODI
		WHERE dam.DUC_EANO = @Ano AND dam.DUC_PNUM = @Numero AND dam.DDO_TIPO = 1 
			AND NOT EXISTS(SELECT 1 FROM TAB_AMEN WITH(NOLOCK) WHERE APA_CHVE = art.APA_CHVE AND INF_CODI = dam.DOC_CODI AND AME_UIMP = 1)
-- remove os registos do sub-detalhe de documentos com origem do Importador (OEA), Declarante (OEA), Declarante (RSI), Valor Aduaneiro Total ou Documento do Armazém
		DELETE FROM PRO_DDOC 		
		WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DDO_TIPO = 0 AND DDO_AUTO IN (1, 2, 3, 4, 7)
-- atualiza o número e restantes dados dos documento automáticos de origem do Tipo Declaração
		UPDATE tb_IMP_DeclaracoesDocumentos SET 
			numero = did.DDO_NUME, 
			dataValidade = did.DDO_DINI,
			id_paisMoeda = pai.PAI_IDTY,
			montante = ISNULL(did.DDO_MONT, 0),
			entidadeEmissora = did.DDO_EEMI,
			id_unidadeMedida = ume.UME_IDTY,
			quantidade = did.DDO_QTDE,
			id_utilizadorControlo = @IdUtilizador,
			dataControlo = @DataAtual
		FROM tb_IMP_DeclaracoesDocumentos AS ddd WITH(NOLOCK) 
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddd.id_documento = doc.DOC_IDTY
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ddd.id_declaracaoIMP = duc.DUC_IDTY
			INNER JOIN TAB_TDED AS tdd WITH(NOLOCK) ON duc.TDE_CODI = tdd.TDE_CODI AND doc.DOC_CODI = tdd.DOC_CODI
			INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND tdd.DOC_CODI = did.DOC_CODI
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON did.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON did.UME_CODI = ume.UME_CODI
		WHERE ddd.id_declaracaoIMP = @IdDeclaracao AND ddd.origem = 1 AND ISNULL(ddd.numero, '') <> ISNULL(did.DDO_NUME, '')
-- remove os registos do sub-detalhe de documentos com origem do Tipo Declaração
		DELETE FROM PRO_DDOC 
		FROM PRO_DDOC AS dad WITH(NOLOCK)						
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dad.DUC_EANO = duc.DUC_EANO AND dad.DUC_PNUM = duc.DUC_PNUM 			
		WHERE dad.DUC_EANO = @Ano AND dad.DUC_PNUM = @Numero AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0
			AND EXISTS(SELECT 1 FROM TAB_TDED WITH(NOLOCK) WHERE TDE_CODI = duc.TDE_CODI AND DOC_CODI = dad.DOC_CODI)			
-- atualiza o número e restantes dados dos documento automáticos de origem do Importador
		UPDATE tb_IMP_DeclaracoesDocumentos SET 
			numero = did.DDO_NUME, 
			dataValidade = did.DDO_DINI,
			id_paisMoeda = pai.PAI_IDTY,
			montante = ISNULL(did.DDO_MONT, 0),
			entidadeEmissora = did.DDO_EEMI,
			id_unidadeMedida = ume.UME_IDTY,
			quantidade = did.DDO_QTDE,
			id_utilizadorControlo = @IdUtilizador,
			dataControlo = @DataAtual
		FROM tb_IMP_DeclaracoesDocumentos AS ddd WITH(NOLOCK) 
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddd.id_documento = doc.DOC_IDTY
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ddd.id_declaracaoIMP = duc.DUC_IDTY
			INNER JOIN TAB_CLDO AS cld WITH(NOLOCK) ON duc.DUC_DST8 = cld.CLI_CODI AND doc.DOC_CODI = cld.DOC_CODI AND cld.CLD_UIMP = 1
			INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND cld.DOC_CODI = did.DOC_CODI
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON did.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON did.UME_CODI = ume.UME_CODI
		WHERE ddd.id_declaracaoIMP = @IdDeclaracao AND ddd.origem = 3 AND ISNULL(ddd.numero, '') <> ISNULL(did.DDO_NUME, '')
-- remove os registos do sub-detalhe de documentos com origem do Importador
		DELETE FROM PRO_DDOC 
		FROM PRO_DDOC AS dad WITH(NOLOCK)						
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dad.DUC_EANO = duc.DUC_EANO AND dad.DUC_PNUM = duc.DUC_PNUM 			
		WHERE dad.DUC_EANO = @Ano AND dad.DUC_PNUM = @Numero AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0
			AND EXISTS(SELECT 1 FROM TAB_CLDO WITH(NOLOCK) WHERE CLI_CODI = duc.DUC_DST8 AND DOC_CODI = dad.DOC_CODI AND CLD_UIMP = 1)
-- atualiza o número e restantes dados dos documento automáticos de origem da Estância
		UPDATE tb_IMP_DeclaracoesDocumentos SET 
			numero = did.DDO_NUME, 
			dataValidade = did.DDO_DINI,
			id_paisMoeda = pai.PAI_IDTY,
			montante = ISNULL(did.DDO_MONT, 0),
			entidadeEmissora = did.DDO_EEMI,
			id_unidadeMedida = ume.UME_IDTY,
			quantidade = did.DDO_QTDE,
			id_utilizadorControlo = @IdUtilizador,
			dataControlo = @DataAtual
		FROM tb_IMP_DeclaracoesDocumentos AS ddd WITH(NOLOCK) 
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddd.id_documento = doc.DOC_IDTY
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ddd.id_declaracaoIMP = duc.DUC_IDTY
			INNER JOIN TAB_ALFD AS ald WITH(NOLOCK) ON duc.ALF_CODI = ald.ALF_CODI AND doc.DOC_CODI = ald.DOC_CODI
			INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND ald.DOC_CODI = did.DOC_CODI
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON did.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON did.UME_CODI = ume.UME_CODI
		WHERE ddd.id_declaracaoIMP = @IdDeclaracao AND ddd.origem = 6 AND ISNULL(ddd.numero, '') <> ISNULL(did.DDO_NUME, '')
-- remove os registos do sub-detalhe de documentos com origem da Estância
		DELETE FROM PRO_DDOC 
		FROM PRO_DDOC AS dad WITH(NOLOCK)						
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dad.DUC_EANO = duc.DUC_EANO AND dad.DUC_PNUM = duc.DUC_PNUM 			
		WHERE dad.DUC_EANO = @Ano AND dad.DUC_PNUM = @Numero AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0
			AND EXISTS(SELECT 1 FROM TAB_ALFD WITH(NOLOCK) WHERE ALF_CODI = duc.ALF_CODI AND DOC_CODI = dad.DOC_CODI)
-- atualiza o número e restantes dados dos documento automáticos de origem do Tipo NIF Exportador
		UPDATE tb_IMP_DeclaracoesDocumentos SET 
			numero = did.DDO_NUME, 
			dataValidade = did.DDO_DINI,
			id_paisMoeda = pai.PAI_IDTY,
			montante = ISNULL(did.DDO_MONT, 0),
			entidadeEmissora = did.DDO_EEMI,
			id_unidadeMedida = ume.UME_IDTY,
			quantidade = did.DDO_QTDE,
			id_utilizadorControlo = @IdUtilizador,
			dataControlo = @DataAtual
		FROM tb_IMP_DeclaracoesDocumentos AS ddd WITH(NOLOCK) 
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddd.id_documento = doc.DOC_IDTY
			INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND doc.DOC_CODI = did.DOC_CODI
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON did.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON did.UME_CODI = ume.UME_CODI
		WHERE ddd.id_declaracaoIMP = @IdDeclaracao AND ddd.origem = 8 AND ISNULL(ddd.numero, '') <> ISNULL(did.DDO_NUME, '')
-- remove o registo do sub-detalhe de documentos com origem do Tipo NIF Exportador
		DELETE FROM PRO_DDOC 			
		WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DDO_TIPO = 0 AND DDO_AUTO = 0 AND DOC_CODI = '3E18'			
-- atualiza o número e restantes dados dos documento automáticos de origem do Tipo NIF Importador
		UPDATE tb_IMP_DeclaracoesDocumentos SET 
			numero = did.DDO_NUME, 
			dataValidade = did.DDO_DINI,
			id_paisMoeda = pai.PAI_IDTY,
			montante = ISNULL(did.DDO_MONT, 0),
			entidadeEmissora = did.DDO_EEMI,
			id_unidadeMedida = ume.UME_IDTY,
			quantidade = did.DDO_QTDE,
			id_utilizadorControlo = @IdUtilizador,
			dataControlo = @DataAtual
		FROM tb_IMP_DeclaracoesDocumentos AS ddd WITH(NOLOCK) 
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddd.id_documento = doc.DOC_IDTY
			INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND doc.DOC_CODI = did.DOC_CODI
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON did.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON did.UME_CODI = ume.UME_CODI
		WHERE ddd.id_declaracaoIMP = @IdDeclaracao AND ddd.origem = 9 AND ISNULL(ddd.numero, '') <> ISNULL(did.DDO_NUME, '')
-- remove o registo do sub-detalhe de documentos com origem do Tipo NIF Importador
		DELETE FROM PRO_DDOC 			
		WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DDO_TIPO = 0 AND DDO_AUTO = 0 AND DOC_CODI = '3E19'
-- atualiza o número e restantes dados dos documento automáticos de origem dos Pedidos
		UPDATE tb_IMP_DeclaracoesDocumentos SET 
			numero = did.DDO_NUME, 
			dataValidade = did.DDO_DINI,
			id_paisMoeda = pai.PAI_IDTY,
			montante = ISNULL(did.DDO_MONT, 0),
			entidadeEmissora = did.DDO_EEMI,
			id_unidadeMedida = ume.UME_IDTY,
			quantidade = did.DDO_QTDE,
			id_utilizadorControlo = @IdUtilizador,
			dataControlo = @DataAtual
		FROM tb_IMP_DeclaracoesDocumentos AS ddd WITH(NOLOCK) 			
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ddd.id_declaracaoIMP = duc.DUC_IDTY
			INNER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON duc.DUC_EANO = dpd.DUC_EANO AND duc.DUC_PNUM = dpd.DUC_PNUM
			INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpd.TXM_CODI = ped.TXM_CODI
			INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND ped.DOC_CODI = did.DOC_CODI
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON did.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON did.UME_CODI = ume.UME_CODI
		WHERE ddd.id_declaracaoIMP = @IdDeclaracao AND ddd.origem = 10 AND ISNULL(ddd.numero, '') <> ISNULL(did.DDO_NUME, '')
-- remove os registos do sub-detalhe de documentos com origem dos Pedidos
		DELETE FROM PRO_DDOC 
		FROM PRO_DDOC AS dad WITH(NOLOCK)										
			INNER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON dad.DUC_EANO = dpd.DUC_EANO AND dad.DUC_PNUM = dpd.DUC_PNUM	
			INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpd.TXM_CODI = ped.TXM_CODI
		WHERE dad.DUC_EANO = @Ano AND dad.DUC_PNUM = @Numero AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0 AND dad.DOC_CODI = ped.DOC_CODI
-- atualiza o número e restantes dados dos documento automáticos de origem do Regime
		UPDATE tb_IMP_DeclaracoesDocumentos SET 
			numero = did.DDO_NUME, 
			dataValidade = did.DDO_DINI,
			id_paisMoeda = pai.PAI_IDTY,
			montante = ISNULL(did.DDO_MONT, 0),
			entidadeEmissora = did.DDO_EEMI,
			id_unidadeMedida = ume.UME_IDTY,
			quantidade = did.DDO_QTDE,
			id_utilizadorControlo = @IdUtilizador,
			dataControlo = @DataAtual
		FROM tb_IMP_DeclaracoesDocumentos AS ddd WITH(NOLOCK) 			
			INNER JOIN PRO_DDOC AS did WITH(NOLOCK) ON did.DUC_EANO = @Ano AND did.DUC_PNUM = @Numero AND did.DUA_CODI = 1 AND did.DDO_TIPO = 0 AND did.DDO_AUTO = 0 AND did.DOC_CODI IN ('Y041', '9E21')
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON did.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON did.UME_CODI = ume.UME_CODI
		WHERE ddd.id_declaracaoIMP = @IdDeclaracao AND ddd.origem = 12 AND ISNULL(ddd.numero, '') <> ISNULL(did.DDO_NUME, '')
-- remove o registo do sub-detalhe de documentos com origem do Regime
		DELETE FROM PRO_DDOC 			
		WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DDO_TIPO = 0 AND DDO_AUTO = 0 AND DOC_CODI IN ('Y041', '9E21')
 -- atualiza registos do sub-detalhe de documentos com origem do Artigo
		UPDATE PRO_DDOC SET 
			DDO_TIPO = doc.DOC_DTRA, 
			DDO_AUTO = 8
		FROM PRO_DDOC AS dad WITH(NOLOCK)						
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON dad.DUC_EANO = adi.DUC_EANO AND dad.DUC_PNUM = adi.DUC_PNUM AND dad.DUA_CODI = adi.DUA_CODI
			INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON adi.APA_CO33 = art.APA_CODI
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI
		WHERE dad.DUC_EANO = @Ano AND dad.DUC_PNUM = @Numero AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0
			AND EXISTS(SELECT 1 FROM TAB_ADOC WITH(NOLOCK) WHERE APA_CHVE = art.APA_CHVE AND DOC_CODI = dad.DOC_CODI AND ADC_UIMP = 1)
-- insere os documentos da 1ª adição manuais
		INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, dataValidade, id_paisMoeda, montante, entidadeEmissora, id_unidadeMedida, quantidade, 
			origem, id_utilizadorControlo, dataControlo)
		SELECT @IdDeclaracao, doc.DOC_DTRA, doc.DOC_IDTY, ddo.DDO_NUME, ddo.DDO_DINI, pai.PAI_IDTY, ISNULL(ddo.DDO_MONT, 0), ddo.DDO_EEMI, ume.UME_IDTY, ddo.DDO_QTDE, 
			0, @IdUtilizador, @DataAtual
		FROM PRO_DDOC AS ddo WITH(NOLOCK) 
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.DOC_CODI = doc.DOC_CODI
			LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON ddo.PAI_CODI = pai.PAI_CODI
			LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON ddo.UME_CODI = ume.UME_CODI
		WHERE ddo.DUC_EANO = @Ano AND ddo.DUC_PNUM = @Numero AND ddo.DUA_CODI = 1 AND ddo.DDO_TIPO = 0 AND ddo.DDO_AUTO = 0
-- remove os registos do sub-detalhe de documentos da 1ª adição com origem manual
		DELETE FROM PRO_DDOC 		
		WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = 1 AND DDO_TIPO = 0 AND DDO_AUTO = 0	
-- atualiza registos do sub-detalhe de marcas e volumes para garantir as regras de acordo com IMP-CAU 
		UPDATE PRO_DU31 SET
			D31_CASR = 0, 
			D31_CASC = 0			
		WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND (D31_CASR = 1 OR D31_CASC = 1)
		UPDATE PRO_DU31 SET			
			D31_QNTD = 0			
		WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND D31_AUTO = 1
-- remove contentores da 1ª adição quando só existe uma adição e tem apenas 1 contentor (que passou para dados gerais)
		DELETE FROM PRO_DCON
		FROM PRO_DCON AS dac WITH(NOLOCK)
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dac.DUC_EANO = duc.DUC_EANO AND dac.DUC_PNUM = duc.DUC_PNUM 			
		WHERE dac.DUC_EANO = @Ano AND dac.DUC_PNUM = @Numero AND duc.DUC_ADI5 = 1
			AND (SELECT COUNT(*) FROM PRO_DCON WITH(NOLOCK) WHERE DUC_EANO = dac.DUC_EANO AND DUC_PNUM = dac.DUC_PNUM AND DUA_CODI = dac.DUA_CODI) = 1
-- obtem as adições da declaração e respetivos dados
		DECLARE @IdAdicao int, @IdDesdobramento int, @NumeroCaucaoDireitos varchar(17), @AnoCaucaoDireitos varchar(4), @TipoCaucaoDireitos varchar(1), @TipoEntidadeCaucaoDireitos int, 
			@NumeroNRGDireitos varchar(24), @CodAlfandegaGarantiaDireitos varchar(8), @CodigoAcessoGarantiaDireitos varchar(4), @OutrasRefGarantiaDireitos varchar(35), 
			@NIFREsponsavelGarantiaDireitos varchar(17), @NumeroCaucaoIVA varchar(17), @AnoCaucaoIVA varchar(4), @TipoCaucaoIVA varchar(1), @TipoEntidadeCaucaoIVA int, @NumeroNRGIVA varchar(24), 
			@CodAlfandegaGarantiaIVA varchar(8), @CodigoAcessoGarantiaIVA varchar(4), @OutrasRefGarantiaIVA varchar(35), @NIFREsponsavelGarantiaIVA varchar(17), @LimpaUnidadeMedida bit, 
			@AtualizaAjustamento bit
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT adi.DUA_CODI, adi.DUA_IDEN, adi.DUA_CAUD, adi.DUA_CAND, adi.DUA_CTID, adi.DUA_CEND, adi.DUA_CAUI, adi.DUA_CANI, adi.DUA_CTII, adi.DUA_CENI, 				
				(SELECT TOP 1 id FROM tb_TBL_Desdobramentos WITH(NOLOCK) WHERE tipoDeclaracao = duc.TDE_1CAS AND regime = adi.DUA_RG37 AND desdobramento1 = adi.DUA_R37B AND ISNULL(desdobramento2, '') = ISNULL(adi.DUA_R37C, '')), 
				(CASE WHEN (ISNULL(adi.DUA_TRIB, 0) NOT IN (0, 1)) AND (ISNULL(adi.UME_CODI, '') <> '') THEN 1 ELSE 0 END), 
				(CASE WHEN (ISNULL(adi.DUA_VROY, 0) <> 0) OR (ISNULL(adi.DUA_MTPR, 0) <> 0) THEN 1 ELSE 0 END)
			FROM PRO_DUAD AS adi WITH(NOLOCK)
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM				
			WHERE adi.DUC_EANO = @Ano AND adi.DUC_PNUM = @Numero
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdAdicao, @NumeroCaucaoDireitos, @AnoCaucaoDireitos, @TipoCaucaoDireitos, @TipoEntidadeCaucaoDireitos, @NumeroCaucaoIVA, @AnoCaucaoIVA, 
			@TipoCaucaoIVA, @TipoEntidadeCaucaoIVA, @IdDesdobramento, @LimpaUnidadeMedida, @AtualizaAjustamento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @NumeroNRGDireitos = NULL 
			SET @CodAlfandegaGarantiaDireitos = NULL  
			SET @CodigoAcessoGarantiaDireitos = NULL  
			SET @OutrasRefGarantiaDireitos = NULL 
			SET @NIFREsponsavelGarantiaDireitos = NULL 
			SET @NumeroNRGIVA = NULL 
			SET @CodAlfandegaGarantiaIVA = NULL  
			SET @CodigoAcessoGarantiaIVA = NULL  
			SET @OutrasRefGarantiaIVA = NULL 
			SET @NIFREsponsavelGarantiaIVA = NULL
-- se caução não for global e garantia dos direitos estiver definida, obtem dados em falta da garantia dos direitos
			IF (@CaucaoGlobal = 0) AND (ISNULL(@NumeroCaucaoDireitos, '') <> '')
			BEGIN
				IF @TipoEntidadeCaucaoDireitos = 0
				BEGIN
					SELECT @NumeroNRGDireitos = (ISNULL(DEC_ACA1, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA1))) + DEC_NCA1 + '/' + ISNULL(DEC_TCA1, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI1, @CodigoAcessoGarantiaDireitos = DEC_CCA1, @OutrasRefGarantiaDireitos = DEC_OCA1
					FROM TAB_DECL WITH(NOLOCK)
					WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA1, '') = @NumeroCaucaoDireitos AND ISNULL(DEC_ACA1, '') = @AnoCaucaoDireitos AND ISNULL(DEC_TCA1, '') = @TipoCaucaoDireitos
					IF ISNULL(@NumeroNRGDireitos, '') = ''
					BEGIN				
						SELECT @NumeroNRGDireitos = (ISNULL(DEC_ACA2, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA2))) + DEC_NCA2 + '/' + ISNULL(DEC_TCA2, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI2, @CodigoAcessoGarantiaDireitos = DEC_CCA2, @OutrasRefGarantiaDireitos = DEC_OCA2
						FROM TAB_DECL WITH(NOLOCK)
						WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA2, '') = @NumeroCaucaoDireitos AND ISNULL(DEC_ACA2, '') = @AnoCaucaoDireitos AND ISNULL(DEC_TCA2, '') = @TipoCaucaoDireitos
						IF ISNULL(@NumeroNRGDireitos, '') = ''
						BEGIN				
							SELECT @NumeroNRGDireitos = (ISNULL(DEC_ACA3, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA3))) + DEC_NCA3 + '/' + ISNULL(DEC_TCA3, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI3, @CodigoAcessoGarantiaDireitos = DEC_CCA3, @OutrasRefGarantiaDireitos = DEC_OCA3
							FROM TAB_DECL WITH(NOLOCK)
							WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA3, '') = @NumeroCaucaoDireitos AND ISNULL(DEC_ACA3, '') = @AnoCaucaoDireitos AND ISNULL(DEC_TCA3, '') = @TipoCaucaoDireitos
							IF ISNULL(@NumeroNRGDireitos, '') = ''
							BEGIN				
								SELECT @NumeroNRGDireitos = (ISNULL(DEC_ACA4, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA4))) + DEC_NCA4 + '/' + ISNULL(DEC_TCA4, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI4, @CodigoAcessoGarantiaDireitos = DEC_CCA4, @OutrasRefGarantiaDireitos = DEC_OCA4
								FROM TAB_DECL WITH(NOLOCK)
								WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA4, '') = @NumeroCaucaoDireitos AND ISNULL(DEC_ACA4, '') = @AnoCaucaoDireitos AND ISNULL(DEC_TCA4, '') = @TipoCaucaoDireitos
								IF ISNULL(@NumeroNRGDireitos, '') = ''
								BEGIN				
									SELECT @NumeroNRGDireitos = (ISNULL(DEC_ACA5, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA5))) + DEC_NCA5 + '/' + ISNULL(DEC_TCA5, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI5, @CodigoAcessoGarantiaDireitos = DEC_CCA5, @OutrasRefGarantiaDireitos = DEC_OCA5
									FROM TAB_DECL WITH(NOLOCK)
									WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA5, '') = @NumeroCaucaoDireitos AND ISNULL(DEC_ACA5, '') = @AnoCaucaoDireitos AND ISNULL(DEC_TCA5, '') = @TipoCaucaoDireitos
								END
							END
						END
					END
				END
				ELSE
				BEGIN
					SELECT @NumeroNRGDireitos = (ISNULL(CLI_ANO1, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA1))) + CLI_NCA1 + '/' + ISNULL(CLI_TCA1, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI1, @CodigoAcessoGarantiaDireitos = CLI_CCA1, @OutrasRefGarantiaDireitos = CLI_OCA1, @NIFREsponsavelGarantiaDireitos = CLI_CNIF
					FROM TAB_CLIE WITH(NOLOCK)
					WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA1, '') = @NumeroCaucaoDireitos AND ISNULL(CLI_ANO1, '') = @AnoCaucaoDireitos AND ISNULL(CLI_TCA1, '') = @TipoCaucaoDireitos
					IF ISNULL(@NumeroNRGDireitos, '') = ''
					BEGIN
						SELECT @NumeroNRGDireitos = (ISNULL(CLI_ANO2, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA2))) + CLI_NCA2 + '/' + ISNULL(CLI_TCA2, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI2, @CodigoAcessoGarantiaDireitos = CLI_CCA2, @OutrasRefGarantiaDireitos = CLI_OCA2, @NIFREsponsavelGarantiaDireitos = CLI_CNIF
						FROM TAB_CLIE WITH(NOLOCK)
						WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA2, '') = @NumeroCaucaoDireitos AND ISNULL(CLI_ANO2, '') = @AnoCaucaoDireitos AND ISNULL(CLI_TCA2, '') = @TipoCaucaoDireitos
						IF ISNULL(@NumeroNRGDireitos, '') = ''
						BEGIN
							SELECT @NumeroNRGDireitos = (ISNULL(CLI_ANO3, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA3))) + CLI_NCA3 + '/' + ISNULL(CLI_TCA3, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI3, @CodigoAcessoGarantiaDireitos = CLI_CCA3, @OutrasRefGarantiaDireitos = CLI_OCA3, @NIFREsponsavelGarantiaDireitos = CLI_CNIF
							FROM TAB_CLIE WITH(NOLOCK)
							WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA3, '') = @NumeroCaucaoDireitos AND ISNULL(CLI_ANO3, '') = @AnoCaucaoDireitos AND ISNULL(CLI_TCA3, '') = @TipoCaucaoDireitos
							IF ISNULL(@NumeroNRGDireitos, '') = ''
							BEGIN
								SELECT @NumeroNRGDireitos = (ISNULL(CLI_ANO4, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA4))) + CLI_NCA4 + '/' + ISNULL(CLI_TCA4, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI4, @CodigoAcessoGarantiaDireitos = CLI_CCA4, @OutrasRefGarantiaDireitos = CLI_OCA4, @NIFREsponsavelGarantiaDireitos = CLI_CNIF
								FROM TAB_CLIE WITH(NOLOCK)
								WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA4, '') = @NumeroCaucaoDireitos AND ISNULL(CLI_ANO4, '') = @AnoCaucaoDireitos AND ISNULL(CLI_TCA4, '') = @TipoCaucaoDireitos
								IF ISNULL(@NumeroNRGDireitos, '') = ''
								BEGIN
									SELECT @NumeroNRGDireitos = (ISNULL(CLI_ANO5, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA5))) + CLI_NCA5 + '/' + ISNULL(CLI_TCA5, '')), @CodAlfandegaGarantiaDireitos = ALF_CODI5, @CodigoAcessoGarantiaDireitos = CLI_CCA5, @OutrasRefGarantiaDireitos = CLI_OCA5, @NIFREsponsavelGarantiaDireitos = CLI_CNIF
									FROM TAB_CLIE WITH(NOLOCK)
									WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA5, '') = @NumeroCaucaoDireitos AND ISNULL(CLI_ANO5, '') = @AnoCaucaoDireitos AND ISNULL(CLI_TCA5, '') = @TipoCaucaoDireitos
								END
							END
						END
					END
				END			
			END			
-- se caução não for global, não for BIVA e garantia do IVA estiver definida, obtem dados em falta da garantia do IVA
			IF (@CaucaoGlobal = 0) AND (@BeneficiarioIVA = 0) AND (ISNULL(@NumeroCaucaoIVA, '') <> '')
			BEGIN
				IF @TipoEntidadeCaucaoIVA = 0
				BEGIN
					SELECT @NumeroNRGIVA = (ISNULL(DEC_ACA1, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA1))) + DEC_NCA1 + '/' + ISNULL(DEC_TCA1, '')), @CodAlfandegaGarantiaIVA = ALF_CODI1, @CodigoAcessoGarantiaIVA = DEC_CCA1, @OutrasRefGarantiaIVA = DEC_OCA1
					FROM TAB_DECL WITH(NOLOCK)
					WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA1, '') = @NumeroCaucaoIVA AND ISNULL(DEC_ACA1, '') = @AnoCaucaoIVA AND ISNULL(DEC_TCA1, '') = @TipoCaucaoIVA
					IF ISNULL(@NumeroNRGIVA, '') = ''
					BEGIN				
						SELECT @NumeroNRGIVA = (ISNULL(DEC_ACA2, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA2))) + DEC_NCA2 + '/' + ISNULL(DEC_TCA2, '')), @CodAlfandegaGarantiaIVA = ALF_CODI2, @CodigoAcessoGarantiaIVA = DEC_CCA2, @OutrasRefGarantiaIVA = DEC_OCA2
						FROM TAB_DECL WITH(NOLOCK)
						WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA2, '') = @NumeroCaucaoIVA AND ISNULL(DEC_ACA2, '') = @AnoCaucaoIVA AND ISNULL(DEC_TCA2, '') = @TipoCaucaoIVA
						IF ISNULL(@NumeroNRGIVA, '') = ''
						BEGIN				
							SELECT @NumeroNRGIVA = (ISNULL(DEC_ACA3, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA3))) + DEC_NCA3 + '/' + ISNULL(DEC_TCA3, '')), @CodAlfandegaGarantiaIVA = ALF_CODI3, @CodigoAcessoGarantiaIVA = DEC_CCA3, @OutrasRefGarantiaIVA = DEC_OCA3
							FROM TAB_DECL WITH(NOLOCK)
							WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA3, '') = @NumeroCaucaoIVA AND ISNULL(DEC_ACA3, '') = @AnoCaucaoIVA AND ISNULL(DEC_TCA3, '') = @TipoCaucaoIVA
							IF ISNULL(@NumeroNRGIVA, '') = ''
							BEGIN				
								SELECT @NumeroNRGIVA = (ISNULL(DEC_ACA4, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA4))) + DEC_NCA4 + '/' + ISNULL(DEC_TCA4, '')), @CodAlfandegaGarantiaIVA = ALF_CODI4, @CodigoAcessoGarantiaIVA = DEC_CCA4, @OutrasRefGarantiaIVA = DEC_OCA4
								FROM TAB_DECL WITH(NOLOCK)
								WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA4, '') = @NumeroCaucaoIVA AND ISNULL(DEC_ACA4, '') = @AnoCaucaoIVA AND ISNULL(DEC_TCA4, '') = @TipoCaucaoIVA
								IF ISNULL(@NumeroNRGIVA, '') = ''
								BEGIN				
									SELECT @NumeroNRGIVA = (ISNULL(DEC_ACA5, '') + '/' + REPLICATE('0', (17 - LEN(DEC_NCA5))) + DEC_NCA5 + '/' + ISNULL(DEC_TCA5, '')), @CodAlfandegaGarantiaIVA = ALF_CODI5, @CodigoAcessoGarantiaIVA = DEC_CCA5, @OutrasRefGarantiaIVA = DEC_OCA5
									FROM TAB_DECL WITH(NOLOCK)
									WHERE DEC_CODI = @CodDeclarante AND ISNULL(DEC_NCA5, '') = @NumeroCaucaoIVA AND ISNULL(DEC_ACA5, '') = @AnoCaucaoIVA AND ISNULL(DEC_TCA5, '') = @TipoCaucaoIVA
								END
							END
						END
					END
				END
				ELSE
				BEGIN
					SELECT @NumeroNRGIVA = (ISNULL(CLI_ANO1, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA1))) + CLI_NCA1 + '/' + ISNULL(CLI_TCA1, '')), @CodAlfandegaGarantiaIVA = ALF_CODI1, @CodigoAcessoGarantiaIVA = CLI_CCA1, @OutrasRefGarantiaIVA = CLI_OCA1, @NIFREsponsavelGarantiaIVA = CLI_CNIF
					FROM TAB_CLIE WITH(NOLOCK)
					WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA1, '') = @NumeroCaucaoIVA AND ISNULL(CLI_ANO1, '') = @AnoCaucaoIVA AND ISNULL(CLI_TCA1, '') = @TipoCaucaoIVA
					IF ISNULL(@NumeroNRGIVA, '') = ''
					BEGIN
						SELECT @NumeroNRGIVA = (ISNULL(CLI_ANO2, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA2))) + CLI_NCA2 + '/' + ISNULL(CLI_TCA2, '')), @CodAlfandegaGarantiaIVA = ALF_CODI2, @CodigoAcessoGarantiaIVA = CLI_CCA2, @OutrasRefGarantiaIVA = CLI_OCA2, @NIFREsponsavelGarantiaIVA = CLI_CNIF
						FROM TAB_CLIE WITH(NOLOCK)
						WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA2, '') = @NumeroCaucaoIVA AND ISNULL(CLI_ANO2, '') = @AnoCaucaoIVA AND ISNULL(CLI_TCA2, '') = @TipoCaucaoIVA
						IF ISNULL(@NumeroNRGIVA, '') = ''
						BEGIN
							SELECT @NumeroNRGIVA = (ISNULL(CLI_ANO3, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA3))) + CLI_NCA3 + '/' + ISNULL(CLI_TCA3, '')), @CodAlfandegaGarantiaIVA = ALF_CODI3, @CodigoAcessoGarantiaIVA = CLI_CCA3, @OutrasRefGarantiaIVA = CLI_OCA3, @NIFREsponsavelGarantiaIVA = CLI_CNIF
							FROM TAB_CLIE WITH(NOLOCK)
							WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA3, '') = @NumeroCaucaoIVA AND ISNULL(CLI_ANO3, '') = @AnoCaucaoIVA AND ISNULL(CLI_TCA3, '') = @TipoCaucaoIVA
							IF ISNULL(@NumeroNRGIVA, '') = ''
							BEGIN
								SELECT @NumeroNRGIVA = (ISNULL(CLI_ANO4, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA4))) + CLI_NCA4 + '/' + ISNULL(CLI_TCA4, '')), @CodAlfandegaGarantiaIVA = ALF_CODI4, @CodigoAcessoGarantiaIVA = CLI_CCA4, @OutrasRefGarantiaIVA = CLI_OCA4, @NIFREsponsavelGarantiaIVA = CLI_CNIF
								FROM TAB_CLIE WITH(NOLOCK)
								WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA4, '') = @NumeroCaucaoIVA AND ISNULL(CLI_ANO4, '') = @AnoCaucaoIVA AND ISNULL(CLI_TCA4, '') = @TipoCaucaoIVA
								IF ISNULL(@NumeroNRGIVA, '') = ''
								BEGIN
									SELECT @NumeroNRGIVA = (ISNULL(CLI_ANO5, '') + '/' + REPLICATE('0', (17 - LEN(CLI_NCA5))) + CLI_NCA5 + '/' + ISNULL(CLI_TCA5, '')), @CodAlfandegaGarantiaIVA = ALF_CODI5, @CodigoAcessoGarantiaIVA = CLI_CCA5, @OutrasRefGarantiaIVA = CLI_OCA5, @NIFREsponsavelGarantiaIVA = CLI_CNIF
									FROM TAB_CLIE WITH(NOLOCK)
									WHERE CLI_CODI = @CodDestinatario AND ISNULL(CLI_NCA5, '') = @NumeroCaucaoIVA AND ISNULL(CLI_ANO5, '') = @AnoCaucaoIVA AND ISNULL(CLI_TCA5, '') = @TipoCaucaoIVA
								END
							END
						END
					END
				END			
			END					
-- atualiza adição para atualização de restantes campos de acordo com IMP-CAU 
			UPDATE PRO_DUAD SET 
				DUA_R37B = DUA_R37B, 
				DUA_VDIR = DUA_VDIR,
				DUA_VOPT = DUA_VOPT, 
				UME_CODI = (CASE @LimpaUnidadeMedida WHEN 1 THEN NULL ELSE UME_CODI END), 
				UME_NOTR = (CASE @LimpaUnidadeMedida WHEN 1 THEN NULL ELSE UME_NOTR END), 
				DUA_VROY = (CASE @AtualizaAjustamento WHEN 1 THEN 0 ELSE DUA_VROY END), 
				DUA_ROYA = (CASE @AtualizaAjustamento WHEN 1 THEN 0 ELSE DUA_ROYA END), 
				DUA_MTPR = (CASE @AtualizaAjustamento WHEN 1 THEN 0 ELSE DUA_MTPR END), 
				DUA_ADRE = NULL, 
				DUA_VIRT = 0, 				
				id_desdobramento = (CASE WHEN id_desdobramento IS NULL THEN @IdDesdobramento ELSE id_desdobramento END), 
				DUA_CAUC = (CASE @CaucaoGlobal WHEN 0 THEN @NumeroNRGDireitos ELSE DUA_CAUC END),						
				DUA_CAUD = (CASE @CaucaoGlobal WHEN 0 THEN @NumeroNRGDireitos ELSE DUA_CAUD END),								
				ALF_CODI = (CASE @CaucaoGlobal WHEN 0 THEN @CodAlfandegaGarantiaDireitos ELSE ALF_CODI END),
				DUA_CCAD = (CASE @CaucaoGlobal WHEN 0 THEN @CodigoAcessoGarantiaDireitos ELSE DUA_CCAD END),
				DUA_CORD = (CASE @CaucaoGlobal WHEN 0 THEN @OutrasRefGarantiaDireitos ELSE DUA_CORD END),
				DUA_CNRD = (CASE @CaucaoGlobal WHEN 0 THEN @NIFREsponsavelGarantiaDireitos ELSE DUA_CNRD END),
				DUA_CAUI = (CASE @CaucaoGlobal WHEN 0 THEN @NumeroNRGIVA ELSE DUA_CAUI END),
				DUA_CANI = (CASE WHEN (@CaucaoGlobal = 0) AND (ISNULL(@NumeroNRGIVA, '') = '') THEN NULL ELSE DUA_CANI END),
				DUA_CTII = (CASE WHEN (@CaucaoGlobal = 0) AND (ISNULL(@NumeroNRGIVA, '') = '') THEN NULL ELSE DUA_CTII END),
				DUA_CENI  = (CASE WHEN (@CaucaoGlobal = 0) AND (ISNULL(@NumeroNRGIVA, '') = '') THEN NULL ELSE DUA_CENI END),
				ALF_CODI1 = (CASE @CaucaoGlobal WHEN 0 THEN @CodAlfandegaGarantiaIVA ELSE ALF_CODI1 END),
				DUA_CCAI = (CASE @CaucaoGlobal WHEN 0 THEN @CodigoAcessoGarantiaIVA ELSE DUA_CCAI END),
				DUA_CORI = (CASE @CaucaoGlobal WHEN 0 THEN @OutrasRefGarantiaIVA ELSE DUA_CORI END), 
				DUA_CNRI = (CASE @CaucaoGlobal WHEN 0 THEN @NIFREsponsavelGarantiaIVA ELSE DUA_CNRI END)
			WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
-- atualiza adição para recalculo de valores apenas quando os campos de unidade de medida ou royalties/matérias-primas foram alterados
			IF (@LimpaUnidadeMedida = 1) OR (@AtualizaAjustamento = 1)
			BEGIN
				DECLARE @Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @ValorAduaneiro numeric(38, 6), @Optativas numeric(38, 6), @BaseTributacaoDireitos numeric(38, 6), 
					@MontanteDireitos numeric(38, 6), @BaseTributacaoIVA numeric(38, 6)
				UPDATE PRO_DUAD SET 										
					@Ajustamento = DUA_AJUS = (CASE 
												WHEN @AtualizaAjustamento = 1 THEN dbo.fn_IMP_CalculaAjustamento(ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0), ISNULL(duc.DUC_TxSE, 0), adi.DUA_VFRE, adi.DUA_VSEG, adi.DUA_VDIR, adi.DUA_ACRE, adi.DUA_DEDU)
												ELSE adi.DUA_AJUS
											END),					
					@ValorEstatistico = DUA_VEST = (CASE 
														WHEN @AtualizaAjustamento = 1 THEN dbo.fn_IMP_CalculaValorEstatistico(ISNULL(adi.DUA_VAEU, 0), @Ajustamento)
														ELSE adi.DUA_VEST
													END),
					@ValorAduaneiro = DUA_VATO = (CASE 
													WHEN @AtualizaAjustamento = 1 THEN @ValorEstatistico
													ELSE adi.DUA_VATO
												END),
					@Optativas = DUA_VOPT = (CASE 
												WHEN @AtualizaAjustamento = 1 THEN dbo.fn_IMP_CalculaValorOptativas(adi.DUC_EANO, adi.DUC_PNUM, adi.DUA_CODI, duc.MTR_PT18, duc.DUC_ADI5, ISNULL(duc.DUC_TVL6, 0), ISNULL(duc.DUC_OP18, 0), ISNULL(duc.DUC_MBRT, 0), ISNULL(duc.DUC_VATT, 0), adi.DUA_MB35, @ValorAduaneiro)
												ELSE adi.DUA_VOPT
											END), 
					@BaseTributacaoDireitos = DUA_BTRI = dbo.fn_IMP_CalculaBaseTributacaoDireitos(adi.DUA_BMAN, adi.DUA_BTRI, adi.DUA_TRIB, adi.DUA_ML38, adi.DUA_US41, @ValorEstatistico, adi.UME_CODI), 										
					@MontanteDireitos = DUA_MTRI = dbo.fn_IMP_CalculaMontanteDireitos(adi.DUA_BMAN, adi.DUA_MTRI, (CASE adi.DUA_TXCO WHEN 1 THEN 0 ELSE 1 END), ISNULL(adi.DUA_TXVL, 0), @BaseTributacaoDireitos),					
					@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0), adi.DUA_VFRE, @Ajustamento, @ValorEstatistico, adi.DUA_VTRA, @Optativas, @MontanteDireitos, adi.DUA_IVAV, adi.DUA_ABTI, adi.DUA_MIVI), 					
					DUA_VIVA = ROUND(@BaseTributacaoIVA * ISNULL(adi.DUA_TIVA, 0) / 100, 2), 					
					DUA_QTDD = (CASE 
									WHEN @LimpaUnidadeMedida = 1 THEN dbo.fn_IMP_CalculaBaseTributacaoDireitos(0, 0, adi.DUA_TRIB, adi.DUA_ML38, adi.DUA_US41, 0, adi.UME_CODI) 
									ELSE adi.DUA_QTDD 
								END)
				FROM PRO_DUAD AS adi WITH(NOLOCK) 
					INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM					
				WHERE adi.DUA_IDEN = @IdAdicao
			END
-- remove os registos do sub-detalhe de menções de origem do artigo
			DELETE FROM PRO_DDOC 
			FROM PRO_DDOC AS dam WITH(NOLOCK)
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON dam.DUC_EANO = adi.DUC_EANO AND dam.DUC_PNUM = adi.DUC_PNUM AND dam.DUA_CODI = adi.DUA_CODI
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON adi.APA_CO33 = art.APA_CODI
			WHERE dam.DUC_EANO = @Ano AND dam.DUC_PNUM = @Numero AND dam.DUA_CODI = @NumAdicao AND dam.DDO_TIPO = 1 AND dam.DDO_AUTO = 0
				AND EXISTS(SELECT 1 FROM TAB_AMEN WITH(NOLOCK) WHERE APA_CHVE = art.APA_CHVE AND INF_CODI = dam.DOC_CODI AND AME_UIMP = 1)
-- processa a numeração dos documentos da adição dado que houve remoções
			SET @NumRegisto = 1
			DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT DDO_IDEN
				FROM PRO_DDOC WITH(NOLOCK)
				WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
			OPEN Documentos
			FETCH NEXT FROM Documentos INTO @IdRegisto
			WHILE @@FETCH_STATUS = 0
			BEGIN							
				UPDATE PRO_DDOC SET DDO_CODI = @NumRegisto
				WHERE DDO_IDEN = @IdRegisto
				SET @NumRegisto = @NumRegisto + 1
				FETCH NEXT FROM Documentos INTO @IdRegisto
			END
			CLOSE Documentos
			DEALLOCATE Documentos
-- atualiza registos do sub-detalhe de veículos para garantir as regras de acordo com IMP-CAU 
			UPDATE PRO_DUBT SET 
				DBT_QUAL = DBT_QUAL,
				CAT_CODI = CAT_CODI,
				TVE_CODI = TVE_CODI, 
				TCO_CODI = TCO_CODI,
				DBT_QTDE = DBT_QTDE, 
				DBT_OUTR = DBT_OUTR
			WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
-- atualiza registos do sub-detalhe de elementos para tributação para garantir as regras de acordo com IMP-CAU 
			UPDATE PRO_DUET SET 
				RRE_CODI = RRE_CODI
			WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
			FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdAdicao, @NumeroCaucaoDireitos, @AnoCaucaoDireitos, @TipoCaucaoDireitos, @TipoEntidadeCaucaoDireitos, @NumeroCaucaoIVA, @AnoCaucaoIVA, 
				@TipoCaucaoIVA, @TipoEntidadeCaucaoIVA, @IdDesdobramento, @LimpaUnidadeMedida, @AtualizaAjustamento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPConverteIMPCAU
	END CATCH		
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPConverteIMPCAU		
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ConverteRegistoParaIMP] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ConverteRegistoParaIMP] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ConverteXMLStandardParaIMPCAU]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_DeclImportacao_ConverteXMLStandardParaIMPCAU] @FicheiroXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @XMLDeclaracaoIMP xml(XMLSC_DeclaracoesImpToGIDWin), @XMLDeclaracaoIMPCAU xml(XMLSC_DeclaracoesIMPCAUToGIDWin)
-- inicia processo de conversão do XML da declaração DUI2 no formato XML da declaração IMP-CAU
	BEGIN TRY	
		SET @NumErro = 0
-- inicia variáveis
		SET @XMLDeclaracaoIMP = @FicheiroXML
		SET @FicheiroXML = NULL
-- constroi XML para declaração IMP-CAU a partir do ficheiro XML no formato standard IMP
		SET @XMLDeclaracaoIMPCAU = 			
			(SELECT t.c.value('@Acao[1]', 'varchar(1)') AS "@acao", 
				(CONVERT(varchar(10), t.c.value('Data[1]', 'datetime'), 127) + 'Z') AS "data", 
				CAST(0 AS bit) AS "despachoCentralizado", 
				(CASE 
					WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1', 'I2') THEN UPPER(ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1')) 
					ELSE 'H1' 
				END) AS "anexoB", 
				NULLIF(t.c.value('CodNatureza[1]', 'varchar(3)'), '') AS "natureza", 
				NULLIF(t.c.value('NumDocTransporte[1]', 'varchar(18)'), '') AS "documentoTransporte", 
				(SELECT 
					(SELECT 						
						NULLIF(t.c.value('NomeExpedidor[1]', 'varchar(70)'), '') AS "nome", 
						ISNULL(NULLIF(t.c.value('MoradaExpedidor[1]', 'varchar(70)'), ''), '*****N/A*****') AS "morada", 
						ISNULL(NULLIF(t.c.value('LocalidadeExpedidor[1]', 'varchar(35)'), ''), '*****N/A*****') AS "localidade", 
						ISNULL(NULLIF(t.c.value('CodPostalExpedidor[1]', 'varchar(12)'), ''), '****N/A****') AS "codigoPostal", 
						ISNULL(NULLIF(t.c.value('LocPostalExpedidor[1]', 'varchar(35)'), ''), '*****N/A*****') AS "localidadePostal", 
						ISNULL(NULLIF(t.c.value('CodPaisExpedidor[1]', 'varchar(2)'), ''), 'PT') AS "pais"
					HAVING ISNULL(t.c.value('NomeExpedidor[1]', 'varchar(70)'), '') <> ''
					FOR XML PATH('exportador'), TYPE), 
					(CASE 
						WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') IN ('H6', 'I2') THEN NULL 
						ELSE NULLIF(t.c.value('CodPais15A[1]', 'varchar(2)'), '') 
					END) AS "paisExpedicao", 
					(SELECT 
						ISNULL(NULLIF(t.c.value('NIFDestinatario[1]', 'varchar(17)'), ''), '999999990') AS "nif", 
						ISNULL(t.c.value('TipoDestinatario[1]', 'int'), (CASE 
							WHEN LEFT(ISNULL(NULLIF(t.c.value('NIFDestinatario[1]', 'varchar(17)'), ''), '999999990'), 1) IN ('1', '2', '3', '4', '9') THEN 1 --S
							WHEN LEFT(ISNULL(NULLIF(t.c.value('NIFDestinatario[1]', 'varchar(17)'), ''), '999999990'), 1) IN ('5', '6', '7', '8') THEN 0 --PC
							ELSE 6 --NE 
						END)) AS "tipoNIF", 
						ISNULL(NULLIF(t.c.value('NomeDestinatario[1]', 'varchar(70)'), ''), '*****N/A*****') AS "nome", 
						ISNULL(NULLIF(t.c.value('MoradaDestinatario[1]', 'varchar(70)'), ''), '*****N/A*****') AS "morada", 
						ISNULL(NULLIF(t.c.value('LocalidadeDestinatario[1]', 'varchar(35)'), ''), '*****N/A*****') AS "localidade", 
						ISNULL(NULLIF(t.c.value('CodPostalDestinatario[1]', 'varchar(12)'), ''), '****N/A****') AS "codigoPostal", 
						ISNULL(NULLIF(t.c.value('LocPostalDestinatario[1]', 'varchar(35)'), ''), '*****N/A*****') AS "localidadePostal", 
						ISNULL(NULLIF(t.c.value('CodPaisDestinatario[1]', 'varchar(2)'), ''), 'PT') AS "pais",
						NULLIF(t.c.value('TelefoneDestinatario[1]', 'varchar(14)'), '') AS "telefone", 
						NULLIF(t.c.value('EmailDestinatario[1]', 'varchar(200)'), '') AS "email"
					FOR XML PATH('importador'), TYPE),
					ISNULL(NULLIF(t.c.value('CodPais17[1]', 'varchar(2)'), ''), 'PT') AS "paisDestino",
					(CASE 
						WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') IN ('H6', 'I1', 'I2') THEN NULL
						ELSE t.c.value('CodRegiaoDestinatario[1]', 'int') 
					END) AS "regiao", 
					(SELECT
						NULLIF(t.c.value('CodDeclarante[1]', 'varchar(6)'), '') AS "codigoDeclarante"
					FOR XML PATH('declarante'), TYPE)
				FOR XML PATH('operadores'), TYPE), 
				NULLIF(t.c.value('NumVossaReferencia[1]', 'varchar(50)'), '') AS "vossaReferencia", 
				NULLIF(t.c.value('CodEstancia[1]', 'varchar(8)'), '') AS "estancia", 
				tde.TDE_CODI AS "tipoDeclaracao", 
				(CASE 
					WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') IN ('H6', 'I1', 'I2') THEN NULL 
					ELSE ISNULL(NULLIF(t.c.value('CodNaturezaTransacao[1]', 'varchar(2)'), ''), '11') 
				END) AS "naturezaTransacao", 
				NULLIF(t.c.value('CodCondEntrega[1]', 'varchar(3)'), '') AS "condicaoEntrega", 
				(SELECT
					NULLIF(t.c.value('DescricaoCondEntrega[1]', 'varchar(30)'), '') AS "localidadeCE", 
					ISNULL((CASE 
						WHEN (cen.CEN_LOCT = 1) AND (cen.CEN_LOCD = 0) THEN NULLIF(t.c.value('CodPaisExpedidor[1]', 'varchar(2)'), '')
						WHEN (cen.CEN_LOCT = 1) AND (cen.CEN_LOCD = 1) THEN NULLIF(t.c.value('CodPaisDestinatario[1]', 'varchar(2)'), '') 
						ELSE NULL
					END), 'PT') AS "paisCE"
				HAVING ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') NOT IN ('H2', 'H6', 'I1', 'I2') AND ISNULL(t.c.value('DescricaoCondEntrega[1]', 'varchar(30)'), '') <> '' 
				FOR XML PATH('localizacao'), TYPE), 
				(SELECT 
					(SELECT
						NULLIF(t.c.value('CodPais22[1]', 'varchar(2)'), '') AS "pais", 							
						CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/PrecoAdicao)', 'float'), 0) AS decimal(18, 3)) AS "valorTotal"
					FOR XML PATH('fatura'), TYPE), 
					(SELECT
						ISNULL(NULLIF(t.c.value('CodPaisFrete[1]', 'varchar(2)'), ''), 'EU') AS "pais", 							
						CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/Frete)', 'float'), 0) AS decimal(18, 3)) AS "valorTotal"
					FOR XML PATH('frete'), TYPE), 
					(SELECT
						ISNULL(NULLIF(t.c.value('CodPaisSeguro[1]', 'varchar(2)'), ''), 'EU') AS "pais", 							
						CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/Seguro)', 'float'), 0) AS decimal(18, 3)) AS "valorTotal"
					FOR XML PATH('seguro'), TYPE), 
					(SELECT
						CAST(ISNULL((CASE WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') IN ('H2', 'H3', 'I2') THEN NULL ELSE t.c.value('sum(Adicoes/Adicao/MassaLiquida)', 'float') END), 0) AS decimal(18, 6)) AS "massaLiquida", 							
						CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/MassaBruta)', 'float'), 0) AS decimal(18, 6)) AS "massaBruta"
					FOR XML PATH('pesos'), TYPE)
				FOR XML PATH('totais'), TYPE), 
				(SELECT
					(SELECT
						NULLIF(t.c.value('CodMeioTransporte21[1]', 'varchar(2)'), '') AS "meioTransporte", 
						(CASE 
							WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') = 'H2' THEN NULL 
							ELSE NULLIF(t.c.value('CodPais21[1]', 'varchar(2)'), '') 
						END) AS "pais"
					HAVING ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') NOT IN ('H6', 'I1', 'I2') AND ISNULL(t.c.value('CodMeioTransporte21[1]', 'varchar(2)'), '') <> '' 
					FOR XML PATH('fronteira'), TYPE), 
					ISNULL(NULLIF(t.c.value('CodMeioTransporte18[1]', 'varchar(2)'), ''), (CASE 
						WHEN t.c.value('CodEstancia[1]', 'varchar(8)') IN ('PT000040', 'PT000340', 'PT000665', 'PT000670') THEN '10'
						WHEN t.c.value('CodEstancia[1]', 'varchar(8)') IN ('PT000015', 'PT000020') THEN '40'						
						WHEN t.c.value('CodEstancia[1]', 'varchar(8)') = 'PT000236' THEN '50'
						ELSE '30'						
					END)) AS "meioTransporteChegada", 
					(CASE 
						WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') IN ('H2', 'H6', 'I1', 'I2') THEN NULL 
						ELSE NULLIF(t.c.value('IdMeioTransporte[1]', 'varchar(30)'), '') 
					END) AS "identificacao", 
					t.c.value('TemContentores[1]', 'int') AS "contentorizada"
				FOR XML PATH('transporte'), TYPE), 
				(SELECT
					(CASE ISNULL(t.c.value('CodLocalAutorizado[1]', 'varchar(17)'), '') 
						WHEN '' THEN 'A' 
						ELSE 'B' 
					END) AS "tipoLocalizacao", 					
					(CASE ISNULL(t.c.value('CodLocalAutorizado[1]', 'varchar(17)'), '') 
						WHEN '' THEN 'V' 
						ELSE 'Y' 
					END) AS "qualificador", 
					NULLIF(t.c.value('CodLocalAutorizado[1]', 'varchar(17)'), '') AS "armazemDTP", 
					NULLIF(t.c.value('CodEstanciaAduaneira[1]', 'varchar(8)'), '') AS "estancia"
				HAVING ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') <> 'H6'
				FOR XML PATH('localizacaoMercadorias'), TYPE), 
				(CASE 
					WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') IN ('H5', 'H6', 'I1', 'I2') THEN NULL
					ELSE NULLIF(t.c.value('CodArmazem[1]', 'varchar(17)'), '')
				END) AS "armazem",
				(SELECT 
					NULLIF(t.c.value('Delegacao[1]', 'varchar(6)'), '') AS "locID", 
					NULLIF(t.c.value('Gateway[1]', 'varchar(6)'), '') AS "gateway", 
					t.c.value('NivelServico[1]', 'int') AS "serviceLevel", 			
					t.c.value('ValorFreteCompanhia[1]', 'decimal(18, 2)') AS "freteOriginal", 
					NULLIF(t.c.value('MoedaFreteCompanhia[1]', 'varchar(3)'), '') AS "moedafreteOriginal", 
					t.c.value('DespesasDHL[1]', 'decimal(18, 2)') AS "despesas", 
					NULLIF(t.c.value('PPouFC[1]', 'varchar(2)'), '') AS "condEntrega", 
					NULLIF(t.c.value('NomeFileUPS[1]', 'varchar(100)'), '') AS "nomeFicheiro"
				HAVING ISNULL(t.c.value('Delegacao[1]', 'varchar(6)'), '') <> '' OR ISNULL(t.c.value('Gateway[1]', 'varchar(6)'), '') <> '' 
					OR ISNULL(t.c.value('NivelServico[1]', 'int'), -1) <> -1 OR ISNULL(t.c.value('ValorFreteCompanhia[1]', 'decimal(18, 2)'), -1) <> -1 
					OR ISNULL(t.c.value('MoedaFreteCompanhia[1]', 'varchar(3)'), '') <> '' OR ISNULL(t.c.value('DespesasDHL[1]', 'decimal(18, 2)'), -1) <> -1 
					OR ISNULL(t.c.value('PPouFC[1]', 'varchar(2)'), '') <> '' OR ISNULL(t.c.value('NomeFileUPS[1]', 'varchar(100)'), '') <> ''
				FOR XML PATH('dadosEspecificos'), TYPE), 
				(SELECT 
					t.c.value('(DepositoTemporario/NumeroPDDT)[1]', 'int') AS "numeroPDDT", 					
					t.c.value('(DepositoTemporario/NumeroPDDTDev)[1]', 'int') AS "numeroPDDTDEV", 
					t.c.value('(DepositoTemporario/NumeroTD)[1]', 'int') AS "numeroTD", 
					t.c.value('(DepositoTemporario/NumeroACTM)[1]', 'int') AS "numeroACTM", 
					t.c.value('(DepositoTemporario/NumeroSequencia)[1]', 'int') AS "numeroSequencia"
				HAVING ISNULL(t.c.value('(DepositoTemporario/NumeroPDDT)[1]', 'int'), -1) <> -1 OR ISNULL(t.c.value('(DepositoTemporario/NumeroPDDTDev)[1]', 'int'), -1) <> -1 
					OR ISNULL(t.c.value('(DepositoTemporario/NumeroTD)[1]', 'int'), -1) <> -1 OR ISNULL(t.c.value('(DepositoTemporario/NumeroACTM)[1]', 'int'), -1) <> -1 
					OR ISNULL(t.c.value('(DepositoTemporario/NumeroSequencia)[1]', 'int'), -1) <> -1
				FOR XML PATH('depositoTemporario'), TYPE), 
				(SELECT 		
					NULLIF(t.c.value('MiniCPA[1]', 'varchar(20)'), '') AS "miniCPA", 
					(CONVERT(varchar(10), t.c.value('DataPrevVoo[1]', 'datetime'), 127) + 'Z') AS "dataVoo", 
					NULLIF(t.c.value('Aeroporto[1]', 'varchar(80)'), '') AS "aeroportoOrigem", 
					NULLIF(t.c.value('NumVoo[1]', 'varchar(20)'), '') AS "numeroVoo", 
					NULLIF(t.c.value('PosicaoAviao[1]', 'varchar(13)'), '') AS "posicaoAviao", 
					NULLIF(t.c.value('Tracking[1]', 'varchar(35)'), '') AS "tracking", 
					NULLIF(t.c.value('TipoCarga[1]', 'varchar(5)'), '') AS "tipoCarga"	
				HAVING ISNULL(t.c.value('MiniCPA[1]', 'varchar(20)'), '') <> '' OR ISNULL(CONVERT(varchar(10), t.c.value('DataPrevVoo[1]', 'datetime'), 127), '') <> ''
					OR ISNULL(t.c.value('Aeroporto[1]', 'varchar(80)'), '') <> '' OR ISNULL(t.c.value('NumVoo[1]', 'varchar(20)'), '') <> '' 
					OR ISNULL(t.c.value('PosicaoAviao[1]', 'varchar(13)'), '') <> '' OR ISNULL(t.c.value('Tracking[1]', 'varchar(35)'), '') <> ''
					OR ISNULL(t.c.value('TipoCarga[1]', 'varchar(5)'), '') <> ''
				FOR XML PATH('dadosAWB'), TYPE), 
				(SELECT 
					NULLIF(t.c.value('NumContaExpedidor[1]', 'varchar(10)'), '') AS "numeroContaExpedidor", 
					NULLIF(t.c.value('NumContaDestinatario[1]', 'varchar(10)'), '') AS "numeroContaDestinatario", 
					NULLIF(t.c.value('NomeDestinatario2[1]', 'varchar(70)'), '') AS "nomeOriginalDestinatario", 
					NULLIF(t.c.value('MoradaDestinatario2[1]', 'varchar(70)'), '') AS "moradaOriginalDestinatario", 
					NULLIF(t.c.value('LocalidadeDestinatario2[1]', 'varchar(35)'), '') AS "localidadeOriginalDestinatario", 
					NULLIF(t.c.value('CodPostalDestinatario2[1]', 'varchar(12)'), '') AS "codigoPostalOriginalDestinatario", 
					NULLIF(t.c.value('LocPostalDestinatario2[1]', 'varchar(35)'), '') AS "localidadePostalOriginalDestinatario", 
					NULLIF(t.c.value('Referencia1[1]', 'varchar(50)'), '') AS "referenciaExterna1", 
					NULLIF(t.c.value('Referencia2[1]', 'varchar(50)'), '') AS "referenciaExterna2", 
					NULLIF(t.c.value('ShipID[1]', 'varchar(11)'), '') AS "shipID"
				HAVING ISNULL(t.c.value('NumContaExpedidor[1]', 'varchar(10)'), '') <> '' OR ISNULL(t.c.value('NumContaDestinatario[1]', 'varchar(10)'), '') <> '' 
					OR ISNULL(t.c.value('NomeDestinatario2[1]', 'varchar(70)'), '') <> '' OR ISNULL(t.c.value('MoradaDestinatario2[1]', 'varchar(70)'), '') <> '' 
					OR ISNULL(t.c.value('LocalidadeDestinatario2[1]', 'varchar(35)'), '') <> '' OR ISNULL(t.c.value('CodPostalDestinatario2[1]', 'varchar(12)'), '') <> '' 
					OR ISNULL(t.c.value('LocPostalDestinatario2[1]', 'varchar(35)'), '') <> '' OR ISNULL(t.c.value('Referencia1[1]', 'varchar(50)'), '') <> '' 
					OR ISNULL(t.c.value('Referencia2[1]', 'varchar(50)'), '') <> '' OR ISNULL(t.c.value('ShipID[1]', 'varchar(11)'), '') <> '' 
				FOR XML PATH('dadosEntidades'), TYPE), 
				(SELECT
					NULLIF(t.c.value('DType[1]', 'varchar(2)'), '') AS "dutyType", 
					t.c.value('Payment[1]', 'int') AS "payment", 
					(CONVERT(varchar(10), t.c.value('DataDocCPA[1]', 'datetime'), 127) + 'Z') AS "dataDocumentoTransporte", 
					NULLIF(t.c.value('NumRequerimento[1]', 'varchar(30)'), '') AS "numeroRequerimento", 
					NULLIF(t.c.value('NumDURetorno[1]', 'varchar(30)'), '') AS "numeroDURetorno", 
					NULLIF(t.c.value('T1Retorno[1]', 'varchar(30)'), '') AS "numeroT1Retorno"
				HAVING ISNULL(t.c.value('DType[1]', 'varchar(2)'), '') <> '' OR ISNULL(t.c.value('Payment[1]', 'int'), -1) <> -1 
					OR ISNULL(CONVERT(varchar(10), t.c.value('DataDocCPA[1]', 'datetime'), 127), '') <> '' OR ISNULL(t.c.value('NumRequerimento[1]', 'varchar(30)'), '') <> '' 
					OR ISNULL(t.c.value('NumDURetorno[1]', 'varchar(30)'), '') <> '' OR ISNULL(t.c.value('T1Retorno[1]', 'varchar(30)'), '') <> '' 
				FOR XML PATH('outrosDados'), TYPE), 
				NULLIF(t.c.value('Observacoes[1]', 'varchar(MAX)'), '') AS "anotacoes", 										
				(SELECT
					t.c.value('CodFollowUp[1]', 'int') AS "codigoFollowUp", 
					NULLIF(t.c.value('CodUtilizadorNomeado[1]', 'varchar(30)'), '') AS "utilizadorNomeado"
				HAVING ISNULL(t.c.value('CodFollowUp[1]', 'int'), -1) <> -1
				FOR XML PATH('followUp'), TYPE), 
				(SELECT
					NULLIF(e.c.value('CodigoCampoExtra[1]', 'varchar(100)'), '') AS "codigoCampoExtra", 
					NULLIF(e.c.value('ValorCampoExtra[1]', 'varchar(2500)'), '') AS "valorCampoExtra"
				FROM t.c.nodes('CamposExtra/CampoExtra') AS e(c)
				FOR XML PATH('campoExtra'), ROOT('camposExtra'), TYPE), 
				(SELECT 
					doc.DOC_DTRA AS "tipoDocumento", 
					doc.DOC_CODI AS "codigoDocumento",
					NULLIF(d.c.value('NumeroDocumento[1]', 'varchar(70)'), '') AS "numeroDocumento"					
				FROM t.c.nodes('Adicoes/Adicao[1]/Documentos/Documento') AS d(c)
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON d.c.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI																	
				WHERE LEFT(ISNULL(d.c.value('CodDocumento[1]', 'varchar(5)'), ''), 1) = 'N'
				FOR XML PATH('documento'), ROOT('documentosECertificados'), TYPE), 				
				(SELECT	a.c.value('@Acao[1]', 'varchar(1)') AS "@acao", 				
					a.c.value('NumAdicao[1]', 'int') AS "numeroAdicao", 
					ISNULL(NULLIF(art.APA_CPAU, ''), '9999999999') AS "codigoPautal", 							
					ISNULL(NULLIF(a.c.value('Designacao[1]', 'varchar(150)'), ''), 'NÃO CLASSIFICADO') AS "designacao", 	
					NULLIF(a.c.value('RegimeB[1]', 'varchar(6)'), '') AS "regimeAdicional", 						
					NULLIF(a.c.value('CodPaisOrigem[1]', 'varchar(2)'), '') AS "paisOrigem",		
					NULLIF(a.c.value('CodPreferencia[1]', 'varchar(3)'), '') AS "preferencia", 
					a.c.value('MetodoAvaliacao[1]', 'int') AS "metodoAvaliacao", 
					a.c.value('MassaLiquida[1]', 'decimal(18, 6)') AS "massaLiquida", 					
					a.c.value('MassaBruta[1]', 'decimal(18, 6)') AS "massaBruta",																					
					a.c.value('QtdUnidades[1]', 'decimal(18, 6)') AS "unidades", 
					a.c.value('PrecoAdicao[1]', 'decimal(18, 3)') AS "montanteAd", 
					a.c.value('Frete[1]', 'decimal(18, 3)') AS "valorFrete", 
					a.c.value('Seguro[1]', 'decimal(18, 3)') AS "valorSeguro", 
					(SELECT
						NULLIF(p.c.value('CodDocumento[1]', 'varchar(5)'), '') AS "codigoDocumento", 
						NULLIF(p.c.value('NumeroDeclSumaria[1]', 'varchar(70)'), '') AS "numeroDocumento"
					FROM a.c.nodes('DeclaracoesSumaria/DeclaracaoSumaria') AS p(c)
					FOR XML PATH('documentoPrecedente'), ROOT('documentosPrecedentes'), TYPE), 
					(SELECT 
						(CASE 
							WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') = 'H6' THEN NULL 
							ELSE NULLIF(m.c.value('CodUnidMedida[1]', 'varchar(3)'), '') 
						END) AS "unidadeMedida", 
						m.c.value('QtdVolumes[1]', 'int') AS "volumes", 
						(CASE 
							WHEN ISNULL(NULLIF(tde.TDE_3CAS, ''), 'H1') = 'H6' THEN NULL 
							ELSE NULLIF(m.c.value('Marca[1]', 'varchar(512)'), '') 
						END) AS "marcas", 
						NULLIF(m.c.value('Numero[1]', 'varchar(20)'), '') AS "numeroObjeto", 
						NULLIF(m.c.value('LOptica[1]', 'varchar(30)'), '') AS "codigoBarras", 
						m.c.value('P[1]', 'bit') AS "parte"		
					FROM a.c.nodes('MarcasEVolumes/MarcaEVolume') AS m(c)	
					WHERE (a.c.value('NumAdicao[1]', 'int') = 1) OR ((a.c.value('NumAdicao[1]', 'int') > 1) AND (m.c.value('P[1]', 'bit') = 0) AND (m.c.value('R[1]', 'bit') = 0))									
					FOR XML PATH('marcaEVolume'), ROOT('marcasEVolumes'), TYPE)					
				FROM t.c.nodes('Adicoes/Adicao') AS a(c)
					LEFT OUTER JOIN TAB_APAU AS art WITH(NOLOCK) ON a.c.value('CodArtigoPautal[1]', 'varchar(22)') = art.APA_CODI
				FOR XML PATH('adicao'), ROOT('adicoes'), TYPE)
			FROM @XMLDeclaracaoIMP.nodes('DeclaracoesImpToGIDWin/Declaracao') AS t(c)	
				INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON t.c.value('CodTipoDeclaracao[1]', 'varchar(4)') = tde.TDE_CODI
				INNER JOIN TAB_CENT AS cen WITH(NOLOCK) ON t.c.value('CodCondEntrega[1]', 'varchar(3)') = cen.CEN_CODI
			FOR XML PATH('declaracao'), ROOT('declaracoesIMPToGIDWin'), TYPE)					
-- devolve XML da declaração IMP-CAU		
		SET @FicheiroXML = @XMLDeclaracaoIMPCAU 
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ConverteXMLStandardParaIMPCAU] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ConverteXMLStandardParaIMPCAU] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_DuplicaDeclaracao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_DuplicaDeclaracao] @Numero int, @Ano int, @NovoNumero int, @Utilizador varchar(30), @NumeroVolsResto int AS
BEGIN 
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @DataAtual datetime, @RefCasa7 varchar(50), @TipoDeclaracao int, @CodExpedidor varchar(18), @CodDestinatario varchar(18), @podeIns int, @NumRefLocal varchar(22), 
		@NIFDeclarante varchar(18), @NovoAno int, @Servico bit	
-- obtem a configurações dos Parametros de Despacho 
	SELECT @podeIns = PDE_NPRO, @RefCasa7 = PDE_RFC7
	FROM TAB_PDES WITH(NOLOCK)
-- obtem dados do processo de origem
	SELECT @TipoDeclaracao = du.DUC_TIPO, @CodExpedidor = du.DUC_EXP2, @CodDestinatario = du.DUC_DST8, @NIFDeclarante = isnull(de.DEC_NIF, ''), @Servico = DUC_SERV
	FROM PRO_DUCG AS du WITH(NOLOCK) 
		INNER JOIN TAB_DECL AS de WITH(NOLOCK) ON du.DEC_CO14 = de.DEC_CODI		
	WHERE du.DUC_PNUM = @Numero AND du.DUC_EANO = @Ano
-- obtem data atual
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem Ano para novo processo em função da data atual
	IF (@Ano < YEAR(@DataAtual)) and (EXISTS(SELECT EMP_CODI FROM GIDWIN.dbo.FAP_EANO WITH(NOLOCK) WHERE EMP_CODI = DB_NAME() and EAN_ANO = YEAR(@DataAtual)))		
		SET @NovoAno = YEAR(@DataAtual)
	ELSE
		SET @NovoAno = @Ano	
-- constroi	Referência Casa 7
	SET @RefCasa7 = REPLACE(@RefCasa7, 'ANO', CAST(@NovoAno as varchar(4)))
	SET @RefCasa7 = REPLACE(@RefCasa7, 'PNUM', CAST(@NovoNumero as varchar(10)))
	IF @TipoDeclaracao = 1 
		SET @RefCasa7 = REPLACE(@RefCasa7, 'CC', @CodDestinatario)
	ELSE 
		SET @RefCasa7 = REPLACE(@RefCasa7, 'CC', @CodExpedidor)	 
-- constroi Referência Local		
	SET @NumRefLocal = STR(@NovoAno, 4) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 7 - LEN(@NovoNumero)) + LTRIM(STR(@NovoNumero, 7))
-- se numeração automatica, incrementa Prox. Nº. Processo nos Parametros de Despacho 
	IF (@podeIns <> 0) AND (@Servico = 0)
		UPDATE TAB_PDES SET PDE_NPRO = @NovoNumero + 1		
-- copia Dados Gerais (Cabeçalho)
	INSERT INTO PRO_DUCG(DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, TDE_CODI, DUC_TIPO, ALF_CODI, DUC_ADI5, DUC_TVL6, PAI_PA10, PAI_PA11, DUC_PA13, DUC_EXP2, DUC_DST8, 
		DEC_CO14, PAI_PA15, PAI_P15A, PAI_P15B, PAI_PA16, PAI_PA17, PAI_P17A, PAI_P17B, MTR_PT18, DUC_MT18, PAI_PA18, DUC_OP18, DUC_CT18, RRE_CO18, MTR_FT21, DUC_MT21, 
		PAI_PA21, DUC_CT19, CEN_CO20, DUC_FR20, DUC_DE20, NTR_CO24, MTR_PF25, MTR_PT26, LME_CO27, DUC_LC27, EAD_CO29, LME_CO30, DUC_LC30, PAI_PR22, DUC_MT22, DUC_TX23, 
		DUC_FRET, PAI_FRET, DUC_TXFR, DUC_SEGU, PAI_SEGU, DUC_TXSE, DUC_MLQT, DUC_MBRT, DUC_VTRN, PAI_VTRN, DUC_TXVT, DUC_VEUR, DUC_VFOB, DUC_DIRT, DUC_TFDA, DUC_ENOM, 
		DUC_EMOR, DUC_ELOC, DUC_ECPO, DUC_ELPO, DUC_ENIF, PAI_ELIV, DUC_DNOM, DUC_DMOR, DUC_DLOC, DUC_DCPO, DUC_DLPO, DUC_DNIF, PAI_DLIV, DUC_TXT1, DUC_TXT2, DUC_TXT3, 
		DUC_HIST, DUC_VLRC, DUC_VLRE, DUC_VATT, DUC_UCRI, DUC_DTCR, DUC_UALT, DUC_DTAL, NDE_NOME, TDE_NOME, ALF_NOME, PAI_NO10, PAI_NO11, PAI_NO15, PAI_NO16, PAI_NO17, 
		PAI_MO22, PAI_MOFT, PAI_MOSG, PAI_MOVT, DEC_NOME, DEC_CENI, EAD_NOME, MTR_NO18, MTR_NO21, DUC_NFOR, DUC_MASC, DES_CODI, DES_DESC, DUC_DOBS, DUC_MOTI, DUC_DDES, 
		DUC_NREQ, DUC_NDUR, DUC_T1RE, DUC_DSRE, DUC_NDPR, DUC_DEEN, DUC_VCHE, DEC_CEDE, DUC_CNOM, DUC_CMOR, DUC_CLOC, DUC_CCPO, DUC_CLPO, DUC_CNIF, PAI_CLIV, DUC_FUNC, 
		DUC_DCED, DUC_DTVO, DUC_REF7, DUC_CPRO, DUC_BUPS, DUC_BFFC, DUC_PARM, DUC_VLRP, DUC_TPDS, DUC_TPDC, DUC_TM21, TDE_1CAS, TDE_2CAS, DUC_GTWY, DUC_DELG, DUC_TMSF, 
		CLI_CODI, CLI_NOME, DUC_CGLB, DUC_CAUC, DUC_CANO, DUC_CTIP, DUC_TLOC, ALF_CODI1, ALF_NOME1, DUC_LAMO, DUC_LALO, DUC_LACP, ARM_CODI, ARM_NOME, TAR_CODI, TAR_DESC, 
		DUC_NRLO, DUC_DUNO, DUC_CENT, NTR_NOME, DUC_VBAT, DUC_TREM, DUC_DTYP, DUC_NVRF, DUC_BIVA, DUC_FUPS, DUC_SHIP, DUC_DDDT, DUC_DTEL, DUC_DEMA, TDO_DOCU, DUC_TSHI, 
		DEC_NIF, DUC_SERV)
	SELECT @NovoNumero, @NovoAno, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), (CASE na.NDE_PART WHEN 1 THEN na.NDE_CODI1 ELSE du.NDE_CODI END), du.DUC_CPRT, du.TDE_CODI, du.DUC_TIPO, du.ALF_CODI, du.DUC_ADI5, (CASE na.NDE_PART WHEN 1 THEN @NumeroVolsResto ELSE du.DUC_TVL6 END), du.PAI_PA10, du.PAI_PA11, du.DUC_PA13, du.DUC_EXP2, du.DUC_DST8, 
		du.DEC_CO14, du.PAI_PA15, du.PAI_P15A, du.PAI_P15B, du.PAI_PA16, du.PAI_PA17, du.PAI_P17A, du.PAI_P17B, du.MTR_PT18, du.DUC_MT18, du.PAI_PA18, du.DUC_OP18, du.DUC_CT18, du.RRE_CO18, du.MTR_FT21, du.DUC_MT21, 
		du.PAI_PA21, du.DUC_CT19, du.CEN_CO20, du.DUC_FR20, du.DUC_DE20, du.NTR_CO24, du.MTR_PF25, du.MTR_PT26, du.LME_CO27, du.DUC_LC27, du.EAD_CO29, du.LME_CO30, du.DUC_LC30, du.PAI_PR22, du.DUC_MT22, du.DUC_TX23, 
		du.DUC_FRET, du.PAI_FRET, du.DUC_TXFR, du.DUC_SEGU, du.PAI_SEGU, du.DUC_TXSE, du.DUC_MLQT, du.DUC_MBRT, du.DUC_VTRN, du.PAI_VTRN, du.DUC_TXVT, du.DUC_VEUR, du.DUC_VFOB, du.DUC_DIRT, du.DUC_TFDA, du.DUC_ENOM, 
		du.DUC_EMOR, du.DUC_ELOC, du.DUC_ECPO, du.DUC_ELPO, du.DUC_ENIF, du.PAI_ELIV, du.DUC_DNOM, du.DUC_DMOR, du.DUC_DLOC, du.DUC_DCPO, du.DUC_DLPO, du.DUC_DNIF, du.PAI_DLIV, du.DUC_TXT1, du.DUC_TXT2, du.DUC_TXT3, 
		du.DUC_HIST, du.DUC_VLRC, du.DUC_VLRE, du.DUC_VATT, @Utilizador, @DataAtual, @Utilizador, @DataAtual, (CASE na.NDE_PART WHEN 1 THEN nr.NDE_NOME ELSE du.NDE_NOME END), du.TDE_NOME, du.ALF_NOME, du.PAI_NO10, du.PAI_NO11, du.PAI_NO15, du.PAI_NO16, du.PAI_NO17, 
		du.PAI_MO22, du.PAI_MOFT, du.PAI_MOSG, du.PAI_MOVT, du.DEC_NOME, du.DEC_CENI, du.EAD_NOME, du.MTR_NO18, du.MTR_NO21, du.DUC_NFOR, du.DUC_MASC, du.DES_CODI, du.DES_DESC, du.DUC_DOBS, du.DUC_MOTI, du.DUC_DDES, 
		du.DUC_NREQ, du.DUC_NDUR, du.DUC_T1RE, du.DUC_DSRE, du.DUC_NDPR, du.DUC_DEEN, du.DUC_VCHE, du.DEC_CEDE, du.DUC_CNOM, du.DUC_CMOR, du.DUC_CLOC, du.DUC_CCPO, du.DUC_CLPO, du.DUC_CNIF, du.PAI_CLIV, du.DUC_FUNC, 
		du.DUC_DCED, (CASE WHEN du.DUC_DTVO IS NULL THEN NULL ELSE CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime) END), @RefCasa7, 0, 0, 0, du.DUC_PARM, du.DUC_VLRP, du.DUC_TPDS, du.DUC_TPDC, du.DUC_TM21, du.TDE_1CAS, du.TDE_2CAS, du.DUC_GTWY, du.DUC_DELG, du.DUC_TMSF, 
		du.CLI_CODI, du.CLI_NOME, du.DUC_CGLB, du.DUC_CAUC, du.DUC_CANO, du.DUC_CTIP, du.DUC_TLOC, du.ALF_CODI1, du.ALF_NOME1, du.DUC_LAMO, du.DUC_LALO, du.DUC_LACP, du.ARM_CODI, du.ARM_NOME, du.TAR_CODI, du.TAR_DESC, 
		@NumRefLocal, du.DUC_DUNO, du.DUC_CENT, du.NTR_NOME, du.DUC_VBAT, du.DUC_TREM, du.DUC_DTYP, du.DUC_NVRF, du.DUC_BIVA, du.DUC_FUPS, du.DUC_SHIP, du.DUC_DDDT, du.DUC_DTEL, du.DUC_DEMA, du.TDO_DOCU, (CASE WHEN (du.DUC_TSHI = 1) AND (na.NDE_PART = 1) THEN 2 ELSE 0 END), 
		DEC_NIF, DUC_SERV
	FROM PRO_DUCG AS du WITH(NOLOCK) 
		INNER JOIN TAB_NDES AS na WITH(NOLOCK) ON du.NDE_CODI = na.NDE_CODI
		LEFT OUTER JOIN TAB_NDES AS nr WITH(NOLOCK) ON na.NDE_CODI1 = nr.NDE_CODI
	WHERE du.DUC_PNUM = @Numero AND du.DUC_EANO = @Ano
-- copia Liquidacao Recapitulativa
	INSERT INTO PRO_DULR(DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, DUL_MONT, DUL_RPRO)
	SELECT @NovoNumero, @NovoAno, RRE_CODI, RRE_NOME, DUL_MONT, DUL_RPRO
	FROM PRO_DULR WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
-- copia Pedidos
	INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC)
	SELECT @NovoAno, @NovoNumero, DPD_CODI, TXM_CODI, DPD_DESC
	FROM PRO_DUPD WITH(NOLOCK)
	WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero
-- copia Adições 
	INSERT INTO PRO_DUAD(DUC_PNUM, DUC_EANO, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, 
		DUA_ML38, DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_LCMB, DUA_CAUC, DUA_CANO, 
		DUA_CTIP, DUA_CENT, ARM_CO49, AGE_CO50, ALF_CO53, DUA_VEST, DUA_AJUS, DUA_CORE, DUA_CONR, DUA_DANO, DUA_DNUM, DUA_DNRS, DUA_DDAT, DUA_LINH, DUA_VATO, DUA_NEPO, 
		DUA_BTRI, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, FLE_CODI, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, PAI_NOME, PRE_NOME, USU_NOME, ARM_NOME, 
		AGE_NOME, ALF_NOME, RRE_NOME, FLE_NOME, UME_NOTR, DUA_TC31, DUA_TC44, DUA_QUAL, DOC_CODI, EAD_CODI, MTR_CODI, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, 
		DUA_ADRE, DUA_2TAR, DUA_3TAR, DUA_MAVA, RRE_NOME1, DUA_BMAN, DUA_CAUD, DUA_CAND, DUA_CTID, DUA_CEND, DUA_IMPI, DUA_CAUI, DUA_CANI, DUA_CTII, DUA_CENI, DUA_1TAR)
	SELECT @NovoNumero, @NovoAno, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, 
		DUA_ML38, DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_LCMB, DUA_CAUC, DUA_CANO, 
		DUA_CTIP, DUA_CENT, ARM_CO49, AGE_CO50, ALF_CO53, DUA_VEST, DUA_AJUS, DUA_CORE, DUA_CONR, DUA_DANO, DUA_DNUM, DUA_DNRS, DUA_DDAT, DUA_LINH, DUA_VATO, DUA_NEPO, 
		DUA_BTRI, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, FLE_CODI, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, PAI_NOME, PRE_NOME, USU_NOME, ARM_NOME, 
		AGE_NOME, ALF_NOME, RRE_NOME, FLE_NOME, UME_NOTR, DUA_TC31, DUA_TC44, DUA_QUAL, DOC_CODI, EAD_CODI, MTR_CODI, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, 
		DUA_ADRE, DUA_2TAR, DUA_3TAR, DUA_MAVA, RRE_NOME1, DUA_BMAN, DUA_CAUD, DUA_CAND, DUA_CTID, DUA_CEND, DUA_IMPI, DUA_CAUI, DUA_CANI, DUA_CTII, DUA_CENI, DUA_1TAR
	FROM PRO_DUAD WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
-- copia Documentos
	INSERT INTO PRO_DDOC(DUC_PNUM, DUC_EANO, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, DDO_DFIM, CEN_CODI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_NINV, DDO_AUTO, 
		DDO_TIPO, DDO_EEMI, UME_CODI, DDO_QTDE)
	SELECT @NovoNumero, @NovoAno, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, (CASE DOC_CODI WHEN 'N934' THEN CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime) ELSE DDO_DINI END), DDO_DFIM, CEN_CODI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_NINV, DDO_AUTO, 
		DDO_TIPO, DDO_EEMI, UME_CODI, DDO_QTDE
	FROM PRO_DDOC WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
-- copia Imposicoes
	INSERT INTO PRO_DUOI(DUC_PNUM, DUC_EANO, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_AGRO, RRE_LIVA, DUO_IMPO, DUO_AUTO, 
		DUO_BMAN, DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT, DET_IDST)
	SELECT @NovoNumero, @NovoAno, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_AGRO, RRE_LIVA, DUO_IMPO, DUO_AUTO, 
		DUO_BMAN, DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT, DET_IDST
	FROM PRO_DUOI WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
-- copia Contentores
	INSERT INTO PRO_DCON(DUC_PNUM, DUC_EANO, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO)
	SELECT @NovoNumero, @NovoAno, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO
	FROM PRO_DCON WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
-- copia Marcas e Volumes
	INSERT INTO PRO_DU31(DUC_PNUM, DUC_EANO, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_CASR, D31_CASC, D31_TTVL, D31_AUTO, D31_LOPT)
	SELECT @NovoNumero, @NovoAno, mv.DUA_CODI, mv.D31_CODI, mv.D31_MARC, mv.D31_NUME, (CASE na.NDE_PART WHEN 1 THEN @NumeroVolsResto ELSE mv.D31_QNTD END), mv.UME_CODI, mv.UME_NOME, mv.D31_CASP, mv.D31_CASR, mv.D31_CASC, mv.D31_TTVL, mv.D31_AUTO, mv.D31_LOPT
	FROM PRO_DU31 AS mv WITH(NOLOCK) 
		INNER JOIN PRO_DUCG AS du WITH(NOLOCK) ON mv.DUC_EANO = du.DUC_EANO AND mv.DUC_PNUM = du.DUC_PNUM
		INNER JOIN TAB_NDES AS na WITH(NOLOCK) ON du.NDE_CODI = na.NDE_CODI
	WHERE mv.DUC_PNUM = @Numero AND mv.DUC_EANO = @Ano
-- copia Regime Anterior / Declaração Sumária para declarações normais
	INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, EAD_CODI, EAD_NOME, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DOC_COD2, DRA_APRG, DRA_APDT, DRA_QUAL, DRA_CODR, 
		DRA_AUTO, DRA_IDCR)
	SELECT @NovoAno, @NovoNumero, ds.DUA_CODI, ds.DRA_CODI, ds.EAD_CODI, ds.EAD_NOME, ds.DOC_CODI, ds.DRA_APAN, ds.DRA_APC1, ds.DRA_APC2, ds.DOC_COD2, ds.DRA_APRG, ds.DRA_APDT, ds.DRA_QUAL, ds.DRA_CODR, 
		ds.DRA_AUTO, ds.DRA_IDCR
	FROM PRO_DURA AS ds WITH(NOLOCK) 
		INNER JOIN PRO_DUCG AS du WITH(NOLOCK) ON ds.DUC_EANO = du.DUC_EANO AND ds.DUC_PNUM = du.DUC_PNUM
	WHERE ds.DUC_PNUM = @Numero AND ds.DUC_EANO = @Ano AND du.DUC_TSHI = 0	
-- copia Bases Tributacao / Veiculos
	INSERT INTO PRO_DUBT(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, UME_CODI, UME_NOME, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, 
		DBT_AUTO, DBT_VLIA, DBT_MARC, DBT_MODE, DBT_CODR, DBT_IDCR)
	SELECT @NovoAno, @NovoNumero, DUA_CODI, DBT_CODI, UME_CODI, UME_NOME, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, 
		DBT_AUTO, DBT_VLIA, DBT_MARC, DBT_MODE, DBT_CODR, DBT_IDCR
	FROM PRO_DUBT WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
-- copia Matriculas/Chassis dos Veiculos
	INSERT INTO PRO_DUVE(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS)
	SELECT @NovoAno, @NovoNumero, DUA_CODI, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS
	FROM PRO_DUVE WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano	
-- copia Elementos para Tributação
	INSERT INTO PRO_DUET(DUC_EANO, DUC_PNUM, DUA_CODI, DET_CODI, DET_TIPO, DET_CIEC, UME_CODI, UME_COD2, DET_QTDE, DET_AUTO, DIT_IDST, RRE_CODI, RRE_NOME, DET_IMPO, DET_TAXA, 
		DET_TXVL, DET_IDST)
	SELECT @NovoAno, @NovoNumero, DUA_CODI, DET_CODI, DET_TIPO, DET_CIEC, UME_CODI, UME_COD2, DET_QTDE, DET_AUTO, DIT_IDST, RRE_CODI, RRE_NOME, DET_IMPO, DET_TAXA, 
		DET_TXVL, DET_IDST
	FROM PRO_DUET WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
-- copia Mercadorias IECS
	INSERT INTO PRO_DUMI(DUC_EANO, DUC_PNUM, DUA_CODI, DMI_CODI, DMI_TIPO, DMI_AIEC, DMI_MARC, DMI_CAPA, DMI_NEMB, DMI_TEOR, TEM_CODI)
	SELECT @NovoAno, @NovoNumero, DUA_CODI, DMI_CODI, DMI_TIPO, DMI_AIEC, DMI_MARC, DMI_CAPA, DMI_NEMB, DMI_TEOR, TEM_CODI
	FROM PRO_DUMI WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano	
-- copia Tributação das Mercadorias IECS
	INSERT INTO PRO_DUIT(DUC_EANO, DUC_PNUM, DUA_CODI, DMI_CODI, DIT_CODI, UME_CODI, UME_COD2, UME_NOME, DIT_QTDE, RRE_CODI, RRE_NOME, DIT_IMPO, DIT_TAXA, DIT_TXVL, DIT_IDST)
	SELECT @NovoAno, @NovoNumero, DUA_CODI, DMI_CODI, DIT_CODI, UME_CODI, UME_COD2, UME_NOME, DIT_QTDE, RRE_CODI, RRE_NOME, DIT_IMPO, DIT_TAXA, DIT_TXVL, DIT_IDST
	FROM PRO_DUIT WITH(NOLOCK)
	WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano		
-- se n.º volumes p/ "Resto" especificado, na declaração de part-shipment atualiza o n.º volumes pendentes p/ rest-shipments
	IF @NumeroVolsResto > 0
	BEGIN
		UPDATE PRO_DUCG SET DUC_VPRS = DUC_VPRS - @NumeroVolsResto
		WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano AND DUC_TSHI = 1	
	END
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_DuplicaDeclaracao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_DuplicaDeclaracao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ExportaDeclaracoesParaIMPCAUDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_DeclImportacao_ExportaDeclaracoesParaIMPCAUDHL] @DataVooReferencia datetime, @BaseDadosIMPCAU varchar(6), @DirFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON
	SET ARITHABORT ON
	SET DATEFORMAT DMY	
-- declaração de variáveis
	DECLARE @ListaErros varchar(MAX), @CodNaturezaErro varchar(3), @CodNaturezaSucesso varchar(3), @IdUtilizador int, @AnoDeclaracaoDUI2 int, @NumDeclaracaoDUI2 int, 
		@DocTransporteDUI2 varchar(18), @IdDeclaracaoDUI2 bigint, @NumErro int, @DataAtual datetime, @XMLDeclaracaoIMPCAU xml(XMLSC_DeclaracoesIMPCAUToGIDWin), 
		@AnoDeclaracaoIMPCAU int, @NumDeclaracaoIMPCAU int, @IdDeclaracaoIMPCAU bigint
	DECLARE @IdFicheiro int, @PathFicheiro varchar(500), @FicheiroBinario varbinary(MAX), @FicheiroBase64 varchar(MAX)
	DECLARE @SQLAExecutar nvarchar(4000), @SQLVariaveis nvarchar(1000), @Erro varchar(MAX)
	DECLARE @NomeFicheiroErro varchar(100), @PathFicheiroErro varchar(500), @i int, @Linha varchar(MAX)
	DECLARE @TmpTblArquivos TABLE(idArquivo int NOT NULL, ficheiroBase64 varchar(MAX) NOT NULL)
-- inicia variáveis
	SET @ListaErros = ''
	SET @CodNaturezaErro = 'ERR'
	SET @CodNaturezaSucesso = 'MOV'
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador
-- valida o utilizador obtido
	IF @IdUtilizador IS NULL
		RAISERROR('O utilizador "%s" não é válido.', 16, 1, @Utilizador)
-- valida a natureza a atribuir à declaração DUI2 em caso de erro na exportação
	IF NOT EXISTS(SELECT 1 FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNaturezaErro AND NDE_PART = 0 AND NDE_VDAR = 0 AND NDE_VEXI = 0)
		RAISERROR('A natureza "%s" não é válida.', 16, 2, @CodNaturezaErro)
-- valida a natureza a atribuir à declaração DUI2 em caso de sucesso na exportação
	IF NOT EXISTS(SELECT 1 FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNaturezaSucesso AND NDE_PART = 0 AND NDE_VDAR = 0 AND NDE_VEXI = 0)
		RAISERROR('A natureza "%s" não é válida.', 16, 3, @CodNaturezaSucesso)
-- obtem as declarações DUI2 com status "Por Enviar", com título de depósito, não pertencentes às naturezas "ERR", "MOV" e ainda "4", "36", "42", "43", "44", "45", "ZZZ" e exista a incidência "A11"
	DECLARE DeclaracoesDUI2 CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT ddg.DUC_EANO, ddg.DUC_PNUM, ddg.DUC_CPRT, ddg.DUC_IDTY
		FROM PRO_DUCG AS ddg WITH(NOLOCK)
			INNER JOIN TAB_SINC AS inc WITH(NOLOCK) ON inc.SIN_CODI = 'A11'
		WHERE ddg.DUC_DUNO = 1 AND ddg.DUC_STAT = 0 AND ddg.DUC_NTDP IS NOT NULL AND ddg.NDE_CODI <> @CodNaturezaErro AND ddg.NDE_CODI <> @CodNaturezaSucesso
			AND ddg.NDE_CODI NOT IN ('4', '36', '42', '43', '44', '45', 'ZZZ') 			
			AND CAST(CONVERT(varchar(10), ddg.DUC_DTVO, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataVooReferencia, 105) AS datetime)
			AND EXISTS(SELECT 1 FROM PRO_DUIN WITH(NOLOCK) WHERE DUC_EANO = ddg.DUC_EANO AND DUC_PNUM = ddg.DUC_PNUM AND SIN_CODI = inc.SIN_CODI)
	OPEN DeclaracoesDUI2
	FETCH NEXT FROM DeclaracoesDUI2 INTO @AnoDeclaracaoDUI2, @NumDeclaracaoDUI2, @DocTransporteDUI2, @IdDeclaracaoDUI2
	WHILE @@FETCH_STATUS = 0
	BEGIN						
-- inicia processo de geração da declaração	IMP-CAU na base de dados IMP-CAU especificada
		BEGIN TRY	
			SET @NumErro = 0
			SET @Erro = ''
-- obtem data atual GMT
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os arquivos da declaração DUI2 para os converter em base64
			DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT DUC_IDEN, DUF_LINK
				FROM PRO_DUFI WITH(NOLOCK)
				WHERE DUC_EANO = @AnoDeclaracaoDUI2 AND DUC_PNUM = @NumDeclaracaoDUI2 AND ISNULL(DUF_LINK, '') <> ''
			OPEN Ficheiros
			FETCH NEXT FROM Ficheiros INTO @IdFicheiro, @PathFicheiro
			WHILE @@FETCH_STATUS = 0
			BEGIN			
				SET @FicheiroBinario = NULL
-- carrega o ficheiro para binario
				SET @SQLAExecutar = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiro + ''', SINGLE_BLOB) AS t)'
				SET @SQLVariaveis = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'			
				EXECUTE sp_executesql @SQLAExecutar, @SQLVariaveis, @OUTFicheiroBinario = @FicheiroBinario OUTPUT		
-- converte ficheiro binario para base64						
				SET @FicheiroBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinario")))', 'varchar(MAX)')	
-- insere ficheiro base64 na tabela tmp de arquivos da declaração DUI2
				INSERT INTO @TmpTblArquivos(idArquivo, ficheiroBase64)
				VALUES(@IdFicheiro, @FicheiroBase64)
				FETCH NEXT FROM Ficheiros INTO @IdFicheiro, @PathFicheiro
			END
			CLOSE Ficheiros
			DEALLOCATE Ficheiros	
-- constroi XML para declaração IMP-CAU a partir da declaração DUI2
			SET @XMLDeclaracaoIMPCAU = 
				(SELECT
					(SELECT 'I' AS "@acao", 
						(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
						CAST(0 AS bit) AS "despachoCentralizado", 
						'H1' AS "anexoB", 
						NULLIF(ddg.NDE_CODI, '') AS "natureza", 
						NULLIF(RTRIM(LTRIM(ddg.DUC_CPRT)), '') AS "documentoTransporte",
						(SELECT 
							(SELECT 							
								NULLIF(RTRIM(LTRIM(ddg.DUC_ENIF)), '') AS "nif", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_ENOM)), '') AS "nome", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_EMOR)), '') AS "morada", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_ELOC)), '') AS "localidade", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_ECPO)), '') AS "codigoPostal", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_ELPO)), '') AS "localidadePostal", 
								NULLIF(ddg.PAI_ELIV, '') AS "pais"
							HAVING ISNULL(RTRIM(LTRIM(ddg.DUC_ENOM)), '') <> ''
							FOR XML PATH('exportador'), TYPE), 
							NULLIF(ddg.PAI_PA15, '') AS "paisExpedicao", 
							(SELECT 
								ISNULL(NULLIF(RTRIM(LTRIM(ddg.DUC_DNIF)), ''), '999999990') AS "nif", 
								ddg.DUC_TPDS AS "tipoNIF", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_DNOM)), '') AS "nome", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_DMOR)), '') AS "morada", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_DLOC)), '') AS "localidade", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_DCPO)), '') AS "codigoPostal", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_DLPO)), '') AS "localidadePostal", 
								NULLIF(ddg.PAI_DLIV, '') AS "pais",
								NULLIF(RTRIM(LTRIM(ddg.DUC_DTEL)), '') AS "telefone", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_DEMA)), '') AS "email"
							FOR XML PATH('importador'), TYPE),
							NULLIF(ddg.PAI_PA17, '') AS "paisDestino",
							ddg.PAI_P17B AS "regiao", 
							(SELECT
								NULLIF(ddg.DEC_CO14, '') AS "codigoDeclarante", 
								(CASE ddg.DUC_TPDC WHEN 2 THEN ddg.DUC_TPDC ELSE NULL END) AS "estatuto"
							FOR XML PATH('declarante'), TYPE)
						FOR XML PATH('operadores'), TYPE),
						NULLIF(RTRIM(LTRIM(ddg.DUC_NVRF)), '') AS "vossaReferencia", 
						NULLIF(ddg.ALF_CODI, '') AS "estancia", 
						NULLIF(ddg.TDE_CODI, '') AS "tipoDeclaracao", 
						NULLIF(ddg.NTR_CO24, '') AS "naturezaTransacao", 
						NULLIF(ddg.CEN_CO20, '') AS "condicaoEntrega", 
						(SELECT
							NULLIF(RTRIM(LTRIM(ddg.DUC_DE20)), '') AS "localidadeCE", 
							ISNULL((SELECT (CASE WHEN CEN_LOCT IS NULL THEN NULL ELSE (CASE CEN_LOCD WHEN 0 THEN NULLIF(ddg.PAI_ELIV, '') ELSE NULLIF(ddg.PAI_DLIV, '') END) END) FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = ddg.CEN_CO20), '--') AS "paisCE" 						
						FOR XML PATH('localizacao'), TYPE), 
						(SELECT 
							(SELECT
								NULLIF(ddg.PAI_PR22, '') AS "pais", 	
								CAST(ISNULL(ddg.DUC_MT22, 0) AS decimal(18, 3)) AS "valorTotal"
							FOR XML PATH('fatura'), TYPE), 
							(SELECT
								NULLIF(ddg.PAI_FRET, '') AS "pais", 							
								CAST(ISNULL(ddg.DUC_FRET, 0) AS decimal(18, 3)) AS "valorTotal"
							FOR XML PATH('frete'), TYPE), 
							(SELECT
								NULLIF(ddg.PAI_SEGU, '') AS "pais", 							
								CAST(ISNULL(ddg.DUC_SEGU, 0) AS decimal(18, 3)) AS "valorTotal"
							FOR XML PATH('seguro'), TYPE), 
							(SELECT
								CAST(ISNULL(ddg.DUC_MLQT, 0) AS decimal(18, 6)) AS "massaLiquida", 							
								CAST(ISNULL(ddg.DUC_MBRT, 0) AS decimal(18, 6)) AS "massaBruta"
							FOR XML PATH('pesos'), TYPE)
						FOR XML PATH('totais'), TYPE), 
						(SELECT	
							NULLIF(RTRIM(LTRIM(ddg.DUC_CPRT)), '') AS "numeroNRUR", 
							(SELECT 
								NULLIF(ddg.MTR_FT21, '') AS "meioTransporte", 
								NULLIF(ddg.PAI_PA21, '') AS "pais"
							HAVING ISNULL(ddg.MTR_FT21, '') <> ''						
							FOR XML PATH('fronteira'), TYPE), 
							NULLIF(ddg.MTR_PT18, '') AS "meioTransporteChegada", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_MT18)), '') AS "identificacao", 
							ddg.DUC_CT19 AS "contentorizada"
						FOR XML PATH('transporte'), TYPE), 
						(SELECT
							(CASE ISNULL(ddg.DUC_TLOC, '') WHEN 'EA' THEN 'A' WHEN 'OL' THEN 'D' ELSE 'B' END) AS "tipoLocalizacao", 
							(CASE ISNULL(ddg.DUC_TLOC, '') WHEN 'EA' THEN 'V' WHEN 'OL' THEN 'Z' ELSE 'Y' END) AS "qualificador", 
							(CASE ISNULL(ddg.DUC_TLOC, '') WHEN 'EA' THEN NULL WHEN 'OL' THEN NULL ELSE NULLIF(ddg.LME_CO30, '') END) AS "armazemDTP", 
							(CASE ISNULL(ddg.DUC_TLOC, '') WHEN 'EA' THEN NULLIF(ddg.ALF_CODI1, '') WHEN 'OL' THEN NULL ELSE NULL END) AS "estancia", 
							(SELECT
								NULLIF(RTRIM(LTRIM(ddg.DUC_LAMO)), '') AS "morada", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_LALO)), '') AS "localidade", 
								NULLIF(RTRIM(LTRIM(ddg.DUC_LACP)), '') AS "codigoPostal"
							HAVING ISNULL(ddg.DUC_TLOC, '') = 'OL'
							FOR XML PATH('endereco'), TYPE)
						FOR XML PATH('localizacaoMercadorias'), TYPE), 
						NULLIF(ddg.ARM_CODI, '') AS "armazem", 				
						(SELECT 
							NULLIF(RTRIM(LTRIM(ddg.DUC_DELG)), '') AS "locID", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_GTWY)), '') AS "gateway", 	
							ddg.DUC_NVSR AS "serviceLevel", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_CIDE)), '') AS "portesAcc", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_POSA)), '') AS "portes", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_REF1)), '') AS "despachoAcc", 								
							CAST(ddg.DUC_VFRC AS decimal(18, 2)) AS "freteOriginal", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_MFRC)), '') AS "moedafreteOriginal", 
							CAST(ddg.DUC_VDES AS decimal(18, 3)) AS "despesas", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_PPFC)), '') AS "condEntrega", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_FUPS)), '') AS "nomeFicheiro"					
						FOR XML PATH('dadosEspecificos'), TYPE), 					
 						(SELECT 
							ddg.DUC_NPDT AS "numeroPDDT", 
							(CONVERT(varchar(10), ddg.DUC_DDTE, 127) + 'Z') AS "dataEntrada", 
							ddg.DUC_NPDD AS "numeroPDDTDEV", 
							ddg.DUC_NTDP AS "numeroTD", 
							ddg.DUC_NACT AS "numeroACTM", 
							ddg.DUC_NSEQ AS "numeroSequencia", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_PARM)), '') AS "posicaoArmazem"
						 FOR XML PATH('depositoTemporario'), TYPE), 	
						 (SELECT 
							NULLIF(RTRIM(LTRIM(ddg.DUC_MCPA)), '') AS "miniCPA", 	
							(CONVERT(varchar(10), ddg.DUC_DTVO, 127) + 'Z') AS "dataVoo", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_AERO)), '') AS "aeroportoOrigem", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_NVOO)), '') AS "numeroVoo", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_POSA)), '') AS "posicaoAviao", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_TRAC)), '') AS "tracking", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_TPCG)), '') AS "tipoCarga"
						FOR XML PATH('dadosAWB'), TYPE), 
						(SELECT 
							NULLIF(RTRIM(LTRIM(ddg.DUC_CIEX)), '') AS "numeroContaExpedidor", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_CIDE)), '') AS "numeroContaDestinatario", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_D2NO)), '') AS "nomeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_D2MO)), '') AS "moradaOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_D2LO)), '') AS "localidadeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_D2CP)), '') AS "codigoPostalOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_D2LP)), '') AS "localidadePostalOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_REF1)), '') AS "referenciaExterna1", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_REF2)), '') AS "referenciaExterna2", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_SHIP)), '') AS "shipID"
						FOR XML PATH('dadosEntidades'), TYPE), 
						(SELECT
							NULLIF(RTRIM(LTRIM(ddg.DUC_DTYP)), '') AS "dutyType", 
							ddg.DUC_PAYM AS "payment", 
							(CONVERT(varchar(10), ddg.DUC_DDDT, 127) + 'Z') AS "dataDocumentoTransporte", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_NREQ)), '') AS "numeroRequerimento", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_NDUR)), '') AS "numeroDURetorno", 
							NULLIF(RTRIM(LTRIM(ddg.DUC_T1RE)), '') AS "numeroT1Retorno"
						FOR XML PATH('outrosDados'), TYPE), 
						NULLIF(RTRIM(LTRIM(CAST(ddg.DUC_HIST AS varchar(MAX)))), '') AS "anotacoes", 
						(SELECT
							ddg.FUP_CODI AS "codigoFollowUp", 
							NULLIF(ddg.DUC_UNMD, '') AS "utilizadorNomeado"
						HAVING ddg.FUP_CODI IS NOT NULL
						FOR XML PATH('followUp'), TYPE), 																
						(SELECT 
							doc.DOC_DTRA AS "tipoDocumento", 
							doc.DOC_CODI AS "codigoDocumento",
							NULLIF(RTRIM(LTRIM(dad.DDO_NUME)), '') AS "numeroDocumento", 
							NULLIF(dad.PAI_CODI, '') AS "pais", 
							CAST(ISNULL(dad.DDO_MONT, 0) AS decimal(18, 2)) AS "montante", 
							NULLIF(RTRIM(LTRIM(dad.DDO_EEMI)), '') AS "entidadeEmissora", 
							NULLIF(dad.UME_CODI, '') AS "unidadeMedida", 
							CAST(dad.DDO_QTDE AS decimal(18, 2)) AS "quantidade"
						FROM PRO_DDOC AS dad WITH(NOLOCK) 
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI
							INNER JOIN PRO_DUAD AS dai WITH(NOLOCK) ON dad.DUC_EANO = dai.DUC_EANO AND dad.DUC_PNUM = dai.DUC_PNUM AND dad.DUA_CODI = dai.DUA_CODI 
							INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON dai.APA_CO33 = art.APA_CODI
							LEFT OUTER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON art.APA_CHVE = ado.APA_CHVE AND doc.DOC_CODI = ado.DOC_CODI AND ado.ADC_UIMP = 1
							LEFT OUTER JOIN TAB_CLDO AS cdo WITH(NOLOCK) ON ddg.DUC_DST8 = cdo.CLI_CODI AND doc.DOC_CODI = cdo.DOC_CODI AND cdo.CLD_UIMP = 1
							LEFT OUTER JOIN TAB_ALFD AS fdo WITH(NOLOCK) ON ddg.ALF_CODI = fdo.ALF_CODI AND doc.DOC_CODI = fdo.DOC_CODI
							LEFT OUTER JOIN TAB_TDED AS tdo WITH(NOLOCK) ON ddg.TDE_CODI = tdo.TDE_CODI AND doc.DOC_CODI = tdo.DOC_CODI
						WHERE dad.DUC_EANO = ddg.DUC_EANO AND dad.DUC_PNUM = ddg.DUC_PNUM AND dad.DUA_CODI = 1 AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0 AND ado.ADC_CODI IS NULL 
							AND cdo.CLD_UIMP IS NULL AND fdo.AFD_CODI IS NULL AND tdo.TDD_CODI IS NULL
						FOR XML PATH('documento'), ROOT('documentosECertificados'), TYPE), 	
						(SELECT 							
							'N337' AS "codigoDocumento",
							NULLIF(RTRIM(LTRIM(DRA_APC1)), '') AS "numeroDocumento"
						FROM PRO_DURA WITH(NOLOCK) 							
						WHERE DUC_EANO = ddg.DUC_EANO AND DUC_PNUM = ddg.DUC_PNUM AND DUA_CODI = 1 AND DRA_QUAL = 'X' AND ddg.DUC_ADI5 = 1
						FOR XML PATH('documentoPrecedente'), ROOT('documentosPrecedentes'), TYPE), 																	
						(SELECT 							
							NULLIF(dpe.TXM_CODI, '') AS "codigoPedido",
							NULLIF(LEFT(RTRIM(LTRIM(dpe.DPD_DESC)), 512), '') AS "numeroPedido"
						FROM PRO_DUPD AS dpe WITH(NOLOCK) 							
							LEFT OUTER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON ddg.TDE_CODI = tdp.TDE_CODI AND dpe.TXM_CODI = tdp.TXM_CODI
						WHERE dpe.DUC_EANO = ddg.DUC_EANO AND dpe.DUC_PNUM = ddg.DUC_PNUM AND dpe.DPD_ORIG = 0 AND tdp.TDP_CODI IS NULL
						FOR XML PATH('pedido'), ROOT('pedidos'), TYPE),								
						(SELECT 
							dad.DUA_CODI AS "numeroAdicao", 
							NULLIF(dad.APA_CP33, '') AS "codigoPautal", 							
							NULLIF(RTRIM(LTRIM(dad.DUA_DESG)), '') AS "designacao", 	
							NULLIF(dad.DUA_R37B, '') AS "regimeAdicional", 							
							NULLIF(dad.PAI_CO34, '') AS "paisOrigem",		
							NULLIF(dad.PRE_CO36, '') AS "preferencia", 
							dad.DUA_MAVA AS "metodoAvaliacao", 
							CAST(dad.DUA_ML38 AS decimal(18, 6)) AS "massaLiquida", 					
							CAST(dad.DUA_MB35 AS decimal(18, 6)) AS "massaBruta",	
							CAST(ISNULL(dad.DUA_US41, 0) AS decimal(18, 6)) AS "unidades", 																				
							CAST(dad.DUA_VA42 AS decimal(18, 3)) AS "montanteAd", 																																				
							CAST(ISNULL(dad.DUA_VFRE, 0) AS decimal(18, 3)) AS "valorFrete", 			
							CAST(ISNULL(dad.DUA_VSEG, 0) AS decimal(18, 3)) AS "valorSeguro", 				
							CAST(ISNULL(dad.DUA_TIVA, 0) AS decimal(18, 2)) AS "taxaIVA", 									
							(SELECT 							
								'N337' AS "codigoDocumento",
								NULLIF(RTRIM(LTRIM(DRA_APC1)), '') AS "numeroDocumento"
							FROM PRO_DURA WITH(NOLOCK) 							
							WHERE DUC_EANO = dad.DUC_EANO AND DUC_PNUM = dad.DUC_PNUM AND DUA_CODI = dad.DUA_CODI AND DRA_QUAL = 'X' AND ddg.DUC_ADI5 > 1
							FOR XML PATH('documentoPrecedente'), ROOT('documentosPrecedentes'), TYPE), 									
							(SELECT 
								NULLIF(UME_CODI, '') AS "unidadeMedida", 
								CAST(D31_QNTD AS int) AS "volumes", 
								NULLIF(RTRIM(LTRIM(D31_MARC)), '') AS "marcas", 									
								D31_CASP AS "parte"					
							FROM PRO_DU31 WITH(NOLOCK)
							WHERE DUC_EANO = dad.DUC_EANO AND DUC_PNUM = dad.DUC_PNUM AND DUA_CODI = dad.DUA_CODI AND dad.DUA_CODI = 1
							FOR XML PATH('marcaEVolume'), ROOT('marcasEVolumes'), TYPE),
							(SELECT 									
								NULLIF(RTRIM(LTRIM(DCO_CNUM)), '') AS "numeroContentor", 	
								NULLIF(RTRIM(LTRIM(DCO_TIPO)), '') AS "tipoContentor"		
							FROM PRO_DCON WITH(NOLOCK)
							WHERE DUC_EANO = dad.DUC_EANO AND DUC_PNUM = dad.DUC_PNUM AND DUA_CODI = dad.DUA_CODI
							FOR XML PATH('contentor'), ROOT('contentores'), TYPE)
						FROM PRO_DUAD AS dad WITH(NOLOCK) 								
						WHERE dad.DUC_EANO = ddg.DUC_EANO AND dad.DUC_PNUM = ddg.DUC_PNUM
						FOR XML PATH('adicao'), ROOT('adicoes'), TYPE), 												
						(SELECT 
							NULLIF(SIN_CODI, '') AS "codigoIncidencia", 
							(CONVERT(varchar(10), DUI_DINI, 127) + 'T' + CONVERT(varchar(8), DUI_HINI, 108) + '.000Z') AS "dataInicio", 
							(CONVERT(varchar(10), DUI_DFIM, 127) + 'T' + CONVERT(varchar(8), DUI_HFIM, 108) + '.000Z') AS "dataFim", 
							NULLIF(RTRIM(LTRIM(CAST(DUI_OBSR AS varchar(MAX)))), '') AS "observacoes", 
							(CASE DUI_REHO WHEN 0 THEN 'R' WHEN 1 THEN 'H' ELSE NULL END) AS "tipoIncidencia"
						FROM PRO_DUIN WITH(NOLOCK) 							
						WHERE DUC_EANO = ddg.DUC_EANO AND DUC_PNUM = ddg.DUC_PNUM
						FOR XML PATH('incidencia'), ROOT('incidencias'), TYPE), 										
						(SELECT 
							FUP_CODI AS "codigoFollowUp", 
							NULLIF(UTI_UTIL, '') AS "utilizador", 
							(CONVERT(varchar(23), DFW_DATA, 127) + 'Z') AS "dataHora"
						FROM PRO_DUFW WITH(NOLOCK) 							
						WHERE DUC_EANO = ddg.DUC_EANO AND DUC_PNUM = ddg.DUC_PNUM
						FOR XML PATH('followUpData'), ROOT('followUps'), TYPE), 						 						
						(SELECT 
							ISNULL(DUO_TIPO, 0) AS "tipoManifesto", 
							NULLIF(PAI_CODI, '') AS "paisManifesto",
							NULLIF(RTRIM(LTRIM(DUO_DESC)), '') AS "descricao",	
							CAST(ISNULL(DUO_VALO, 0) AS decimal(18, 3)) AS "valor", 						
							NULLIF(LEFT(DUO_MOED, 2), '') AS "paisMoeda",							
							CAST(ISNULL(DUO_TFAC, 0) AS decimal(18, 3)) AS "totalFatura",
							NULLIF(RTRIM(LTRIM(DUO_CPA2)), '') AS "numeroCPA", 
							CAST(ISNULL(DUO_PES2, 0) AS decimal(18, 3)) AS "pesoBruto"
						FROM PRO_DUOD WITH(NOLOCK) 							
						WHERE DUC_EANO = ddg.DUC_EANO AND DUC_PNUM = ddg.DUC_PNUM
						FOR XML PATH('manifesto'), ROOT('manifestos'), TYPE), 
						(SELECT 
							NULLIF(RTRIM(LTRIM(dfi.DUF_NOMF)), '') AS "nomeArquivo", 
							NULLIF(RTRIM(LTRIM(dfi.DUF_DESC)), '') AS "descricaoArquivo", 
							ISNULL(NULLIF(dfi.DUF_TMSG, ''), 'OUTRO') AS "tipoArquivo",
							dfi.DUF_ORIG AS "origemArquivo", 
							tfi.ficheiroBase64 AS "ficheiroBase64"
						FROM PRO_DUFI AS dfi WITH(NOLOCK) 							
							INNER JOIN @TmpTblArquivos AS tfi ON dfi.DUC_IDEN = tfi.idArquivo
						WHERE dfi.DUC_EANO = ddg.DUC_EANO AND dfi.DUC_PNUM = ddg.DUC_PNUM
						FOR XML PATH('arquivo'), ROOT('arquivos'), TYPE)								
					FROM PRO_DUCG AS ddg WITH(NOLOCK) 						
					WHERE ddg.DUC_IDTY = @IdDeclaracaoDUI2
					FOR XML PATH('declaracao'), TYPE)
				FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da declaração IMP-CAU				
			SET @SQLAExecutar = N'EXEC @OUTNumErro = ' + @BaseDadosIMPCAU + '.dbo.sp_IMP_Declaracoes_ImportaDeXML @INXMLDeclaracaoIMPCAU, @INIdUtilizador, @OUTErro OUTPUT'
			SET @SQLVariaveis = N'@INXMLDeclaracaoIMPCAU xml, @INIdUtilizador int, @OUTNumErro int OUTPUT, @OUTErro varchar(MAX) OUTPUT'
			EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INXMLDeclaracaoIMPCAU = @XMLDeclaracaoIMPCAU, @INIdUtilizador = @IdUtilizador, @OUTNumErro = @NumErro OUTPUT, @OUTErro = @Erro OUTPUT		
-- senão houver erros na geração, efetua processamentos finais
			IF @NumErro = 0
			BEGIN
				SET @AnoDeclaracaoIMPCAU = NULL
				SET @NumDeclaracaoIMPCAU = NULL
				SET @IdDeclaracaoIMPCAU = NULL
-- obtem o id da declaração IMP-CAU gerada
				SET @SQLAExecutar = N'SELECT TOP 1 @OUTAnoDeclaracaoIMPCAU = DUC_EANO, @OUTNumDeclaracaoIMPCAU = DUC_PNUM, @OUTIdDeclaracaoIMPCAU = DUC_IDTY FROM ' + @BaseDadosIMPCAU + '.dbo.PRO_DUCG WITH(NOLOCK) WHERE DUC_EANO = YEAR(@INDataAtual) AND DUC_CPRT = @INDocTransporteDUI2 ORDER BY DUC_IDTY DESC'
				SET @SQLVariaveis = N'@INDataAtual datetime, @INDocTransporteDUI2 varchar(18), @OUTAnoDeclaracaoIMPCAU int OUTPUT, @OUTNumDeclaracaoIMPCAU int OUTPUT, @OUTIdDeclaracaoIMPCAU bigint OUTPUT'
				EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INDataAtual = @DataAtual, @INDocTransporteDUI2 = @DocTransporteDUI2, @OUTAnoDeclaracaoIMPCAU = @AnoDeclaracaoIMPCAU OUTPUT, @OUTNumDeclaracaoIMPCAU = @NumDeclaracaoIMPCAU OUTPUT, @OUTIdDeclaracaoIMPCAU = @IdDeclaracaoIMPCAU OUTPUT
-- verifica se a declaração IMP-CAU foi corretamente gerada
				IF @IdDeclaracaoIMPCAU IS NULL
					RAISERROR('Declaração IMP-CAU não foi gerada.', 16, 4)
-- atualiza o número dos documento automáticos de origem do tipo de declaração
				SET @SQLAExecutar = N'UPDATE ' + @BaseDadosIMPCAU + '.dbo.tb_IMP_DeclaracoesDocumentos SET numero = dad.DDO_NUME FROM ' + @BaseDadosIMPCAU + '.dbo.tb_IMP_DeclaracoesDocumentos AS did WITH(NOLOCK) INNER JOIN ' + @BaseDadosIMPCAU + '.dbo.TAB_DOCU AS doc WITH(NOLOCK) ON did.id_documento = doc.DOC_IDTY INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON ddg.DUC_EANO = @INAnoDeclaracaoDUI2 AND ddg.DUC_PNUM = @INNumDeclaracaoDUI2 INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON dad.DUC_EANO = ddg.DUC_EANO AND dad.DUC_PNUM = ddg.DUC_PNUM AND dad.DUA_CODI = 1 AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0 AND doc.DOC_CODI = dad.DOC_CODI INNER JOIN TAB_TDED AS tdo WITH(NOLOCK) ON ddg.TDE_CODI = tdo.TDE_CODI AND dad.DOC_CODI = tdo.DOC_CODI	WHERE did.id_declaracaoIMP = @INIdDeclaracaoIMPCAU AND did.origem = 1 AND ISNULL(did.numero, '''') <> ISNULL(dad.DDO_NUME, '''')'
				SET @SQLVariaveis = N'@INAnoDeclaracaoDUI2 int, @INNumDeclaracaoDUI2 int, @INIdDeclaracaoIMPCAU bigint'
				EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INAnoDeclaracaoDUI2 = @AnoDeclaracaoDUI2, @INNumDeclaracaoDUI2 = @NumDeclaracaoDUI2, @INIdDeclaracaoIMPCAU = @IdDeclaracaoIMPCAU
-- atualiza o número dos documento automáticos de origem da alfândega
				SET @SQLAExecutar = N'UPDATE ' + @BaseDadosIMPCAU + '.dbo.tb_IMP_DeclaracoesDocumentos SET numero = dad.DDO_NUME FROM ' + @BaseDadosIMPCAU + '.dbo.tb_IMP_DeclaracoesDocumentos AS did WITH(NOLOCK) INNER JOIN ' + @BaseDadosIMPCAU + '.dbo.TAB_DOCU AS doc WITH(NOLOCK) ON did.id_documento = doc.DOC_IDTY INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON ddg.DUC_EANO = @INAnoDeclaracaoDUI2 AND ddg.DUC_PNUM = @INNumDeclaracaoDUI2 INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON dad.DUC_EANO = ddg.DUC_EANO AND dad.DUC_PNUM = ddg.DUC_PNUM AND dad.DUA_CODI = 1 AND dad.DDO_TIPO = 0 AND dad.DDO_AUTO = 0 AND doc.DOC_CODI = dad.DOC_CODI INNER JOIN TAB_ALFD AS fdo WITH(NOLOCK) ON ddg.ALF_CODI = fdo.ALF_CODI AND dad.DOC_CODI = fdo.DOC_CODI	WHERE did.id_declaracaoIMP = @INIdDeclaracaoIMPCAU AND did.origem = 6 AND ISNULL(did.numero, '''') <> ISNULL(dad.DDO_NUME, '''')'
				SET @SQLVariaveis = N'@INAnoDeclaracaoDUI2 int, @INNumDeclaracaoDUI2 int, @INIdDeclaracaoIMPCAU bigint'
				EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INAnoDeclaracaoDUI2 = @AnoDeclaracaoDUI2, @INNumDeclaracaoDUI2 = @NumDeclaracaoDUI2, @INIdDeclaracaoIMPCAU = @IdDeclaracaoIMPCAU
-- remove precedente criado pelo automatismo do regime da declaração IMP-CAU, apenas quando a mesma tem mais que 1 adição
				SET @SQLAExecutar = N'IF EXISTS(SELECT 1 FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_IDTY = @INIdDeclaracaoIMPCAU AND DUC_ADI5 > 1) BEGIN DELETE FROM tb_IMP_DeclaracoesPrecedentes WHERE id_declaracaoIMP = @INIdDeclaracaoIMPCAU AND origem = 1 END'
				SET @SQLVariaveis = N'@INIdDeclaracaoIMPCAU bigint'
				EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INIdDeclaracaoIMPCAU = @IdDeclaracaoIMPCAU
-- remove o primeiro registo de follow-up criado pelo automatismo existente nos dados gerais das declarações IMP-CAU p/ evitar duplicação
				SET @SQLAExecutar = N'DELETE FROM ' + @BaseDadosIMPCAU + '.dbo.PRO_DUFW WHERE DUC_EANO = @INAnoDeclaracaoIMPCAU AND DUC_PNUM = @INNumDeclaracaoIMPCAU AND DFW_CODI = (SELECT MIN(DFW_CODI) FROM ' + @BaseDadosIMPCAU + '.dbo.PRO_DUFW WITH(NOLOCK) WHERE DUC_EANO = @INAnoDeclaracaoIMPCAU AND DUC_PNUM = @INNumDeclaracaoIMPCAU)'
				SET @SQLVariaveis = N'@INAnoDeclaracaoIMPCAU int, @INNumDeclaracaoIMPCAU int'
				EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INAnoDeclaracaoIMPCAU = @AnoDeclaracaoIMPCAU, @INNumDeclaracaoIMPCAU = @NumDeclaracaoIMPCAU
-- Coloca a declaração DUI2 com natureza de sucesso da exportação e bloqueada
				UPDATE PRO_DUCG SET NDE_CODI = @CodNaturezaSucesso, NDE_NOME = (SELECT NDE_NOME FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNaturezaSucesso), DUC_BLOQ = 1, 
					DUC_UALT = @Utilizador, DUC_DTAL = @DataAtual
				WHERE DUC_IDTY = @IdDeclaracaoDUI2
			END
			ELSE
				RAISERROR('Declaração IMP-CAU não foi gerada! ERRO: "%s".', 16, 5, @Erro)				
		END TRY
		BEGIN CATCH
-- Coloca a declaração DUI2 com natureza de erro da exportação
			UPDATE PRO_DUCG SET NDE_CODI = @CodNaturezaErro, NDE_NOME = (SELECT NDE_NOME FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNaturezaErro), 
				DUC_UALT = @Utilizador, DUC_DTAL = @DataAtual
			WHERE DUC_IDTY = @IdDeclaracaoDUI2
-- constroi mensagem de erro detalhada						
			SET @ListaErros = ISNULL(@ListaErros, '') + 
								'**********************************************************************************************************' + CHAR(12) +
								'** ERRO NA EXPORTACAO DA DECLARACAO DUI2 *****************************************************************' + CHAR(12) + 
								'**********************************************************************************************************' + CHAR(12) + 
								'Dados da Declaracao DUI2: ' + CHAR(12) + 								
								' » Doc. Transporte: ' + ISNULL(@DocTransporteDUI2, '') + CHAR(12) +
								' » No. Declaracao: ' + CAST(@AnoDeclaracaoDUI2 AS varchar(4)) + '/' + CAST(@NumDeclaracaoDUI2 AS varchar(50)) + CHAR(12) +
								' » Id. Declaracao: ' + CAST(@IdDeclaracaoDUI2 AS varchar(50)) + CHAR(12) +								
								' » Erro: ' + ERROR_MESSAGE() + CHAR(12) + 
								' » Detalhe: Número=' + CAST(ERROR_NUMBER() AS varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() AS varchar(5)) + ',Estado=' + CAST(ERROR_STATE() AS varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() AS varchar(5)) + CHAR(12)
		END CATCH			
		FETCH NEXT FROM DeclaracoesDUI2 INTO @AnoDeclaracaoDUI2, @NumDeclaracaoDUI2, @DocTransporteDUI2, @IdDeclaracaoDUI2
	END
	CLOSE DeclaracoesDUI2
	DEALLOCATE DeclaracoesDUI2	
-- se ocorreram erros no processo de exportação das declarações DUI2 para IMP-CAU, gera ficheiro de erros
	IF ISNULL(@ListaErros, '') <> ''
	BEGIN			
		SET @NomeFicheiroErro = 'GIDWinErrorLogExportDUI2ToIMPCAU_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), '-', ''), ':', ''), '.', ''), ' ', '') + '.txt'
		SET @PathFicheiroErro = @DirFicheiroErros + '/' + @NomeFicheiroErro
		SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
		WHILE @i > 0
		BEGIN
			SET @Erro = ''
			SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
			EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erro OUTPUT
			IF ISNULL(@Erro, '') <> ''
				RAISERROR('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 6, @PathFicheiroErro, @Erro)				
			SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
		END			
	END	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ExportaDeclaracoesParaIMPCAUDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ExportaDeclaracoesParaIMPCAUDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ExportaFicheiroDARP]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ExportaFicheiroDARP] @AnoProcesso int, @NumProcesso int, @FicheiroXML xml(XMLSC_DeclaracoesImpToDARP) OUTPUT, @LinhaXMLEncoding varchar(200) OUTPUT AS
BEGIN
	SET DATEFORMAT DMY
-- atribui linha de encoding (definido no schema) para depois ser incluída no ficheiro XML a gerar
	SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="UTF-8"?>'	
-- constroi XML para ficheiro DARP
	SET @FicheiroXML = 				
		(SELECT 
			(SELECT (CASE WHEN DUC_STAT = 3 THEN 'D' WHEN DUC_REVI > 0 THEN 'U' ELSE 'I' END) as "accao", 
				ISNULL(DUC_UALT, DUC_UCRI) as "utilizadorCriacao", 
				(SELECT 
					(SELECT NULLIF(D31_NUME, '') as "objecto"
					FROM PRO_DU31 WITH(NOLOCK)
					WHERE DUC_EANO = PRO_DUCG.DUC_EANO and DUC_PNUM = PRO_DUCG.DUC_PNUM and D31_CASP = 0
					FOR XML PATH(''), TYPE)
				FOR XML PATH('numeroLocalObjecto'), TYPE),
				(SELECT TOP 1 NULLIF(DUF_LINK, '') FROM PRO_DUFI WITH(NOLOCK) WHERE DUC_EANO = PRO_DUCG.DUC_EANO and DUC_PNUM = PRO_DUCG.DUC_PNUM and DUF_TMSG = 'IM006A.1' ORDER BY DUF_DATA DESC) as "nomePDF",
				DUC_NRLO as "numeroReferenciaLocal",
				NULLIF(DUC_REGL, '') as "numeroRegistoLiquidacao",
				NULLIF(DUC_NORD, '') as "numeroOrdem",
				(CONVERT(varchar(10), DUC_NDAT, 120) + 'Z') as "dataNumeroOrdem", 
				(CONVERT(varchar(10), DUC_DTAS, 120) + 'Z') as "dataAutorizacaoSaida", 
				NDE_CODI as "natureza",
				DUC_ADI5 as "numeroTotalAdicoes", 
				CAST(ISNULL(DUC_TVL6, 0) as int) as "numeroTotalVolumes", 
				CAST(ROUND(ISNULL(DUC_FRET, 0) / ISNULL(DUC_TXFR, 1), 2) + ROUND(ISNULL(DUC_SEGU, 0) / ISNULL(DUC_TXSE, 1), 2) as numeric(28, 2)) as "totalDespesas", 
				CAST(ROUND(ISNULL(DUC_OP18, 0) * ISNULL(DUC_TVL6, 0), 2) as numeric(28, 2)) as "totalVDA", 				
				CAST(ISNULL((SELECT SUM(ISNULL(DUO_MONT, 0)) FROM PRO_DUOI WITH(NOLOCK) WHERE DUC_EANO = PRO_DUCG.DUC_EANO AND DUC_PNUM = PRO_DUCG.DUC_PNUM AND ISNULL(DUO_CAUC, '') <> ''), 0) as numeric(28, 2)) as "totalRecapitulativo", 
				(SELECT NULLIF(PAI_MO22, '') as "codigoMoedaFacturacao", 
					CAST(ISNULL(DUC_MT22, 0) as numeric(28, 3)) as "montanteTotalFacturado", 
					CAST(ISNULL(DUC_TX23, 1) as numeric(28, 6)) as "taxaCambio"
				FOR XML PATH('montante'), TYPE),
				(CASE ISNULL(DUC_FRET, 0) WHEN 0 THEN NULL ELSE NULLIF(PAI_MOFT, '') END) as "frete/codigoMoedaFrete", 
				(CASE ISNULL(DUC_FRET, 0) WHEN 0 THEN NULL ELSE CAST(ISNULL(DUC_FRET, 0) as numeric(28, 3)) END) as "frete/montanteFrete", 
				(CASE ISNULL(DUC_FRET, 0) WHEN 0 THEN NULL ELSE CAST(ISNULL(DUC_TXFR, 1) as numeric(28, 6)) END) as "frete/taxaCambio", 
				(CASE ISNULL(DUC_SEGU, 0) WHEN 0 THEN NULL ELSE NULLIF(PAI_MOSG, '') END) as "seguro/codigoMoedaSeguro", 
				(CASE ISNULL(DUC_SEGU, 0) WHEN 0 THEN NULL ELSE CAST(ISNULL(DUC_SEGU, 0) as numeric(28, 3)) END) as "seguro/montanteSeguro", 
				(CASE ISNULL(DUC_SEGU, 0) WHEN 0 THEN NULL ELSE CAST(ISNULL(DUC_TXSE, 1) as numeric(28, 6)) END) as "seguro/taxaCambio", 
				NULLIF(PAI_DLIV + DUC_DNIF, '') as "destinatario/numeroIdentificacao"				
			FROM PRO_DUCG WITH(NOLOCK) 
			WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso
			FOR XML PATH('cabecalho'), TYPE),
			(SELECT 
				(SELECT adi.DUA_CODI as "numeroAdicao", 
					NULLIF(adi.APA_CP33, '') as "codigoMercadorias", 
					NULLIF(adi.DUA_DESG, '') as "designacaoMercadorias",
					NULLIF(adi.PRE_CO36, '') as "preferencia", 
					NULLIF(adi.PAI_CO34, '') as "codigoPaisOrigem", 
					(SELECT ISNULL(NULLIF(D31_MARC, ''), 'CART.POSTAL') as "marca", 
						NULLIF(D31_NUME, '') as "numeros", 
						NULLIF(D31_LOPT, '') as "Loptica", 
						ISNULL(NULLIF(UME_CODI, ''), 'CT') as "naturezaVolumes", 
						CAST(D31_QNTD as int) as "quantidadeMercadoria"
					FROM PRO_DU31 WITH(NOLOCK) 						
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI
					FOR XML PATH('volume'), TYPE), 
					(SELECT 
						(SELECT DOC_CODI as "codigoMencao", 								
							CAST(ISNULL(DDO_MONT, 0) as numeric(28, 2)) as "montanteVDA"
						FROM PRO_DDOC WITH(NOLOCK) 							
						WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 1 AND DOC_CODI = 'VDA' AND duc.DUC_DUNO <> 2
						FOR XML PATH('mencaoEspecial'), TYPE),
						(SELECT 
							ped.TXM_CODI as "codigoMencao", 								
							CAST(ISNULL(REPLACE(dap.numero, ',', '.'), 0) as numeric(28, 2)) as "montanteVDA"
						FROM tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK)
							INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dap.id_pedido = ped.TXM_IDTY							
						WHERE dap.id_adicao = adi.DUA_IDEN AND ped.TXM_CODI = 'G1VDA' AND duc.DUC_DUNO = 2
						FOR XML PATH('mencaoEspecial'), TYPE)
					FOR XML PATH('documentosCertificados'), TYPE), 
					(SELECT 
						(SELECT RRE_CODI as "rubricaReceita", 								
							NULLIF(RRE_NOME, '') as "descricaoRubrica", 
							NULLIF(DUO_IMPO, '') as "tipoImposicao", 
							CAST(ISNULL(DUO_BTRI, 0) as numeric(28, 3)) as "baseTributacao",
							CAST(ISNULL(DUO_TXVL, 0) as numeric(28, 4)) as "taxaImposicao", 
							CAST(ISNULL(DUO_MONT, 0) as numeric(28, 2)) as "montanteImposicao"
						FROM PRO_DUOI WITH(NOLOCK) 
						WHERE DUC_EANO = adi.DUC_EANO and DUC_PNUM = adi.DUC_PNUM and DUA_CODI = adi.DUA_CODI
						FOR XML PATH('imposicoes'), TYPE)
					FOR XML PATH('liquidacaoDefinitiva'), TYPE)
				FROM PRO_DUAD AS adi WITH(NOLOCK) 
					INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
				WHERE adi.DUC_EANO = @AnoProcesso AND adi.DUC_PNUM = @NumProcesso
				FOR XML PATH('adicao'), TYPE)
			FOR XML PATH('adicoes'), TYPE)
		FOR XML PATH('DARP'), ELEMENTS)
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ExportaFicheiroDARP] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ExportaFicheiroDARP] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ExportaFicheiroOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ExportaFicheiroOGMA] @NomeFicheiroXML varchar(100), @Utilizador varchar(30), @FicheiroXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdDeclaracao bigint, @NumAdicao int, @Regime varchar(4), @PathFicheiroXML varchar(500), @ComandoSQL varchar(1500), @FicheiroTXT varchar(MAX)	
	DECLARE @TmpFicheiroOGMA TABLE(
		ID int NOT NULL IDENTITY(1, 1), 	
		DUC_IDTY bigint NOT NULL, 
		DUA_CODI int NOT NULL, 
		DUA_RG37 varchar(4) NOT NULL, 
		FICHEIRO xml NOT NULL)
-- inicia processo de geração da declaração	DUI2
	BEGIN TRY	
		SET @NumErro = 0		
-- cria tabela temporária p/ conteudo de cada ficheiro
		CREATE TABLE #ConteudoFicheiro(CONTEUDO varchar(MAX) COLLATE Latin1_General_CI_AI)
-- obtem as declarações DUI2 e respetivos ficheiros XML associados ao nome do ficheiro OGMA recebido
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT duc.DUC_IDTY, dua.DUA_CODI, dua.DUA_RG37, dfm.DUF_LINK				
			FROM PRO_DUCG AS duc WITH(NOLOCK) 			
				INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM 
				INNER JOIN PRO_DUFI AS dfm WITH(NOLOCK) ON duc.DUC_EANO = dfm.DUC_EANO AND duc.DUC_PNUM = dfm.DUC_PNUM AND duc.DUC_FUPS = dfm.DUF_NOMF AND dfm.DUF_ORIG = 3 AND dfm.DUF_ENVI = 0								
			WHERE duc.DUC_FUPS = @NomeFicheiroXML
			ORDER BY duc.DUC_IDTY, dua.DUA_CODI
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumAdicao, @Regime, @PathFicheiroXML
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @FicheiroTXT = NULL			
-- processa a importação dos dados do ficheiro XML na tabela temporária
			SET @ComandoSQL = 'BULK INSERT #ConteudoFicheiro FROM ''' + @PathFicheiroXML + ''''
			EXEC (@ComandoSQL)
-- obtem o xml do ficheiro importado (se xml não minified, torna-o minified)
			SELECT @FicheiroTXT = COALESCE(@FicheiroTXT, '') + CONTEUDO
			FROM #ConteudoFicheiro
-- converte para xml com a remoção do encoding
			SET @FicheiroXML = REPLACE(@FicheiroTXT, ' encoding="UTF-8"', '')
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- insere na tabela tmp o ficheiro XML associado à declaração
			INSERT INTO @TmpFicheiroOGMA(DUC_IDTY, DUA_CODI, DUA_RG37, FICHEIRO)
			VALUES(@IdDeclaracao, @NumAdicao, @Regime, @FicheiroXML.query('(FICH_DESPCHANTE/FICH_DESPCHANTE_LINE[NOTAS=sql:variable("@Regime")])[sql:variable("@NumAdicao")]'))
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumAdicao, @Regime, @PathFicheiroXML
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- remove a tabela temporária
		DROP TABLE #ConteudoFicheiro
-- constroi XML para ficheiro XML no formato OGMA a partir da declaração DUI2 e respetivo ficheiro original
		SET @FicheiroXML = 
			(SELECT
				(SELECT 
					f.x.value('DT_PROCESSO[1]', 'varchar(10)') AS "DT_PROCESSO", 
					f.x.value('PROCESSO[1]', 'varchar(100)') AS "PROCESSO", 
					f.x.value('TIPO[1]', 'varchar(1)') AS "TIPO", 
					f.x.value('BI_LI_ID[1]', 'varchar(45)') AS "BI_LI_ID", 
					f.x.value('AWB[1]', 'varchar(25)') AS "AWB", 
					f.x.value('RO_ID[1]', 'varchar(45)') AS "RO_ID", 
					f.x.value('PO[1]', 'varchar(20)') AS "PO", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('ARTIGO[1]', 'varchar(40)')) AS "ARTIGO", 
					f.x.value('QTD_REC[1]', 'varchar(45)') AS "QTD_REC", 
					f.x.value('UOM_REC[1]', 'varchar(3)') AS "UOM_REC", 
					f.x.value('VALOR_UNIT_REC[1]', 'varchar(45)') AS "VALOR_UNIT_REC", 
					f.x.value('RRM[1]', 'varchar(30)') AS "RRM", 
					f.x.value('LOTE[1]', 'varchar(80)') AS "LOTE", 
					f.x.value('SERIAL_NUM[1]', 'varchar(250)') AS "SERIAL_NUM", 
					f.x.value('PP_OGMA[1]', 'varchar(22)') AS "PP_OGMA", 
					f.x.value('NOTAS[1]', 'varchar(100)') AS "NOTAS", 
					ISNULL(duc.DUC_NORD, '') AS "DAU", 
					duc.DUC_REVI AS "REVISAO", 
					ISNULL(CONVERT(varchar(10), duc.DUC_NDAT, 105), '') AS "DAU_DATE", 
					ISNULL(dua.DUA_RG37, '') AS "REGIME", 
					dua.DUA_CODI AS "NUM_ADIC", 
					ISNULL(dua.APA_CP33, '') AS "PP_ALF", 
					f.x.value('QTD_REC[1]', 'varchar(45)') AS "QTD_ALF", 
					f.x.value('UOM_REC[1]', 'varchar(3)') AS "UOM_ALF", 
					CAST(dua.DUA_MB35 AS decimal(28, 6)) AS "PESO_GROSS_ALF", 
					CAST(dua.DUA_ML38 AS decimal(28, 6)) AS "PESO_NET_TOTAL_ALF", 
					CAST(ROUND((dua.DUA_ML38 / ISNULL(CAST(NULLIF(f.x.value('QTD_REC[1]', 'varchar(45)'), '') AS decimal(28, 6)), 1)), 6) AS decimal(28, 6)) AS "PESO_NET_UNIT_ALF", 
					CAST(dua.DUA_VEST AS decimal(28, 6)) AS "VALOR_ALF", 
					(LTRIM(STR(duc.DUC_PNUM, 7, 0)) + '/' + RIGHT(STR(duc.DUC_EANO, 4, 0), 2)) AS "N_PROC_DESPACHANTE", 
					FLOOR(ISNULL(duc.DUC_TVL6, 0)) AS "N_VOLUMES", 
					f.x.value('CLASSIFICACAO[1]', 'varchar(50)') AS "CLASSIFICACAO", 
					f.x.value('LICENCA[1]', 'varchar(50)') AS "LICENCA", 
					f.x.value('END_USER[1]', 'varchar(50)') AS "END_USER", 
					f.x.value('GUIA[1]', 'varchar(20)') AS "GUIA", 
					f.x.value('QTD_EXP[1]', 'varchar(45)') AS "QTD_EXP", 
					f.x.value('UOM_EXP[1]', 'varchar(3)') AS "UOM_EXP", 
					f.x.value('VALOR_UNIT_EXP[1]', 'varchar(45)') AS "VALOR_UNIT_EXP", 
					f.x.value('DAU[1]', 'varchar(20)') AS "DAU_PREC", 
					f.x.value('REVISAO[1]', 'varchar(45)') AS "REVISAO_PREC", 
					f.x.value('DAU_DATE[1]', 'varchar(10)') AS "DAU_DATE_PREC", 
					f.x.value('REGIME[1]', 'varchar(4)') AS "REGIME_PREC", 
					f.x.value('NUM_ADIC_PREC[1]', 'varchar(45)') AS "NUM_ADIC_PREC", 
					f.x.value('PP_ALF[1]', 'varchar(22)') AS "PP_PREC", 
					f.x.value('PESO_GROSS[1]', 'varchar(45)') AS "PESO_GROSS", 
					f.x.value('PESO_NET_TOTAL[1]', 'varchar(45)') AS "PESO_NET_TOTAL", 
					f.x.value('KEY_ADIC_PREC[1]', 'varchar(45)') AS "KEY_ADIC_PREC", 
					f.x.value('N_PROC_DESPACHANTE_PREC[1]', 'varchar(10)') AS "N_PROC_DESPACHANTE_PREC", 
					f.x.value('BEM[1]', 'varchar(1)') AS "BEM", 
					f.x.value('DESIGN_REC[1]', 'varchar(100)') AS "DESIGN_REC", 
					f.x.value('DESIGN_EXP[1]', 'varchar(100)') AS "DESIGN_EXP", 
					f.x.value('WEIGHT_UNIT[1]', 'varchar(45)') AS "WEIGHT_UNIT", 
					f.x.value('UOM_WEIGHT[1]', 'varchar(12)') AS "UOM_WEIGHT", 
					f.x.value('PESO_NET_REMAINING[1]', 'varchar(45)') AS "PESO_NET_REMAINING", 
					f.x.value('COUNTRY_EXP[1]', 'varchar(50)') AS "COUNTRY_EXP", 
					f.x.value('TIPO_EXP[1]', 'varchar(15)') AS "TIPO_EXP", 
					f.x.value('PROCESS_TYPE[1]', 'varchar(2)') AS "PROCESS_TYPE", 
					f.x.value('FACTURA[1]', 'varchar(100)') AS "FACTURA", 
					f.x.value('PROJECTO[1]', 'varchar(25)') AS "PROJECTO", 
					f.x.value('PAIS_EXP_MERCADORIA[1]', 'varchar(3)') AS "PAIS_EXP_MERCADORIA", 
					f.x.value('TIPO_CERTIFICADO[1]', 'varchar(100)') AS "TIPO_CERTIFICADO", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('EXPEDIDOR[1]', 'varchar(200)')) AS "EXPEDIDOR", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('DESTINATARIO[1]', 'varchar(200)')) AS "DESTINATARIO", 
					f.x.value('DATA_FATURA[1]', 'varchar(10)') AS "DATA_FATURA", 
					f.x.value('PACKING_SLIP[1]', 'varchar(25)') AS "PACKING_SLIP", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('DESIGNACAO_MERCADORIA[1]', 'varchar(100)')) AS "DESIGNACAO_MERCADORIA", 
					f.x.value('PAIS_ORIGEM_MERCADORIA[1]', 'varchar(3)') AS "PAIS_ORIGEM_MERCADORIA", 
					f.x.value('AUTORIZ_REGIME_EVOLUCAO[1]', 'varchar(35)') AS "AUTORIZ_REGIME_EVOLUCAO", 
					f.x.value('DT_AUTORIZ_REGIME_EVOLUCAO[1]', 'varchar(10)') AS "DT_AUTORIZ_REGIME_EVOLUCAO", 
					f.x.value('AUTORIZACAO_PREC[1]', 'varchar(35)') AS "AUTORIZACAO_PREC", 
					f.x.value('GARANTIA[1]', 'varchar(10)') AS "GARANTIA", 
					f.x.value('VALOR_FRETE_LOTE[1]', 'varchar(45)') AS "VALOR_FRETE_LOTE", 
					f.x.value('TAXA_CAMBIO[1]', 'varchar(45)') AS "TAXA_CAMBIO", 
					f.x.value('CODIGO_MOEDA_FATURACAO[1]', 'varchar(3)') AS "CODIGO_MOEDA_FATURACAO", 
					f.x.value('TAXA_CAMBIO_PREC[1]', 'varchar(45)') AS "TAXA_CAMBIO_PREC", 
					f.x.value('NUMERO_CERTIFICADO[1]', 'varchar(100)') AS "NUMERO_CERTIFICADO", 
					f.x.value('DATA_CERTIFICADO[1]', 'varchar(10)') AS "DATA_CERTIFICADO", 
					f.x.value('COD_OPERACAO[1]', 'varchar(10)') AS "COD_OPERACAO", 
					f.x.value('TIPO_PROCEDIMENTO[1]', 'varchar(20)') AS "TIPO_PROCEDIMENTO", 
					f.x.value('DOCS_USAR_DESP_EXP[1]', 'varchar(10)') AS "DOCS_USAR_DESP_EXP" 
				FROM @TmpFicheiroOGMA AS fch	
					CROSS APPLY fch.FICHEIRO.nodes('FICH_DESPCHANTE_LINE') AS f(x)
					INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON fch.DUC_IDTY = duc.DUC_IDTY	
					INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM AND fch.DUA_CODI = dua.DUA_CODI
				ORDER BY fch.ID
				FOR XML PATH('FICH_DESPCHANTE_LINE'), TYPE)				
			FOR XML PATH('FICH_DESPCHANTE'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH				
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ExportaFicheiroOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ExportaFicheiroOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ExportaFicheirosXMLResposta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ExportaFicheirosXMLResposta] @DataReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @DataAtual datetime, @DirGeracaoFicheiro nvarchar(500), @AnoDeclaracao int, @NumDeclaracao int, @CodResposta int, @EstadoOperacao varchar(3), @FicheiroXML xml, @PathFicheiroTmpXML nvarchar(4000)		
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem a diretoria p/ geração do ficheiro XML
	SELECT @DirGeracaoFicheiro = PFC_PEPA 
	FROM TAB_PFCT WITH(NOLOCK)
-- obtem a lista de respostas de "Entrada" inseridas e ainda não exportadas
	DECLARE Respostas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT DUC_EANO, DUC_PNUM, DRP_CODI, DRP_ESTO
		FROM PRO_DURP WITH(NOLOCK)
		WHERE DRP_FLUX = 0 AND DRP_EXPO = 0 AND CAST(CONVERT(varchar(10), DRP_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, DRP_DATA), 105) AS datetime)
	OPEN Respostas
	FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @EstadoOperacao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro de dados da resposta
		SET @FicheiroXML = 				
			(SELECT 
				NULLIF(mvl.D31_NUME, '') as "numeroLocalObjecto", 
				NULLIF(duc.DUC_CPRT, '') as "numeroOrigemObjecto", 			
				NULLIF(duc.DUC_NORD, '') as "numeroOrdem",
				res.DRP_ESTO as "incidencia",
				(CASE WHEN DRP_ESTO IN ('RE', 'AP', 'ALT') THEN CAST(res.DRP_RESP as varchar(1000)) ELSE NULL END) as "descricaoIncidencia",
				CONVERT(varchar(19), res.DRP_DATA, 120) as "dataIncidencia"
			FROM PRO_DURP AS res WITH(NOLOCK) INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON res.DUC_EANO = duc.DUC_EANO AND res.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM AND dua.DUA_CODI = 1
				LEFT OUTER JOIN PRO_DU31 AS mvl WITH(NOLOCK) ON dua.DUC_EANO = mvl.DUC_EANO AND dua.DUC_PNUM = mvl.DUC_PNUM AND dua.DUA_CODI = mvl.DUA_CODI AND mvl.D31_CODI = 1
			WHERE res.DUC_EANO = @AnoDeclaracao AND res.DUC_PNUM = @NumDeclaracao AND res.DRP_CODI = @CodResposta			
			FOR XML PATH('INCIDENCIA'), ELEMENTS)		
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirGeracaoFicheiro + '\' + CAST(@NumDeclaracao AS varchar(20)) + '_' + @EstadoOperacao + '_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML c/ encoding UTF-8
		EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroTmpXML			
-- atualiza resposta p/ sinalizar como já enviada
		UPDATE PRO_DURP SET DRP_EXPO = 1
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DRP_CODI = @CodResposta			
		FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @EstadoOperacao
	END
	CLOSE Respostas
	DEALLOCATE Respostas	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ExportaFicheirosXMLResposta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ExportaFicheirosXMLResposta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ExportaFicheirosXMLRespostaKHUNENAGEL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ExportaFicheirosXMLRespostaKHUNENAGEL] @DirDestinoFicheirosXML varchar(500), @DataReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @CodResposta int, @NumeroOrdem varchar(20), @NumeroRefLocal varchar(22), @FicheiroXML xml, @PathFicheiroTmpXML nvarchar(4000), @IDTabelaTmp varchar(100), 
		@Comando nvarchar(4000) 
-- verifica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirDestinoFicheirosXML), 1, 1) <> '\'
		SET @DirDestinoFicheirosXML = @DirDestinoFicheirosXML + '\'
-- obtem a lista de respostas de "Entrada" inseridas, ainda não exportadas, com o estado de operação como "AP" e cuja declaração tem n.º ordem e o país é "GB" para construir a mensagem "customsDeclarationSubmitted"
	DECLARE Respostas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT res.DUC_EANO, res.DUC_PNUM, res.DRP_CODI, duc.DUC_NORD
		FROM PRO_DURP AS res WITH(NOLOCK) INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON res.DUC_EANO = duc.DUC_EANO AND res.DUC_PNUM = duc.DUC_PNUM		
		WHERE res.DRP_FLUX = 0 AND res.DRP_EXPO = 0 AND res.DRP_ESTO = 'AP' AND ISNULL(duc.DUC_NORD, '') <> '' AND duc.PAI_PA15 = 'GB' AND CAST(CONVERT(varchar(10), DRP_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, DRP_DATA), 105) AS datetime)
	OPEN Respostas
	FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroOrdem
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro XML customsDeclarationSubmitted
		SET @FicheiroXML = 				
			(SELECT 
				(SELECT NULLIF(duc.PAI_PA15, '') AS "countryOfOrigin",
					NULLIF(duc.PAI_PA17, '') AS "countryOfDestination", 
					NULLIF(duc.DUC_CPRT, '') AS "identificationNumber", 
					'IMPORT' AS "customsProcedure", 
					NULLIF(duc.DUC_NORD, '') AS "customerReference" 
				FOR XML PATH('customsDeclarationReference'), TYPE),
				CONVERT(datetime, duc.DUC_DENV, 126) AS "statusDate"
			FROM PRO_DUCG AS duc WITH(NOLOCK) 
			WHERE duc.DUC_EANO = @AnoDeclaracao AND duc.DUC_PNUM = @NumDeclaracao
			FOR XML PATH('customsDeclarationSubmitted'), ELEMENTS)		
-- obtem nome p/ tabela temporaria do XML
		SET @IDTabelaTmp = '##_tmpTABExportXML_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '')
-- cria tabela temporaria p/ XML e insere o XML
		SET @Comando = N'CREATE TABLE ' + @IDTabelaTmp + ' (Bulkcol xml) INSERT INTO ' + @IDTabelaTmp + '(Bulkcol) VALUES(@FicheiroXML)'	
		EXECUTE sp_executesql @Comando, N'@FicheiroXML xml', @FicheiroXML
-- constroi full path para geração do ficheiro XML customsDeclarationSubmitted
		SET @PathFicheiroTmpXML = @DirDestinoFicheirosXML + 'sacs-customs-declaration-submitted-' + @NumeroOrdem + '-' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML de customsDeclarationSubmitted
		SET @Comando = 'bcp "SELECT Bulkcol FROM ' + @IDTabelaTmp + '" queryout "' + @PathFicheiroTmpXML + '" -w -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
-- remove tabela temporaria criada p/ XML 	
		SET @Comando = N'DROP TABLE ' + @IDTabelaTmp
		EXECUTE sp_executesql @Comando				
-- atualiza resposta p/ sinalizar como já enviada
		UPDATE PRO_DURP SET DRP_EXPO = 1
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DRP_CODI = @CodResposta
			
		FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroOrdem
	END
	CLOSE Respostas
	DEALLOCATE Respostas
-- obtem a lista de respostas de "Entrada" inseridas, ainda não exportadas, com o estado de operação como "AS" e cuja declaração tem AS e o país é "GB" para construir a mensagem "customsDeclarationCleared"
	DECLARE Respostas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT res.DUC_EANO, res.DUC_PNUM, res.DRP_CODI, duc.DUC_NORD
		FROM PRO_DURP AS res WITH(NOLOCK) INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON res.DUC_EANO = duc.DUC_EANO AND res.DUC_PNUM = duc.DUC_PNUM		
		WHERE res.DRP_FLUX = 0 AND res.DRP_EXPO = 0 AND res.DRP_ESTO = 'AS' AND duc.DUC_ASAI = 1 AND duc.PAI_PA15 = 'GB' AND CAST(CONVERT(varchar(10), DRP_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, DRP_DATA), 105) AS datetime)
	OPEN Respostas
	FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroOrdem
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro XML customsDeclarationCleared
		SET @FicheiroXML = 				
			(SELECT 
				(SELECT NULLIF(duc.PAI_PA15, '') AS "countryOfOrigin",
					NULLIF(duc.PAI_PA17, '') AS "countryOfDestination", 
					NULLIF(duc.DUC_CPRT, '') AS "identificationNumber", 
					'IMPORT' AS "customsProcedure", 
					NULLIF(duc.DUC_CPRT, '') AS "customerReference" 
				FOR XML PATH('customsDeclarationReference'), TYPE),
				CONVERT(datetime, res.DRP_DATA, 126) AS "statusDate"
			FROM PRO_DUCG AS duc WITH(NOLOCK) INNER JOIN PRO_DURP AS res WITH(NOLOCK) ON duc.DUC_EANO = res.DUC_EANO AND duc.DUC_PNUM = res.DUC_PNUM AND res.DRP_CODI = @CodResposta
			WHERE duc.DUC_EANO = @AnoDeclaracao AND duc.DUC_PNUM = @NumDeclaracao
			FOR XML PATH('customsDeclarationCleared'), ELEMENTS)		
-- obtem nome p/ tabela temporaria do XML
		SET @IDTabelaTmp = '##_tmpTABExportXML_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '')
-- cria tabela temporaria p/ XML e insere o XML
		SET @Comando = N'CREATE TABLE ' + @IDTabelaTmp + ' (Bulkcol xml) INSERT INTO ' + @IDTabelaTmp + '(Bulkcol) VALUES(@FicheiroXML)'	
		EXECUTE sp_executesql @Comando, N'@FicheiroXML xml', @FicheiroXML
-- constroi full path para geração do ficheiro XML customsDeclarationCleared
		SET @PathFicheiroTmpXML = @DirDestinoFicheirosXML + 'sacs-customs-declaration-cleared-' + @NumeroOrdem + '-' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML de customsDeclarationCleared
		SET @Comando = 'bcp "SELECT Bulkcol FROM ' + @IDTabelaTmp + '" queryout "' + @PathFicheiroTmpXML + '" -w -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
-- remove tabela temporaria criada p/ XML 	
		SET @Comando = N'DROP TABLE ' + @IDTabelaTmp
		EXECUTE sp_executesql @Comando				
-- atualiza resposta p/ sinalizar como já enviada
		UPDATE PRO_DURP SET DRP_EXPO = 1
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DRP_CODI = @CodResposta
			
		FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroOrdem
	END
	CLOSE Respostas
	DEALLOCATE Respostas	
-- obtem a lista de respostas de "Entrada" inseridas, ainda não exportadas, com o estado de operação como "RE" e cuja declaração não tem n.º ordem e o país é "GB" para construir a mensagem "customsStatusRejectedCustomsAuthority"
	DECLARE Respostas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT res.DUC_EANO, res.DUC_PNUM, res.DRP_CODI, duc.DUC_NRLO
		FROM PRO_DURP AS res WITH(NOLOCK) INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON res.DUC_EANO = duc.DUC_EANO AND res.DUC_PNUM = duc.DUC_PNUM		
		WHERE res.DRP_FLUX = 0 AND res.DRP_EXPO = 0 AND res.DRP_ESTO = 'RE' AND ISNULL(duc.DUC_NORD, '') = '' AND duc.PAI_PA15 = 'GB' AND CAST(CONVERT(varchar(10), DRP_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, DRP_DATA), 105) AS datetime)
	OPEN Respostas
	FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroRefLocal
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro XML customsStatusRejectedCustomsAuthority
		SET @FicheiroXML = 				
			(SELECT 
				(SELECT NULLIF(duc.PAI_PA15, '') AS "countryOfOrigin",
					NULLIF(duc.PAI_PA17, '') AS "countryOfDestination", 
					NULLIF(duc.DUC_CPRT, '') AS "identificationNumber", 
					'IMPORT' AS "customsProcedure", 
					NULLIF(duc.DUC_CPRT, '') AS "customerReference" 
				FOR XML PATH('customsDeclarationReference'), TYPE),
				CONVERT(datetime, res.DRP_DATA, 126) AS "statusDate", 
				'IM002A' AS "customsMessage", 
				(SELECT '01' AS "line", 
					NULLIF(CAST(res.DRP_RESP AS varchar(MAX)), '') AS "message"					
				FOR XML PATH('rejectionReasons'), TYPE)
			FROM PRO_DUCG AS duc WITH(NOLOCK) INNER JOIN PRO_DURP AS res WITH(NOLOCK) ON duc.DUC_EANO = res.DUC_EANO AND duc.DUC_PNUM = res.DUC_PNUM AND res.DRP_CODI = @CodResposta
			WHERE duc.DUC_EANO = @AnoDeclaracao AND duc.DUC_PNUM = @NumDeclaracao
			FOR XML PATH('customsStatusRejectedCustomsAuthority'), ELEMENTS)		
-- obtem nome p/ tabela temporaria do XML
		SET @IDTabelaTmp = '##_tmpTABExportXML_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '')
-- cria tabela temporaria p/ XML e insere o XML
		SET @Comando = N'CREATE TABLE ' + @IDTabelaTmp + ' (Bulkcol xml) INSERT INTO ' + @IDTabelaTmp + '(Bulkcol) VALUES(@FicheiroXML)'	
		EXECUTE sp_executesql @Comando, N'@FicheiroXML xml', @FicheiroXML
-- constroi full path para geração do ficheiro XML customsStatusRejectedCustomsAuthority
		SET @PathFicheiroTmpXML = @DirDestinoFicheirosXML + 'sacs-customs-declaration-rejected-by-customs-authority-' + @NumeroRefLocal + '-' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML de customsStatusRejectedCustomsAuthority
		SET @Comando = 'bcp "SELECT Bulkcol FROM ' + @IDTabelaTmp + '" queryout "' + @PathFicheiroTmpXML + '" -w -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
-- remove tabela temporaria criada p/ XML 	
		SET @Comando = N'DROP TABLE ' + @IDTabelaTmp
		EXECUTE sp_executesql @Comando				
-- atualiza resposta p/ sinalizar como já enviada
		UPDATE PRO_DURP SET DRP_EXPO = 1
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DRP_CODI = @CodResposta
			
		FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroRefLocal
	END
	CLOSE Respostas
	DEALLOCATE Respostas
-- obtem a lista de respostas de "Entrada" inseridas, ainda não exportadas, com o estado de operação como "ND" e cuja declaração tem n.º ordem e o país é "GB" para construir a mensagem "customsStatusDuties"
	DECLARE Respostas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT res.DUC_EANO, res.DUC_PNUM, res.DRP_CODI, duc.DUC_NORD
		FROM PRO_DURP AS res WITH(NOLOCK) INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON res.DUC_EANO = duc.DUC_EANO AND res.DUC_PNUM = duc.DUC_PNUM		
		WHERE res.DRP_FLUX = 0 AND res.DRP_EXPO = 0 AND res.DRP_ESTO = 'ND' AND ISNULL(duc.DUC_NORD, '') <> '' AND duc.PAI_PA15 = 'GB' AND CAST(CONVERT(varchar(10), DRP_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, DRP_DATA), 105) AS datetime)
	OPEN Respostas
	FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroOrdem
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro XML customsStatusDuties
		SET @FicheiroXML = 				
			(SELECT 
				(SELECT NULLIF(duc.PAI_PA15, '') AS "countryOfOrigin",
					NULLIF(duc.PAI_PA17, '') AS "countryOfDestination", 
					NULLIF(duc.DUC_CPRT, '') AS "identificationNumber", 
					'IMPORT' AS "customsProcedure", 
					NULLIF(duc.DUC_CPRT, '') AS "customerReference" 
				FOR XML PATH('customsDeclarationReference'), TYPE), 
				(SELECT
					(SELECT 'CUSTOMS' AS "dutiesGroup", 
						NULLIF(doi.DUO_IMPO, '') AS "dutiesType",  
						CAST(SUM(ISNULL(doi.DUO_MONT, 0)) AS decimal(18, 2)) AS "dutiesAmount", 
						CAST(SUM(ISNULL(doi.DUO_TXVL, 0)) AS decimal(18, 2)) AS "dutiesRate", 						
						'EUR' AS "currency"
					FROM PRO_DUOI AS doi WITH(NOLOCK) 
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
					GROUP BY doi.DUO_IMPO
					FOR XML PATH('duty'), TYPE)
				FOR XML PATH('duties'), TYPE)				
			FROM PRO_DUCG AS duc WITH(NOLOCK) 
			WHERE duc.DUC_EANO = @AnoDeclaracao AND duc.DUC_PNUM = @NumDeclaracao
			FOR XML PATH('customsStatusDuties'), ELEMENTS)		
-- obtem nome p/ tabela temporaria do XML
		SET @IDTabelaTmp = '##_tmpTABExportXML_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '')
-- cria tabela temporaria p/ XML e insere o XML
		SET @Comando = N'CREATE TABLE ' + @IDTabelaTmp + ' (Bulkcol xml) INSERT INTO ' + @IDTabelaTmp + '(Bulkcol) VALUES(@FicheiroXML)'	
		EXECUTE sp_executesql @Comando, N'@FicheiroXML xml', @FicheiroXML
-- constroi full path para geração do ficheiro XML customsStatusDuties
		SET @PathFicheiroTmpXML = @DirDestinoFicheirosXML + 'sacs-customs-declaration-duties-' + @NumeroOrdem + '-' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML de customsStatusDuties
		SET @Comando = 'bcp "SELECT Bulkcol FROM ' + @IDTabelaTmp + '" queryout "' + @PathFicheiroTmpXML + '" -w -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
-- remove tabela temporaria criada p/ XML 	
		SET @Comando = N'DROP TABLE ' + @IDTabelaTmp
		EXECUTE sp_executesql @Comando				
-- atualiza resposta p/ sinalizar como já enviada
		UPDATE PRO_DURP SET DRP_EXPO = 1
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DRP_CODI = @CodResposta
			
		FETCH NEXT FROM Respostas INTO @AnoDeclaracao, @NumDeclaracao, @CodResposta, @NumeroOrdem
	END
	CLOSE Respostas
	DEALLOCATE Respostas
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ExportaFicheirosXMLRespostaKHUNENAGEL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ExportaFicheirosXMLRespostaKHUNENAGEL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ExportaFicheiroTXTVeiculosRENAULTDACIA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ExportaFicheiroTXTVeiculosRENAULTDACIA] @LstDeclaracoes xml, @FicheiroTXT varchar(MAX) OUTPUT, @MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @DataHoraAtual datetime, @CodEstancia varchar(8), @NumOrdem varchar(20), @DataOrdem datetime, @DataHoraCriacao datetime, @Chassi varchar(22)
-- obtem a data hora atual
	SET @DataHoraAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia variaveis
	SET @FicheiroTXT = ''
-- obtem os chassis dos veiculos da 1ª adição das declarações especificadas
	DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT duc.ALF_CODI, duc.DUC_NORD, duc.DUC_NDAT, duc.DUC_DTCR, dch.DVC_CHAS
		FROM @LstDeclaracoes.nodes('LstDeclaracoes/Declaracao') AS XML_DECS(DEC_DATA) INNER JOIN PRO_DUCG AS duc ON XML_DECS.DEC_DATA.value('DUC_EANO[1]', 'int') = duc.DUC_EANO AND XML_DECS.DEC_DATA.value('DUC_PNUM[1]', 'int') = duc.DUC_PNUM
			INNER JOIN PRO_DUAD AS dua ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM AND dua.DUA_CODI = 1
			INNER JOIN PRO_DUBT AS dve ON dua.DUC_EANO = dve.DUC_EANO AND dua.DUC_PNUM = dve.DUC_PNUM AND dua.DUA_CODI = dve.DUA_CODI
			INNER JOIN PRO_DUVE AS dch ON dve.DUC_EANO = dch.DUC_EANO AND dve.DUC_PNUM = dch.DUC_PNUM AND dve.DUA_CODI = dch.DUA_CODI AND dve.DBT_CODI = dch.DBT_CODI		
		ORDER BY dch.DUC_EANO, dch.DUC_PNUM, dch.DUA_CODI, dch.DBT_CODI, dch.DVC_CODI
	OPEN Chassis
	FETCH NEXT FROM Chassis INTO @CodEstancia, @NumOrdem, @DataOrdem, @DataHoraCriacao, @Chassi
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @FicheiroTXT = @FicheiroTXT + @Chassi + REPLICATE(' ', 25 - LEN(@Chassi))
		SET @FicheiroTXT = @FicheiroTXT + CONVERT(varchar(8), @DataHoraCriacao, 112) 
		SET @FicheiroTXT = @FicheiroTXT + '2'
		SET @FicheiroTXT = @FicheiroTXT + @CodEstancia + REPLICATE(' ', 8 - LEN(@CodEstancia))
		SET @FicheiroTXT = @FicheiroTXT + STR(YEAR(@DataOrdem), 4)
		SET @FicheiroTXT = @FicheiroTXT + RIGHT(@NumOrdem, 8) + REPLICATE(' ', 8 - LEN(RIGHT(@NumOrdem, 8)))
		SET @FicheiroTXT = @FicheiroTXT + CONVERT(varchar(8), @DataOrdem, 112) 
		SET @FicheiroTXT = @FicheiroTXT + CONVERT(varchar(8), @DataHoraAtual, 112)
		SET @FicheiroTXT = @FicheiroTXT + REPLACE(CONVERT(varchar(8), @DataHoraAtual, 114), ':', '')
		SET @FicheiroTXT = @FicheiroTXT + CHAR(13) + CHAR(10)
		FETCH NEXT from Chassis into @CodEstancia, @NumOrdem, @DataOrdem, @DataHoraCriacao, @Chassi
	END
	CLOSE Chassis
	DEALLOCATE Chassis
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ExportaFicheiroTXTVeiculosRENAULTDACIA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ExportaFicheiroTXTVeiculosRENAULTDACIA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_GeraDeclaracoesDeXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_DeclImportacao_GeraDeclaracoesDeXML] @XMLDeclaracoes xml(XMLSC_DeclaracoesImpToGIDWin), @Utilizador varchar(30), @MensagemErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @NumErro int, @CamposAdicionais int, @DataAtual datetime, @ExtraFieldUPDATEValue varchar(20), @Resultado int, @AuxMsgErro varchar(MAX), @Acao varchar(1), 
		@Data datetime, @CodNatureza varchar(3), @NumDocTransporte varchar(18), @CodTipoDeclaracao varchar(4), @CodEstancia varchar(8), @CodExpedidor varchar(18), 
		@CodDestinatario varchar(18), @CodDeclarante varchar(6), @CodPais15A varchar(2), @CodPais16 varchar(2), @CodPais17 varchar(2), @CodMeioTransporte18 varchar(2), 
		@IdMeioTransporte varchar(30), @CodMeioTransporte21 varchar(2), @CodPais21 varchar(2), @TemContentores int, @CodCondEntrega varchar(3), 
		@DescricaoCondEntrega varchar(30), @CodNaturezaTransacao varchar(2), @CodEstanciaAduaneira varchar(8), @CodLocalAutorizado varchar(17), @CodArmazem varchar(17), 
		@CodPais22 varchar(2), @CodPaisFrete varchar(2), @CodPaisSeguro varchar(2), @NomeExpedidor varchar(70), @MoradaExpedidor varchar(70), @LocalidadeExpedidor varchar(35), 
		@CodPostalExpedidor varchar(12), @LocPostalExpedidor varchar(35), @NIFExpedidor varchar(18), @CodPaisExpedidor varchar(2), @NomeDestinatario varchar(70), 
		@MoradaDestinatario varchar(70), @LocalidadeDestinatario varchar(35), @CodPostalDestinatario varchar(12), @LocPostalDestinatario varchar(35), 
		@TelefoneDestinatario varchar(14), @EmailDestinatario varchar(200), @NIFDestinatario varchar(18), @TipoDestinatario int, @CodPaisDestinatario varchar(2), 
		@CodRegiaoDestinatario int, @ObsDesalfandegamento varchar(MAX), @NumRequerimento varchar(30), @NumDURetorno varchar(30), @T1Retorno varchar(30), @DataPrevVoo datetime, 
		@Payment int, @NumVossaReferencia varchar(50), @NumContaExpedidor varchar(10), @NumContaDestinatario varchar(10), @Aeroporto varchar(80), @PPouFC varchar(2), 
		@NumVoo varchar(20), @MiniCPA varchar(20), @Referencia1 varchar(50), @Referencia2 varchar(50), @ShipID varchar(11), @Tracking varchar(35), @DType varchar(2), 
		@PosicaoAviao varchar(9), @TipoCarga varchar(5), @NomeFileUPS varchar(100), @NomeDestinatario2 varchar(70), @MoradaDestinatario2 varchar(70), 
		@LocalidadeDestinatario2 varchar(35), @CodPostalDestinatario2 varchar(12), @LocPostalDestinatario2 varchar(35), @Gateway varchar(6), @Delegacao varchar(6), 
		@EDeclaracaoImportacao int, @ValorFreteCompanhia numeric(38, 6), @MoedaFreteCompanhia varchar(3), @NivelServico int, @CodFollowUp int, 
		@CodUtilizadorNomeado varchar(30), @DataDocCPA datetime, @TipoManifestoCAB varchar(1), @ValorDespesasDHL numeric(38, 6), @NumeroDGASDS varchar(50), 
		@Observacoes varchar(MAX), @CamposExtra xml, @NumeroPDDT int, @NumeroPDDTDev int, @NumeroTD int, @NumeroACTM int, @NumeroSequencia int, @Adicoes xml, @Manifestos xml, 
		@Incidencias xml, @Arquivos xml
	DECLARE @NumProxProcesso int, @AnoProcesso int, @Tipo int, @Referencia7 varchar(30), @DirArquivos varchar(250), @DescricaoCodAutorizado varchar(70), @CambioMoeda numeric(38, 6), 
		@CambioFrete numeric(38, 6), @CambioSeguro numeric(38, 6), @CodPaisVerbaTrans varchar(2), @NomeNatureza varchar(35), @NomeTipoDeclaracao varchar(35), @NomeEstancia varchar(70), 
		@NomePais15 varchar(35), @NomePais16 varchar(35), @NomePais17 varchar(35), @MoedaPais22 varchar(3), @MoedaPaisFrete varchar(3), @MoedaPaisSeguro varchar(3), 
		@MoedaPaisVerbaTrans varchar(3), @NomeDeclarante varchar(70), @CedulaDeclarante varchar(18), @NomeMeioTransporte18 varchar(35), @TipoMeioTransporte18 int, @NomeMeioTransporte21 varchar(35), 
		@PosArmazem varchar(4), @TipoDeclarante int, @1CasaTipoDeclaracao varchar(5), @2CasaTipoDeclaracao varchar(4), @CodClienteServico varchar(18), @NomeClienteServico varchar(70), 
		@ClienteBeneficiarioIVA bit, @NumCaucaoDeclarante varchar(17), @AnoCaucaoDeclarante varchar(4), @TipoCaucaoDeclarante varchar(1), @EntidadeCaucaoDeclarante int, @NIFDeclarante varchar(18), 
		@NumReferenciaLocal varchar(22), @NomeNaturezaTransacao varchar(70), @CodFormula int, @DescricaoFormula varchar(70), @FormulaFOB bit, @SomaFormula bit, 
		@OptativasMeioTransporte18 numeric(38, 6), @CodPreferencia varchar(3), @CodRegime varchar(4), @TotalAdicoes int, @MontanteTotal numeric(38, 6), @FreteTotal numeric(38, 6), 
		@SeguroTotal numeric(38, 6), @MassaLiquidaTotal numeric(38, 6), @MassaBrutaTotal numeric(38, 6), @ValorAduaneiroTotal numeric(38, 6), @TotalVolumes numeric(38, 6), 
		@TotalLinhasDirty numeric(38, 6), @TotalLinhasClean numeric(38, 6), @TotalLinhasScan numeric(38, 6), @TipoLocalicao varchar(2), @NomeEstanciaAduaneira varchar(70), 
		@ValorTrafego numeric(38, 6), @TotalLiquidacao numeric(38, 6), @NomeArmazem varchar(70), @CodTipoArmazem varchar(1), @NomeTipoArmazem varchar(35), @CodPaisArmazem varchar(2), 
		@NomePaisArmazem varchar(35)
	DECLARE @AcaoAdicao varchar(1), @NumAdicao int, @CodArtigoPautal varchar(22), @Designacao varchar(150), @CodPaisOrigem varchar(2), @CodPreferenciaAd varchar(3), @RegimeB varchar(6), 
		@MassaBruta numeric(38, 6), @MassaLiquida numeric(38, 6), @QtdUnidades numeric(38, 6), @PrecoAdicao numeric(38, 6), @Frete numeric(38, 6), @Seguro numeric(38, 6), @MetodoAvaliacao int, 
		@MarcasEVolumes xml, @DeclaracoesSumaria xml, @Documentos xml
	DECLARE @CodUnidMedida varchar(3), @TxIVA numeric(38, 6), @TipoTributacao int, @CodUnidSuplementar varchar(10), @CodRubricaPreferencia int, @TipoTaxaPreferencia int, 
		@Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @BaseTribDireitos numeric(38, 6), @ETxComposta bit, @TaxaValor numeric(38, 6), @MontanteDireitos numeric(38, 6), 
		@CodRubricaIVA int, @PrecoAdicaoEUR numeric(38, 6), @CodPautal varchar(22), @NomePaisOrigem varchar(35), @NomePreferencia varchar(70), @NomeUnidSuplementar varchar(10), 
		@NomeRubricaIVA varchar(70), @NomeUnidMedida varchar(35), @FatorUnidMedida numeric(38, 6), @ImposicaoDireitos varchar(3), @AdicionalTARIC varchar(10), @AdicionalIVA int, 
		@AdicionalIC1 varchar(4), @AdicionalIC2 varchar(4), @AdicionalIC3 varchar(4), @ImposicaoIVA varchar(3), @NomeRubricaPreferencia varchar(70), @ValorOptativas numeric(38, 6), 
		@BaseTribIVA numeric(38, 6), @MontanteIVA numeric(38, 6), @MontanteRubricaCTT numeric(38, 6), @MassaBrtTotalAdicoesXML numeric(38, 6), @MontanteTotalAdicoesXML numeric(38, 6), 
		@TotalVolumesXML numeric(38, 6), @NumCaucaoIVA varchar(17), @AnoCaucaoIVA varchar(4), @TipoCaucaoIVA varchar(1), @EntidadeCaucaoIVA int
	DECLARE @Marca varchar(20), @Numero varchar(20), @QtdVolumes numeric(38, 6), @CodUnidadeMedida varchar(3), @P bit, @R bit, @C bit, @LOptica varchar(30)
	DECLARE @NumMarca int, @NomeUnidadeMedida varchar(35), @VolsAZero bit	
	DECLARE @TipoDeclSumaria varchar(4), @CodDocumento varchar(5), @NumeroDeclSumaria varchar(20), @DataApresentacao datetime, @CodEstanciaDeclSumaria varchar(8), @Regime varchar(2)
	DECLARE @NumDeclSumaria int, @NomeEstanciaDeclSumaria varchar(35), @IdDeclSumaria varchar(20)		
	DECLARE @NumeroDocumento varchar(70), @DataEmissao datetime, @NomeDocumento varchar(150), @MontanteDocumento numeric(38, 6), @TipoDocumento int, @DocumentoAuto int 
	DECLARE @NumDocumento int, @IdDocumento int
	DECLARE @ImposicaoAuto int, @CodRubrica int, @NomeRubrica varchar(70), @RubricaIVA bit, @ImposicaoRubrica varchar(3), @TaxaValorImposicao numeric(38, 6), @BaseTribImposicao numeric(38, 6), 
		@MontanteImposicao numeric(38, 6), @ImposicaoTaxa bit, @NumCaucao varchar(17), @AnoCaucao varchar(4), @TipoCaucao varchar(1), @EntidadeCaucao int
	DECLARE @NumImposicao int
	DECLARE @CodPaisManifesto varchar(2), @DescricaoManifesto varchar(104), @ValorManifesto numeric(38, 6), @MoedaManifesto varchar(3), @TotalFaturaManifesto numeric(38, 6), @NumeroCPAManifesto varchar(35), 
		@PesoManifesto numeric(38, 6), @TipoManifesto int
	DECLARE @CodStatusIncidencia varchar(8), @DataInicio datetime, @DataFim datetime, @TipoIncidencia varchar(1), @DescricaoStatusIncidencia varchar(60), @ReleaseHoldIncidencia int
	DECLARE @NumLinhaManifesto int, @NumLinhaIncidencia int
	DECLARE @NomeFicheiro varchar(100), @DescricaoFicheiro varchar(150), @TipoFicheiro varchar(8), @OrigemFicheiro int, @FicheiroBase64 varchar(MAX)
	DECLARE @ExtFicheiro varchar(10), @PathFicheiro varchar(500), @FicheiroBinario varbinary(MAX), @Obj int
-- inicia variaveis 
	SET @NumErro = 0
	SET @MensagemErro = ''
-- obtem nos campos adicionais qual o tipo de empresa configurada
	SELECT TOP 1 @CamposAdicionais = ISNULL(PDE_CADI, 0)
	FROM TAB_PDES WITH(NOLOCK)
-- carrega declarações XML p/ INSERT
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT XML_DECL.DCL_DATA.value('@Acao[1]', 'varchar(1)'), XML_DECL.DCL_DATA.value('Data[1]', 'varchar(10)'), XML_DECL.DCL_DATA.value('CodNatureza[1]', 'varchar(3)'), 
			NULLIF(XML_DECL.DCL_DATA.value('NumDocTransporte[1]', 'varchar(18)'), ''), XML_DECL.DCL_DATA.value('CodTipoDeclaracao[1]', 'varchar(4)'), 
			XML_DECL.DCL_DATA.value('CodEstancia[1]', 'varchar(8)'), NULLIF(XML_DECL.DCL_DATA.value('CodExpedidor[1]', 'varchar(18)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodDestinatario[1]', 'varchar(18)'), ''), XML_DECL.DCL_DATA.value('CodDeclarante[1]', 'varchar(6)'), 
			NULLIF(XML_DECL.DCL_DATA.value('CodPais15A[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodPais16[1]', 'varchar(2)'), ''),  
			NULLIF(XML_DECL.DCL_DATA.value('CodPais17[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodMeioTransporte18[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('IdMeioTransporte[1]', 'varchar(30)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodMeioTransporte21[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodPais21[1]', 'varchar(2)'), ''), XML_DECL.DCL_DATA.value('TemContentores[1]', 'int'), 
			XML_DECL.DCL_DATA.value('CodCondEntrega[1]', 'varchar(3)'), NULLIF(XML_DECL.DCL_DATA.value('DescricaoCondEntrega[1]', 'varchar(30)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodNaturezaTransacao[1]', 'varchar(2)'), ''), XML_DECL.DCL_DATA.value('CodEstanciaAduaneira[1]', 'varchar(8)'), 
			XML_DECL.DCL_DATA.value('CodLocalAutorizado[1]', 'varchar(17)'), NULLIF(XML_DECL.DCL_DATA.value('CodArmazem[1]', 'varchar(17)'), ''), 
			XML_DECL.DCL_DATA.value('CodPais22[1]', 'varchar(2)'), NULLIF(XML_DECL.DCL_DATA.value('CodPaisFrete[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodPaisSeguro[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('NomeExpedidor[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('MoradaExpedidor[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocalidadeExpedidor[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodPostalExpedidor[1]', 'varchar(12)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocPostalExpedidor[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('NIFExpedidor[1]', 'varchar(18)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodPaisExpedidor[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('NomeDestinatario[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('MoradaDestinatario[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('LocalidadeDestinatario[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodPostalDestinatario[1]', 'varchar(12)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('LocPostalDestinatario[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('TelefoneDestinatario[1]', 'varchar(14)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('EmailDestinatario[1]', 'varchar(200)'), ''), NULLIF(XML_DECL.DCL_DATA.value('NIFDestinatario[1]', 'varchar(18)'), ''), 
			XML_DECL.DCL_DATA.value('TipoDestinatario[1]', 'int'), NULLIF(XML_DECL.DCL_DATA.value('CodPaisDestinatario[1]', 'varchar(2)'), ''), 
			XML_DECL.DCL_DATA.value('CodRegiaoDestinatario[1]', 'int'), NULLIF(XML_DECL.DCL_DATA.value('ObsDesalfandegamento[1]', 'varchar(MAX)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('NumRequerimento[1]', 'varchar(30)'), ''), NULLIF(XML_DECL.DCL_DATA.value('NumDURetorno[1]', 'varchar(30)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('T1Retorno[1]', 'varchar(30)'), ''), XML_DECL.DCL_DATA.value('DataPrevVoo[1]', 'varchar(10)'), XML_DECL.DCL_DATA.value('Payment[1]', 'int'), 
			NULLIF(XML_DECL.DCL_DATA.value('NumVossaReferencia[1]', 'varchar(50)'), ''), NULLIF(XML_DECL.DCL_DATA.value('NumContaExpedidor[1]', 'varchar(10)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('NumContaDestinatario[1]', 'varchar(10)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Aeroporto[1]', 'varchar(80)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('PPouFC[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('NumVoo[1]', 'varchar(20)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('MiniCPA[1]', 'varchar(20)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Referencia1[1]', 'varchar(50)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Referencia2[1]', 'varchar(50)'), ''), NULLIF(XML_DECL.DCL_DATA.value('ShipID[1]', 'varchar(11)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Tracking[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DType[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('PosicaoAviao[1]', 'varchar(9)'), ''), NULLIF(XML_DECL.DCL_DATA.value('TipoCarga[1]', 'varchar(5)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('NomeFileUPS[1]', 'varchar(100)'), ''), NULLIF(XML_DECL.DCL_DATA.value('NomeDestinatario2[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('MoradaDestinatario2[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocalidadeDestinatario2[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodPostalDestinatario2[1]', 'varchar(12)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocPostalDestinatario2[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Gateway[1]', 'varchar(6)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Delegacao[1]', 'varchar(6)'), ''), 
			XML_DECL.DCL_DATA.value('EDeclaracaoImportacao[1]', 'int'), ISNULL(XML_DECL.DCL_DATA.value('ValorFreteCompanhia[1]', 'numeric(38, 6)'), 0), 
			NULLIF(XML_DECL.DCL_DATA.value('MoedaFreteCompanhia[1]', 'varchar(3)'), ''), XML_DECL.DCL_DATA.value('NivelServico[1]', 'int'), 
			XML_DECL.DCL_DATA.value('CodFollowUp[1]', 'int'), NULLIF(XML_DECL.DCL_DATA.value('CodUtilizadorNomeado[1]', 'varchar(30)'), ''), 
			XML_DECL.DCL_DATA.value('DataDocCPA[1]', 'varchar(10)'), NULLIF(XML_DECL.DCL_DATA.value('TipoManifesto[1]', 'varchar(1)'), ''), 	
			ISNULL(XML_DECL.DCL_DATA.value('DespesasDHL[1]', 'numeric(38, 6)'), 0), NULLIF(XML_DECL.DCL_DATA.value('NumeroDGASDS[1]', 'varchar(50)'), ''),
			NULLIF(XML_DECL.DCL_DATA.value('Observacoes[1]', 'varchar(MAX)'), ''), XML_DECL.DCL_DATA.query('CamposExtra'), 
			XML_DECL.DCL_DATA.value('(DepositoTemporario/NumeroPDDT)[1]', 'int'), XML_DECL.DCL_DATA.value('(DepositoTemporario/NumeroPDDTDev)[1]', 'int'), 
			XML_DECL.DCL_DATA.value('(DepositoTemporario/NumeroTD)[1]', 'int'), XML_DECL.DCL_DATA.value('(DepositoTemporario/NumeroACTM)[1]', 'int'), 
			XML_DECL.DCL_DATA.value('(DepositoTemporario/NumeroSequencia)[1]', 'int'), XML_DECL.DCL_DATA.query('Adicoes'), 
			XML_DECL.DCL_DATA.query('Manifestos'), XML_DECL.DCL_DATA.query('Incidencias'), XML_DECL.DCL_DATA.query('Arquivos')
		FROM @XMLDeclaracoes.nodes('DeclaracoesImpToGIDWin/Declaracao') as XML_DECL(DCL_DATA)		
		WHERE XML_DECL.DCL_DATA.value('@Acao[1]', 'varchar(1)') IN ('I', 'U')
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @Acao, @Data, @CodNatureza, @NumDocTransporte, @CodTipoDeclaracao, @CodEstancia, @CodExpedidor, @CodDestinatario, @CodDeclarante, @CodPais15A, @CodPais16, 
		@CodPais17, @CodMeioTransporte18, @IdMeioTransporte, @CodMeioTransporte21, @CodPais21, @TemContentores, @CodCondEntrega, @DescricaoCondEntrega, @CodNaturezaTransacao, @CodEstanciaAduaneira, 
		@CodLocalAutorizado, @CodArmazem, @CodPais22, @CodPaisFrete, @CodPaisSeguro, @NomeExpedidor, @MoradaExpedidor, @LocalidadeExpedidor, @CodPostalExpedidor, @LocPostalExpedidor, 
		@NIFExpedidor, @CodPaisExpedidor, @NomeDestinatario, @MoradaDestinatario, @LocalidadeDestinatario, @CodPostalDestinatario, @LocPostalDestinatario, @TelefoneDestinatario, @EmailDestinatario, 
		@NIFDestinatario, @TipoDestinatario, @CodPaisDestinatario, @CodRegiaoDestinatario, @ObsDesalfandegamento, @NumRequerimento, @NumDURetorno, @T1Retorno, @DataPrevVoo, @Payment, 
		@NumVossaReferencia, @NumContaExpedidor, @NumContaDestinatario, @Aeroporto, @PPouFC, @NumVoo, @MiniCPA, @Referencia1, @Referencia2, @ShipID, @Tracking, @DType, @PosicaoAviao, @TipoCarga, 
		@NomeFileUPS, @NomeDestinatario2, @MoradaDestinatario2, @LocalidadeDestinatario2, @CodPostalDestinatario2, @LocPostalDestinatario2, @Gateway, @Delegacao, @EDeclaracaoImportacao, 
		@ValorFreteCompanhia, @MoedaFreteCompanhia, @NivelServico, @CodFollowUp, @CodUtilizadorNomeado, @DataDocCPA, @TipoManifestoCAB, @ValorDespesasDHL, @NumeroDGASDS, @Observacoes, @CamposExtra, 
		@NumeroPDDT, @NumeroPDDTDev, @NumeroTD, @NumeroACTM, @NumeroSequencia, @Adicoes, @Manifestos, @Incidencias, @Arquivos
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- inicia transacção para inserção dados da declaração
		BEGIN TRANSACTION	
		BEGIN TRY	
			SET @NumProxProcesso = NULL
			SET @AnoProcesso = NULL
			SET @ExtraFieldUPDATEValue = NULL
-- obtem data atual GMT
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem dados da Natureza
			SELECT @NomeNatureza = NDE_NOME
			FROM TAB_NDES WITH(NOLOCK)
			WHERE NDE_CODI = @CodNatureza	
-- obtem dados do Tipo de Declaração
			SELECT @NomeTipoDeclaracao = TDE_NOME, @Tipo = ISNULL(TDE_NATU, 1), @1CasaTipoDeclaracao = TDE_1CAS, @2CasaTipoDeclaracao = TDE_2CAS, @CodPreferencia = PRE_CODI, 
				@CodRegime = TDE_REGI
			FROM TAB_TDEC WITH(NOLOCK)
			WHERE TDE_CODI = @CodTipoDeclaracao			  
-- obtem dados das Estancias/Alfandegas
			SELECT @NomeEstancia = ALF_NOME
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE ALF_CODI = @CodEstancia	
			SELECT @NomeEstanciaAduaneira = ALF_NOME
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE ALF_CODI = @CodEstanciaAduaneira	
-- obtem dados do Local Autorizado
			SELECT @DescricaoCodAutorizado = LME_NOME
			FROM TAB_LMER WITH(NOLOCK)
			WHERE LME_CODI = @CodLocalAutorizado
-- obtem dados do Armazém
			SELECT @NomeArmazem = ARM_NOME, @CodTipoArmazem = TAR_CODI, @CodPaisArmazem = 'PT'
			FROM TAB_ARMZ WITH(NOLOCK)
			WHERE ARM_CODI = @CodArmazem
-- obtem dados do Tipo de Armazém
			SELECT @NomeTipoArmazem = TAR_DESC
			FROM TAB_TARM WITH(NOLOCK)
			WHERE TAR_CODI = @CodTipoArmazem
-- obtem dados da Natureza de Transação
			SELECT @NomeNaturezaTransacao = NTR_NOME
			FROM TAB_NTRA WITH(NOLOCK)
			WHERE NTR_CODI = @CodNaturezaTransacao		
-- obtem dados de Declarante
			SELECT @NomeDeclarante = DEC_NOME, @CedulaDeclarante = ISNULL(NULLIF(DEC_CEDU, ''), DEC_NIF), @TipoDeclarante = DEC_TIPO, @NumCaucaoDeclarante = DEC_NCA1, 
				@AnoCaucaoDeclarante = DEC_ACA1, @TipoCaucaoDeclarante = DEC_TCA1, @EntidadeCaucaoDeclarante = 0, @NIFDeclarante = DEC_NIF
			FROM TAB_DECL WITH(NOLOCK)
			WHERE DEC_CODI = @CodDeclarante		
-- obtem dados do Expedidor se este estiver preenchido
			IF @CodExpedidor IS NOT NULL
			BEGIN
				SELECT @NomeExpedidor = ISNULL(FOR_NOME, @NomeExpedidor), @MoradaExpedidor = ISNULL(FOR_MORA, @MoradaExpedidor), 
					@LocalidadeExpedidor = ISNULL(FOR_LOCA, @LocalidadeExpedidor), @CodPostalExpedidor = ISNULL(FOR_CPOS, @CodPostalExpedidor), 
					@LocPostalExpedidor = ISNULL(FOR_LPOS, @LocPostalExpedidor), @NIFExpedidor = ISNULL(FOR_NIF, @NIFExpedidor), 
					@CodPaisExpedidor = PAI_CODI
				FROM TAB_FORN WITH(NOLOCK)
				WHERE FOR_CODI = @CodExpedidor
			END
-- obtem dados do Destinatário se este estiver preenchido
			IF @CodDestinatario IS NOT NULL
			BEGIN
				SELECT @NomeDestinatario = cl.CLI_NOME, @MoradaDestinatario = cl.CLI_MORA, @LocalidadeDestinatario = ISNULL(cl.CLI_LOCA, @LocalidadeDestinatario), 
					@CodPostalDestinatario = ISNULL(cl.CLI_CPOS, @CodPostalDestinatario), @LocPostalDestinatario = ISNULL(cl.CLI_LPOS, @LocPostalDestinatario), 
					@NIFDestinatario = cl.CLI_NIF, @CodPaisDestinatario = cl.PAI_CODI, @CodRegiaoDestinatario = cl.RES_CODI, @AdicionalIVA = cl.CLI_AIVA, 
					@TipoDestinatario = ISNULL((CASE cl.CLI_TNIF WHEN 2 THEN 1 ELSE cl.CLI_TNIF END), @TipoDestinatario), @CodClienteServico = cl.CLI_SENT, 
					@NomeClienteServico = cs.CLI_NOME, @ClienteBeneficiarioIVA = (CASE WHEN (cl.CLI_BIVA = 1) AND (@Data >= CAST(CONVERT(varchar(10), cl.CLI_DIBI, 105) as datetime)) THEN 1 ELSE 0 END),
					@TelefoneDestinatario = ISNULL(cl.CLI_TELF, @TelefoneDestinatario), @EmailDestinatario = ISNULL(cl.CLI_EMAI, @EmailDestinatario)
				FROM TAB_CLIE AS cl WITH(NOLOCK) 
					LEFT OUTER JOIN TAB_CLIE AS cs WITH(NOLOCK) ON cl.CLI_SENT = cs.CLI_CODI
				WHERE cl.CLI_CODI = @CodDestinatario			
			END
			ELSE
				SELECT @ClienteBeneficiarioIVA = 0
-- obtem dados da Condição Entrega
			SELECT @DescricaoCondEntrega = (CASE WHEN @DescricaoCondEntrega IS NOT NULL THEN @DescricaoCondEntrega WHEN ISNULL(CEN_LOCT, 0) = 0 THEN NULL WHEN ISNULL(CEN_LOCD, 0) = 0 THEN @LocalidadeExpedidor ELSE @LocalidadeDestinatario END),
				@CodFormula = (CASE CEN_CODI WHEN 'XXX' THEN (CASE ISNULL(@CodPaisFrete, '') WHEN '' THEN FIN_CODI2 ELSE FIN_CODI1 END) ELSE (CASE WHEN CEN_FOR1 = 1 THEN FIN_CODI1 WHEN CEN_FOR2 = 1 THEN FIN_CODI2 WHEN CEN_FOR3 = 1 THEN FIN_CODI3 WHEN CEN_FOR4 = 1 THEN FIN_CODI4 WHEN CEN_FOR5 = 1 THEN FIN_CODI5 ELSE NULL END) END)					
			FROM TAB_CENT WITH(NOLOCK)
			WHERE CEN_CODI = @CodCondEntrega			
-- obtem dados em falta
			SELECT @AnoProcesso = YEAR(@Data), @CodPais15A = ISNULL(@CodPais15A, @CodPaisExpedidor), @CodPais16 = ISNULL(@CodPais16, @CodPaisExpedidor),
				@CodPais17 = ISNULL(@CodPais17, @CodPaisDestinatario), @CodPaisFrete = ISNULL(@CodPaisFrete, 'EU'), @CodPaisSeguro = ISNULL(@CodPaisSeguro, 'EU'), 
				@CodPaisVerbaTrans = 'EU', @CodMeioTransporte21 = ISNULL(@CodMeioTransporte21, @CodMeioTransporte18), @PosArmazem = ('C' + RIGHT(@NumDocTransporte, 1)), 
				@TipoLocalicao = (CASE WHEN @CodEstanciaAduaneira IS NOT NULL THEN 'EA' WHEN @CodLocalAutorizado IS NOT NULL THEN 'LA' ELSE NULL END)				
-- obtem câmbio do País do Frete
			SET @CambioFrete = dbo.FNT_Geral_ObtemCambio(0, @CodPaisFrete, @Data)		
-- obtem câmbio do País do Seguro
			SET @CambioSeguro = dbo.FNT_Geral_ObtemCambio(0, @CodPaisSeguro, @Data)										
-- obtem câmbio do País da Moeda
			SET @CambioMoeda = dbo.FNT_Geral_ObtemCambio(0, @CodPais22, @Data)			
-- ajusta valores de câmbio
			SELECT @CambioMoeda = (CASE @CambioMoeda WHEN 0 THEN 1 ELSE @CambioMoeda END), @CambioFrete = (CASE @CambioFrete WHEN 0 THEN 1 ELSE @CambioFrete END),
				@CambioSeguro = (CASE @CambioSeguro WHEN 0 THEN 1 ELSE @CambioSeguro END)
-- obtem o total de massa bruta, massa líquida e preço das adições existentes no xml da declaração
			SELECT @MassaBrtTotalAdicoesXML = SUM(XML_ADIC.ADI_DATA.value('MassaBruta[1]', 'numeric(38, 6)')), 				
				@MontanteTotalAdicoesXML = SUM(XML_ADIC.ADI_DATA.value('PrecoAdicao[1]', 'numeric(38, 6)'))
			FROM @Adicoes.nodes('Adicoes/Adicao') as XML_ADIC(ADI_DATA)	
-- obtem dados dos Meios de Transporte
			SELECT @NomeMeioTransporte18 = mtr.MTR_NOME, @TipoMeioTransporte18 = ISNULL(mtr.MTR_VPVL, 0), 
				@OptativasMeioTransporte18 = (CASE mtr.MTR_OPAU 
												WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
																	FROM TAB_MTRO WITH(NOLOCK) 
																	WHERE MTR_IDTY = mtr.MTR_IDTY 
																		AND @MassaBrtTotalAdicoesXML BETWEEN MTO_LMNP AND MTO_LMXP 
																		AND ROUND(@MontanteTotalAdicoesXML / @CambioMoeda, 2) BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
												ELSE ISNULL(mtr.MTR_VOP1, 0) 
											END)				
			FROM TAB_MTRA AS mtr WITH(NOLOCK)
			WHERE mtr.MTR_CODI = @CodMeioTransporte18			
			SELECT @NomeMeioTransporte21 = MTR_NOME
			FROM TAB_MTRA WITH(NOLOCK)
			WHERE MTR_CODI = @CodMeioTransporte21
-- obtem dados da formula obtida		
			SELECT @DescricaoFormula = NULLIF(FIN_DESC, ''), @FormulaFOB = FIN_VFOB, 
				@SomaFormula = (CASE 
									WHEN ISNULL(NULLIF(CHARINDEX('+', ISNULL(FIN_DESC, '')), 0), 999999999) < ISNULL(NULLIF(CHARINDEX('-', ISNULL(FIN_DESC, '')), 0), 999999999) THEN 1 
									ELSE 0 
								END)			
			FROM TAB_FINC WITH(NOLOCK)
			WHERE FIN_CODI = @CodFormula															
-- obtem dados dos vários Países		
			SELECT @NomePais15 = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPais15A
			SELECT @NomePais16 = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPais16
			SELECT @NomePais17 = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPais17
			SELECT @MoedaPais22 = PAI_PREF
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPais22
			SELECT @MoedaPaisFrete = PAI_PREF
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPaisFrete			
			SELECT @MoedaPaisSeguro = PAI_PREF
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPaisSeguro
			SELECT @MoedaPaisVerbaTrans = PAI_PREF
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPaisVerbaTrans
			SELECT @NomePaisArmazem = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPaisArmazem
-- obtem dados dos Parametros Despachos
			SELECT TOP 1 @NumProxProcesso = PDE_NPRO, @AdicionalIVA = ISNULL(@AdicionalIVA, PDE_ADIV), @ValorTrafego = (CASE @TipoMeioTransporte18 WHEN 2 THEN ISNULL(PDE_TPOS1, 0) ELSE 0 END), 
				@Referencia7 = REPLACE(REPLACE(REPLACE(PDE_RFC7, 'ANO', CAST(YEAR(@Data) as varchar(4))), 'PNUM', CAST(PDE_NPRO as varchar(50))), 'CC', ISNULL(@CodDestinatario, '')), 
				@DirArquivos = PDE_EPDI
			FROM TAB_PDES		
-- obtem mais dados em falta
			SELECT @NumReferenciaLocal = (CAST(YEAR(@Data) as varchar(4)) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 7 - LEN(CAST(@NumProxProcesso as varchar(50)))) + CAST(@NumProxProcesso as varchar(50))),				
				@TotalAdicoes = 0, @MontanteTotal = 0, @FreteTotal = 0, @SeguroTotal = 0, @MassaLiquidaTotal = 0, @MassaBrutaTotal = 0, @ValorAduaneiroTotal = 0, 
				@TotalVolumes = 0, @NumLinhaManifesto = 0, @NumLinhaIncidencia = 0, @TotalLinhasDirty = 0, @TotalLinhasClean = 0, @TotalLinhasScan = 0
-- se ação for de "Insert"
			IF @Acao = 'I'
			BEGIN
-- insere Dados Gerais da declaração
				INSERT INTO PRO_DUCG(DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, TDE_CODI, DUC_TIPO, ALF_CODI, DUC_ADI5, DUC_TVL6, DUC_REF7, PAI_PA10, DUC_EXP2, DUC_DST8, DEC_CO14, PAI_PA15, 
					PAI_P15A, PAI_PA16, PAI_PA17, PAI_P17A, PAI_P17B, MTR_PT18, DUC_MT18, DUC_OP18, DUC_CT18, MTR_FT21, PAI_PA21, DUC_CT19, CEN_CO20, DUC_FR20, DUC_DE20, NTR_CO24, DUC_LC27, 
					LME_CO30, DUC_LC30, PAI_PR22, DUC_MT22, DUC_TX23, DUC_FRET, PAI_FRET, DUC_TXFR, DUC_SEGU, PAI_SEGU, DUC_TXSE, DUC_MLQT, DUC_MBRT, DUC_VTRN, PAI_VTRN, DUC_TXVT, DUC_VEUR, 
					DUC_UFOB, DUC_VFOB, DUC_DIRT, DUC_TFDA, DUC_ENOM, DUC_EMOR, DUC_ELOC, DUC_ECPO, DUC_ELPO, DUC_ENIF, PAI_ELIV, DUC_DNOM, DUC_DMOR, DUC_DLOC, DUC_DCPO, DUC_DLPO, DUC_DNIF, 
					PAI_DLIV, DUC_HIST, DUC_VLRC, DUC_VLRE, DUC_VATT, DUC_UCRI, DUC_DTCR, NDE_NOME, TDE_NOME, ALF_NOME, PAI_NO10, PAI_NO15, PAI_NO16, PAI_NO17, PAI_MO22, PAI_MOFT, PAI_MOSG, 
					PAI_MOVT, DEC_NOME, DEC_CENI, MTR_NO18, MTR_NO21, DUC_DOBS, DUC_NREQ, DUC_NDUR, DUC_T1RE, DUC_VCHE, DUC_DTVO, DUC_PAYM, DUC_NPDT, DUC_NPDD, DUC_NTDP, DUC_NVRF, DUC_PARM, 
					DUC_TREM, DUC_CIEX, DUC_CIDE, DUC_AERO, DUC_PPFC, DUC_NVOO, DUC_MCPA, DUC_NSEQ, DUC_REF1, DUC_REF2, DUC_SHIP, DUC_TRAC, DUC_DTYP, DUC_POSA, DUC_TPCG, DUC_FUPS, DUC_VDIR, 
					DUC_VCLE, DUC_D2NO, DUC_D2MO, DUC_D2LO, DUC_D2CP, DUC_D2LP, FIN_CODI, MNF_PESO, MNF_PAIS, MNF_MOED, MNF_VALO, DUC_TPDS, DUC_TPDC, TDE_1CAS, TDE_2CAS, DUC_GTWY, DUC_DELG, 
					CLI_CODI, CLI_NOME, DUC_CGLB, DUC_CAUC, DUC_CANO, DUC_CTIP, DUC_TLOC, ALF_CODI1, ALF_NOME1, ARM_CODI, ARM_NOME, TAR_CODI, TAR_DESC, DUC_NRLO, DUC_DUNO, DUC_CENT, NTR_NOME, 
					DUC_VBAT, DUC_VSCA, DUC_VFRC, DUC_MFRC, DUC_NVSR, FUP_CODI, DUC_DDDT, DUC_UNMD, DUC_TMAN, DUC_NACT, DUC_BIVA, DUC_VDES, DUC_DTEL, DUC_DEMA)		
				VALUES(@NumProxProcesso, @AnoProcesso, @Data, @CodNatureza, @NumDocTransporte, @CodTipoDeclaracao, @Tipo, @CodEstancia, @TotalAdicoes, @TotalVolumes, @Referencia7, @CodPaisArmazem, @CodExpedidor, @CodDestinatario, @CodDeclarante, @CodPais15A, 
					@CodPais15A, @CodPais16, @CodPais17, @CodPais17, @CodRegiaoDestinatario, @CodMeioTransporte18, @IdMeioTransporte, @OptativasMeioTransporte18, @ValorTrafego, @CodMeioTransporte21, @CodPais21, @TemContentores, @CodCondEntrega, @DescricaoFormula, @DescricaoCondEntrega, @CodNaturezaTransacao, @NumeroDGASDS, 
					@CodLocalAutorizado, @DescricaoCodAutorizado, @CodPais22, @MontanteTotal, @CambioMoeda, @FreteTotal, @CodPaisFrete, @CambioFrete, @SeguroTotal, @CodPaisSeguro, @CambioSeguro, @MassaLiquidaTotal, @MassaBrutaTotal, 0.000000, @CodPaisVerbaTrans, 0.000000, 0.000000, 
					@FormulaFOB, 0.000000, 0.000000, 0.000000, @NomeExpedidor, @MoradaExpedidor, @LocalidadeExpedidor, @CodPostalExpedidor, @LocPostalExpedidor, @NIFExpedidor, @CodPaisExpedidor, @NomeDestinatario, @MoradaDestinatario, @LocalidadeDestinatario, @CodPostalDestinatario, @LocPostalDestinatario, @NIFDestinatario, 
					@CodPaisDestinatario, @Observacoes, 0.000000, NULL, @ValorAduaneiroTotal, @Utilizador, @DataAtual, @NomeNatureza, @NomeTipoDeclaracao, @NomeEstancia, @NomePaisArmazem, @NomePais15, @NomePais16, @NomePais17, @MoedaPais22, @MoedaPaisFrete, @MoedaPaisSeguro, 
					@MoedaPaisVerbaTrans, @NomeDeclarante, @CedulaDeclarante, @NomeMeioTransporte18, @NomeMeioTransporte21, @ObsDesalfandegamento, @NumRequerimento, @NumDURetorno, @T1Retorno, 0.000000, @DataPrevVoo, @Payment, @NumeroPDDT, @NumeroPDDTDev, @NumeroTD, @NumVossaReferencia, @PosArmazem, 
					@MassaBrutaTotal, @NumContaExpedidor, @NumContaDestinatario, @Aeroporto, @PPouFC, @NumVoo, @MiniCPA, @NumeroSequencia, @Referencia1, @Referencia2, @ShipID, @Tracking, @DType, @PosicaoAviao, @TipoCarga, @NomeFileUPS, @TotalLinhasDirty, 
					@TotalLinhasClean, @NomeDestinatario2, @MoradaDestinatario2, @LocalidadeDestinatario2, @CodPostalDestinatario2, @LocPostalDestinatario2, @CodFormula, @MassaBrutaTotal, @CodPais22, @MoedaPais22, @MontanteTotal, @TipoDestinatario, @TipoDeclarante, @1CasaTipoDeclaracao, @2CasaTipoDeclaracao, @Gateway, @Delegacao, 
					@CodClienteServico, @NomeClienteServico, 1, @NumCaucaoDeclarante, @AnoCaucaoDeclarante, @TipoCaucaoDeclarante, @TipoLocalicao, @CodEstanciaAduaneira, @NomeEstanciaAduaneira, @CodArmazem, @NomeArmazem, @CodTipoArmazem, @NomeTipoArmazem, @NumReferenciaLocal, @EDeclaracaoImportacao, @EntidadeCaucaoDeclarante, @NomeNaturezaTransacao, 
					1, @TotalLinhasScan, @ValorFreteCompanhia, @MoedaFreteCompanhia, @NivelServico, @CodFollowUp, @DataDocCPA, @CodUtilizadorNomeado, @TipoManifestoCAB, @NumeroACTM, @ClienteBeneficiarioIVA, @ValorDespesasDHL, @TelefoneDestinatario, @EmailDestinatario)				
-- actualiza Nº. Prox. Processo nos Parametros Despachos
				UPDATE TAB_PDES SET PDE_NPRO = PDE_NPRO + 1		
-- insere pedidos definidos no tipo de declaração no detalhe de Pedidos da declaração
				INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC)	
				SELECT @AnoProcesso, @NumProxProcesso, ROW_NUMBER() OVER(ORDER BY TDP_CODI), TXM_CODI, TDP_TEXT
				FROM TAB_TDEP WITH(NOLOCK)
				WHERE TDE_CODI = @CodTipoDeclaracao
				ORDER BY TDP_CODI	
			END	
			ELSE			
			BEGIN		
-- obtem o tipo de update especifico a realizar
				SELECT TOP 1 @ExtraFieldUPDATEValue = t.c.value('ValorCampoExtra[1]', 'varchar(20)')
				FROM @CamposExtra.nodes('CamposExtra/CampoExtra') AS t(c) 
				WHERE t.c.value('CodigoCampoExtra[1]', 'varchar(100)') = 'UPDATE' AND @CamposAdicionais = 3 --DHL						
-- obtem dados da declaração a actualizar
				IF @CamposAdicionais = 8 --ENTREPOSTO
				BEGIN
					SELECT @NumProxProcesso = DUC_PNUM, @CodMeioTransporte18 = MTR_PT18, @TotalLinhasClean = ISNULL(DUC_VCLE, 0), @TotalLinhasScan = DUC_VSCA
					FROM PRO_DUCG WITH(NOLOCK)
					WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = ISNULL((SELECT t.c.value('ValorCampoExtra[1]', 'varchar(20)')
																FROM @CamposExtra.nodes('CamposExtra/CampoExtra') AS t(c)
																WHERE t.c.value('CodigoCampoExtra[1]', 'varchar(100)') = 'DUC_PNUM'), -1)
				END	
				ELSE
				BEGIN
					SELECT TOP 1 @NumProxProcesso = DUC_PNUM, @AnoProcesso = DUC_EANO, @SeguroTotal = ISNULL(DUC_SEGU, 0), @CodMeioTransporte18 = MTR_PT18, 
						@TotalLinhasClean = ISNULL(DUC_VCLE, 0), @TotalLinhasScan = DUC_VSCA, 
						@TotalAdicoes = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_ADI5 ELSE @TotalAdicoes END), 
						@FreteTotal = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 <= 1) THEN @FreteTotal ELSE ISNULL(DUC_FRET, 0) END)						 						
					FROM PRO_DUCG WITH(NOLOCK)
					WHERE (DUC_EANO = YEAR(@DataAtual) or DUC_EANO = (YEAR(@DataAtual) - 1)) and DUC_CPRT = @NumDocTransporte and (CAST(CONVERT(varchar(10), DUC_DTVO, 105) as datetime) = CAST(CONVERT(varchar(10), @DataPrevVoo, 105) as datetime) or (DUC_DTVO IS NULL and @DataPrevVoo IS NULL))
				END
-- valida se declaração para actualização foi encontrada
				IF @NumProxProcesso IS NULL
				BEGIN
					IF @DataPrevVoo IS NOT NULL
						SELECT @AuxMsgErro = 'Declaração c/ Documento de Transporte N.º "' + @NumDocTransporte + '" e data de voo "' + CONVERT(varchar(10), @DataPrevVoo, 105) + '" não foi encontrada!'
					ELSE
						SELECT @AuxMsgErro = 'Declaração c/ Documento de Transporte N.º "' + @NumDocTransporte + '" e s/ data de voo não foi encontrada!'					
					RAISERROR(@AuxMsgErro, 16, 1)
				END
-- obtem dados dos Meios de Transporte
				SELECT @TipoMeioTransporte18 = ISNULL(mtr.MTR_VPVL, 0), @OptativasMeioTransporte18 = (CASE mtr.MTR_OPAU 
														WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
																			FROM TAB_MTRO WITH(NOLOCK) 
																			WHERE MTR_IDTY = mtr.MTR_IDTY 
																				AND @MassaBrtTotalAdicoesXML BETWEEN MTO_LMNP AND MTO_LMXP 
																				AND ROUND(@MontanteTotalAdicoesXML / @CambioMoeda, 2) BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
														ELSE ISNULL(mtr.MTR_VOP1, 0) 
													END)				
				FROM TAB_MTRA AS mtr WITH(NOLOCK)
				WHERE mtr.MTR_CODI = @CodMeioTransporte18	
-- remove o detalhe de Manifestos de linhas "Dirty" da declaração
				IF ISNULL(@ExtraFieldUPDATEValue, '') <> 'DHL-PORTAL'
				BEGIN
					DELETE FROM PRO_DUOD
					WHERE DUO_TIPO = 0 and DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProxProcesso
				END
-- processa a remoção de outros detalhes em função do tipo de empresa
				IF @CamposAdicionais = 8 --ENTREPOSTO
				BEGIN
-- remove o detalhe da Liquidação Recapitulativa da declaração
					DELETE FROM PRO_DULR
					WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProxProcesso
-- remove todas as Adições existentes na declaração
					DELETE FROM PRO_DUAD
					WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProxProcesso
				END
				ELSE
				IF ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL'
				BEGIN
					UPDATE PRO_DUCG SET 
						NDE_CODI = @CodNatureza, 
						NDE_NOME = @NomeNatureza, 	
						FUP_CODI = ISNULL(@CodFollowUp, FUP_CODI), 	
						DUC_UNMD = (CASE WHEN @CodFollowUp IS NOT NULL THEN NULL ELSE DUC_UNMD END),  
						/*DUC_TMSF = @TipoMascara,
						DUC_MASC = @CodMascara,*/
						CEN_CO20 = @CodCondEntrega, 
						DUC_DE20 = @DescricaoCondEntrega, 						 
						FIN_CODI = @CodFormula, 
						DUC_FR20 = @DescricaoFormula, 
						DUC_UFOB = @FormulaFOB, 
						DUC_VFOB = (CASE @FormulaFOB WHEN 0 THEN 0 ELSE DUC_VFOB END),																								
						PAI_FRET = (CASE WHEN DUC_ADI5 > 1 THEN PAI_FRET ELSE @CodPaisFrete END),
						PAI_MOFT = (CASE WHEN DUC_ADI5 > 1 THEN PAI_MOFT ELSE @MoedaPaisFrete END), 
						DUC_TXFR = (CASE WHEN DUC_ADI5 > 1 THEN DUC_TXFR ELSE @CambioFrete END), 
						DUC_DST8 = @CodDestinatario, 
						DUC_DNOM = @NomeDestinatario,
						DUC_DMOR = @MoradaDestinatario, 
						DUC_DLOC = @LocalidadeDestinatario, 
						DUC_DCPO = @CodPostalDestinatario,
						DUC_DLPO = @LocPostalDestinatario,
						DUC_DNIF = @NIFDestinatario, 
						PAI_DLIV = @CodPaisDestinatario, 
						DUC_TPDS = @TipoDestinatario, 
						CLI_CODI = @CodClienteServico,  
						CLI_NOME = @NomeClienteServico,  
						DUC_BIVA = @ClienteBeneficiarioIVA, 
						DUC_DTEL = @TelefoneDestinatario,
						DUC_DEMA = @EmailDestinatario,
						PAI_P17B = @CodRegiaoDestinatario, 
						DUC_REF7 = REPLACE(DUC_REF7, DUC_DST8, @CodDestinatario), 
						PAI_PA17 = @CodPais17, 
						PAI_NO17 = @NomePais17, 
						PAI_P17A = @CodPais17, 								
						DUC_UALT = @Utilizador, 
						DUC_DTAL = @DataAtual
					WHERE DUC_PNUM = @NumProxProcesso AND DUC_EANO = @AnoProcesso					
				END
				ELSE				
				BEGIN
-- remove o detalhe de Marcas e Volumes das adições da declaração
					DELETE FROM PRO_DU31
					WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProxProcesso
				END
			END	
-- altera ação da declaração de modo a ignorar a leitura das adições
			IF (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (@TotalAdicoes > 1) 
				SET @Acao = ''	
-- carrega Adições XML da declaração
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT ISNULL(NULLIF(XML_ADIC.ADI_DATA.value('@Acao[1]', 'varchar(1)'), ''), @Acao), XML_ADIC.ADI_DATA.value('NumAdicao[1]', 'int'), 
					XML_ADIC.ADI_DATA.value('CodArtigoPautal[1]', 'varchar(22)'), NULLIF(XML_ADIC.ADI_DATA.value('Designacao[1]', 'varchar(150)'), ''), 
					NULLIF(XML_ADIC.ADI_DATA.value('CodPaisOrigem[1]', 'varchar(2)'), ''), ISNULL(NULLIF(XML_ADIC.ADI_DATA.value('CodPreferencia[1]', 'varchar(3)'), ''), @CodPreferencia), 
					NULLIF(XML_ADIC.ADI_DATA.value('RegimeB[1]', 'varchar(6)'), ''), XML_ADIC.ADI_DATA.value('MassaBruta[1]', 'numeric(38, 6)'), 
					XML_ADIC.ADI_DATA.value('MassaLiquida[1]', 'numeric(38, 6)'), ISNULL(XML_ADIC.ADI_DATA.value('QtdUnidades[1]', 'numeric(38, 6)'), 0), 
					XML_ADIC.ADI_DATA.value('PrecoAdicao[1]', 'numeric(38, 6)'), ISNULL(XML_ADIC.ADI_DATA.value('Frete[1]', 'numeric(38, 6)'), 0), 
					ISNULL(XML_ADIC.ADI_DATA.value('Seguro[1]', 'numeric(38, 6)'), 0), ISNULL(XML_ADIC.ADI_DATA.value('MetodoAvaliacao[1]', 'int'), 1), 
					XML_ADIC.ADI_DATA.query('MarcasEVolumes'), XML_ADIC.ADI_DATA.query('DeclaracoesSumaria'), XML_ADIC.ADI_DATA.query('Documentos')
				FROM @Adicoes.nodes('Adicoes/Adicao') as XML_ADIC(ADI_DATA)
				WHERE ISNULL(NULLIF(XML_ADIC.ADI_DATA.value('@Acao[1]', 'varchar(1)'), ''), @Acao) IN ('I', 'U')
			OPEN Adicoes
			FETCH NEXT FROM Adicoes INTO @AcaoAdicao, @NumAdicao, @CodArtigoPautal, @Designacao, @CodPaisOrigem, @CodPreferenciaAd, @RegimeB, @MassaBruta, @MassaLiquida, @QtdUnidades, @PrecoAdicao, 
				@Frete, @Seguro, @MetodoAvaliacao, @MarcasEVolumes, @DeclaracoesSumaria, @Documentos
			WHILE @@FETCH_STATUS = 0
			BEGIN		
-- obtem o total de volumes existentes no xml da adição
				SELECT @TotalVolumesXML = SUM(XML_VOLS.VOL_DATA.value('QtdVolumes[1]', 'numeric(38, 6)'))
				FROM @MarcasEVolumes.nodes('MarcasEVolumes/MarcaEVolume') as XML_VOLS(VOL_DATA)			
-- obtem dados da Preferência
				SELECT @NomePreferencia = PRE_NOME, @CodRubricaPreferencia = RRE_CODI, @TipoTaxaPreferencia = PRE_TAXA
				FROM TAB_PREF WITH(NOLOCK)
				WHERE PRE_CODI = @CodPreferenciaAd				
-- obtem dados do Artigo Pautal
				SELECT @CodUnidMedida = UME_CODI, @TipoTributacao = ISNULL(APA_TRIB, 0), @CodUnidSuplementar = USU_CODI, @Designacao = ISNULL(@Designacao, APA_DESG), 
					@CodPautal = APA_CPAU, @AdicionalTARIC = APA_ATAR, @AdicionalIC1 = APA_AIC1, @AdicionalIC2 = APA_AIC2, @AdicionalIC3 = APA_AIC3, 
					@QtdUnidades = (CASE WHEN (@QtdUnidades > 0) AND (ISNULL(USU_CODI, '') = '') THEN 0 ELSE @QtdUnidades END), 
					@TxIVA = (CASE WHEN (SUBSTRING(@CodRegime, 1, 2) in ('42', '51', '53', '71')) or (@RegimeB in ('C08', 'C30')) THEN 0 
						ELSE ISNULL(APA_TIVA, 0) END), 										
					@TaxaValor = (CASE WHEN (SUBSTRING(@CodRegime, 1, 2) in ('51', '53', '71')) or (@RegimeB in ('C07', 'C08', 'C30')) THEN 0 
						ELSE (CASE ISNULL(APA_TRIB, 0) WHEN 0 THEN (CASE APA_TXCO WHEN 0 THEN (CASE WHEN (@QtdUnidades > 0) AND (ISNULL(USU_CODI, '') = '') THEN 0 ELSE @QtdUnidades END) ELSE 0 END) 
							WHEN 1 THEN (CASE @TipoTaxaPreferencia WHEN 1 THEN ISNULL(APA_TPMN, 0) 
								WHEN 2 THEN ISNULL((SELECT ISNULL(APS_SPMN, 0) FROM TAB_APSP WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_SPMN, 0)) 
								WHEN 3 THEN ISNULL((SELECT ISNULL(APE_EFMN, 0) FROM TAB_APEF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_EFMN, 0)) 
								ELSE 0 END) 
							WHEN 3 THEN (CASE @TipoTaxaPreferencia WHEN 1 THEN (ISNULL((SELECT ISNULL(APT_TFT, 0) + DATEDIFF(MONTH, APT_DATA, @DataAtual) * ISNULL(APT_INCR, 0) FROM TAB_APTF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), 0) + ISNULL(APA_TPT, 0)) 
								WHEN 2 THEN ISNULL((SELECT ISNULL(APS_SPG, 0) FROM TAB_APSP WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_SPG, 0)) 
								WHEN 3 THEN ISNULL((SELECT ISNULL(APE_EFTA, 0) FROM TAB_APEF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_EFTA, 0)) 
								ELSE 0 END) 
							ELSE 0 END) END), 					
					@ETxComposta = (CASE ISNULL(APA_TRIB, 0) WHEN 0 THEN (CASE APA_TXCO WHEN 0 THEN CAST(1 as bit) ELSE CAST(0 as bit) END) WHEN 1 THEN CAST(1 as bit) ELSE CAST(0 as bit) END)
				FROM TAB_APAU WITH(NOLOCK)
				WHERE APA_CODI = @CodArtigoPautal	
-- obtem dados da Unidade Suplementar
				SELECT @NomeUnidSuplementar = USU_SIGL
				FROM TAB_USUP WITH(NOLOCK)
				WHERE USU_CODI = @CodUnidSuplementar
-- obtem dados da Unidade Medida
				SELECT @NomeUnidMedida = UME_NOME, @FatorUnidMedida = UME_FACT
				FROM TAB_UMED WITH(NOLOCK)
				WHERE UME_CODI = @CodUnidMedida
-- obtem dados dos Parâmetros Aplicação
				SELECT TOP 1 @CodRubricaIVA = (CASE ROUND(@TxIVA, 2) WHEN PAP_TXIS THEN RRE_CDIS WHEN PAP_TXRD THEN RRE_CDRD WHEN PAP_TXIN THEN RRE_CDIN WHEN PAP_TXNR THEN RRE_CDNR ELSE NULL END)
				FROM TAB_PAPL WITH(NOLOCK)
-- obtem dados das Rubricas
				SELECT @NomeRubricaPreferencia = RRE_NOME, @ImposicaoDireitos = RRE_IMPO
				FROM TAB_RREC WITH(NOLOCK)
				WHERE RRE_CODI = @CodRubricaPreferencia
				SELECT @NomeRubricaIVA = RRE_NOME, @ImposicaoIVA = RRE_IMPO
				FROM TAB_RREC WITH(NOLOCK)
				WHERE RRE_CODI = @CodRubricaIVA
-- calula valor EUR da adição
				SET @PrecoAdicaoEUR = ROUND(@PrecoAdicao / @CambioMoeda, 2)					
-- calcula valor do ajustamento da adição
				SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@DescricaoFormula, 0, @CambioFrete, @CambioSeguro, @Frete, @Seguro, 0, 0, 0)					
-- calcula valor estatistico da adição
				SET @ValorEstatistico = dbo.fn_IMP_CalculaValorEstatistico(@PrecoAdicaoEUR, @Ajustamento)					
-- calcula valor da base de tributação dos direitos da adição				
				IF @TipoTributacao = 0
					SET @BaseTribDireitos = ROUND(@QtdUnidades / @FatorUnidMedida, 3)
				ELSE
					IF @TipoTributacao = 1
						SET @BaseTribDireitos = ROUND(@MassaLiquida / @FatorUnidMedida, 3)
					ELSE
						IF @TipoTributacao = 3
						BEGIN
							IF @SomaFormula = 1
								SET @BaseTribDireitos = ROUND(@ValorEstatistico, 3)
							ELSE
								SET @BaseTribDireitos = ROUND(@PrecoAdicaoEUR, 3)
						END
						ELSE	
							SET @BaseTribDireitos = 0		
-- calcula montante de tributação dos direitos da adição 
				SET @MontanteDireitos = dbo.fn_IMP_CalculaMontanteDireitos(0, 0, ~(@ETxComposta), @TaxaValor, @BaseTribDireitos)
-- calcula valor de optativas da adição 				
				IF @TipoMeioTransporte18 = 2 -- por volume
					SET @ValorOptativas = ROUND(@TotalVolumesXML * @OptativasMeioTransporte18, 2)			
				ELSE
					SET @ValorOptativas = ROUND(@MassaBruta * (@OptativasMeioTransporte18 * CEILING(@MassaBrtTotalAdicoesXML / 100)) / @MassaBrtTotalAdicoesXML, 2)
-- calcula montante p/ rubrica dos CTT a inserir no detalhe do anexo de Imposições da adição
				SET @MontanteRubricaCTT = ROUND(@ValorTrafego * @TotalVolumesXML, 2)					
-- calcula valor da base de tributação do IVA da adição	
				SET @BaseTribIVA = dbo.fn_IMP_CalculaBaseTributacaoIVA(@DescricaoFormula, 0, @CambioFrete, @Frete, @Ajustamento, @ValorEstatistico, 0, @ValorOptativas, @MontanteDireitos, 0, 0, @MontanteRubricaCTT)							
-- calcula montante de tributação do IVA da adição
				SET @MontanteIVA = ROUND(@BaseTribIVA * @TxIVA / 100, 2)															
-- obtem dados em falta				
				SELECT @CodPaisOrigem = ISNULL(@CodPaisOrigem, @CodPais16), 
					@NumCaucaoIVA = (CASE WHEN (@ClienteBeneficiarioIVA = 1) and (@CodRegime in ('4000', '4051', '4071', '4900', '5300', '6123')) THEN NULL ELSE @NumCaucaoDeclarante END), 
					@AnoCaucaoIVA = (CASE WHEN (@ClienteBeneficiarioIVA = 1) and (@CodRegime in ('4000', '4051', '4071', '4900', '5300', '6123')) THEN NULL ELSE @AnoCaucaoDeclarante END), 
					@TipoCaucaoIVA = (CASE WHEN (@ClienteBeneficiarioIVA = 1) and (@CodRegime in ('4000', '4051', '4071', '4900', '5300', '6123')) THEN NULL ELSE @TipoCaucaoDeclarante END),
					@EntidadeCaucaoIVA = (CASE WHEN (@ClienteBeneficiarioIVA = 1) and (@CodRegime in ('4000', '4051', '4071', '4900', '5300', '6123')) THEN NULL ELSE @EntidadeCaucaoDeclarante END)
-- obtem dados do País Origem
				SELECT @NomePaisOrigem = PAI_NOME
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @CodPaisOrigem		
-- inicia variaveis				
				SELECT @NumMarca = 0, @NumDeclSumaria = 0, @NumDocumento = 0, @NumImposicao = 0
-- se ação for de "Insert"
				IF @AcaoAdicao = 'I'
				BEGIN
-- insere Adições na declaração		
					INSERT INTO PRO_DUAD(DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, 
						DUA_ML38, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_CAUC, DUA_CANO, DUA_CTIP, DUA_CENT, DUA_VEST, 
						DUA_AJUS, DUA_DANO, DUA_VATO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, PAI_NOME, PRE_NOME, 
						USU_NOME, RRE_NOME, UME_NOTR, DUA_MTPR, DUA_QUAL, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_2TAR, DUA_3TAR, DUA_MAVA, RRE_NOME1, DUA_CAUD, DUA_CAND, DUA_CTID, DUA_CEND, DUA_IMPI, 
						DUA_CAUI, DUA_CANI, DUA_CTII, DUA_CENI, DUA_1TAR)
					VALUES(@AnoProcesso, @NumProxProcesso, @NumAdicao, @CodArtigoPautal, @CodUnidMedida, @TxIVA, @TipoTributacao, 0.000000, 0.000000, @CodPaisOrigem, @MassaBruta, @CodPreferenciaAd, @CodRubricaPreferencia, @CodRegime, @RegimeB, 
						@MassaLiquida, @QtdUnidades, @CodUnidSuplementar, @PrecoAdicao, @Frete, @Seguro, 0.000000, 0.000000, 0.000000, 0.000000, @ValorOptativas, @Designacao, @NumCaucaoDeclarante, @AnoCaucaoDeclarante, @TipoCaucaoDeclarante, @EntidadeCaucaoDeclarante, @ValorEstatistico, 
						@Ajustamento, @AnoProcesso, @ValorEstatistico, @BaseTribDireitos, @ETxComposta, @TaxaValor, @MontanteDireitos, 0.000000, @BaseTribIVA, @CodRubricaIVA, '0', 0.000000, @MontanteIVA, @PrecoAdicaoEUR, @CodPautal, @NomePaisOrigem, @NomePreferencia, 
						@NomeUnidSuplementar, @NomeRubricaIVA, @NomeUnidMedida, 0.000000, 'X', @ImposicaoDireitos, @AdicionalTARIC, @AdicionalIVA, @AdicionalIC2, @AdicionalIC3, @MetodoAvaliacao, @NomeRubricaPreferencia, @NumCaucaoDeclarante, @AnoCaucaoDeclarante, @TipoCaucaoDeclarante, @EntidadeCaucaoDeclarante, @ImposicaoIVA, 
						@NumCaucaoIVA, @AnoCaucaoIVA, @TipoCaucaoIVA, @EntidadeCaucaoIVA, @AdicionalIC1)
-- carrega Declação Sumária XML da adição
					DECLARE DeclSumaria CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
						SELECT XML_DSUM.DSM_DATA.value('Tipo[1]', 'varchar(4)'), XML_DSUM.DSM_DATA.value('CodDocumento[1]', 'varchar(5)'), 
							XML_DSUM.DSM_DATA.value('NumeroDeclSumaria[1]', 'varchar(20)'), XML_DSUM.DSM_DATA.value('DataApresentacao[1]', 'datetime'), 
							NULLIF(XML_DSUM.DSM_DATA.value('CodEstancia[1]', 'varchar(8)'), ''), NULLIF(XML_DSUM.DSM_DATA.value('Regime[1]', 'varchar(2)'), '')				
						FROM @DeclaracoesSumaria.nodes('DeclaracoesSumaria/DeclaracaoSumaria') as XML_DSUM(DSM_DATA)
					OPEN DeclSumaria
					FETCH NEXT from DeclSumaria into @TipoDeclSumaria, @CodDocumento, @NumeroDeclSumaria, @DataApresentacao, @CodEstanciaDeclSumaria, @Regime
					WHILE @@FETCH_STATUS = 0
					BEGIN	
-- obtem dados da Estância
						SELECT @NomeEstanciaDeclSumaria = EAD_NOME
						FROM TAB_EADU WITH(NOLOCK)
						WHERE EAD_CODI = @CodUnidadeMedida				
-- obtem dados em falta
						SELECT @NumDeclSumaria = @NumDeclSumaria + 1, @IdDeclSumaria = REPLACE(CAST(CONVERT(numeric(38, 12), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) as varchar(20)), '.', ',')
-- insere Declaração Sumária na adição
						INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, EAD_CODI, EAD_NOME, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APRG, DRA_APDT, 
							DRA_QUAL, DRA_IDCR)
						VALUES(@AnoProcesso, @NumProxProcesso, @NumAdicao, @NumDeclSumaria, @CodEstanciaDeclSumaria, @NomeEstanciaDeclSumaria, @CodDocumento, 
							YEAR(@DataApresentacao), @NumeroDeclSumaria, 'NP', @Regime, @DataApresentacao, @TipoDeclSumaria, @IdDeclSumaria)		
						FETCH NEXT from DeclSumaria into @TipoDeclSumaria, @CodDocumento, @NumeroDeclSumaria, @DataApresentacao, @CodEstanciaDeclSumaria, @Regime
					END
					CLOSE DeclSumaria
					DEALLOCATE DeclSumaria					
-- carrega Documentos da adição mais Documentos e Menções configurados
					DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR						
						SELECT 1, 5, NULL, NULL, INF_CODI, INF_DESI, @ValorOptativas
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_IMPC = 0 AND INF_CODI = 'VDA' and SUBSTRING(@CodRegime, 1, 2) <> '71' and SUBSTRING(@CodRegime, 1, 2) <> '78'	
						UNION ALL
						SELECT 0, 0, 'S/N', @Data, ad.DOC_CODI, ad.DOC_NOME, 0
						FROM TAB_ADOC AS ad WITH(NOLOCK)
							INNER JOIN TAB_DOCU AS d WITH(NOLOCK) ON ad.DOC_CODI = d.DOC_CODI
							INNER JOIN TAB_APAU AS a WITH(NOLOCK) ON ad.APA_CHVE = a.APA_CHVE
						WHERE ad.ADC_UIMP = 1 and a.APA_CODI = @CodArtigoPautal
						UNION ALL
						SELECT 0, 0, NULLIF(XML_DOCS.DOC_DATA.value('NumeroDocumento[1]', 'varchar(35)'), ''), XML_DOCS.DOC_DATA.value('DataEmissao[1]', 'datetime'), doc.DOC_CODI, doc.DOC_NOME, 0
						FROM @Documentos.nodes('Documentos/Documento') AS XML_DOCS(DOC_DATA) 
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI 
						WHERE doc.DOC_DESP = 1 and LEN(doc.DOC_CODI) <= 4
						UNION ALL
						SELECT 0, 7, arm.ARM_NAUT, arm.ARM_DATA, arm.DOC_CODI, doc.DOC_NOME, 0
						FROM TAB_ARMZ AS arm WITH(NOLOCK) 
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON arm.DOC_CODI = doc.DOC_CODI
						WHERE ISNULL(arm.ARM_NAUT, '') <> '' AND arm.ARM_CODI = @CodArmazem
						UNION ALL
						SELECT 1, 0, NULL, NULL, am.INF_CODI, am.INF_DESI, 0
						FROM TAB_AMEN AS am WITH(NOLOCK)
							INNER JOIN TAB_INFC AS m WITH(NOLOCK) ON am.INF_CODI = m.INF_CODI
							INNER JOIN TAB_APAU AS a WITH(NOLOCK) ON am.APA_CHVE = a.APA_CHVE
						WHERE am.AME_UIMP = 1 AND m.INF_IMPC = 0 AND a.APA_CODI = @CodArtigoPautal
						UNION ALL
						SELECT 1, 0, NULLIF(cli.CLI_NDHA, ''), cli.CLI_DTDH, men.INF_CODI, men.INF_DESI, 0
						FROM TAB_INFC AS men WITH(NOLOCK)
							LEFT OUTER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON cli.CLI_CODI = @CodDestinatario
						WHERE men.INF_IMPC = 0 AND men.INF_CODI = 'DHAB' AND (@2CasaTipoDeclaracao <> 'B' OR ISNULL(@CodTipoArmazem, '') <> 'D') AND (LEFT(@CodRegime, 1) <> '7' OR ISNULL(@CodTipoArmazem, '') = 'D')
							AND @TipoDeclarante = 3 AND SUBSTRING(@CedulaDeclarante, 5, 1) = 'I'			
						UNION ALL
						SELECT 1, 0, NULLIF(cli.CLI_NDHA, ''), cli.CLI_DTDH, men.INF_CODI, men.INF_DESI, 0
						FROM TAB_INFC AS men WITH(NOLOCK)
							LEFT OUTER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON cli.CLI_CODI = @CodDestinatario
						WHERE men.INF_IMPC = 0 AND men.INF_CODI = 'PROC' AND (@2CasaTipoDeclaracao <> 'B' OR ISNULL(@CodTipoArmazem, '') <> 'D') AND (LEFT(@CodRegime, 1) <> '7' OR ISNULL(@CodTipoArmazem, '') = 'D')
										AND @TipoDeclarante = 2 
						UNION ALL
						SELECT 1, 0, NULL, NULL, INF_CODI, INF_DESI, 0
						FROM TAB_INFC WITH(NOLOCK)
						WHERE INF_IMPC = 0 AND INF_CODI = 'PCEDP' and @2CasaTipoDeclaracao <> 'B' and LEFT(@CodRegime, 1) <> '7' and @TipoDeclarante = 3 and SUBSTRING(@CedulaDeclarante, 5, 1) = 'I'       
						UNION ALL
						SELECT 1, 0, NULL, NULL, tm.INF_CODI, me.INF_DESI, 0
						FROM TAB_TDEM AS tm WITH(NOLOCK)
							INNER JOIN TAB_INFC AS me WITH(NOLOCK) ON tm.INF_CODI = me.INF_CODI
						WHERE me.INF_IMPC = 0 AND tm.TDE_CODI = @CodTipoDeclaracao										
					OPEN Documentos
					FETCH NEXT from Documentos into @TipoDocumento, @DocumentoAuto, @NumeroDocumento, @DataEmissao, @CodDocumento, @NomeDocumento, @MontanteDocumento
					WHILE @@FETCH_STATUS = 0
					BEGIN				
-- obtem dados em falta
						SELECT @NumDocumento = @NumDocumento + 1
-- insere Documento na adição
						INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, DDO_MONT, DDO_DPRZ, DDO_AUTO, DDO_TIPO)
						VALUES(@AnoProcesso, @NumProxProcesso, @NumAdicao, @NumDocumento, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataEmissao, @MontanteDocumento, 0, 
							@DocumentoAuto, @TipoDocumento)		
						FETCH NEXT from Documentos into @TipoDocumento, @DocumentoAuto, @NumeroDocumento, @DataEmissao, @CodDocumento, @NomeDocumento, @MontanteDocumento
					END
					CLOSE Documentos
					DEALLOCATE Documentos			
-- carrega Imposicoes da adição
					DECLARE Imposicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
						SELECT 0, pd.RRE_CDPT, rr.RRE_NOME, rr.RRE_IVA, rr.RRE_IMPO, @ValorTrafego, @TotalVolumesXML, @MontanteRubricaCTT, 0, @NumCaucaoDeclarante, @AnoCaucaoDeclarante, @TipoCaucaoDeclarante, @EntidadeCaucaoDeclarante					
						FROM TAB_PDES AS pd WITH(NOLOCK) 
							INNER JOIN TAB_RREC AS rr WITH(NOLOCK) ON pd.RRE_CDPT = rr.RRE_CODI
						WHERE @ValorTrafego > 0
						UNION ALL
						SELECT 1, RRE_CODI, RRE_NOME, RRE_IVA, @ImposicaoDireitos, @TaxaValor, @BaseTribDireitos, @MontanteDireitos, (CASE @ETxComposta WHEN 1 THEN 0 ELSE 1 END), @NumCaucaoDeclarante, @AnoCaucaoDeclarante, @TipoCaucaoDeclarante, @EntidadeCaucaoDeclarante
						FROM TAB_RREC WITH(NOLOCK)
						WHERE RRE_CODI = @CodRubricaPreferencia
						UNION ALL
						SELECT 2, RRE_CODI, RRE_NOME, RRE_IVA, @ImposicaoIVA, @TxIVA, @BaseTribIVA, @MontanteIVA, 1, @NumCaucaoIVA, @AnoCaucaoIVA, @TipoCaucaoIVA, @EntidadeCaucaoIVA
						FROM TAB_RREC WITH(NOLOCK)
						WHERE RRE_CODI = @CodRubricaIVA		
					OPEN Imposicoes
					FETCH NEXT from Imposicoes into @ImposicaoAuto, @CodRubrica, @NomeRubrica, @RubricaIVA, @ImposicaoRubrica, @TaxaValorImposicao, @BaseTribImposicao, 
						@MontanteImposicao, @ImposicaoTaxa, @NumCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao
					WHILE @@FETCH_STATUS = 0
					BEGIN				
-- obtem dados em falta
						SELECT @NumImposicao = @NumImposicao + 1
-- insere Documento na adição
						INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_LIVA, DUO_IMPO, DUO_AUTO, 
							DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT)
						VALUES(@AnoProcesso, @NumProxProcesso, @NumAdicao, @NumImposicao, @CodRubrica, @NomeRubrica, @ImposicaoTaxa, @BaseTribImposicao, @TaxaValorImposicao, 
							@MontanteImposicao, @RubricaIVA, @ImposicaoRubrica, @ImposicaoAuto, @NumCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao)		
						FETCH NEXT from Imposicoes into @ImposicaoAuto, @CodRubrica, @NomeRubrica, @RubricaIVA, @ImposicaoRubrica, @TaxaValorImposicao, @BaseTribImposicao, 
							@MontanteImposicao, @ImposicaoTaxa, @NumCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao
					END
					CLOSE Imposicoes
					DEALLOCATE Imposicoes	
-- incrementa totais de frete e seguro
					SELECT @FreteTotal = @FreteTotal + @Frete, @SeguroTotal = @SeguroTotal + @Seguro
				END
				ELSE
				BEGIN					
-- actualiza Adições na declaração		
					UPDATE PRO_DUAD SET 
						APA_CO33 = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @CodArtigoPautal ELSE APA_CO33 END), 
						APA_CP33 = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @CodPautal ELSE APA_CP33 END), 
						DUA_DESG = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @Designacao ELSE DUA_DESG END), 
						USU_CO41 = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @CodUnidSuplementar ELSE USU_CO41 END), 
						USU_NOME = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @NomeUnidSuplementar ELSE USU_NOME END), 
						DUA_TRIB = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @TipoTributacao ELSE DUA_TRIB END),
						DUA_TIVA = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @TxIVA ELSE DUA_TIVA END), 
						RRE_CODI = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @CodRubricaIVA ELSE RRE_CODI END), 
						RRE_NOME = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @NomeRubricaIVA ELSE RRE_NOME END), 
						DUA_IMPI = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @ImposicaoIVA ELSE DUA_IMPI END), 
						DUA_ATAR = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @AdicionalTARIC ELSE DUA_ATAR END), 
						DUA_1TAR = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @AdicionalIC1 ELSE DUA_1TAR END), 
						DUA_2TAR = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @AdicionalIC2 ELSE DUA_2TAR END), 
						DUA_3TAR = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @AdicionalIC3 ELSE DUA_3TAR END), 
						UME_CODI = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @CodUnidMedida ELSE UME_CODI END),
						UME_NOTR = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @NomeUnidMedida ELSE UME_NOTR END), 
						DUA_TXCO = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @ETxComposta ELSE DUA_TXCO END), 
						DUA_TXVL = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @TaxaValor ELSE DUA_TXVL END),
						DUA_MB35 = @MassaBruta, 
						DUA_ML38 = @MassaLiquida, 
						DUA_US41 = @QtdUnidades, 
						DUA_VA42 = @PrecoAdicao, 
						DUA_VFRE = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @Frete ELSE DUA_VFRE END), 
						DUA_AJUS = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN @Ajustamento ELSE DUA_AJUS END), 
						DUA_VEST = @ValorEstatistico, 
						DUA_VATO = @ValorEstatistico, 
						DUA_BTRI = @ValorEstatistico, 
						DUA_VAEU = @PrecoAdicaoEUR, 
						DUA_VOPT = @ValorOptativas, 
						DUA_MTRI = (CASE DUA_TXCO WHEN 1 THEN ROUND(@ValorEstatistico * @TaxaValor / 100, 2) ELSE ROUND(@ValorEstatistico * @TaxaValor, 2) END), 										
						DUA_BTIV =  ROUND(@ValorEstatistico + @ValorOptativas, 2), 
						DUA_VIVA =  ROUND(ROUND(@ValorEstatistico + @ValorOptativas, 2) * DUA_TIVA / 100, 2)						
					WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProxProcesso and DUA_CODI = @NumAdicao
-- incrementa total do frete
					IF ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL'
						SET @FreteTotal = @FreteTotal + @Frete	
				END
-- incrementa restantes totais
				SELECT @TotalAdicoes = @TotalAdicoes + 1, @MontanteTotal = @MontanteTotal + @PrecoAdicao, @MassaLiquidaTotal = @MassaLiquidaTotal + @MassaLiquida, 
					@MassaBrutaTotal = @MassaBrutaTotal + @MassaBruta, @ValorAduaneiroTotal = @ValorAduaneiroTotal + @ValorEstatistico					
-- carrega Marcas e Volumes XML da adição
				DECLARE MarcasEVols CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT NULLIF(XML_VOLS.VOL_DATA.value('Marca[1]', 'varchar(20)'), ''), NULLIF(XML_VOLS.VOL_DATA.value('Numero[1]', 'varchar(20)'), ''), 
						XML_VOLS.VOL_DATA.value('QtdVolumes[1]', 'numeric(38, 6)'), XML_VOLS.VOL_DATA.value('CodUnidMedida[1]', 'varchar(3)'), 
						XML_VOLS.VOL_DATA.value('P[1]', 'bit'), XML_VOLS.VOL_DATA.value('R[1]', 'bit'), XML_VOLS.VOL_DATA.value('C[1]', 'bit'), 
						NULLIF(XML_VOLS.VOL_DATA.value('LOptica[1]', 'varchar(30)'), '')
					FROM @MarcasEVolumes.nodes('MarcasEVolumes/MarcaEVolume') as XML_VOLS(VOL_DATA)
					WHERE ISNULL(@ExtraFieldUPDATEValue, '') <> 'DHL-PORTAL'
				OPEN MarcasEVols
				FETCH NEXT from MarcasEVols into @Marca, @Numero, @QtdVolumes, @CodUnidadeMedida, @P, @R, @C, @LOptica
				WHILE @@FETCH_STATUS = 0
				BEGIN	
-- obtem dados da Unidade Medida
					SELECT @NomeUnidadeMedida = UME_NOME, @VolsAZero = UME_TVOL
					FROM TAB_UMED WITH(NOLOCK)
					WHERE UME_CODI = @CodUnidadeMedida				
-- obtem dados em falta
					SELECT @NumMarca = @NumMarca + 1			
-- insere Marcas e Volumes na adição
					INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_CASR, 
						D31_CASC, D31_TTVL, D31_LOPT)
					VALUES(@AnoProcesso, @NumProxProcesso, @NumAdicao, @NumMarca, @Marca, @Numero, @QtdVolumes, @CodUnidadeMedida, @NomeUnidadeMedida, @P, 
						@R, @C, @VolsAZero, @LOptica)
-- incrementa total de volumes apenas quando não é "P"
					IF @P = 0
						SELECT @TotalVolumes = @TotalVolumes + @QtdVolumes				
					FETCH NEXT from MarcasEVols into @Marca, @Numero, @QtdVolumes, @CodUnidadeMedida, @P, @R, @C, @LOptica
				END
				CLOSE MarcasEVols
				DEALLOCATE MarcasEVols															
				FETCH NEXT FROM Adicoes INTO @AcaoAdicao, @NumAdicao, @CodArtigoPautal, @Designacao, @CodPaisOrigem, @CodPreferenciaAd, @RegimeB, @MassaBruta, @MassaLiquida, @QtdUnidades, @PrecoAdicao, 
					@Frete, @Seguro, @MetodoAvaliacao, @MarcasEVolumes, @DeclaracoesSumaria, @Documentos
			END
			CLOSE Adicoes
			DEALLOCATE Adicoes	
-- carrega Manifestos XML da declaração
			DECLARE Manifestos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT NULLIF(XML_MANF.MNF_DATA.value('CodPais[1]', 'varchar(2)'), ''), NULLIF(XML_MANF.MNF_DATA.value('Descricao[1]', 'varchar(104)'), ''), 
					ISNULL(XML_MANF.MNF_DATA.value('Valor[1]', 'numeric(38, 6)'), 0), NULLIF(XML_MANF.MNF_DATA.value('Moeda[1]', 'varchar(3)'), ''), 
					ISNULL(XML_MANF.MNF_DATA.value('TotalFatura[1]', 'numeric(38, 6)'), 0), XML_MANF.MNF_DATA.value('NumeroCPA[1]', 'varchar(35)'), 
					ISNULL(XML_MANF.MNF_DATA.value('Peso[1]', 'numeric(38, 6)'), 0), XML_MANF.MNF_DATA.value('Tipo[1]', 'int')								
				FROM @Manifestos.nodes('Manifestos/DadosManifesto') as XML_MANF(MNF_DATA)
			OPEN Manifestos
			FETCH NEXT from Manifestos into @CodPaisManifesto, @DescricaoManifesto, @ValorManifesto, @MoedaManifesto, @TotalFaturaManifesto, 
				@NumeroCPAManifesto, @PesoManifesto, @TipoManifesto
			WHILE @@FETCH_STATUS = 0
			BEGIN			
-- obtem dados em falta
				SELECT @NumLinhaManifesto = @NumLinhaManifesto + 1			
-- insere Manifesto na declaração
				INSERT INTO PRO_DUOD(DUC_EANO, DUC_PNUM, DUO_CODI, PAI_CODI, DUO_DESC, DUO_VALO, DUO_MOED, DUO_TFAC, DUO_CPA2, DUO_PES2, DUO_TIPO)
				VALUES(@AnoProcesso, @NumProxProcesso, @NumLinhaManifesto, @CodPaisManifesto, @DescricaoManifesto, @ValorManifesto, @MoedaManifesto, 
					@TotalFaturaManifesto, @NumeroCPAManifesto, @PesoManifesto, @TipoManifesto)
-- incrementa variaveis
				SELECT @TotalLinhasDirty = @TotalLinhasDirty + (CASE @TipoManifesto WHEN 0 THEN 1 ELSE 0 END),
					@TotalLinhasClean = @TotalLinhasClean + (CASE @TipoManifesto WHEN 1 THEN 1 ELSE 0 END), 
					@TotalLinhasScan = @TotalLinhasScan + (CASE @TipoManifesto WHEN 2 THEN 1 ELSE 0 END)				
				FETCH NEXT from Manifestos into @CodPaisManifesto, @DescricaoManifesto, @ValorManifesto, @MoedaManifesto, @TotalFaturaManifesto, 
					@NumeroCPAManifesto, @PesoManifesto, @TipoManifesto
			END
			CLOSE Manifestos
			DEALLOCATE Manifestos	
-- carrega Incidências XML da declaração
			DECLARE Incidencias CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT XML_INCI.INC_DATA.value('CodStatusIncidencia[1]', 'varchar(8)'), 
					XML_INCI.INC_DATA.value('DataInicio[1]', 'datetime'), 
					XML_INCI.INC_DATA.value('DataFim[1]', 'datetime'), 
					NULLIF(XML_INCI.INC_DATA.value('Observacoes[1]', 'varchar(MAX)'), ''),
					NULLIF(XML_INCI.INC_DATA.value('TipoIncidencia[1]', 'varchar(1)'), '')
				FROM @Incidencias.nodes('Incidencias/DadosIncidencia') as XML_INCI(INC_DATA)
			OPEN Incidencias
			FETCH NEXT from Incidencias into @CodStatusIncidencia, @DataInicio, @DataFim, @Observacoes, @TipoIncidencia
			WHILE @@FETCH_STATUS = 0
			BEGIN			
-- obtem dados do Status de Incidência
				IF EXISTS(SELECT SIN_CODI FROM TAB_SINC WITH(NOLOCK) WHERE SIN_CODI = @CodStatusIncidencia)
				BEGIN
					SELECT @DescricaoStatusIncidencia = SIN_DESP, @ReleaseHoldIncidencia = ISNULL((CASE @TipoIncidencia WHEN 'R' THEN 0 WHEN 'H' THEN 1 ELSE NULL END), NULL)
					FROM TAB_SINC WITH(NOLOCK)
					WHERE SIN_CODI = @CodStatusIncidencia		
				END
				ELSE
				BEGIN
					SELECT @DescricaoStatusIncidencia = COS_POST, @ReleaseHoldIncidencia = ISNULL((CASE @TipoIncidencia WHEN 'R' THEN 0 WHEN 'H' THEN 1 ELSE NULL END), (CASE WHEN COS_RELI = 1 THEN 0 WHEN COS_HOLD = 1 THEN 1 ELSE NULL END))
					FROM TAB_COSM WITH(NOLOCK)
					WHERE COS_CODE = @CodStatusIncidencia	
				END	
-- obtem dados em falta
				SELECT @NumLinhaIncidencia = @NumLinhaIncidencia + 1
-- insere Incidência na declaração
				INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM, DUI_OBSR, DUI_REHO)
				VALUES(@AnoProcesso, @NumProxProcesso, @NumLinhaIncidencia, @CodStatusIncidencia, @DescricaoStatusIncidencia, 
					ISNULL(CAST(CONVERT(varchar(10), @DataInicio, 105) AS datetime), CAST(CONVERT(varchar(10), @DataAtual, 105) as datetime)), 
					ISNULL(CAST(CONVERT(varchar(12), @DataInicio, 114) AS datetime), CAST(CONVERT(varchar(12), @DataAtual, 114) AS datetime)), 
					ISNULL(CAST(CONVERT(varchar(10), @DataFim, 105) AS datetime), CAST(CONVERT(varchar(10), @DataAtual, 105) as datetime)), 
					ISNULL(CAST(CONVERT(varchar(12), @DataFim, 114) AS datetime), CAST(CONVERT(varchar(12), @DataAtual, 114) AS datetime)), @Observacoes, @ReleaseHoldIncidencia)				
				FETCH NEXT from Incidencias into @CodStatusIncidencia, @DataInicio, @DataFim, @Observacoes, @TipoIncidencia
			END
			CLOSE Incidencias
			DEALLOCATE Incidencias	
-- processa criação de diretoria no arquivo documental para os arquivos a anexar à declaração de Importação
			IF ISNULL(CAST(@Arquivos AS varchar(MAX)), '') <> ''
			BEGIN
-- procede à alteração da diretoria de dicionários para a diretoria de arquivo documental
				SET @DirArquivos = REPLACE(@DirArquivos, '\MSGS\DICS', '\DOCUMENTOS')
-- verifica se diretoria tem backslash no final	
				IF SUBSTRING(REVERSE(@DirArquivos), 1, 1) <> '\'
					SET @DirArquivos = @DirArquivos + '\'					
-- constroi path completa diretoria dos anexos da declaração de Importação
				SET @DirArquivos = @DirArquivos + CAST(@AnoProcesso AS varchar(4)) + '\DU' + REPLICATE('0', (8 - LEN(CAST(@NumProxProcesso AS varchar(8))))) + CAST(@NumProxProcesso AS varchar(8)) + '\'
-- processa a criação diretoria dos anexos da declaração de Importação
				EXEC GIDWIN.dbo.SP_Externo_CriaDiretoria @DirArquivos, @AuxMsgErro OUTPUT
				IF ISNULL(@AuxMsgErro, '') <> ''
					RAISERROR ('Não foi possível criar a diretoria "%s"! ERRO: "%s".', 16, 2, @PathFicheiro, @AuxMsgErro)								
			END
-- carrega arquivos XML da declaração
			DECLARE Arquivos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT t.a.value('Nome[1]', 'varchar(100)'), 
					t.a.value('Descricao[1]', 'varchar(150)'), 
					NULLIF(t.a.value('Tipo[1]', 'varchar(8)'), ''), 
					t.a.value('Origem[1]', 'int'),
					t.a.value('Base64[1]', 'varchar(MAX)')
				FROM @Arquivos.nodes('Arquivos/Ficheiro') AS t(a)
			OPEN Arquivos
			FETCH NEXT FROM Arquivos INTO @NomeFicheiro, @DescricaoFicheiro, @TipoFicheiro, @OrigemFicheiro, @FicheiroBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN							
-- obtem extensão do ficheiro a anexar
				SET @ExtFicheiro = REVERSE(SUBSTRING(REVERSE(@NomeFicheiro), 1, CHARINDEX('.', REVERSE(@NomeFicheiro))))
-- constroi path completa c/ novo nome p/ ficheiro a anexar
				SET @PathFicheiro = @DirArquivos + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(50), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121), '-', ''), ':', ''), '.', ''), ' ', '') + REPLICATE('0', (8 - LEN(CAST(@NumProxProcesso AS varchar(8))))) + CAST(@NumProxProcesso AS varchar(8)) + @ExtFicheiro
-- converte o Base64 para varbinary 
				SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@FicheiroBase64"))', 'varbinary(MAX)')				
-- gera o ficheiro a anexar no arquivo documental
				BEGIN TRY
					EXEC sp_OACreate 'ADODB.Stream', @Obj OUTPUT
					EXEC sp_OASetProperty @Obj, 'Type', 1
					EXEC sp_OAMethod @Obj, 'Open'
					EXEC sp_OAMethod @Obj, 'Write', NULL, @FicheiroBinario
					EXEC sp_OAMethod @Obj, 'SaveToFile', NULL, @PathFicheiro, 2
					EXEC sp_OAMethod @Obj, 'Close'
					EXEC sp_OADestroy @Obj
				END TRY    
				BEGIN CATCH
					EXEC sp_OADestroy @Obj
				END CATCH		
-- insere arquivo na declaração
				INSERT INTO PRO_DUFI(DUC_PNUM, DUC_EANO, DUF_DESC, DUF_LINK, DUF_DATA, DUF_NOMF, DUF_UTIL, DUF_TMSG, DUF_ORIG)
				VALUES(@NumProxProcesso, @AnoProcesso, @DescricaoFicheiro, @PathFicheiro, @DataAtual, @NomeFicheiro, @Utilizador, @TipoFicheiro, @OrigemFicheiro)				
				FETCH NEXT FROM Arquivos INTO @NomeFicheiro, @DescricaoFicheiro, @TipoFicheiro, @OrigemFicheiro, @FicheiroBase64
			END
			CLOSE Arquivos
			DEALLOCATE Arquivos
-- insere rubricas no detalhe da Liquidação da declaração
			IF (@Acao = 'I') OR ((@Acao = 'U') AND (@CamposAdicionais = 8)) --ENTREPOSTO
			BEGIN		
				INSERT INTO PRO_DULR(DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, DUL_MONT, DUL_MTAG)
				SELECT DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, SUM((CASE DUO_DEST WHEN 0 THEN ISNULL(DUO_MONT, 0) ELSE 0 END)), SUM((CASE DUO_DEST WHEN 1 THEN DUO_MTAG ELSE 0 END))
				FROM PRO_DUOI WITH(NOLOCK)
				WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProxProcesso
				GROUP BY DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME
				ORDER BY RRE_CODI								
			END
-- carrega Documentos da adição					
			IF ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL'
			BEGIN
				DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_ADIC.ADI_DATA.value('NumAdicao[1]', 'int'), XML_ADIC.ADI_DATA.query('Documentos')
					FROM @Adicoes.nodes('Adicoes/Adicao') as XML_ADIC(ADI_DATA)					
				OPEN Adicoes
				FETCH NEXT FROM Adicoes INTO @NumAdicao, @Documentos
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @NumDocumento = ISNULL((SELECT MAX(DDO_CODI) FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProxProcesso AND DUA_CODI = @NumAdicao), 0)
					DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR												
						SELECT 0, 0, NULLIF(XML_DOCS.DOC_DATA.value('NumeroDocumento[1]', 'varchar(35)'), ''), XML_DOCS.DOC_DATA.value('DataEmissao[1]', 'datetime'), doc.DOC_CODI, doc.DOC_NOME, 0, dad.DDO_IDEN
						FROM @Documentos.nodes('Documentos/Documento') AS XML_DOCS(DOC_DATA) 
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI 
							LEFT OUTER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON dad.DUC_EANO = @AnoProcesso AND dad.DUC_PNUM = @NumProxProcesso AND dad.DUA_CODI = @NumAdicao AND doc.DOC_CODI = dad.DOC_CODI
						WHERE doc.DOC_DESP = 1 and LEN(doc.DOC_CODI) <= 4 
					OPEN Documentos
					FETCH NEXT from Documentos into @TipoDocumento, @DocumentoAuto, @NumeroDocumento, @DataEmissao, @CodDocumento, @NomeDocumento, @MontanteDocumento, @IdDocumento
					WHILE @@FETCH_STATUS = 0
					BEGIN	
-- altera o documento na adicao se este já existir
						IF @IdDocumento IS NOT NULL
						BEGIN		
							UPDATE PRO_DDOC SET 
								DDO_NUME = @NumeroDocumento, 
								DDO_DINI = @DataEmissao, 
								DDO_MONT = @MontanteDocumento									
							WHERE DDO_IDEN = @IdDocumento	
						END
						ELSE			
						BEGIN
							SET @NumDocumento = @NumDocumento + 1
	-- insere Documento na adição
							INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, DDO_MONT, DDO_DPRZ, DDO_AUTO, DDO_TIPO)
							VALUES(@AnoProcesso, @NumProxProcesso, @NumAdicao, @NumDocumento, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataEmissao, @MontanteDocumento, 0, 
								@DocumentoAuto, @TipoDocumento)		
						END
						FETCH NEXT from Documentos into @TipoDocumento, @DocumentoAuto, @NumeroDocumento, @DataEmissao, @CodDocumento, @NomeDocumento, @MontanteDocumento, @IdDocumento
					END
					CLOSE Documentos
					DEALLOCATE Documentos
					FETCH NEXT FROM Adicoes INTO @NumAdicao, @Documentos
				END
				CLOSE Adicoes
				DEALLOCATE Adicoes
			END
-- obtem o valor total liquidação no detalhe da Liquidação da declaração de importação 
			SET @TotalLiquidacao = ISNULL((SELECT SUM(DUL_MONT) FROM PRO_DULR WITH(NOLOCK) WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProxProcesso), 0)								
-- actualiza campos totalizadores na declaração
			UPDATE PRO_DUCG SET 
				DUC_ADI5 = @TotalAdicoes, 
				DUC_TVL6 = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN DUC_TVL6 ELSE @TotalVolumes END), 
				DUC_MT22 = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_VATT ELSE @MontanteTotal END), 
				DUC_FRET = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_FRET ELSE @FreteTotal END), 
				DUC_SEGU = @SeguroTotal, 
				DUC_OP18 = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_OP18 ELSE @OptativasMeioTransporte18 END), 
				PAI_PR22 = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN PAI_PR22 ELSE @CodPais22 END), 
				DUC_TX23 = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_TX23 ELSE @CambioMoeda END), 
				DUC_MLQT = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_MLQT ELSE @MassaLiquidaTotal END), 
				DUC_MBRT = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_MBRT ELSE @MassaBrutaTotal END), 
				DUC_VEUR = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_VEUR ELSE ROUND(@MontanteTotal / @CambioMoeda, 2) END), 
				DUC_VATT = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_VATT ELSE @ValorAduaneiroTotal END), 
				DUC_UALT = @Utilizador, 
				DUC_DTAL = @DataAtual, 
				PAI_MO22 = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN PAI_MO22 ELSE @MoedaPais22 END), 
				DUC_TREM = (CASE WHEN (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (DUC_ADI5 > 1) THEN DUC_TREM ELSE @MassaBrutaTotal END), 
				DUC_FUPS = @NomeFileUPS, 
				DUC_VDIR = @TotalLinhasDirty, 
				DUC_VCLE = @TotalLinhasClean, 
				MNF_PESO = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN MNF_PESO ELSE @MassaBrutaTotal END), 
				MNF_PAIS = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN MNF_PAIS ELSE @CodPais22 END), 
				MNF_MOED = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN MNF_MOED ELSE @MoedaPais22 END), 
				MNF_VALO = (CASE WHEN ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL' THEN MNF_VALO ELSE @MontanteTotal END), 
				DUC_VSCA = @TotalLinhasScan, 
				DUC_VFRC = @ValorFreteCompanhia, 
				DUC_MFRC = @MoedaFreteCompanhia, 
				DUC_NVSR = @NivelServico, 
				DUC_VLRC = @TotalLiquidacao, 
				DUC_VLRE = dbo.FNT_Extenso_ValorPorExtenso(@TotalLiquidacao, 'euros', 'cêntimos')
			WHERE DUC_PNUM = @NumProxProcesso and DUC_EANO = @AnoProcesso			
-- processa recalculos dos dados da declaração
			IF ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL'
			BEGIN
				EXEC @Resultado = SP_DeclImportacao_AtualizaDadosDeclaracao @NumProxProcesso, @AnoProcesso, NULL, NULL, @Utilizador, @AuxMsgErro OUTPUT, NULL, NULL, 1 
				IF @Resultado > 0
					RAISERROR('Erro no recalculo dos dados da declaração n.º "%d"! ERRO: "%s".', 16, 3, @NumProxProcesso, @AuxMsgErro)
			END
		END TRY
		BEGIN CATCH					
-- constroi mensagem de erro detalhada
			SET @NumErro = 1 
			SELECT @MensagemErro = @MensagemErro + 								   
								   '.Doc. Transporte N.º:' + @NumDocTransporte + CHAR(12) +
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), @DataAtual, 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
-- em caso de erro faz rollback da transacção iniciada						           
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION	
		END CATCH	
-- se sucesso faz commit da transacção iniciada
		IF @@TRANCOUNT > 0
			COMMIT TRANSACTION			
		FETCH NEXT FROM Declaracoes INTO @Acao, @Data, @CodNatureza, @NumDocTransporte, @CodTipoDeclaracao, @CodEstancia, @CodExpedidor, @CodDestinatario, @CodDeclarante, @CodPais15A, @CodPais16, 
			@CodPais17, @CodMeioTransporte18, @IdMeioTransporte, @CodMeioTransporte21, @CodPais21, @TemContentores, @CodCondEntrega, @DescricaoCondEntrega, @CodNaturezaTransacao, @CodEstanciaAduaneira, 
			@CodLocalAutorizado, @CodArmazem, @CodPais22, @CodPaisFrete, @CodPaisSeguro, @NomeExpedidor, @MoradaExpedidor, @LocalidadeExpedidor, @CodPostalExpedidor, @LocPostalExpedidor, 
			@NIFExpedidor, @CodPaisExpedidor, @NomeDestinatario, @MoradaDestinatario, @LocalidadeDestinatario, @CodPostalDestinatario, @LocPostalDestinatario, @TelefoneDestinatario, @EmailDestinatario, 
			@NIFDestinatario, @TipoDestinatario, @CodPaisDestinatario, @CodRegiaoDestinatario, @ObsDesalfandegamento, @NumRequerimento, @NumDURetorno, @T1Retorno, @DataPrevVoo, @Payment, 
			@NumVossaReferencia, @NumContaExpedidor, @NumContaDestinatario, @Aeroporto, @PPouFC, @NumVoo, @MiniCPA, @Referencia1, @Referencia2, @ShipID, @Tracking, @DType, @PosicaoAviao, @TipoCarga, 
			@NomeFileUPS, @NomeDestinatario2, @MoradaDestinatario2, @LocalidadeDestinatario2, @CodPostalDestinatario2, @LocPostalDestinatario2, @Gateway, @Delegacao, @EDeclaracaoImportacao, 
			@ValorFreteCompanhia, @MoedaFreteCompanhia, @NivelServico, @CodFollowUp, @CodUtilizadorNomeado, @DataDocCPA, @TipoManifestoCAB, @ValorDespesasDHL, @NumeroDGASDS, @Observacoes, @CamposExtra, 
			@NumeroPDDT, @NumeroPDDTDev, @NumeroTD, @NumeroACTM, @NumeroSequencia, @Adicoes, @Manifestos, @Incidencias, @Arquivos
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro			
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_GeraDeclaracoesDeXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_GeraDeclaracoesDeXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaDAERetorno]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaDAERetorno] @AnoProcesso int, @NumProcesso int, @NumeroDAE varchar(21), @Utilizador varchar(30), @MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Erro int, @CodAlfandegaNumeroDAE varchar(8), @BaseDados varchar(6), @ComandoSQL nvarchar(4000), @VariaveisSQL nvarchar(3000), @CodAlfandegaIMP varchar(8), @CodDeclaranteIMP varchar(6), 
		@TipoDeclaranteIMP int, @CodPaisFreteIMP varchar(2), @AutSaidaIMP bit, @MassaBrtTotalIMP numeric(38, 6), @CodMeioTransporteIMP varchar(2), @TipoMeioTransporteIMP int, 
		@CambioFreteIMP numeric(38, 6), @CambioSeguroIMP numeric(38, 6), @OptativasMeioTransporte18IMP numeric(38, 6), @NumCaucaoIMP varchar(24), @AnoCaucaoIMP varchar(4), 
		@TipoCaucaoIMP varchar(1), @EntCaucaoIMP int, @NumTotalPedidos int, @VolsCleanIMP numeric(38, 6)
	DECLARE @AnoDeclaracao int, @CodigoDeclaracao int, @CodDeclarante varchar(6), @DataDAE datetime, @CodTipoDeclaracao varchar(4), @CodExpedidor varchar(18), @NomeDestinatario varchar(70), 
		@MoradaDestinatario varchar(70), @LocalidadeDestinatario varchar(35), @CodPostalDestinatario varchar(12), @LocPostalDestinatario varchar(35), @NIFDestinatario varchar(18), 
		@CodPaisDestinatario varchar(2), @CodCondEntrega varchar(3), @CodPaisMontante varchar(2), @MontanteTotal numeric(38, 6), @MassaLiqTotal numeric(38, 6), @MassaBrtTotal numeric(38, 6), 
		@AdicoesTotal int, @VolumesTotal numeric(38, 6), @NomeExpedidor varchar(70), @MoradaExpedidor varchar(70), @LocalidadeExpedidor varchar(35), @CodPostalExpedidor varchar(12), 
		@LocPostalExpedidor varchar(35), @NIFExpedidor varchar(18), @CodPaisExpedidor varchar(2), @TipoNIFExpedidor int, @CodRegiaoExpedidor int, @TelefoneExpedidor varchar(14), 
		@EmailExpedidor varchar(200), @AdicionalIVAExpedidor int, @BeneficiarioIVAExpedidor bit, @NomePaisExpedidor varchar(35), @NomePaisDestinatario varchar(35)
	DECLARE @Data datetime, 
		@CodNatureza varchar(3), @NomeNatureza varchar(35), 
		@NomeTipoDeclaracao varchar(35), @Casa1TipoDeclaracao varchar(5), @Casa2TipoDeclaracao varchar(4), @NaturezaTipoDeclaracao int, @CodPreferencia varchar(3), @CodRegime varchar(4), @CodDesdobramento varchar(3), 
		@DescricaoCondEntrega varchar(30), @CodFormulaCondEntrega int, @DescricaoFormula varchar(70), @ValorFOBFormula bit, @SomaFormula bit, 
		@PrefMoedaMontante varchar(3), @CambioMoedaMontante numeric(38, 6), @ValorEUR numeric(38, 6), @Referencia7 varchar(30), 
		@CodNatTransacao varchar(2), @NomeNatTransacao varchar(70), 
		@CodPaisOrigem varchar(2), @NomePaisOrigem varchar(35),
		@FreteTotal numeric(38, 6)
	DECLARE @IDAdicao int, @NumeroAdicao int, @CodArtigo varchar(22), @MassaLiquida numeric(38, 6), @QtdUnidades numeric(38, 6), @CodUnidSuplementar varchar(10), @PrecoAdicao numeric(38, 6), 
		@NumeroDoc varchar(70), @DataDoc datetime
	DECLARE	@IDAdicaoIMP int, @SeguroAdicaoIMP numeric(38, 6), @UltNumeroAnexoDocs int, @UltNumeroAnexoDeclSumaria int, @UltNumeroAnexoImposicoes int
	DECLARE @CodPautalArtigo varchar(22), @CodUnidSuplementarArtigo varchar(10), @TipoTributacaoArtigo int, @TxIVAArtigo numeric(38, 6), @CodMercPerArtigo varchar(10), @IC1Artigo varchar(4), 
		@IC2Artigo varchar(4), @IC3Artigo varchar(4), @CodUnidTributacaoArtigo varchar(3), @TributacaoValorArtigo bit, @DescricaoArtigo varchar(150), 
		@Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @BaseTribDireitos numeric(38, 6), @TaxaValor numeric(38, 6), @MontanteDireitos numeric(38, 6), @PrecoAdicaoEUR numeric(38, 6), 
		@MassaBruta numeric(38, 6), @Frete numeric(38, 6), @ValorOptativas numeric(38, 6), @BaseTribIVA numeric(38, 6), @MontanteIVA numeric(38, 6), 
		@NomePreferencia varchar(70), @CodRubricaPreferencia int, @TipoTaxaPreferencia int, @NomeUnidSuplementar varchar(10), @NomeUnidMedida varchar(35), @CodRubricaIVA int, 
		@NomeRubricaIVA varchar(70), @FatorUnidMedida numeric(38, 6), @ImposicaoDireitos varchar(3), @ImposicaoIVA varchar(3), @NomeRubricaPreferencia varchar(70), 
		@NumCaucaoIVA varchar(24), @AnoCaucaoIVA varchar(4), @TipoCaucaoIVA varchar(1), @EntidadeCaucaoIVA int
	DECLARE @ValorAduaneiroTotal numeric(38, 6), @SomaFreteAdicoes numeric(38, 6)
	DECLARE @NumeroDocumento varchar(70), @DataEmissao datetime, @CodDocumento varchar(5), @NomeDocumento varchar(150), @MontanteDocumento numeric(38, 6), @TipoDocumento int, @DocumentoAuto int 
	DECLARE @ImposicaoAuto int, @CodRubrica int, @NomeRubrica varchar(70), @RubricaIVA bit, @ImposicaoRubrica varchar(3), @TaxaValorImposicao numeric(38, 6), @BaseTribImposicao numeric(38, 6), 
		@MontanteImposicao numeric(38, 6), @ImposicaoTaxa bit, @NumCaucao varchar(24), @AnoCaucao varchar(4), @TipoCaucao varchar(1), @EntidadeCaucao int
-- inicia variáveis
	SET @Erro = 0	
	SET @Data = CAST(CONVERT(varchar(10), GETDATE(), 105) AS datetime)
	SET @CodNatureza = '40'	
	SET @CodNatTransacao = '21'
	SET @CodPaisOrigem = 'EU'
	SET @ValorAduaneiroTotal = 0	
	SET @SomaFreteAdicoes = 0
	SET @TipoMeioTransporteIMP = 0
	SET @OptativasMeioTransporte18IMP = 0
	SET @UltNumeroAnexoDocs = 0
	SET @UltNumeroAnexoDeclSumaria = 0
	SET @UltNumeroAnexoImposicoes = 0
-- cria tabela temporária de adições
	CREATE TABLE #tmpAdicoesRetorno (EXA_CHVE int NOT NULL, 
		EXA_LINH int NOT NULL, 
		APA_CO33 varchar(22) COLLATE Latin1_General_CI_AI NOT NULL, 
		EXA_MBRT numeric(38, 6) NOT NULL,
		EXA_MLQD numeric(38, 6) NOT NULL, 
		EXA_QUSU numeric(38, 6) NOT NULL, 
		USU_CODI varchar(10) COLLATE Latin1_General_CI_AI NULL, 
		EXA_VALO numeric(38, 6) NOT NULL)
-- inicia transacção para importação dos dados da DAE na Declarações de Importação
	BEGIN TRANSACTION		
	BEGIN TRY
-- valida o número DAE
		IF (ISNULL(@NumeroDAE, '') = '') OR (LEN(@NumeroDAE) < 20)
			RAISERROR('Número DAE introduzido não é válido.', 16, 1)
-- extrai o código da alfandega do numero DAE
		SET @CodAlfandegaNumeroDAE = RIGHT(SUBSTRING(@NumeroDAE, 5, 8), 3)
-- obtem a base de dados para obter a declaração de Exportação/XML a retornar
		IF @CodAlfandegaNumeroDAE = '015'
			SET @BaseDados = 'GIDW10'						
		ELSE
			SET @BaseDados = 'GIDW11'				
-- obtem dados da declaração de Importação
		SELECT @CodAlfandegaIMP = ALF_CODI, @CodDeclaranteIMP = DEC_CO14, @TipoDeclaranteIMP = DUC_TPDC, @MassaBrtTotalIMP = ISNULL(DUC_MBRT, 0), @CodPaisFreteIMP = ISNULL(PAI_FRET, ''), 
			@CambioFreteIMP = ISNULL(DUC_TXFR, 1), @CambioSeguroIMP = ISNULL(DUC_TXSE, 1), @AutSaidaIMP = DUC_ASAI, @NumCaucaoIMP = DUC_CAUC, @AnoCaucaoIMP = DUC_CANO, @TipoCaucaoIMP = DUC_CTIP, 
			@EntCaucaoIMP = DUC_CENT, @CodMeioTransporteIMP = MTR_PT18, @VolsCleanIMP = ISNULL(DUC_VCLE, 0)
		FROM PRO_DUCG WITH(NOLOCK) 			
		WHERE DUC_PNUM = @NumProcesso AND DUC_EANO = @AnoProcesso 
-- obtem os dados da declaração de Exportação/XML com o numero DAE
		SET @VariaveisSQL = N'@INNumeroDAE varchar(21), @INData datetime, @INCodAlfandegaIMP varchar(8), @INMassaBrtTotalIMP numeric(38, 6), @INVolsCleanIMP numeric(38, 6), @OUTAnoDeclaracao int OUTPUT, 
			@OUTCodigoDeclaracao int OUTPUT, @OUTCodDeclarante varchar(6) OUTPUT, @OUTDataDAE datetime OUTPUT, @OUTCodTipoDeclaracao varchar(4) OUTPUT, @OUTCodExpedidor varchar(18) OUTPUT, 
			@OUTNomeDestinatario varchar(70) OUTPUT, @OUTMoradaDestinatario varchar(70) OUTPUT, @OUTLocalidadeDestinatario varchar(35) OUTPUT, @OUTCodPostalDestinatario varchar(12) OUTPUT, 
			@OUTLocPostalDestinatario varchar(35) OUTPUT, @OUTNIFDestinatario varchar(18) OUTPUT, @OUTCodPaisDestinatario varchar(2) OUTPUT, @OUTCodCondEntrega varchar(3) OUTPUT, 
			@OUTCodPaisMontante varchar(2) OUTPUT, @OUTMontanteTotal numeric(38, 6) OUTPUT, @OUTMassaLiqTotal numeric(38, 6) OUTPUT, @OUTMassaBrtTotal numeric(38, 6) OUTPUT, @OUTAdicoesTotal int OUTPUT, 
			@OUTVolumesTotal numeric(38, 6) OUTPUT, @OUTNomeExpedidor varchar(70) OUTPUT, @OUTMoradaExpedidor varchar(70) OUTPUT, @OUTLocalidadeExpedidor varchar(35) OUTPUT, 
			@OUTCodPostalExpedidor varchar(12) OUTPUT, @OUTLocPostalExpedidor varchar(35) OUTPUT, @OUTNIFExpedidor varchar(18) OUTPUT, @OUTCodPaisExpedidor varchar(2) OUTPUT, @OUTTipoNIFExpedidor int OUTPUT, 
			@OUTCodRegiaoExpedidor int OUTPUT, @OUTTelefoneExpedidor varchar(14) OUTPUT, @OUTEmailExpedidor varchar(200) OUTPUT, @OUTAdicionalIVAExpedidor int OUTPUT, @OUTBeneficiarioIVAExpedidor bit OUTPUT, 
			@OUTNomePaisExpedidor varchar(35) OUTPUT, @OUTNomePaisDestinatario varchar(35) OUTPUT'
		SET @ComandoSQL = N'SET DATEFORMAT DMY 
			SELECT @OUTAnoDeclaracao = exm.EXM_EANO, @OUTCodigoDeclaracao = exm.EXM_CODI, @OUTCodDeclarante = exm.DEC_CODI, @OUTDataDAE = exm.EXM_DDGA, @OUTCodTipoDeclaracao = exm.TDE_COD1, 
				@OUTCodExpedidor = exm.CLI_COD2, @OUTNomeDestinatario = exm.FOR_NOM8, @OUTMoradaDestinatario = exm.FOR_MOR8, @OUTLocalidadeDestinatario = exm.FOR_LOC8, @OUTCodPostalDestinatario = exm.FOR_CPO8, 
				@OUTLocPostalDestinatario = exm.FOR_LPO8, @OUTNIFDestinatario = exm.FOR_NIF8, @OUTCodPaisDestinatario = exm.FOR_PAI8, @OUTCodPaisMontante = exm.PAI_CO22, @OUTMontanteTotal = exm.EXM_MT22, 
				@OUTMassaLiqTotal = exm.EXM_TMLQ, 
				@OUTMassaBrtTotal = (CASE @INVolsCleanIMP WHEN 0 THEN exm.EXM_TMBR ELSE @INMassaBrtTotalIMP END), 
				@OUTAdicoesTotal = exm.EXM_TAD5, @OUTVolumesTotal = exm.EXM_TVL6, 
				@OUTCodCondEntrega = (CASE @INCodAlfandegaIMP WHEN ''PT000020'' THEN ''XXX'' ELSE exm.CEN_CO20 END), 
				@OUTNomeExpedidor = cli.CLI_NOME, @OUTMoradaExpedidor = cli.CLI_MORA, @OUTLocalidadeExpedidor = cli.CLI_LOCA, @OUTCodPostalExpedidor = cli.CLI_CPOS, @OUTLocPostalExpedidor = cli.CLI_LPOS, 
				@OUTNIFExpedidor = cli.CLI_NIF, @OUTCodPaisExpedidor = cli.PAI_CODI, @OUTTipoNIFExpedidor = cli.CLI_TNIF, @OUTCodRegiaoExpedidor = cli.RES_CODI, @OUTTelefoneExpedidor = cli.CLI_TELF, 
				@OUTEmailExpedidor = cli.CLI_EMAI, @OUTAdicionalIVAExpedidor = cli.CLI_AIVA, 
				@OUTBeneficiarioIVAExpedidor = (CASE WHEN (cli.CLI_BIVA = 1) AND (@INData >= CAST(CONVERT(varchar(10), cli.CLI_DIBI, 105) as datetime)) THEN 1 ELSE 0 END), 
				@OUTNomePaisExpedidor = pex.PAI_NOME, @OUTNomePaisDestinatario = pfo.PAI_NOME
			FROM ' + @BaseDados + '.dbo.PRO_EXML AS exm WITH(NOLOCK) INNER JOIN ' + @BaseDados + '.dbo.TAB_CLIE AS cli WITH(NOLOCK) ON exm.CLI_COD2 = cli.CLI_CODI
				INNER JOIN ' + @BaseDados + '.dbo.TAB_PAIS AS pex WITH(NOLOCK) ON cli.PAI_CODI = pex.PAI_CODI
				LEFT OUTER JOIN ' + @BaseDados + '.dbo.TAB_PAIS AS pfo WITH(NOLOCK) ON exm.FOR_PAI8 = pfo.PAI_CODI
			WHERE exm.EXM_NDGA = @INNumeroDAE'		
		EXEC sp_executesql @ComandoSQL, @VariaveisSQL, @INNumeroDAE = @NumeroDAE, @INData = @Data, @INCodAlfandegaIMP = @CodAlfandegaIMP, @INMassaBrtTotalIMP = @MassaBrtTotalIMP, 
			@INVolsCleanIMP = @VolsCleanIMP, @OUTAnoDeclaracao = @AnoDeclaracao OUTPUT, @OUTCodigoDeclaracao = @CodigoDeclaracao OUTPUT, @OUTCodDeclarante = @CodDeclarante OUTPUT, @OUTDataDAE = @DataDAE OUTPUT, 
			@OUTCodTipoDeclaracao = @CodTipoDeclaracao OUTPUT, @OUTCodExpedidor = @CodExpedidor OUTPUT, @OUTNomeDestinatario = @NomeDestinatario OUTPUT, @OUTMoradaDestinatario = @MoradaDestinatario OUTPUT, 
			@OUTLocalidadeDestinatario = @LocalidadeDestinatario OUTPUT, @OUTCodPostalDestinatario = @CodPostalDestinatario OUTPUT, @OUTLocPostalDestinatario = @LocPostalDestinatario OUTPUT, 
			@OUTNIFDestinatario = @NIFDestinatario OUTPUT, @OUTCodPaisDestinatario = @CodPaisDestinatario OUTPUT, @OUTCodCondEntrega = @CodCondEntrega OUTPUT, @OUTCodPaisMontante = @CodPaisMontante OUTPUT, 
			@OUTMontanteTotal = @MontanteTotal OUTPUT, @OUTMassaLiqTotal = @MassaLiqTotal OUTPUT, @OUTMassaBrtTotal = @MassaBrtTotal OUTPUT, @OUTAdicoesTotal = @AdicoesTotal OUTPUT, 
			@OUTVolumesTotal = @VolumesTotal OUTPUT, @OUTNomeExpedidor = @NomeExpedidor OUTPUT, @OUTMoradaExpedidor = @MoradaExpedidor OUTPUT, @OUTLocalidadeExpedidor = @LocalidadeExpedidor OUTPUT, 
			@OUTCodPostalExpedidor = @CodPostalExpedidor OUTPUT, @OUTLocPostalExpedidor = @LocPostalExpedidor OUTPUT, @OUTNIFExpedidor = @NIFExpedidor OUTPUT, @OUTCodPaisExpedidor = @CodPaisExpedidor OUTPUT, 
			@OUTTipoNIFExpedidor = @TipoNIFExpedidor OUTPUT, @OUTCodRegiaoExpedidor = @CodRegiaoExpedidor OUTPUT, @OUTTelefoneExpedidor = @TelefoneExpedidor OUTPUT, @OUTEmailExpedidor = @EmailExpedidor OUTPUT, 
			@OUTAdicionalIVAExpedidor = @AdicionalIVAExpedidor OUTPUT, @OUTBeneficiarioIVAExpedidor = @BeneficiarioIVAExpedidor OUTPUT, @OUTNomePaisExpedidor = @NomePaisExpedidor OUTPUT, 
			@OUTNomePaisDestinatario = @NomePaisDestinatario OUTPUT
-- insere na tabela tmp de adições as adições da declaração de Exportação/XML
		SET @VariaveisSQL = N'@INAnoDeclaracao int, @INCodigoDeclaracao int, @INCodDeclarante varchar(6)'
		SET @ComandoSQL = N'INSERT INTO #tmpAdicoesRetorno(EXA_CHVE, EXA_LINH, APA_CO33, EXA_MBRT, EXA_MLQD, EXA_QUSU, USU_CODI, EXA_VALO)
			SELECT EXA_CHVE, EXA_LINH, APA_CO33, ISNULL(EXA_MBRT, 0), ISNULL(EXA_MLQD, 0), ISNULL(EXA_QUSU, 0), USU_CODI, ISNULL(EXA_VALO, 0)			
			FROM ' + @BaseDados + '.dbo.PRO_EXAD WITH(NOLOCK)
			WHERE EXM_EANO = @INAnoDeclaracao AND EXM_CODI = @INCodigoDeclaracao AND EXM_COPE = @INCodDeclarante 
			ORDER BY EXA_LINH'
		EXEC sp_executesql @ComandoSQL, @VariaveisSQL, @INAnoDeclaracao = @AnoDeclaracao, @INCodigoDeclaracao = @CodigoDeclaracao, @INCodDeclarante = @CodDeclarante
-- verifica se existe uma declaração de Exportação/XML com o numero DAE
		IF @AnoDeclaracao IS NULL
			RAISERROR('Número DAE introduzido inexistente.', 16, 2)
-- valida a natureza
		IF NOT EXISTS(SELECT NDE_CODI FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNatureza)
			RAISERROR('Natureza inexistente.', 16, 3)
		ELSE
			SELECT @NomeNatureza = NDE_NOME FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNatureza
-- calcula o tipo de declaração
		IF (@TipoNIFExpedidor = 6) AND (SUBSTRING(@CodTipoDeclaracao, 1, 2) = 'EU')
			SET @CodTipoDeclaracao = 'REE'
		ELSE
			IF (@TipoNIFExpedidor = 6) AND (SUBSTRING(@CodTipoDeclaracao, 1, 2) <> 'EU')
				SET @CodTipoDeclaracao = 'RET'
			ELSE
				IF (@TipoNIFExpedidor = 0) AND (SUBSTRING(@CodTipoDeclaracao, 1, 2) = 'EU')
					SET @CodTipoDeclaracao = 'RNE'
				ELSE
					IF (@TipoNIFExpedidor = 0) AND (SUBSTRING(@CodTipoDeclaracao, 1, 2) <> 'EU')
						SET @CodTipoDeclaracao = 'RNT'
					ELSE
						SET @CodTipoDeclaracao = NULL
-- valida o tipo de declaração
		IF NOT EXISTS(SELECT TDE_CODI FROM TAB_TDEC WITH(NOLOCK) WHERE TDE_NATU = 1 AND TDE_CODI = @CodTipoDeclaracao)
			RAISERROR('Tipo de declaração inválida ou inexistente.', 16, 4)
		ELSE
			SELECT @NomeTipoDeclaracao = TDE_NOME, @Casa1TipoDeclaracao = TDE_1CAS, @Casa2TipoDeclaracao = TDE_2CAS, @NaturezaTipoDeclaracao = TDE_NATU, @CodPreferencia = PRE_CODI, @CodRegime = TDE_REGI, @CodDesdobramento = TDE_DESD FROM TAB_TDEC WITH(NOLOCK) WHERE TDE_NATU = 1 and TDE_CODI = @CodTipoDeclaracao		
-- valida condição de entrega				
		IF NOT EXISTS(SELECT CEN_CODI FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = @CodCondEntrega)
			RAISERROR('Condição de entrega inexistente.', 16, 5)
		ELSE 
			SELECT @DescricaoCondEntrega = (CASE WHEN @CodAlfandegaIMP = 'PT000020' THEN 'RETORNO' WHEN ISNULL(CEN_LOCT, 0) = 0 THEN NULL WHEN ISNULL(CEN_LOCD, 0) = 0 THEN @LocalidadeExpedidor ELSE @LocalidadeDestinatario END), @CodFormulaCondEntrega = (CASE CEN_CODI WHEN 'XXX' THEN (CASE ISNULL(@CodPaisFreteIMP, '') WHEN '' THEN FIN_CODI2 ELSE FIN_CODI1 END) ELSE (CASE WHEN CEN_FOR1 = 1 THEN FIN_CODI1 WHEN CEN_FOR2 = 1 THEN FIN_CODI2 WHEN CEN_FOR3 = 1 THEN FIN_CODI3 WHEN CEN_FOR4 = 1 THEN FIN_CODI4 WHEN CEN_FOR5 = 1 THEN FIN_CODI5 ELSE NULL END) END) FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = @CodCondEntrega
-- valida natureza de trasnsação				
		IF NOT EXISTS(SELECT NTR_CODI FROM TAB_NTRA WITH(NOLOCK) WHERE NTR_CODI = @CodNatTransacao)
			RAISERROR('Natureza de transação inexistente.', 16, 6)
		ELSE
			SELECT @NomeNatTransacao = NTR_NOME FROM TAB_NTRA WITH(NOLOCK) WHERE NTR_CODI = @CodNatTransacao
-- valida país de origem
		IF NOT EXISTS(SELECT PAI_CODI FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem)
			RAISERROR('País de origem inexistente.', 16, 7)		
		ELSE
			SELECT @NomePaisOrigem = NULLIF(PAI_NOME, '') FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem
-- obtem dados da Preferência
		SELECT @NomePreferencia = PRE_NOME, @CodRubricaPreferencia = RRE_CODI, @TipoTaxaPreferencia = PRE_TAXA
		FROM TAB_PREF
		WHERE PRE_CODI = @CodPreferencia					
-- obtem dados dos Parametros Despachos
		SELECT TOP 1 @AdicionalIVAExpedidor = ISNULL(@AdicionalIVAExpedidor, PDE_ADIV), @Referencia7 = REPLACE(REPLACE(REPLACE(PDE_RFC7, 'ANO', CAST(YEAR(@Data) as varchar(4))), 'PNUM', CAST(@NumProcesso as varchar(50))), 'CC', ISNULL(@CodExpedidor, ''))
		FROM TAB_PDES WITH(NOLOCK)
-- obtem dados da formula obtida		
		SELECT @DescricaoFormula = NULLIF(FIN_DESC, ''), @ValorFOBFormula = FIN_VFOB, @SomaFormula = (CASE WHEN ISNULL(NULLIF(CHARINDEX('+', ISNULL(FIN_DESC, '')), 0), 999999999) < ISNULL(NULLIF(CHARINDEX('-', ISNULL(FIN_DESC, '')), 0), 999999999) THEN 1 ELSE 0 END)
		FROM TAB_FINC WITH(NOLOCK)
		WHERE FIN_CODI = @CodFormulaCondEntrega
-- obtem dados da moeda do montante
		SELECT @PrefMoedaMontante = NULLIF(PAI_PREF, ''), @CambioMoedaMontante = ISNULL((CASE (SELECT PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN TAB_PAIS.PAI_CODI THEN (SELECT PAP_TAXA FROM TAB_PAPL WITH(NOLOCK)) ELSE (SELECT TOP 1 CPA_VEND FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = TAB_PAIS.PAI_CODI and CPA_DATA <= CAST(CONVERT(varchar(10), GETDATE(), 105) + ' 23:58:58' as datetime) ORDER BY CPA_DATA DESC) END), 1) 
		FROM TAB_PAIS WITH(NOLOCK)
		WHERE PAI_CODI = @CodPaisMontante
-- calcula o valor do Frete p/ declaração
		SET @FreteTotal = dbo.FNT_DeclImportacao_CalculaFreteAcordado(@CodCondEntrega, @CodPaisDestinatario, @MassaBrtTotal, 0)
-- calcula valor EUR p/ declaração
		SET @ValorEUR = ROUND((@MontanteTotal / @CambioMoedaMontante), 2)		
-- obtem dados dos Meios de Transporte
		SELECT @TipoMeioTransporteIMP = ISNULL(mtr.MTR_VPVL, 0), 
			@OptativasMeioTransporte18IMP = (CASE mtr.MTR_OPAU 
												WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
																	FROM TAB_MTRO WITH(NOLOCK) 
																	WHERE MTR_IDTY = mtr.MTR_IDTY 
																		AND @MassaBrtTotal BETWEEN MTO_LMNP AND MTO_LMXP 
																		AND @ValorEUR BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
												ELSE ISNULL(mtr.MTR_VOP1, 0) 
											END)				
		FROM TAB_MTRA AS mtr WITH(NOLOCK)
		WHERE mtr.MTR_CODI = @CodMeioTransporteIMP	
-- atualiza dados da declaração de importação				
		UPDATE PRO_DUCG SET DUC_DATA = @Data, NDE_CODI = @CodNatureza, NDE_NOME = @NomeNatureza, TDE_CODI = @CodTipoDeclaracao, TDE_NOME = @NomeTipoDeclaracao, TDE_1CAS = @Casa1TipoDeclaracao, 
			TDE_2CAS = @Casa2TipoDeclaracao, DUC_TIPO = @NaturezaTipoDeclaracao, DUC_ADI5 = @AdicoesTotal, DUC_TVL6 = @VolumesTotal, DUC_REF7 = @Referencia7, DUC_EXP2 = NULL, 
			DUC_DST8 = @CodExpedidor, DUC_ENOM = @NomeDestinatario, DUC_EMOR = @MoradaDestinatario, DUC_ELOC = @LocalidadeDestinatario, DUC_ECPO = @CodPostalDestinatario, 
			DUC_ELPO = @LocPostalDestinatario, PAI_ELIV = @CodPaisDestinatario, DUC_ENIF = @NIFDestinatario, PAI_PA15 = @CodPaisDestinatario, PAI_NO15 = @NomePaisDestinatario, 
			PAI_P15A = @CodPaisDestinatario, PAI_PA16 = @CodPaisDestinatario, PAI_NO16 = @NomePaisDestinatario, DUC_DNOM = @NomeExpedidor, DUC_DMOR = @MoradaExpedidor, 
			DUC_DLOC = @LocalidadeExpedidor, DUC_DCPO = @CodPostalExpedidor, DUC_DLPO = @LocPostalExpedidor, PAI_DLIV = @CodPaisExpedidor, DUC_DNIF = @NIFExpedidor, DUC_TPDS = @TipoNIFExpedidor, 
			PAI_P17B = @CodRegiaoExpedidor, DUC_DTEL = @TelefoneExpedidor, DUC_DEMA = @EmailExpedidor, PAI_PA17 = @CodPaisExpedidor, PAI_NO17 = @NomePaisExpedidor, PAI_P17A = @CodPaisExpedidor, 
			DUC_OP18 = @OptativasMeioTransporte18IMP, CEN_CO20 = @CodCondEntrega, DUC_DE20 = @DescricaoCondEntrega, FIN_CODI = @CodFormulaCondEntrega, DUC_FR20 = @DescricaoFormula, 
			DUC_UFOB = @ValorFOBFormula, PAI_PR22 = @CodPaisMontante, PAI_MO22 = @PrefMoedaMontante, DUC_TX23 = @CambioMoedaMontante, DUC_MT22 = @MontanteTotal, DUC_VEUR = @ValorEUR, 
			NTR_CO24 = @CodNatTransacao, NTR_NOME = @NomeNatTransacao, DUC_MLQT = @MassaLiqTotal, DUC_FRET = @FreteTotal, DUC_MBRT = @MassaBrtTotal, DUC_TREM = @MassaBrtTotal, 
			DUC_BIVA = @BeneficiarioIVAExpedidor, DUC_UALT = @Utilizador, DUC_DTAL = GETDATE()
		WHERE DUC_PNUM = @NumProcesso AND DUC_EANO = @AnoProcesso
-- se declaração de Importação não tiver "Aut. Saída", procede à inserção dos Pedidos configurados no Tipo Declaração 
		IF @AutSaidaIMP = 0
		BEGIN
-- obtem o número total de Pedidos já existentes na declaração de Importação
			SELECT @NumTotalPedidos = COUNT(*)
			FROM PRO_DUPD
			WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso
-- insere Pedidos na declaração de Importação
			INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC)
			SELECT @AnoProcesso, @NumProcesso, (@NumTotalPedidos + ROW_NUMBER() OVER(ORDER BY TDP_CODI)), TXM_CODI, TDP_TEXT
			FROM TAB_TDEP WITH(NOLOCK)
			WHERE TDE_CODI = @CodTipoDeclaracao
			ORDER BY TDP_CODI
		END
-- obtem as adições da declaração de Exportação/XML			 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
			SELECT EXA_CHVE, EXA_LINH, APA_CO33, EXA_MBRT, EXA_MLQD, EXA_QUSU, USU_CODI, EXA_VALO
			FROM #tmpAdicoesRetorno
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IDAdicao, @NumeroAdicao, @CodArtigo, @MassaBruta, @MassaLiquida, @QtdUnidades, @CodUnidSuplementar, @PrecoAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @IDAdicaoIMP = NULL
-- obtem dados da adição na Importação
			SELECT @IDAdicaoIMP = dua.DUA_IDEN, @SeguroAdicaoIMP = ISNULL(dua.DUA_VSEG, 0), 
				@MassaBruta = (CASE @VolsCleanIMP WHEN 0 THEN @MassaBruta ELSE dua.DUA_MB35 END), 
				@UltNumeroAnexoDocs = (SELECT COUNT(*) FROM PRO_DDOC WHERE DUC_EANO = dua.DUC_EANO and DUC_PNUM = dua.DUC_PNUM and DUA_CODI = dua.DUA_CODI),
				@UltNumeroAnexoDeclSumaria = (SELECT COUNT(*) FROM PRO_DURA WHERE DUC_EANO = dua.DUC_EANO and DUC_PNUM = dua.DUC_PNUM and DUA_CODI = dua.DUA_CODI),
				@UltNumeroAnexoImposicoes = (SELECT COUNT(*) FROM PRO_DUOI WHERE DUC_EANO = dua.DUC_EANO and DUC_PNUM = dua.DUC_PNUM and DUA_CODI = dua.DUA_CODI)
			FROM PRO_DUAD AS dua WITH(NOLOCK)
			WHERE dua.DUC_EANO = @AnoProcesso AND dua.DUC_PNUM = @NumProcesso AND dua.DUA_CODI = @NumeroAdicao	
-- se adição não existir, coloca valor do seguro a zero
			IF @IDAdicaoIMP IS NULL			
				SET @SeguroAdicaoIMP = 0
-- verifica se artigo existe, senão assume o artigo "genérico"
			IF NOT EXISTS(SELECT APA_CODI FROM TAB_APAU WITH(NOLOCK) WHERE APA_INAC = 0 AND APA_FLUX IN (0, 1) AND APA_CODI = @CodArtigo)
				SET @CodArtigo = '0000000000'
-- obtem dados do Artigo Pautal
			SELECT @CodPautalArtigo = APA_CPAU, @DescricaoArtigo = APA_DESG, @CodUnidSuplementarArtigo = USU_CODI, @TipoTributacaoArtigo = ISNULL(APA_TRIB, 0), 
				@TxIVAArtigo = (CASE WHEN (SUBSTRING(@CodRegime, 1, 2) in ('42', '51', '53', '71')) or (@CodDesdobramento in ('4FF', '4FC', 'C08', 'C30', 'F01')) THEN 0 ELSE APA_TIVA END), 
				@CodMercPerArtigo = APA_ATAR, @IC1Artigo = APA_AIC1, @IC2Artigo = APA_AIC2, @IC3Artigo = APA_AIC3, @CodUnidTributacaoArtigo = UME_CODI, 
				@TributacaoValorArtigo = (CASE ISNULL(APA_TRIB, 0) WHEN 0 THEN (CASE APA_TXCO WHEN 0 THEN 1 ELSE 0 END) WHEN 1 THEN 1 ELSE 0 END), 
				@TaxaValor = (CASE WHEN (SUBSTRING(@CodRegime, 1, 2) in ('51', '53', '71')) or (@CodDesdobramento in ('4FC', 'C07', 'C08', 'C30', 'F01')) THEN 0 
					ELSE (CASE ISNULL(APA_TRIB, 0) WHEN 0 THEN (CASE APA_TXCO WHEN 0 THEN @QtdUnidades ELSE 0 END) 
						WHEN 1 THEN (CASE @TipoTaxaPreferencia WHEN 1 THEN ISNULL(APA_TPMN, 0) 
									WHEN 2 THEN ISNULL((SELECT ISNULL(APS_SPMN, 0) FROM TAB_APSP WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_SPMN, 0)) 
									WHEN 3 THEN ISNULL((SELECT ISNULL(APE_EFMN, 0) FROM TAB_APEF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_EFMN, 0)) 
									ELSE 0 END) 
						WHEN 3 THEN (CASE @TipoTaxaPreferencia WHEN 1 THEN (ISNULL((SELECT ISNULL(APT_TFT, 0) + DATEDIFF(MONTH, APT_DATA, GETDATE()) * ISNULL(APT_INCR, 0) FROM TAB_APTF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), 0) + ISNULL(APA_TPT, 0)) 
									WHEN 2 THEN ISNULL((SELECT ISNULL(APS_SPG, 0) FROM TAB_APSP WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_SPG, 0)) 
									WHEN 3 THEN ISNULL((SELECT ISNULL(APE_EFTA, 0) FROM TAB_APEF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_EFTA, 0)) 
									ELSE 0 END) 
						ELSE 0 END) 
				END) 
			FROM TAB_APAU WITH(NOLOCK)
			WHERE APA_CODI = @CodArtigo
-- obtem dados da Unidade Suplementar
			SELECT @NomeUnidSuplementar = USU_SIGL
			FROM TAB_USUP WITH(NOLOCK) 
			WHERE USU_CODI = @CodUnidSuplementar
-- obtem dados da unidade de medida obtida
			SELECT @NomeUnidMedida = UME_NOME, @FatorUnidMedida = UME_FACT
			FROM TAB_UMED WITH(NOLOCK) 
			WHERE UME_CODI = @CodUnidTributacaoArtigo
-- obtem dados dos Parâmetros Aplicação
			SELECT TOP 1 @CodRubricaIVA = (CASE ROUND(@TxIVAArtigo, 2) WHEN PAP_TXIS THEN RRE_CDIS WHEN PAP_TXRD THEN RRE_CDRD WHEN PAP_TXIN THEN RRE_CDIN WHEN PAP_TXNR THEN RRE_CDNR ELSE NULL END)
			FROM TAB_PAPL WITH(NOLOCK) 
-- obtem dados das Rubricas
			SELECT @NomeRubricaPreferencia = RRE_NOME, @ImposicaoDireitos = RRE_IMPO
			FROM TAB_RREC WITH(NOLOCK) 
			WHERE RRE_CODI = @CodRubricaPreferencia
			SELECT @NomeRubricaIVA = RRE_NOME, @ImposicaoIVA = RRE_IMPO
			FROM TAB_RREC WITH(NOLOCK) 		
			WHERE RRE_CODI = @CodRubricaIVA
-- calula valor EUR da adição
			SET @PrecoAdicaoEUR = ROUND(@PrecoAdicao / @CambioMoedaMontante, 2)	
-- calcular valor do frete 							
			IF @NumeroAdicao < @AdicoesTotal
				SET @Frete = ROUND(@FreteTotal * @MassaBruta / @MassaBrtTotal, 3)
			ELSE
				SET @Frete = ROUND(@FreteTotal - @SomaFreteAdicoes, 3)
-- calcula valor do ajustamento da adição
			IF @SomaFormula = 1
				SET @Ajustamento = ROUND(ROUND(@Frete / @CambioFreteIMP, 2) + ROUND(@SeguroAdicaoIMP / @CambioSeguroIMP, 2), 2)
			ELSE
				SET @Ajustamento = ROUND((ROUND(@Frete / @CambioFreteIMP, 2) * -1) - ROUND(@SeguroAdicaoIMP / @CambioSeguroIMP, 2), 2)		
-- calcula valor estatistico da adição
			SET @ValorEstatistico = @PrecoAdicaoEUR + @Ajustamento	
-- calcula valor da base de tributação dos direitos da adição
			IF @TipoTributacaoArtigo = 0
				SET @BaseTribDireitos = ROUND(@QtdUnidades / @FatorUnidMedida, 3)
			ELSE
				IF @TipoTributacaoArtigo = 1
					SET @BaseTribDireitos = ROUND(@MassaLiquida / @FatorUnidMedida, 3)
				ELSE
					IF @TipoTributacaoArtigo = 3
					BEGIN
						IF @SomaFormula = 1
							SET @BaseTribDireitos = ROUND(@ValorEstatistico, 3)
						ELSE
							SET @BaseTribDireitos = ROUND(@PrecoAdicaoEUR, 3)
					END
					ELSE	
						SET @BaseTribDireitos = 0		
-- calcula montante de tributação dos direitos da adição 
			IF @TributacaoValorArtigo = 1
				SET @MontanteDireitos = ROUND(@BaseTribDireitos * @TaxaValor, 2)					
			ELSE
				SET @MontanteDireitos = ROUND(@BaseTribDireitos * @TaxaValor / 100, 2)
-- calcula valor de optativas da adição 
			IF @TipoMeioTransporteIMP = 2 -- por volume
				SET @ValorOptativas = ROUND(@VolumesTotal * @OptativasMeioTransporte18IMP, 2)			
			ELSE
				SET @ValorOptativas = ROUND(@MassaBruta * (@OptativasMeioTransporte18IMP * CEILING(@MassaBrtTotal / 100)) / @MassaBrtTotal, 2)					
-- calcula valor da base de tributação do IVA da adição				
			IF @SomaFormula = 1
				SET @BaseTribIVA = ROUND(@PrecoAdicaoEUR + ROUND(@Frete / @CambioFreteIMP, 2) + ROUND(@SeguroAdicaoIMP / @CambioSeguroIMP, 2) + @ValorOptativas + @MontanteDireitos, 2)
			ELSE
				SET @BaseTribIVA = ROUND(@PrecoAdicaoEUR + @ValorOptativas + @MontanteDireitos, 2)					
-- calcula montante de tributação do IVA da adição
			SET @MontanteIVA = ROUND(@BaseTribIVA * @TxIVAArtigo / 100, 2)	
-- obtem dados em falta				
			SELECT @AdicionalIVAExpedidor = (CASE WHEN (@BeneficiarioIVAExpedidor = 1) OR (SUBSTRING(@CodRegime, 1, 2) = '42') THEN NULL ELSE @AdicionalIVAExpedidor END),
				@NumCaucaoIVA = (CASE WHEN (@BeneficiarioIVAExpedidor = 1) AND (@CodRegime IN ('4000', '4051', '4071', '4900', '5300', '6110', '6123')) THEN NULL ELSE @NumCaucaoIMP END), 
				@AnoCaucaoIVA = (CASE WHEN (@BeneficiarioIVAExpedidor = 1) AND (@CodRegime IN ('4000', '4051', '4071', '4900', '5300', '6110', '6123')) THEN NULL ELSE @AnoCaucaoIMP END), 
				@TipoCaucaoIVA = (CASE WHEN (@BeneficiarioIVAExpedidor = 1) AND (@CodRegime IN ('4000', '4051', '4071', '4900', '5300', '6110', '6123')) THEN NULL ELSE @TipoCaucaoIMP END),
				@EntidadeCaucaoIVA = (CASE WHEN (@BeneficiarioIVAExpedidor = 1) AND (@CodRegime IN ('4000', '4051', '4071', '4900', '5300', '6110', '6123')) THEN NULL ELSE @EntCaucaoIMP END)								
-- processa editação ou inserção conforme se adição existe na declaração de Importação
			IF @IDAdicaoIMP IS NOT NULL		
			BEGIN				
				UPDATE PRO_DUAD SET APA_CO33 = @CodArtigo, APA_CP33 = NULLIF(@CodPautalArtigo, ''), DUA_DESG = NULLIF(@DescricaoArtigo, ''), USU_CO41 = @CodUnidSuplementarArtigo, 
					USU_NOME = @NomeUnidSuplementar, DUA_TRIB = @TipoTributacaoArtigo, DUA_TIVA = @TxIVAArtigo, DUA_ATAR = @CodMercPerArtigo, DUA_1TAR = @IC1Artigo, DUA_2TAR = @IC2Artigo, 
					DUA_3TAR = @IC3Artigo, UME_CODI = @CodUnidTributacaoArtigo, UME_NOTR = @NomeUnidMedida, DUA_TXCO = @TributacaoValorArtigo, PAI_CO34 = @CodPaisOrigem, PAI_NOME = @NomePaisOrigem, 
					DUA_MB35 = @MassaBruta, DUA_ML38 = @MassaLiquida, DUA_RG37 = @CodRegime, DUA_R37B = @CodDesdobramento, DUA_R37C = NULL, DUA_US41 = @QtdUnidades, DUA_VA42 = @PrecoAdicao, DUA_VFRE = @Frete, 
					RRE_CODI = @CodRubricaIVA, RRE_NOME = @NomeRubricaIVA, DUA_IMPI = @ImposicaoIVA, DUA_AJUS = @Ajustamento, DUA_VEST = @ValorEstatistico, DUA_VAEU = @PrecoAdicaoEUR, 
					DUA_VATO = @ValorEstatistico, DUA_TXVL = @TaxaValor, DUA_BTRI = @BaseTribDireitos, DUA_MTRI = @MontanteDireitos, DUA_VOPT = @ValorOptativas, DUA_BTIV = @BaseTribIVA, 
					DUA_VIVA = @MontanteIVA, PRE_CO36 = @CodPreferencia, PRE_NOME = @NomePreferencia, RRE_PREF = @CodRubricaPreferencia, RRE_NOME1 = @NomeRubricaPreferencia, DUA_IMPO = @ImposicaoDireitos,
					DUA_CAUI = @NumCaucaoIVA, DUA_CANI = @AnoCaucaoIVA, DUA_CTII = @TipoCaucaoIVA, DUA_CENI = @EntidadeCaucaoIVA, DUA_AIVA = @AdicionalIVAExpedidor
				WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumeroAdicao
			END
			ELSE
			BEGIN				
				INSERT INTO PRO_DUAD(DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, DUA_ML38, DUA_US41, 
					USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_CAUC, DUA_CANO, DUA_CTIP, DUA_CENT, DUA_VEST, DUA_AJUS, DUA_DANO, DUA_VATO, 
					DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, PAI_NOME, PRE_NOME, USU_NOME, RRE_NOME, UME_NOTR, DUA_MTPR, DUA_QUAL, 
					DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_2TAR, DUA_3TAR, DUA_MAVA, RRE_NOME1, DUA_CAUD, DUA_CAND, DUA_CTID, DUA_CEND, DUA_IMPI, DUA_CAUI, DUA_CANI, DUA_CTII, DUA_CENI, DUA_1TAR)
				VALUES(@AnoProcesso, @NumProcesso, @NumeroAdicao, @CodArtigo, @CodUnidTributacaoArtigo, @TxIVAArtigo, @TipoTributacaoArtigo, 0.000000, 0.000000, @CodPaisOrigem, @MassaBruta, @CodPreferencia, 
					@CodRubricaPreferencia, @CodRegime, @CodDesdobramento, @MassaLiquida, @QtdUnidades, @CodUnidSuplementar, @PrecoAdicao, @Frete, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 
					@ValorOptativas, @DescricaoArtigo, @NumCaucaoIMP, @AnoCaucaoIMP, @TipoCaucaoIMP, @EntCaucaoIMP, @ValorEstatistico, @Ajustamento, @AnoProcesso, @ValorEstatistico, @BaseTribDireitos, 
					@TributacaoValorArtigo, @TaxaValor, @MontanteDireitos, 0.000000, @BaseTribIVA, @CodRubricaIVA, '0', 0.000000, @MontanteIVA, @PrecoAdicaoEUR, @CodPautalArtigo, @NomePaisOrigem, 
					@NomePreferencia, @NomeUnidSuplementar, @NomeRubricaIVA, @NomeUnidMedida, 0.000000, 'X', @ImposicaoDireitos, @CodMercPerArtigo, @AdicionalIVAExpedidor, @IC2Artigo, @IC3Artigo, 1, 
					@NomeRubricaPreferencia, @NumCaucaoIMP, @AnoCaucaoIMP, @TipoCaucaoIMP, @EntCaucaoIMP, @ImposicaoIVA, @NumCaucaoIVA, @AnoCaucaoIVA, @TipoCaucaoIVA, @EntidadeCaucaoIVA, @IC1Artigo)
			END			
-- incrementa variaveis			
			SET @SomaFreteAdicoes = @SomaFreteAdicoes + @Frete
			SET @ValorAduaneiroTotal = @ValorAduaneiroTotal + @ValorEstatistico
-- efetua a gestão das marcas e volumes das adiçoes
			IF @IDAdicaoIMP IS NOT NULL		
			BEGIN
				UPDATE PRO_DU31 SET D31_QNTD = @VolumesTotal, D31_CASP = (CASE WHEN (@AdicoesTotal > 1) AND (@NumeroAdicao < @AdicoesTotal) THEN 1 ELSE 0 END), 
					D31_CASR = (CASE WHEN (@AdicoesTotal > 1) AND (@NumeroAdicao = @AdicoesTotal) THEN 1 ELSE 0 END)
				WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumeroAdicao
			END
			ELSE
			BEGIN
				INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_CASR, D31_CASC, D31_TTVL, D31_LOPT)
				SELECT DUC_EANO, DUC_PNUM, @NumeroAdicao, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, (CASE WHEN (@AdicoesTotal > 1) AND (@NumeroAdicao < @AdicoesTotal) THEN 1 ELSE 0 END), 
					(CASE WHEN (@AdicoesTotal > 1) AND (@NumeroAdicao = @AdicoesTotal) THEN 1 ELSE 0 END), D31_CASC, D31_TTVL, D31_LOPT
				FROM PRO_DU31 
				WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = 1				
			END
-- efetua a gestão das declarações sumárias das adiçoes
			IF @IDAdicaoIMP IS NOT NULL		
			BEGIN
				INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APRG, DRA_APDT, DRA_QUAL, DRA_IDCR)
				SELECT @AnoProcesso, @NumProcesso, @NumeroAdicao, (@UltNumeroAnexoDeclSumaria + 1), DOC_CODI, YEAR(@DataDAE), @NumeroDAE, 'NP', '10', @DataDAE, 'Z', 
					REPLACE(CAST(CONVERT(numeric(38, 12), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) as varchar(20)), '.', ',')
				FROM TAB_DOCU
				WHERE DOC_CODI = 'EX'					
			END
			ELSE
			BEGIN
				INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, EAD_CODI, EAD_NOME, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APRG, DRA_APDT, DRA_QUAL, DRA_IDCR, DRA_CODR, DRA_AUTO)
				SELECT DUC_EANO, DUC_PNUM, @NumeroAdicao, DRA_CODI, EAD_CODI, EAD_NOME, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APRG, DRA_APDT, DRA_QUAL, 
					REPLACE(CAST(CONVERT(numeric(38, 12), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) as varchar(20)), '.', ','), 
					(CASE WHEN (DRA_QUAL = 'X' AND DRA_AUTO = 0) THEN DRA_IDCR ELSE NULL END), (CASE WHEN (DRA_QUAL = 'X' AND DRA_AUTO = 0) THEN 1 ELSE 0 END)
				FROM PRO_DURA 
				WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = 1				
			END
-- atualiza os documentos "N380" e "N740" já existente na adição com os mesmos valores da Exportação/XML
			IF @IDAdicaoIMP IS NOT NULL		
			BEGIN
				SET @VariaveisSQL = N'@INIDAdicao int, @OUTNumeroDoc varchar(70) OUTPUT, @OUTDataDoc datetime OUTPUT'
-- obtem documento "N380" na Exportação/XML
				SET @ComandoSQL = N'SELECT @OUTNumeroDoc = EXD_NREF, @OUTDataDoc = EXD_DTEM
					FROM ' + @BaseDados + '..PRO_EXDA WITH(NOLOCK) 
					WHERE EXA_CHVE = @INIDAdicao AND DOC_CODI = ''N380'''
				EXEC sp_executesql @ComandoSQL, @VariaveisSQL, @INIDAdicao = @IDAdicao, @OUTNumeroDoc = @NumeroDoc OUTPUT, @OUTDataDoc = @DataDoc OUTPUT
-- atualiza documento "N380" nos documentos
				UPDATE PRO_DDOC SET DDO_NUME = @NumeroDoc, DDO_DINI = @DataDoc
				WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumeroAdicao AND DOC_CODI = 'N380'
-- obtem documento "N740" na Exportação/XML				
				SET @ComandoSQL = N'SELECT @OUTNumeroDoc = EXD_NREF, @OUTDataDoc = EXD_DTEM
					FROM ' + @BaseDados + '..PRO_EXDA WITH(NOLOCK) 
					WHERE EXA_CHVE = @INIDAdicao AND DOC_CODI = ''N740'''
				EXEC sp_executesql @ComandoSQL, @VariaveisSQL, @INIDAdicao = @IDAdicao, @OUTNumeroDoc = @NumeroDoc OUTPUT, @OUTDataDoc = @DataDoc OUTPUT
-- atualiza documento "N740" nos documentos							
				UPDATE PRO_DDOC SET DDO_NUME = @NumeroDoc, DDO_DINI = @DataDoc
				WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumeroAdicao AND DOC_CODI = 'N740'
			END
-- carrega os documentos e menções configurados
			DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT 0, 0, 'S/N', @Data, ad.DOC_CODI, ad.DOC_NOME, 0
				FROM TAB_ADOC AS ad WITH(NOLOCK) INNER JOIN TAB_DOCU AS d WITH(NOLOCK) ON ad.DOC_CODI = d.DOC_CODI
					INNER JOIN TAB_APAU AS a WITH(NOLOCK) ON ad.APA_CHVE = a.APA_CHVE
				WHERE ad.ADC_UIMP = 1 AND a.APA_CODI = @CodArtigo
				UNION ALL					
				SELECT 1, 0, NULL, NULL, am.INF_CODI, am.INF_DESI, 0
				FROM TAB_AMEN AS am WITH(NOLOCK) INNER JOIN TAB_INFC AS m WITH(NOLOCK) ON am.INF_CODI = m.INF_CODI
					INNER JOIN TAB_APAU AS a ON am.APA_CHVE = a.APA_CHVE
				WHERE am.AME_UIMP = 1 AND m.INF_IMPC = 0 AND a.APA_CODI = @CodArtigo
				UNION ALL				
				SELECT 0, 0, (CASE td.DOC_CODI WHEN '9D06' THEN @NumeroDAE ELSE NULL END), (CASE td.DOC_CODI WHEN '9D06' THEN @DataDAE ELSE NULL END), td.DOC_CODI, td.DOC_NOME, 0
				FROM TAB_TDED AS td WITH(NOLOCK) INNER JOIN TAB_DOCU AS d WITH(NOLOCK) ON td.DOC_CODI = d.DOC_CODI
				WHERE td.TDE_CODI = @CodTipoDeclaracao
				UNION ALL
				SELECT 1, 0, (CASE tm.INF_CODI WHEN 'NIVA' THEN @NIFExpedidor ELSE NULL END), NULL, tm.INF_CODI, me.INF_DESI, 0
				FROM TAB_TDEM AS tm WITH(NOLOCK) INNER JOIN TAB_INFC AS me WITH(NOLOCK) ON tm.INF_CODI = me.INF_CODI
				WHERE me.INF_IMPC = 0 AND tm.TDE_CODI = @CodTipoDeclaracao	
				UNION ALL
				SELECT 0, 2, c.DEC_NAOE, c.DEC_DTOE, d.DOC_CODI, d.DOC_NOME, 0
				FROM TAB_DECL AS c WITH(NOLOCK) INNER JOIN TAB_DOCU AS d WITH(NOLOCK) ON (CASE @TipoDeclaranteIMP WHEN 2 THEN c.DOC_CDOE ELSE c.DOC_CODI2 END) = d.DOC_CODI
				WHERE c.DEC_FXOE IN (0, 1) AND ISNULL(c.DEC_NAOE, '') <> '' AND c.DEC_CODI = @CodDeclaranteIMP AND @NumeroAdicao = 1
			OPEN Documentos
			FETCH NEXT from Documentos into @TipoDocumento, @DocumentoAuto, @NumeroDocumento, @DataEmissao, @CodDocumento, @NomeDocumento, @MontanteDocumento
			WHILE @@FETCH_STATUS = 0
			BEGIN				
-- obtem dados em falta
				SET @UltNumeroAnexoDocs = @UltNumeroAnexoDocs + 1
-- insere Documento na adição
				INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, DDO_MONT, DDO_DPRZ, DDO_AUTO, DDO_TIPO)
				VALUES(@AnoProcesso, @NumProcesso, @NumeroAdicao, @UltNumeroAnexoDocs, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataEmissao, @MontanteDocumento, 0, @DocumentoAuto, @TipoDocumento)		
				FETCH NEXT from Documentos into @TipoDocumento, @DocumentoAuto, @NumeroDocumento, @DataEmissao, @CodDocumento, @NomeDocumento, @MontanteDocumento
			END
			CLOSE Documentos
			DEALLOCATE Documentos
-- carrega Imposicoes da adição
			DECLARE Imposicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR				
				SELECT 1, RRE_CODI, RRE_NOME, RRE_IVA, @ImposicaoDireitos, @TaxaValor, @BaseTribDireitos, @MontanteDireitos, (CASE @TributacaoValorArtigo WHEN 1 THEN 0 ELSE 1 END), @NumCaucaoIMP, @AnoCaucaoIMP, @TipoCaucaoIMP, @EntCaucaoIMP
				FROM TAB_RREC
				WHERE RRE_CODI = @CodRubricaPreferencia
				UNION ALL
				SELECT 2, RRE_CODI, RRE_NOME, RRE_IVA, @ImposicaoIVA, @TxIVAArtigo, @BaseTribIVA, @MontanteIVA, 1, @NumCaucaoIVA, @AnoCaucaoIVA, @TipoCaucaoIVA, @EntidadeCaucaoIVA
				FROM TAB_RREC
				WHERE RRE_CODI = @CodRubricaIVA		
			OPEN Imposicoes
			FETCH NEXT from Imposicoes into @ImposicaoAuto, @CodRubrica, @NomeRubrica, @RubricaIVA, @ImposicaoRubrica, @TaxaValorImposicao, @BaseTribImposicao, @MontanteImposicao, @ImposicaoTaxa, @NumCaucao, 
				@AnoCaucao, @TipoCaucao, @EntidadeCaucao
			WHILE @@FETCH_STATUS = 0
			BEGIN						
-- verifcia se imposição existe para editar ou inserir
				IF EXISTS(SELECT DUO_CODI FROM PRO_DUOI WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumeroAdicao AND DUO_AUTO = @ImposicaoAuto)	
				BEGIN
					UPDATE PRO_DUOI SET RRE_CODI = @CodRubrica, RRE_NOME = @NomeRubrica, DUO_TIPO = @ImposicaoTaxa, DUO_BTRI = @BaseTribImposicao, DUO_TXVL = @TaxaValorImposicao, DUO_MONT = @MontanteImposicao, 
						RRE_LIVA = @RubricaIVA, DUO_IMPO = @ImposicaoRubrica, DUO_CAUC = @NumCaucao, DUO_CANO = @AnoCaucao, DUO_CTIP = @TipoCaucao, DUO_CENT = @EntidadeCaucao
					WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumeroAdicao AND DUO_AUTO = @ImposicaoAuto
				END
				ELSE
				BEGIN	
					SET @UltNumeroAnexoImposicoes = @UltNumeroAnexoImposicoes + 1
					INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_LIVA, DUO_IMPO, DUO_AUTO, DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT)
					VALUES(@AnoProcesso, @NumProcesso, @NumeroAdicao, @UltNumeroAnexoImposicoes, @CodRubrica, @NomeRubrica, @ImposicaoTaxa, @BaseTribImposicao, @TaxaValorImposicao, @MontanteImposicao, 
						@RubricaIVA, @ImposicaoRubrica, @ImposicaoAuto, @NumCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao)		
				END
				FETCH NEXT from Imposicoes into @ImposicaoAuto, @CodRubrica, @NomeRubrica, @RubricaIVA, @ImposicaoRubrica, @TaxaValorImposicao, @BaseTribImposicao, @MontanteImposicao, @ImposicaoTaxa, 
					@NumCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao
			END
			CLOSE Imposicoes
			DEALLOCATE Imposicoes
			FETCH NEXT FROM Adicoes INTO @IDAdicao, @NumeroAdicao, @CodArtigo, @MassaBruta, @MassaLiquida, @QtdUnidades, @CodUnidSuplementar, @PrecoAdicao
-- actualiza campos totalizadores na declaração
			UPDATE PRO_DUCG SET DUC_VATT = @ValorAduaneiroTotal
			WHERE DUC_PNUM = @NumProcesso and DUC_EANO = @AnoProcesso
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) 
			+ ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- remove tabela temporária de adições
	DROP TABLE #tmpAdicoesRetorno
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaDAERetorno] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaDAERetorno] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaDeclaracoesDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaDeclaracoesDHL] @DirectoriaErros varchar(500), @CodAeroporto varchar(3), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
-- declaração de variáveis
	DECLARE @NumDocTransporte varchar(12), @AeroportoOrigem varchar(3), @AeroportoDestino varchar(3), @NumVolumes int, @ComandoDOS varchar(1000), 
		@PathFicheiro varchar(500), @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin), @ListaErros varchar(MAX), @i int, @Erros varchar(MAX), @Linha varchar(MAX)
-- cria tabela temporária p/ lista de regiões
	CREATE TABLE #Regioes(CODPOSTAL_DE int, CODPOSTAL_A int, CODREGIAO int)	
-- insere mapeamento de códigos postais c/ regiões respetivas
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(2000, 2399, 36)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(2400, 2599, 92)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3000, 3099, 91)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3100, 3199, 92)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3200, 3499, 91)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3500, 3699, 93)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3700, 3899, 90)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(4000, 4699, 81)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(4700, 4999, 10)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5000, 5199, 84)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5200, 5399, 85)	
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5400, 5499, 84)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(6000, 6199, 94)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(6200, 6499, 95)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7000, 7099, 44)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7100, 7199, 45)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7200, 7499, 44)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7500, 7599, 40)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7600, 7999, 43)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(8000, 8999, 50)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(9000, 9499, 70)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(9500, 9999, 60)		
-- cria tabela temporária p/ detalhe de AWB decompostos em função do Nº. Vols de cada declaração DHL
	CREATE TABLE #cdsalertsCPAs(HAHAWB varchar(12) COLLATE Latin1_General_CI_AI, HAOSTN varchar(3) COLLATE Latin1_General_CI_AI, 
		HADSTN varchar(3) COLLATE Latin1_General_CI_AI, AWB_DETALHE varchar(18) COLLATE Latin1_General_CI_AI)	
-- obtem a lista de declarações a importar que tenham N.º Volumes maior que 1
	DECLARE DeclaracoesDHL CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT HAHAWB, HAOSTN, HADSTN, (HDAPCO - 1)
		FROM GIDWIN..cdsalerts
		WHERE HAPGTW = @CodAeroporto and SINGINT = 0 and HDAPCO > 1
	OPEN DeclaracoesDHL
	FETCH NEXT from DeclaracoesDHL into @NumDocTransporte, @AeroportoOrigem, @AeroportoDestino, @NumVolumes
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @i = 1
		WHILE @i <= @NumVolumes
		BEGIN
			INSERT INTO #cdsalertsCPAs(HAHAWB, HAOSTN, HADSTN, AWB_DETALHE)
			VALUES(@NumDocTransporte, @AeroportoOrigem, @AeroportoDestino, (RTRIM(LTRIM(@NumDocTransporte)) + '_' + CAST(@i as varchar(5))))
			SET @i = @i + 1
		END
		FETCH NEXT from DeclaracoesDHL into @NumDocTransporte, @AeroportoOrigem, @AeroportoDestino, @NumVolumes
	END
	CLOSE DeclaracoesDHL
	DEALLOCATE DeclaracoesDHL			
-- inicia variaveis		
	SET @ListaErros = ''		
	BEGIN TRY	
-- obtem lista das declarações de importação da tabela DHL em formato XML 	
		SET @DocumentoXML = 
			(SELECT
				(SELECT 'I' "@Acao", (CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 127) + 'Z') "Data", 
					(CASE WHEN dadosDHL.HDMFSP in ('ACH5', 'ACH6', 'CASH', 'DDP5', 'DDP6') THEN 'PRE' ELSE 'CDS' END) "CodNatureza", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HAHAWB)), '') "NumDocTransporte", 
					(CASE WHEN dadosDHL.HDCOO in ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS') THEN 'EUA' ELSE 'IMA' END) "CodTipoDeclaracao", 
					(CASE RTRIM(LTRIM(dadosDHL.HAPGTW)) WHEN 'LIS' THEN 'PT000015' ELSE 'PT000020' END) "CodEstancia", 
					(CASE (SELECT COUNT(*) FROM TAB_CLIE WHERE CLI_NIF = RTRIM(LTRIM(dadosDHL.HACVAT))) WHEN 0 THEN NULL ELSE (SELECT TOP 1 CLI_CODI FROM TAB_CLIE WHERE CLI_NIF = RTRIM(LTRIM(dadosDHL.HACVAT))) END) "CodDestinatario", 
					'01' "CodDeclarante", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HDCOO)), '') "CodPais15A", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HDCOO)), '') "CodPais16",					
					'40' "CodMeioTransporte18", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HDMOVN)), '') "IdMeioTransporte", 
					'40' "CodMeioTransporte21", 0 "TemContentores", 
					ISNULL(NULLIF(RTRIM(LTRIM(dadosDHL.SDTERM)), ''), 'XXX') "CodCondEntrega", 										
					'11' "CodNaturezaTransacao", 
					(CASE RTRIM(LTRIM(dadosDHL.HAPGTW)) WHEN 'LIS' THEN 'DTP00000487015PT' ELSE 'DTP00000473020PT' END) "CodLocalAutorizado",
					ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(dadosDHL.SDPCUR, 1, 2))), ''), 'EU') "CodPais22", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HASHIP)), '') "NomeExpedidor", 
					NULLIF(RTRIM(LTRIM(RTRIM(LTRIM(ISNULL(dadosDHL.HASHP1, ''))) + ' ' + RTRIM(LTRIM(ISNULL(dadosDHL.HASHP2, ''))))), '') "MoradaExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HASHP3)), '') "LocalidadeExpedidor", 
					ISNULL(NULLIF(RTRIM(LTRIM(dadosDHL.HASZIP)), ''), '.') "CodPostalExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HASHP3)), '') "LocPostalExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HDCOO)), '') "CodPaisExpedidor", 					
					NULLIF(RTRIM(LTRIM(dadosDHL.HACGEE)), '') "NomeDestinatario", 
					NULLIF(RTRIM(LTRIM(RTRIM(LTRIM(ISNULL(dadosDHL.HACGE1, ''))) + ' ' + RTRIM(LTRIM(ISNULL(dadosDHL.HACGE2, ''))))), '') "MoradaDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HACGE3)), '') "LocalidadeDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HACZIP)), '') "CodPostalDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HACGE3)), '') "LocPostalDestinatario", 					
					NULLIF(RTRIM(LTRIM(dadosDHL.HACTEL)), '') "TelefoneDestinatario", 					
					NULLIF(RTRIM(LTRIM(dadosDHL.HAMAIL)), '') "EmailDestinatario", 						
					NULLIF(RTRIM(LTRIM(dadosDHL.HACVAT)), '') "NIFDestinatario", 					
					'PT' "CodPaisDestinatario",					
					(CASE ISNUMERIC(SUBSTRING(RTRIM(LTRIM(dadosDHL.HACZIP)), 1, 4)) WHEN 1 THEN ISNULL((SELECT CODREGIAO FROM #Regioes WHERE CAST(SUBSTRING(RTRIM(LTRIM(dadosDHL.HACZIP)), 1, 4) as int) BETWEEN CODPOSTAL_DE AND CODPOSTAL_A), 35) ELSE NULL END) "CodRegiaoDestinatario",
					(CONVERT(varchar(10), CAST(STR(dadosDHL.HDMOVS, 8) as datetime), 127) + 'Z') "DataPrevVoo",
					NULLIF(RTRIM(LTRIM(dadosDHL.HACNUM)), '') "NumContaExpedidor",	
					NULLIF(RTRIM(LTRIM(dadosDHL.HDCMRN)), '') "NumContaDestinatario",				
					NULLIF(RTRIM(LTRIM(dadosDHL.HDDGTW)), '') "Aeroporto", 					
					NULLIF(RTRIM(LTRIM(dadosDHL.HDMOVN)), '') "NumVoo",
					NULLIF(RTRIM(LTRIM(dadosDHL.HAHAWB)), '') "MiniCPA",
					NULLIF(RTRIM(LTRIM(dadosDHL.HACGEE)), '') "Referencia1",
					NULLIF(SUBSTRING(RTRIM(LTRIM(RTRIM(LTRIM(ISNULL(dadosDHL.HACGE1, ''))) + ' ' + RTRIM(LTRIM(ISNULL(dadosDHL.HACGE2, ''))))), 1, 50), '') "Referencia2",
					NULLIF(RTRIM(LTRIM(dadosDHL.HDDPRD)), '') "ShipID", 					
					NULLIF(RTRIM(LTRIM(dadosDHL.HAHAWB)), '') "Tracking",
					NULLIF(SUBSTRING(RTRIM(LTRIM(dadosDHL.HDMFSP)), 1, 2), '') "DType",	
					NULLIF(RTRIM(LTRIM(dadosDHL.HADSTN)), '') "PosicaoAviao",				
					NULLIF(RTRIM(LTRIM(dadosDHL.HDCSTS)), '') "TipoCarga",
					NULLIF(RTRIM(LTRIM(dadosDHL.HAOSTN)), '') "NomeFileUPS",
					NULLIF(RTRIM(LTRIM(dadosDHL.HACGEE)), '') "NomeDestinatario2", 
					NULLIF(RTRIM(LTRIM(RTRIM(LTRIM(ISNULL(dadosDHL.HACGE1, ''))) + ' ' + RTRIM(LTRIM(ISNULL(dadosDHL.HACGE2, ''))))), '') "MoradaDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HACGE3)), '') "LocalidadeDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HACZIP)), '') "CodPostalDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosDHL.HACGE3)), '') "LocPostalDestinatario2", 					
					1 "EDeclaracaoImportacao", 
					(CASE WHEN dadosDHL.HDMFSP in ('ACH5', 'ACH6', 'CASH', 'DDP5', 'DDP6') THEN 0 ELSE 999 END) "CodFollowUp",
					(CONVERT(varchar(10), CAST(STR(dadosDHL.HA_CRT_DT, 8) as datetime), 127) + 'Z') "DataDocCPA", 
					(SELECT
						(SELECT 1 "NumAdicao", 
							(CASE RTRIM(LTRIM(ISNULL(dadosDHL.SDCOMC, ''))) WHEN '' THEN '0000000000' ELSE (CASE (SELECT COUNT(*) FROM TAB_APAU WHERE APA_CPAU = RTRIM(LTRIM(dadosDHL.SDCOMC))) WHEN 0 THEN '0000000000' ELSE (SELECT TOP 1 APA_CODI FROM TAB_APAU WHERE APA_CPAU = RTRIM(LTRIM(dadosDHL.SDCOMC))) END) END) "CodArtigoPautal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(dadosDHL.SDCNTR, 1, 2))), '') "CodPaisOrigem",
							CAST(dadosDHL.SDIBWG as numeric(28, 6)) "MassaBruta",							
							CAST(ISNULL(dadosDHL.SDINWG, 0.000000) as numeric(28, 6)) "MassaLiquida",
							0.000000 "QtdUnidades",
							CAST(dadosDHL.SDPVAL as numeric(28, 6)) "PrecoAdicao",
							1 "MetodoAvaliacao",
							(SELECT
								(SELECT 'LETREIRO' "Marca", 									
									CAST(dadosDHL.HDAPCO as numeric(28, 6)) "QtdVolumes",
									'CT' "CodUnidMedida", CAST(0 as bit) "P", CAST(0 as bit) "R", CAST(0 as bit) "C"						
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE)
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE),
					(SELECT
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(dadosDHL.SDCNTR, 1, 2))), '') "CodPais",
							NULLIF(RTRIM(LTRIM(dadosDHL.HADESC)), '') "Descricao",							
							NULLIF(RTRIM(LTRIM(dadosDHL.SDPCUR)), '') "Moeda",							
							CAST(dadosDHL.SDPVAL as numeric(28, 6)) "TotalFatura",
							NULLIF(RTRIM(LTRIM(dadosDHL.HAHAWB)), '') "NumeroCPA",
							CAST(dadosDHL.SDIBWG as numeric(28, 6)) "Peso",
							0 "Tipo"
						FOR XML PATH('DadosManifesto'), TYPE),
						(SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(dadosDHL.SDCNTR, 1, 2))), '') "CodPais",
							NULLIF(RTRIM(LTRIM(dadosDHL.HADESC)), '') "Descricao",							
							NULLIF(RTRIM(LTRIM(dadosDHL.SDPCUR)), '') "Moeda",							
							CAST(dadosDHL.SDPVAL as numeric(28, 6)) "TotalFatura",
							AWB_DETALHE "NumeroCPA",
							CAST(dadosDHL.SDIBWG as numeric(28, 6)) "Peso",
							0 "Tipo"
						FROM #cdsalertsCPAs
						WHERE HAHAWB = dadosDHL.HAHAWB and HAOSTN = dadosDHL.HAOSTN and HADSTN = dadosDHL.HADSTN
						FOR XML PATH('DadosManifesto'), TYPE)
					FOR XML PATH('Manifestos'), TYPE)
				FROM GIDWIN..cdsalerts as dadosDHL 
				WHERE dadosDHL.HAPGTW = @CodAeroporto and dadosDHL.SINGINT = 0
					and NOT EXISTS(SELECT DUC_PNUM FROM PRO_DUCG WHERE DUC_EANO = YEAR(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) and DUC_CPRT = NULLIF(RTRIM(LTRIM(dadosDHL.HAHAWB)), ''))
				FOR XML PATH('Declaracao'), TYPE)				
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)				
-- processa a geração das Declarações de Importação carregadas no XML			
		EXEC SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @ListaErros OUTPUT		
-- actualiza as Declarações de Importação DHL processadas
		UPDATE GIDWIN..cdsalerts SET SINGINT = 1
		FROM PRO_DUCG
		WHERE GIDWIN..cdsalerts.HAPGTW = @CodAeroporto and GIDWIN..cdsalerts.SINGINT = 0 and NULLIF(RTRIM(LTRIM(GIDWIN..cdsalerts.HAHAWB)), '') = PRO_DUCG.DUC_CPRT and 
			NULLIF(RTRIM(LTRIM(GIDWIN..cdsalerts.HAOSTN)), '') = PRO_DUCG.DUC_FUPS
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @ListaErros = @ListaErros + 
							   '**********************************************************************************************************' + CHAR(12) +
							   '** ERRO NA CONVERSAO DE DADOS DHL ************************************************************************' + CHAR(12) + 							   
							   '**********************************************************************************************************' + CHAR(12) + 							   
							   '.Aeroporto Destino:  ' + @CodAeroporto + CHAR(12) +								   
							   '.Detalhe Erro:       ' + CHAR(12) +
							   '		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
							   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
							   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
							   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
							   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
							   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
							   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
	END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
	IF ISNULL(@ListaErros, '') <> ''
	BEGIN					
		SET @PathFicheiro = @DirectoriaErros + '\' + REPLACE(CAST(CAST(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT() as numeric(38,6)) as varchar(20)), '.', '_') + '.txt.err'
		SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
		WHILE @i > 0
		BEGIN
			SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
			EXEC GIDWIN..SP_Externo_EscreveLinhaFicheiro @PathFicheiro, @Linha, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)				
			SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
		END			
	END	
-- remove a tabela temporária
	DROP TABLE #cdsalertsCPAs	
	DROP TABLE #Regioes			
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaDeclaracoesDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaDeclaracoesDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaDeclaracoesTNT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaDeclaracoesTNT] @DirectoriaErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumDocTransporte varchar(18), @AeroportoOrigem varchar(3), @AeroportoDestino varchar(3), @TipoManifesto varchar(1), @DataVoo datetime, @NumVolumes int, @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin), 
		@ListaErros varchar(MAX), @i int, @Erros varchar(MAX), @PathFicheiroErro varchar(500), @Linha varchar(MAX)
-- cria tabela temporária p/ detalhe de AWB decompostos em função do Nº. Vols de cada declaração TNT
	CREATE TABLE #IMP_CPAS(DU2_CPRT varchar(18) COLLATE Latin1_General_CI_AI, DU2_AERP varchar(3) COLLATE Latin1_General_CI_AI, 
		DU2_AERD varchar(3) COLLATE Latin1_General_CI_AI, DU2_TMAN varchar(1) COLLATE Latin1_General_CI_AI, DU2_DTVO datetime, 
		CPA_CPR2 varchar(35) COLLATE Latin1_General_CI_AI)	
-- obtem a lista de declarações a importar que tenham N.º Volumes maior que 1 
	DECLARE DeclaracoesTNT CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT DU2_CPRT, DU2_AERP, DU2_AERD, DU2_TMAN, DU2_DTVO, (DU2_TVL6 - 1)
		FROM IMP_DUI2
		WHERE DU2_SINT = 0 and DU2_TVL6 > 1 and ROUND((DU2_MT22 / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL) WHEN SUBSTRING(DU2_PR22, 1, 2) THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL)
										ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
											FROM TAB_CPAI
											WHERE PAI_CODI = SUBSTRING(DU2_PR22, 1, 2) and CPA_DATA <= CAST(CONVERT(varchar(10), GETDATE(), 105) + ' 23:58:58' as datetime)
											ORDER BY CPA_DATA desc) END), 1)), 2) > 150
	OPEN DeclaracoesTNT
	FETCH NEXT from DeclaracoesTNT into @NumDocTransporte, @AeroportoOrigem, @AeroportoDestino, @TipoManifesto, @DataVoo, @NumVolumes
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @i = 1
		WHILE @i <= @NumVolumes
		BEGIN
			INSERT INTO #IMP_CPAS(DU2_CPRT, DU2_AERP, DU2_AERD, DU2_TMAN, DU2_DTVO, CPA_CPR2)
			VALUES(@NumDocTransporte, @AeroportoOrigem, @AeroportoDestino, @TipoManifesto, @DataVoo, (RTRIM(LTRIM(@NumDocTransporte)) + '_' + CAST(@i as varchar(5))))
			SET @i = @i + 1
		END
		FETCH NEXT from DeclaracoesTNT into @NumDocTransporte, @AeroportoOrigem, @AeroportoDestino, @TipoManifesto, @DataVoo, @NumVolumes
	END
	CLOSE DeclaracoesTNT
	DEALLOCATE DeclaracoesTNT			
-- inicia variaveis		
	SET @ListaErros = ''		
	BEGIN TRY	
-- obtem lista das declarações de importação do repostório de Declarações p/ integração em formato XML 	
		SET @DocumentoXML = 
			(SELECT
				(SELECT 'I' "@Acao", (CONVERT(varchar(10), GETDATE(), 127) + 'Z') "Data", '99' "CodNatureza", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CPRT)), '') "NumDocTransporte", 
					(CASE WHEN RTRIM(LTRIM(dadosTNT.DU2_PA15)) IN ('CH', 'NO', 'GB', 'TR', 'LI', 'SM', 'AD', 'GI', 'UA') THEN 'EUA' ELSE 'IMA' END) "CodTipoDeclaracao", 
					RTRIM(LTRIM(dadosTNT.DU2_ALFA)) "CodEstancia", 
					(CASE (SELECT COUNT(*) FROM TAB_CLIE WHERE CLI_CEAN = NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CEAN)), '')) WHEN 0 THEN (CASE (SELECT COUNT(*) FROM TAB_CLIE WHERE CLI_NIF = NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNIF)), '')) WHEN 0 THEN NULL ELSE (SELECT TOP 1 CLI_CODI FROM TAB_CLIE WHERE CLI_NIF = NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNIF)), '')) END) ELSE (SELECT TOP 1 CLI_CODI FROM TAB_CLIE WHERE CLI_CEAN = NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CEAN)), '')) END) "CodDestinatario", 
					'0691I8' "CodDeclarante", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA15)), '') "CodPais15A", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA16)), '') "CodPais16",					
					(CASE WHEN NULLIF(RTRIM(LTRIM(dadosTNT.DU2_NVSR)), '') IN (9, 10, 12, 15) THEN '40' ELSE '30' END) "CodMeioTransporte18", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_MT18)), '') "IdMeioTransporte", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_TR21)), '') "CodMeioTransporte21", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA21)), '') "CodPais21",
					dadosTNT.DU2_CT19 "TemContentores", RTRIM(LTRIM(dadosTNT.DU2_CO20)) "CodCondEntrega", 										
					RTRIM(LTRIM(dadosTNT.DU2_CO24)) "CodNaturezaTransacao", 
					RTRIM(LTRIM(dadosTNT.DU2_CO30)) "CodLocalAutorizado",
					RTRIM(LTRIM(dadosTNT.DU2_PR22)) "CodPais22", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ENOM)), '') "NomeExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_EMOR)), '') "MoradaExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ELOC)), '') "LocalidadeExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ECPO)), '') "CodPostalExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_ELPO)), '') "LocPostalExpedidor", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA15)), '') "CodPaisExpedidor", 					
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNOM)), '') "NomeDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DMOR)), '') "MoradaDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLOC)), '') "LocalidadeDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DCPO)), '') "CodPostalDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLPO)), '') "LocPostalDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNIF)), '') "NIFDestinatario", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA17)), '') "CodPaisDestinatario",					
					(CONVERT(varchar(10), dadosTNT.DU2_DTVO, 127) + 'Z') "DataPrevVoo",
					dadosTNT.DU2_PAYM "Payment",
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_NVRF)), '') "NumVossaReferencia", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CIEX)), '') "NumContaExpedidor",	
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_CIDE)), '') "NumContaDestinatario", 				
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_AERO)), '') "Aeroporto", 	
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PPFC)), '') "PPouFC", 				
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_NVOO)), '') "NumVoo",
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_MCPA)), '') "MiniCPA",
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_REF1)), '') "Referencia1",
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_REF2)), '') "Referencia2",					
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_SHIP)), '') "ShipID", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_TRAC)), '') "Tracking",					
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DTYP)), '') "DType",	
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_AERP)), '') "PosicaoAviao",				
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_TPCG)), '') "TipoCarga",
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_AERD)), '') "NomeFileUPS",
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DNOM)), '') "NomeDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DMOR)), '') "MoradaDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLOC)), '') "LocalidadeDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DCPO)), '') "CodPostalDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DLPO)), '') "LocPostalDestinatario2", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_GTWY)), '') "Gateway", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DELG)), '') "Delegacao",
					1 "EDeclaracaoImportacao", 
					dadosTNT.DU2_NVSR "NivelServico", 
					6 "CodFollowUp",
					(CONVERT(varchar(10), dadosTNT.DU2_DTIN, 127) + 'Z') "DataDocCPA", 
					NULLIF(RTRIM(LTRIM(dadosTNT.DU2_TMAN)), '') "TipoManifesto", 
					(SELECT
						(SELECT 1 "NumAdicao", 
							(CASE RTRIM(LTRIM(ISNULL(dadosTNT.DU2_CO33, ''))) WHEN '' THEN '0000000000' ELSE (CASE (SELECT COUNT(*) FROM TAB_APAU WHERE APA_CPAU = RTRIM(LTRIM(dadosTNT.DU2_CO33))) WHEN 0 THEN '0000000000' ELSE (SELECT TOP 1 APA_CODI FROM TAB_APAU WHERE APA_CPAU = RTRIM(LTRIM(dadosTNT.DU2_CO33))) END) END) "CodArtigoPautal", 							
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA16)), '') "CodPaisOrigem",
							CAST(dadosTNT.DU2_MBRT as numeric(28, 6)) "MassaBruta",							
							CAST(dadosTNT.DU2_MLQT as numeric(28, 6)) "MassaLiquida",
							CAST(dadosTNT.DU2_US41 as numeric(28, 6)) "QtdUnidades",
							CAST(dadosTNT.DU2_MT22 as numeric(28, 6)) "PrecoAdicao",
							1 "MetodoAvaliacao",
							(SELECT
								(SELECT 'S/M' "Marca", 									
									CAST(dadosTNT.DU2_TVL6 as numeric(28, 6)) "QtdVolumes",
									'CT' "CodUnidMedida", CAST(0 as bit) "P", CAST(0 as bit) "R", CAST(0 as bit) "C"						
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE)
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE),
					(SELECT
						(SELECT NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA16)), '') "CodPais",
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DESG)), '') "Descricao",							
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PR22)), '') "Moeda",							
							CAST(dadosTNT.DU2_MT22 as numeric(28, 6)) "TotalFatura",
							RTRIM(LTRIM(dadosTNT.DU2_CPRT)) "NumeroCPA",
							CAST(dadosTNT.DU2_MBRT as numeric(28, 6)) "Peso",
							0 "Tipo"
						FOR XML PATH('DadosManifesto'), TYPE),
						(SELECT NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PA16)), '') "CodPais",
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_DESG)), '') "Descricao",							
							NULLIF(RTRIM(LTRIM(dadosTNT.DU2_PR22)), '') "Moeda",									
							CAST(dadosTNT.DU2_MT22 as numeric(28, 6)) "TotalFatura",
							CPA_CPR2 "NumeroCPA",
							CAST(dadosTNT.DU2_MBRT as numeric(28, 6)) "Peso",
							0 "Tipo"
						FROM #IMP_CPAS
						WHERE DU2_CPRT = dadosTNT.DU2_CPRT and DU2_AERP = dadosTNT.DU2_AERP and DU2_AERD = dadosTNT.DU2_AERD 
							and DU2_TMAN = dadosTNT.DU2_TMAN and DU2_DTVO = dadosTNT.DU2_DTVO
						FOR XML PATH('DadosManifesto'), TYPE)
					FOR XML PATH('Manifestos'), TYPE),
					(SELECT
						(SELECT 'PAC' "CodStatusIncidencia"
						FOR XML PATH('DadosIncidencia'), TYPE)
					FOR XML PATH('Incidencias'), TYPE)
				FROM IMP_DUI2 as dadosTNT 
				WHERE dadosTNT.DU2_SINT = 0 AND ROUND((dadosTNT.DU2_MT22 / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN SUBSTRING(dadosTNT.DU2_PR22, 1, 2) THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
										ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
											FROM TAB_CPAI WITH(NOLOCK)
											WHERE PAI_CODI = SUBSTRING(dadosTNT.DU2_PR22, 1, 2) and CPA_DATA <= CAST(CONVERT(varchar(10), GETDATE(), 105) + ' 23:58:58' as datetime)
											ORDER BY CPA_DATA desc) END), 1)), 2) > 150
				FOR XML PATH('Declaracao'), TYPE)				
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)				
-- processa a geração das Declarações de Importação carregadas no XML		
		EXEC SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @ListaErros OUTPUT		
-- actualiza as Declarações de Importação TNT processadas
		UPDATE IMP_DUI2 SET DU2_SINT = 1, DU2_DTEX = GETDATE()
		FROM PRO_DUCG WITH(NOLOCK)
		WHERE IMP_DUI2.DU2_SINT = 0 AND ROUND((IMP_DUI2.DU2_MT22 / ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN SUBSTRING(IMP_DUI2.DU2_PR22, 1, 2) THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
										ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
											FROM TAB_CPAI WITH(NOLOCK)
											WHERE PAI_CODI = SUBSTRING(IMP_DUI2.DU2_PR22, 1, 2) and CPA_DATA <= CAST(CONVERT(varchar(10), GETDATE(), 105) + ' 23:58:58' as datetime)
											ORDER BY CPA_DATA desc) END), 1)), 2) > 150
			AND RTRIM(LTRIM(IMP_DUI2.DU2_CPRT)) = PRO_DUCG.DUC_CPRT AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_AERP)), '') = PRO_DUCG.DUC_POSA AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_AERD)), '') = PRO_DUCG.DUC_FUPS 
			AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_TMAN)), '') = PRO_DUCG. DUC_TMAN AND IMP_DUI2.DU2_DTVO = PRO_DUCG.DUC_DTVO
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @ListaErros = @ListaErros + 
							   '**********************************************************************************************************' + CHAR(12) +
							   '** ERRO NA CONVERSAO DE DADOS TNT ************************************************************************' + CHAR(12) + 							   
							   '**********************************************************************************************************' + CHAR(12) + 							   							   
							   '.Detalhe Erro:       ' + CHAR(12) +
							   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
							   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
							   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
							   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
							   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
							   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
							   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
	END CATCH
-- se ocorreram erros no tratamento das declarações ou processamento das declarações, gera ficheiro de erros
	IF ISNULL(@ListaErros, '') <> ''
	BEGIN							
		SET @PathFicheiroErro = @DirectoriaErros + '\' + REPLACE(CAST(CAST(GETDATE() as numeric(38,6)) as varchar(20)), '.', '_') + '.txt'															
		SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
		WHILE @i > 0
		BEGIN
			SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
			EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
			SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
		END					
	END	
-- remove a tabela temporária
	DROP TABLE #IMP_CPAS				
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaDeclaracoesTNT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaDeclaracoesTNT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheiroDARP]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheiroDARP] @NumProcesso int, @AnoProcesso int, @CodNatureza varchar(3), @CodCondEntrega varchar(3), @CodPaisMontante varchar(2), 
	@Montante numeric(38, 6), @CodPaisFrete varchar(2), @Frete numeric(38, 6), @CodPaisSeguro varchar(2), @Seguro numeric(38, 6), @CodArtigo varchar(22), 
	@CodPaisOrigem varchar(2), @Regime1Desdobramento varchar(6), @QtdUnidades numeric(38, 6), @LstDocumentos xml, @DataApresentacao datetime, @Utilizador varchar(30), 
	@MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Erro int, @DataDecl datetime, @CodTipoDecl varchar(4), @1CasaTipoDecl varchar(5), @LocalidadeExpedidorDecl varchar(35), @LocalidadeDestinatarioDecl varchar(35), @TxFDADecl numeric(38, 6), 
		@TotalVolsDecl numeric(38, 6), @TipoDeclaranteDecl int, @CedulaDeclaranteDecl varchar(18), @ValorOptativasDecl numeric(38, 6), @ValorTrafegoDecl numeric(38, 6), 
		@NumCaucaoDecl varchar(24), @AnoCaucaoDecl varchar(4), @TipoCaucaoDecl varchar(1), @EntCaucaoDecl int, @AutSaidaDecl bit, @EEntrepostoAduaneiroDecl bit, @EVolumeMeioTransporte bit, 
		@NumAdicao int, @RegimeAd varchar(4), @MassaLiqAd numeric(38, 6), @VerbaTransAd numeric(38, 6), @RoyaltiesAd numeric(38, 6), @MatPrimasAd numeric(38, 6), 
		@DireitosAd numeric(38, 6), @CodRubDireitosAd int, @ImposicaoDireitosAd varchar(3), @BaseManualAd bit, @NumCaucaoDireitosAd varchar(24), @AnoCaucaoDireitosAd varchar(4), 
		@TipoCaucaoDireitosAd varchar(1), @EntCaucaoDireitosAd int, @ValorISVAd numeric(38, 6), @AjusteBTIAd numeric(38, 6), @TipoTaxaPreferencia int, @UltNumeroAnexoDocs int, 
		@UltNumeroAnexoImps int, @NomeNatureza varchar(35), @LugarCondEntrega varchar(30), @CodFormulaCondEntrega int, @PrefMoedaMontante varchar(3), @CambioMoedaMontante numeric(38, 6), 
		@PrefMoedaFrete varchar(3), @CambioMoedaFrete numeric(38, 6), @PrefMoedaSeguro varchar(3), @CambioMoedaSeguro numeric(38, 6), @CodPautalArtigo varchar(22), 
		@DescArtigo varchar(150), @CodUnidSuplementarArtigo varchar(10), @TipoTributacaoArtigo int, @TxIVAArtigo numeric(38, 6), @CodMercPerArtigo varchar(10), @IC1Artigo varchar(4), 
		@IC2Artigo varchar(4), @IC3Artigo varchar(4), @CodUnidTributacaoArtigo varchar(3), @TributacaoValorArtigo bit, @NomePaisOrigem varchar(35), @DescricaoFormula varchar(70), 
		@ValorFOBFormula bit, @SomaFormula bit, @NomeUnidSuplementar varchar(10), @CodRubricaIVA int, @NomeRubricaIVA varchar(70), @ImposicaoIVA varchar(3), @NumCaucaoIVAAd varchar(24), 
		@AnoCaucaoIVAAd varchar(4), @TipoCaucaoIVAAd varchar(1), @EntCaucaoIVAAd int, @NomeUnidMedida varchar(35), @FatorUnidMedida numeric(38, 6), @ValorEUR numeric(38, 6), 
		@Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @TaxaValor numeric(38, 6), @BaseTribDireitos numeric(38, 6), @MontanteTribDireitos numeric(38, 6), 
		@ValorOptativas numeric(38, 6), @BaseTribIVA numeric(38, 6), @MontanteTribIVA numeric(38, 6), @MontanteRubricaCTT numeric(38, 6), @TotalLiquidacao numeric(38, 6),
		@CodPaisFreteOriginal varchar(2)
-- inicia variáveis
	SET @Erro = 0	
	SET @Montante = ISNULL(@Montante, 0)
	SET @CodPaisFrete = NULLIF(@CodPaisFrete, '')
	SET @Frete = ISNULL(@Frete, 0)
	SET @CodPaisSeguro = NULLIF(@CodPaisSeguro, '')
	SET @Seguro = ISNULL(@Seguro, 0)
	SET @Regime1Desdobramento = NULLIF(@Regime1Desdobramento, '')
	SET @QtdUnidades = ISNULL(@QtdUnidades, 0)
	SET @CodPaisFreteOriginal = @CodPaisFrete
-- inicia transacção para atualização dos dados DARP na Declarações de Importação
	BEGIN TRANSACTION		
	BEGIN TRY	
-- obtem dados da declaração de importação	
		SELECT @DataDecl = duc.DUC_DATA, @CodTipoDecl = duc.TDE_CODI, @1CasaTipoDecl = duc.TDE_1CAS, @TotalVolsDecl = ISNULL(duc.DUC_TVL6, 0), @TipoDeclaranteDecl = duc.DUC_TPDC, 
			@CedulaDeclaranteDecl = duc.DEC_CENI, @ValorOptativasDecl = ISNULL(duc.DUC_OP18, 0), @ValorTrafegoDecl = ISNULL(duc.DUC_CT18, 0), 
			@LocalidadeExpedidorDecl = duc.DUC_ELOC, @LocalidadeDestinatarioDecl = duc.DUC_DLOC, @CodPaisFrete = ISNULL(@CodPaisFrete, duc.PAI_FRET), 
			@CodPaisSeguro = ISNULL(@CodPaisSeguro, duc.PAI_SEGU), @TxFDADecl = ISNULL(duc.DUC_TFDA, 0), @NumCaucaoDecl = duc.DUC_CAUC, @AnoCaucaoDecl = duc.DUC_CANO, 
			@TipoCaucaoDecl = duc.DUC_CTIP, @EntCaucaoDecl = duc.DUC_CENT, @AutSaidaDecl = duc.DUC_ASAI, 
			@EEntrepostoAduaneiroDecl = (CASE WHEN ((duc.TDE_2CAS = 'B') and (LEFT(duc.TAR_CODI, 1) = 'D')) or ((LEFT(dua.DUA_RG37, 1) = '7') and (LEFT(duc.TAR_CODI, 1) <> 'D')) THEN 1 ELSE 0 END), 			
			@EVolumeMeioTransporte = (CASE ISNULL(mtr.MTR_VPVL, 0) WHEN 2 THEN 1 ELSE 0 END), @NumAdicao = dua.DUA_CODI, @RegimeAd = dua.DUA_RG37, @MassaLiqAd = dua.DUA_ML38, 
			@VerbaTransAd = ISNULL(dua.DUA_VTRA, 0), @RoyaltiesAd = ISNULL(dua.DUA_VROY, 0), @MatPrimasAd = ISNULL(dua.DUA_MTPR, 0), @DireitosAd = ISNULL(dua.DUA_VDIR, 0), 
			@CodRubDireitosAd = dua.RRE_PREF, @ImposicaoDireitosAd = dua.DUA_IMPO, @BaseManualAd = dua.DUA_BMAN, @NumCaucaoDireitosAd = dua.DUA_CAUD, 
			@AnoCaucaoDireitosAd = dua.DUA_CAND, @TipoCaucaoDireitosAd = dua.DUA_CTID, @EntCaucaoDireitosAd = dua.DUA_CEND, @ValorISVAd = ISNULL(dua.DUA_IVAV, 0), 
			@AjusteBTIAd = dua.DUA_ABTI, @NumCaucaoIVAAd = dua.DUA_CAUI, @AnoCaucaoIVAAd = dua.DUA_CANI, @TipoCaucaoIVAAd = dua.DUA_CTII, @EntCaucaoIVAAd = dua.DUA_CENI, 
			@TipoTaxaPreferencia = pre.PRE_TAXA, 			
			@UltNumeroAnexoDocs = (SELECT COUNT(*) FROM PRO_DDOC WHERE DUC_EANO = dua.DUC_EANO and DUC_PNUM = dua.DUC_PNUM and DUA_CODI = dua.DUA_CODI), 
			@UltNumeroAnexoImps = (SELECT COUNT(*) FROM PRO_DUOI WHERE DUC_EANO = dua.DUC_EANO and DUC_PNUM = dua.DUC_PNUM and DUA_CODI = dua.DUA_CODI)
		FROM PRO_DUCG AS duc WITH(NOLOCK)
			INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO and duc.DUC_PNUM = dua.DUC_PNUM and dua.DUA_CODI = 1 
			LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON duc.MTR_PT18 = mtr.MTR_CODI
			LEFT OUTER JOIN TAB_PREF AS pre WITH(NOLOCK) ON dua.PRE_CO36 = pre.PRE_CODI			
		WHERE duc.DUC_PNUM = @NumProcesso and duc.DUC_EANO = @AnoProcesso
-- valida declaração de importação
		IF @DataDecl IS NULL
			RAISERROR('Declaração de importação inexistente ou sem adição n.º1.', 16, 1)
-- valida natureza	
		IF ISNULL(@CodNatureza, '') = ''
			RAISERROR('Natureza não pode ser nula ou vazia.', 16, 2)
		ELSE
			IF NOT EXISTS(SELECT NDE_CODI FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNatureza)
				RAISERROR('Natureza inexistente.', 16, 3)
			ELSE
				SELECT @NomeNatureza = NDE_NOME FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = @CodNatureza			
-- valida condição de entrega				
		IF ISNULL(@CodCondEntrega, '') = ''
			RAISERROR('Condição de entrega não pode ser nula ou vazia.', 16, 4)
		ELSE
			IF NOT EXISTS(SELECT CEN_CODI FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = @CodCondEntrega)
				RAISERROR('Condição de entrega inexistente.', 16, 5)
			ELSE
				SELECT @LugarCondEntrega = (CASE WHEN ISNULL(CEN_LOCT, 0) = 0 THEN NULL WHEN ISNULL(CEN_LOCD, 0) = 0 THEN @LocalidadeExpedidorDecl ELSE @LocalidadeDestinatarioDecl END), @CodFormulaCondEntrega = (CASE CEN_CODI WHEN 'XXX' THEN (CASE ISNULL(@CodPaisFreteOriginal, '') WHEN '' THEN FIN_CODI2 ELSE FIN_CODI1 END) ELSE (CASE WHEN CEN_FOR1 = 1 THEN FIN_CODI1 WHEN CEN_FOR2 = 1 THEN FIN_CODI2 WHEN CEN_FOR3 = 1 THEN FIN_CODI3 WHEN CEN_FOR4 = 1 THEN FIN_CODI4 WHEN CEN_FOR5 = 1 THEN FIN_CODI5 ELSE NULL END) END) FROM TAB_CENT WITH(NOLOCK) WHERE CEN_CODI = @CodCondEntrega			
-- valida país do montante
		IF ISNULL(@CodPaisMontante, '') = ''
			RAISERROR('País do montante não pode ser nulo ou vazio.', 16, 6)
		ELSE
			IF NOT EXISTS(SELECT PAI_CODI FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisMontante)
				RAISERROR('País do montante inexistente.', 16, 7)		
			ELSE
				SELECT @PrefMoedaMontante = NULLIF(PAI_PREF, ''), @CambioMoedaMontante = ISNULL((CASE (SELECT PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN TAB_PAIS.PAI_CODI THEN (SELECT PAP_TAXA FROM TAB_PAPL WITH(NOLOCK)) ELSE (SELECT TOP 1 CPA_VEND FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = TAB_PAIS.PAI_CODI and CPA_DATA <= CAST(CONVERT(varchar(10), GETDATE(), 105) + ' 23:58:58' as datetime) ORDER BY CPA_DATA DESC) END), 1) FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisMontante			
-- valida país do frete			
		IF ISNULL(@CodPaisFrete, '') = ''
			RAISERROR('País do frete não pode ser nulo ou vazio.', 16, 8)
		ELSE
			IF NOT EXISTS(SELECT PAI_CODI FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisFrete)
				RAISERROR('País do frete inexistente.', 16, 9)		
			ELSE
				SELECT @PrefMoedaFrete = NULLIF(PAI_PREF, ''), @CambioMoedaFrete = ISNULL((CASE (SELECT PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN TAB_PAIS.PAI_CODI THEN (SELECT PAP_TAXA FROM TAB_PAPL WITH(NOLOCK)) ELSE (SELECT TOP 1 CPA_VEND FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = TAB_PAIS.PAI_CODI and CPA_DATA <= CAST(CONVERT(varchar(10), GETDATE(), 105) + ' 23:58:58' as datetime) ORDER BY CPA_DATA DESC) END), 1) FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisFrete			
-- valida país do seguro			
		IF ISNULL(@CodPaisSeguro, '') = ''
			RAISERROR('País do seguro não pode ser nulo ou vazio.', 16, 10)
		ELSE
			IF NOT EXISTS(SELECT PAI_CODI FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisSeguro)
				RAISERROR('País do seguro inexistente.', 16, 11)		
			ELSE
				SELECT @PrefMoedaSeguro = NULLIF(PAI_PREF, ''), @CambioMoedaSeguro = ISNULL((CASE (SELECT PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) WHEN TAB_PAIS.PAI_CODI THEN (SELECT PAP_TAXA FROM TAB_PAPL WITH(NOLOCK)) ELSE (SELECT TOP 1 CPA_VEND FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = TAB_PAIS.PAI_CODI and CPA_DATA <= CAST(CONVERT(varchar(10), GETDATE(), 105) + ' 23:58:58' as datetime) ORDER BY CPA_DATA DESC) END), 1) FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisSeguro			
-- valida código artigo
		IF ISNULL(@CodArtigo, '') = ''
			RAISERROR('Código artigo não pode ser nulo ou vazio.', 16, 12)
		ELSE
			IF NOT EXISTS(SELECT APA_CODI FROM TAB_APAU WITH(NOLOCK) WHERE APA_INAC = 0 and APA_FLUX in (0, 1) and APA_CODI = @CodArtigo)
				RAISERROR('Código artigo inexistente, inativo ou não está devidamente configurado.', 16, 13)		
			ELSE
				SELECT @CodPautalArtigo = APA_CPAU, @DescArtigo = APA_DESG, @CodUnidSuplementarArtigo = USU_CODI, @TipoTributacaoArtigo = APA_TRIB, @TxIVAArtigo = (CASE WHEN (SUBSTRING(@RegimeAd, 1, 2) in ('42', '51', '53', '71')) or (@Regime1Desdobramento in ('C08', 'C30')) THEN 0 ELSE APA_TIVA END), @CodMercPerArtigo = APA_ATAR, @IC1Artigo = APA_AIC1, @IC2Artigo = APA_AIC2, @IC3Artigo = APA_AIC3, @CodUnidTributacaoArtigo = UME_CODI, @TributacaoValorArtigo = (CASE APA_TRIB WHEN 0 THEN (CASE APA_TXCO WHEN 0 THEN 1 ELSE 0 END) WHEN 1 THEN 1 ELSE 0 END), @TaxaValor = (CASE WHEN (SUBSTRING(@RegimeAd, 1, 2) in ('51', '53', '71')) or (@Regime1Desdobramento in ('C07', 'C08', 'C30')) THEN 0 ELSE (CASE APA_TRIB WHEN 0 THEN (CASE APA_TXCO WHEN 0 THEN @QtdUnidades ELSE 0 END) WHEN 1 THEN (CASE @TipoTaxaPreferencia WHEN 1 THEN ISNULL(APA_TPMN, 0) WHEN 2 THEN ISNULL((SELECT ISNULL(APS_SPMN, 0) FROM TAB_APSP WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_SPMN, 0)) WHEN 3 THEN ISNULL((SELECT ISNULL(APE_EFMN, 0) FROM TAB_APEF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_EFMN, 0)) ELSE 0 END) WHEN 3 THEN (CASE @TipoTaxaPreferencia WHEN 1 THEN (ISNULL((SELECT ISNULL(APT_TFT, 0) + DATEDIFF(MONTH, APT_DATA, GETDATE()) * ISNULL(APT_INCR, 0) FROM TAB_APTF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), 0) + ISNULL(APA_TPT, 0)) WHEN 2 THEN ISNULL((SELECT ISNULL(APS_SPG, 0) FROM TAB_APSP WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_SPG, 0)) WHEN 3 THEN ISNULL((SELECT ISNULL(APE_EFTA, 0) FROM TAB_APEF WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem and APA_CHVE = TAB_APAU.APA_CHVE), ISNULL(APA_EFTA, 0)) ELSE 0 END) ELSE 0 END) END) FROM TAB_APAU WITH(NOLOCK) WHERE APA_INAC = 0 and APA_FLUX in (0, 1) and APA_CODI = @CodArtigo
-- valida país de origem
		IF ISNULL(@CodPaisOrigem, '') = ''
			RAISERROR('País de origem não pode ser nulo ou vazio.', 16, 14)
		ELSE
			IF NOT EXISTS(SELECT PAI_CODI FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem)
				RAISERROR('País de origem inexistente.', 16, 15)		
			ELSE
				SELECT @NomePaisOrigem = NULLIF(PAI_NOME, '') FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem			
-- valida 1º desdobramento do regime
		IF (ISNULL(@Regime1Desdobramento, '') <> '') and (NOT EXISTS(SELECT C37_IDEN FROM GIDWIN.dbo.RGR_IC37 WITH(NOLOCK) WHERE C37_R37A = @RegimeAd and C37_EXPO = 0 and C37_TIPO = @1CasaTipoDecl and C37_R37B = @Regime1Desdobramento))
			RAISERROR('Desdobramento inválido.', 16, 16)	
-- valida data de apresentação
		IF @DataApresentacao IS NULL
			RAISERROR('Data de apresentação não pode ser nula.', 16, 17)
-- obtem dados da formula obtida		
		SELECT @DescricaoFormula = NULLIF(FIN_DESC, ''), @ValorFOBFormula = FIN_VFOB, @SomaFormula = (CASE WHEN CHARINDEX('+', ISNULL(FIN_DESC, '')) < CHARINDEX('-', ISNULL(FIN_DESC, '')) THEN 1 ELSE 0 END)
		FROM TAB_FINC WITH(NOLOCK) 
		WHERE FIN_CODI = @CodFormulaCondEntrega		
-- obtem dados da unidade suplementar obtida
		SELECT @NomeUnidSuplementar = USU_SIGL
		FROM TAB_USUP WITH(NOLOCK) 
		WHERE USU_CODI = @CodUnidSuplementarArtigo		
-- obtem dados da taxa de IVA obtida
		SELECT @CodRubricaIVA = t.RRE_CODI, @NomeRubricaIVA = t.RRE_NOME, @ImposicaoIVA = t.RRE_IMPO
		FROM (SELECT pa.PAP_TXIS as TAXA, rr.RRE_CODI, rr.RRE_NOME, rr.RRE_IMPO
			FROM TAB_PAPL as pa WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON pa.RRE_CDIS = rr.RRE_CODI
			UNION ALL
			SELECT pa.PAP_TXRD, rr.RRE_CODI, rr.RRE_NOME, rr.RRE_IMPO
			FROM TAB_PAPL as pa WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON pa.RRE_CDRD = rr.RRE_CODI
			UNION ALL
			SELECT pa.PAP_TXIN, rr.RRE_CODI, rr.RRE_NOME, rr.RRE_IMPO
			FROM TAB_PAPL as pa WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON pa.RRE_CDIN = rr.RRE_CODI
			UNION ALL
			SELECT pa.PAP_TXNR, rr.RRE_CODI, rr.RRE_NOME, rr.RRE_IMPO
			FROM TAB_PAPL as pa WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON pa.RRE_CDNR = rr.RRE_CODI) as t
		WHERE t.TAXA = @TxIVAArtigo	
-- obtem dados da unidade de medida obtida
		SELECT @NomeUnidMedida = UME_NOME, @FatorUnidMedida = UME_FACT
		FROM TAB_UMED WITH(NOLOCK) 
		WHERE UME_CODI = @CodUnidTributacaoArtigo	
-- calula valor EUR p/ declaração e adição
		SET @ValorEUR = ROUND((@Montante / @CambioMoedaMontante), 2)		
-- calcula valor do ajustamento da adição
		IF @TxFDADecl = 0		
		BEGIN
			IF @SomaFormula = 1
				SET @Ajustamento = ROUND(ROUND(@Frete / @CambioMoedaFrete, 2) + ROUND(@Seguro / @CambioMoedaSeguro, 2) + @RoyaltiesAd + @MatPrimasAd + @DireitosAd, 2)
			ELSE
				SET @Ajustamento = ROUND((ROUND(@Frete / @CambioMoedaFrete, 2) * -1) - ROUND(@Seguro / @CambioMoedaSeguro, 2) + @RoyaltiesAd + @MatPrimasAd - @DireitosAd, 2)
		END
		ELSE
		BEGIN
			IF @SomaFormula = 1
				SET @Ajustamento = ROUND(ROUND(@Frete / @CambioMoedaFrete * @TxFDADecl / 100, 2) + ROUND(@Seguro / @CambioMoedaSeguro, 2) + @RoyaltiesAd + @MatPrimasAd + @DireitosAd, 2)
			ELSE
				SET @Ajustamento = ROUND((ROUND(@Frete / @CambioMoedaFrete * @TxFDADecl / 100, 2) * -1) - ROUND(@Seguro / @CambioMoedaSeguro, 2) + @RoyaltiesAd + @MatPrimasAd - @DireitosAd, 2)
		END
-- calcula valor estatistico da adição
		SET @ValorEstatistico = @ValorEUR + @Ajustamento - @MatPrimasAd		
-- calcula valor da base de tributação dos direitos da adição
		IF @BaseManualAd = 0
		BEGIN
			IF @TipoTributacaoArtigo = 0
				SET @BaseTribDireitos = ROUND(@QtdUnidades / @FatorUnidMedida, 3)
			ELSE
				IF @TipoTributacaoArtigo = 1
					SET @BaseTribDireitos = ROUND(@MassaLiqAd / @FatorUnidMedida, 3)
				ELSE
					IF @TipoTributacaoArtigo = 3
					BEGIN
						IF @SomaFormula = 1
							SET @BaseTribDireitos = ROUND(@ValorEstatistico - @DireitosAd, 3)
						ELSE
							SET @BaseTribDireitos = ROUND(@ValorEUR - @DireitosAd + @RoyaltiesAd, 3)
					END
					ELSE	
						SET @BaseTribDireitos = 0
		END
		ELSE	
			SET @BaseTribDireitos = 0
-- calcula montante de tributação dos direitos da adição (código comentado pq o cliente CTT só utiliza tributação por % e não se consegue simular o problema de apesar dos artigos estarem bem configurados c/ % aplicar o montante p/ valor)
		/*IF @TributacaoValorArtigo = 1*/
			SET @MontanteTribDireitos = ROUND(@BaseTribDireitos * @TaxaValor / 100, 2)
		/*ELSE
			SET @MontanteTribDireitos = ROUND(@BaseTribDireitos * @TaxaValor, 2)*/
-- calcula valor de optativas da adição (a aplicação tem calculos diferentes para determinar este valor. Optou-se pela aplicação direta da formula de calcula dos CTT)
		IF @EVolumeMeioTransporte = 1
			SET @ValorOptativas = ROUND(@TotalVolsDecl * @ValorOptativasDecl, 2)			
		ELSE
			SET @ValorOptativas = 0	
-- caclula montante p/ rubrica dos CTT a inserir no detalhe do anexo de Imposições da adição
		SET @MontanteRubricaCTT = ROUND(@ValorTrafegoDecl * @TotalVolsDecl, 2)
-- calcula valor da base de tributação do IVA da adição
		IF @SomaFormula = 1
			SET @BaseTribIVA = ROUND(@ValorEUR + ROUND(@Frete / @CambioMoedaFrete, 2) + ROUND(@Seguro / @CambioMoedaSeguro, 2) + @VerbaTransAd + @ValorOptativas + @MontanteTribDireitos + @ValorISVAd + @MontanteRubricaCTT + @RoyaltiesAd + @AjusteBTIAd, 2)
		ELSE
			IF @TxFDADecl = 0
				SET @BaseTribIVA = ROUND(@ValorEUR + @VerbaTransAd + @ValorOptativas + @MontanteTribDireitos + @ValorISVAd + @MontanteRubricaCTT - @DireitosAd + @RoyaltiesAd + @AjusteBTIAd, 2)
			ELSE
				SET @BaseTribIVA = ROUND(@ValorEUR + + ROUND(@Seguro / @CambioMoedaSeguro, 2) + @VerbaTransAd + @ValorOptativas + @MontanteTribDireitos + @ValorISVAd + @MontanteRubricaCTT - @DireitosAd + @RoyaltiesAd + @AjusteBTIAd, 2)				
-- calcula montante de tributação do IVA da adição
		SET @MontanteTribIVA = ROUND(@BaseTribIVA * @TxIVAArtigo / 100, 2)	
-- atualiza dados da declaração de importação				
		UPDATE PRO_DUCG SET NDE_CODI = @CodNatureza, NDE_NOME = @NomeNatureza, PAI_PA15 = @CodPaisOrigem, PAI_NO15 = @NomePaisOrigem, PAI_P15A = @CodPaisOrigem, 
			PAI_PA16 = @CodPaisOrigem, PAI_NO16 = @NomePaisOrigem, CEN_CO20 = @CodCondEntrega, DUC_DE20 = NULLIF(@LugarCondEntrega, ''), 
			FIN_CODI = @CodFormulaCondEntrega, DUC_FR20 = @DescricaoFormula, DUC_UFOB = @ValorFOBFormula, PAI_PR22 = @CodPaisMontante, PAI_MO22 = @PrefMoedaMontante, 
			DUC_TX23 = @CambioMoedaMontante, DUC_MT22 = @Montante, DUC_VEUR = @ValorEUR, PAI_FRET = @CodPaisFrete, PAI_MOFT = @PrefMoedaFrete, DUC_TXFR = @CambioMoedaFrete, 
			DUC_FRET = @Frete, PAI_SEGU = @CodPaisSeguro, PAI_MOSG = @PrefMoedaSeguro, DUC_TXSE = @CambioMoedaSeguro, DUC_SEGU = @Seguro, PAI_ELIV = @CodPaisOrigem, 
			DUC_VATT = @ValorEstatistico, DUC_UALT = @Utilizador, DUC_DTAL = GETDATE(), DUC_DTVO = CAST(CONVERT(varchar(10), GETDATE(), 105) as datetime)
		WHERE DUC_PNUM = @NumProcesso and DUC_EANO = @AnoProcesso
-- atualiza adição da declaração de importação
		UPDATE PRO_DUAD SET APA_CO33 = @CodArtigo, APA_CP33 = NULLIF(@CodPautalArtigo, ''), DUA_DESG = NULLIF(@DescArtigo, ''), USU_CO41 = @CodUnidSuplementarArtigo, 
			USU_NOME = @NomeUnidSuplementar, DUA_TRIB = @TipoTributacaoArtigo, DUA_TIVA = @TxIVAArtigo, DUA_ATAR = @CodMercPerArtigo, DUA_1TAR = @IC1Artigo, 
			DUA_2TAR = @IC2Artigo, DUA_3TAR = @IC3Artigo, UME_CODI = @CodUnidTributacaoArtigo, UME_NOTR = @NomeUnidMedida, DUA_TXCO = @TributacaoValorArtigo, 
			PAI_CO34 = @CodPaisOrigem, PAI_NOME = @NomePaisOrigem, DUA_R37B = @Regime1Desdobramento, DUA_R37C = NULL, DUA_US41 = @QtdUnidades, DUA_VA42 = @Montante, 
			DUA_VFRE = @Frete, DUA_VSEG = @Seguro, RRE_CODI = @CodRubricaIVA, RRE_NOME = @NomeRubricaIVA, DUA_IMPI = @ImposicaoIVA, DUA_AJUS = @Ajustamento, 
			DUA_VEST = @ValorEstatistico, DUA_VAEU = @ValorEUR, DUA_VATO = @ValorEstatistico, DUA_TXVL = @TaxaValor, DUA_BTRI = @BaseTribDireitos, 
			DUA_MTRI = @MontanteTribDireitos, DUA_VOPT = @ValorOptativas, DUA_BTIV = @BaseTribIVA, DUA_VIVA = @MontanteTribIVA
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso and DUA_CODI = @NumAdicao
-- insere documentos especificados no ficheiro mais os configurados no artigo pautal no detalhe do anexo de Documentos da adição		
		INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, DDO_TIPO, DDO_MONT, DDO_AUTO)
		SELECT @AnoProcesso, @NumProcesso, @NumAdicao, (@UltNumeroAnexoDocs + ROW_NUMBER() OVER(ORDER BY t.ORIG)), t.DOC_CODI, t.DOC_NOME, t.NUMERO, t.DATA, t.TIPO, t.MONTANTE, t.AUTOMATICO
		FROM (SELECT 0 as ORIG, 0 as TIPO, 0 as AUTOMATICO, 'S/N' as NUMERO, @DataDecl as DATA, ad.DOC_CODI, ad.DOC_NOME, 0 as MONTANTE
			FROM TAB_ADOC as ad INNER JOIN TAB_DOCU as d WITH(NOLOCK) ON ad.DOC_CODI = d.DOC_CODI
				INNER JOIN TAB_APAU as a WITH(NOLOCK) ON ad.APA_CHVE = a.APA_CHVE
			WHERE ad.ADC_UIMP = 1 and a.APA_CODI = @CodArtigo
			UNION ALL
			SELECT 1, 0, 0, XML_DOCS.DOC_DATA.value('Numero[1]', 'varchar(35)'), XML_DOCS.DOC_DATA.value('Data[1]', 'datetime'), doc.DOC_CODI, doc.DOC_NOME, 0
			FROM @LstDocumentos.nodes('Documentos/Documento') as XML_DOCS(DOC_DATA) INNER JOIN TAB_DOCU as doc WITH(NOLOCK) ON XML_DOCS.DOC_DATA.value('Codigo[1]', 'varchar(5)') = doc.DOC_CODI 
			WHERE doc.DOC_DESP = 1 and LEN(doc.DOC_CODI) <= 4
			UNION ALL
			SELECT 2, 1, 0, NULL, NULL, am.INF_CODI, am.INF_DESI, 0
			FROM TAB_AMEN as am WITH(NOLOCK) INNER JOIN TAB_INFC as m WITH(NOLOCK) ON am.INF_CODI = m.INF_CODI
				INNER JOIN TAB_APAU as a WITH(NOLOCK) ON am.APA_CHVE = a.APA_CHVE
			WHERE am.AME_UIMP = 1 AND m.INF_IMPC = 0 AND a.APA_CODI = @CodArtigo
			UNION ALL
			SELECT 3, 1, 0, NULL, NULL, INF_CODI, INF_DESI, 0
			FROM TAB_INFC WITH(NOLOCK) 
			WHERE INF_IMPC = 0 AND INF_CODI = 'DHAB' and @EEntrepostoAduaneiroDecl = 0 and @TipoDeclaranteDecl = 3 and SUBSTRING(@CedulaDeclaranteDecl, 5, 1) = 'I'			
			UNION ALL
			SELECT 4, 1, 0, NULL, NULL, tm.INF_CODI, me.INF_DESI, 0
            FROM TAB_TDEM as tm WITH(NOLOCK) INNER JOIN TAB_INFC as me WITH(NOLOCK) ON tm.INF_CODI = me.INF_CODI
            WHERE me.INF_IMPC = 0 AND tm.TDE_CODI = @CodTipoDecl and @AutSaidaDecl = 0
            UNION ALL
			SELECT 5, 1, 5, NULL, NULL, INF_CODI, INF_DESI, ROUND((CASE @TxFDADecl WHEN 0 THEN (@ValorOptativas + @VerbaTransAd) ELSE (CASE WHEN @Ajustamento >= 0 THEN (@ValorOptativas + (@Frete / @CambioMoedaFrete / 100 * (100 - @TxFDADecl))) ELSE (@ValorOptativas + (@Frete / @CambioMoedaFrete / 100 * @TxFDADecl)) END) END), 2)
			FROM TAB_INFC WITH(NOLOCK) 
			WHERE INF_IMPC = 0 AND INF_CODI = 'VDA' and SUBSTRING(@RegimeAd, 1, 2) <> '71' and SUBSTRING(@RegimeAd, 1, 2) <> '78') as t			
-- insere rubricas no detalhe do anexo de Imposições da adição
		INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_LIVA, DUO_IMPO, DUO_AUTO, DUO_BMAN, DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT)
		SELECT @AnoProcesso, @NumProcesso, @NumAdicao, (@UltNumeroAnexoImps + ROW_NUMBER() OVER(ORDER BY t.ORIG)), t.RRE_CODI, t.RRE_NOME, t.TIPO, t.BASETRIB, t.TAXAVALOR, t.MONTANTE, t.RRE_IVA, t.RRE_IMPO, t.AUTOMATICO, t.BASEMANUAL, t.NUMCAUCAO, t.ANOCAUCAO, t.TIPOCAUCAO, t.ENTCAUCAO
		FROM (SELECT 0 as ORIG, 0 as AUTOMATICO, pd.RRE_CDPT as RRE_CODI, rr.RRE_NOME, rr.RRE_IVA, rr.RRE_IMPO, @ValorTrafegoDecl as TAXAVALOR, @TotalVolsDecl as BASETRIB, @MontanteRubricaCTT as MONTANTE, 0 as TIPO, 0 as BASEMANUAL, @NumCaucaoDecl as NUMCAUCAO, @AnoCaucaoDecl as ANOCAUCAO, @TipoCaucaoDecl as TIPOCAUCAO, @EntCaucaoDecl as ENTCAUCAO
			FROM TAB_PDES as pd WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON pd.RRE_CDPT = rr.RRE_CODI
			WHERE @ValorTrafegoDecl > 0
			UNION ALL
			SELECT 1, 1, RRE_CODI, RRE_NOME, RRE_IVA, @ImposicaoDireitosAd, @TaxaValor, @BaseTribDireitos, @MontanteTribDireitos, (CASE @TributacaoValorArtigo WHEN 1 THEN 0 ELSE 1 END), @BaseManualAd, @NumCaucaoDireitosAd, @AnoCaucaoDireitosAd, @TipoCaucaoDireitosAd, @EntCaucaoDireitosAd
			FROM TAB_RREC WITH(NOLOCK) 
			WHERE RRE_CODI = @CodRubDireitosAd
			UNION ALL
			SELECT 2, 2, RRE_CODI, RRE_NOME, RRE_IVA, @ImposicaoIVA, @TxIVAArtigo, @BaseTribIVA, @MontanteTribIVA, 1, 0, @NumCaucaoIVAAd, @AnoCaucaoIVAAd, @TipoCaucaoIVAAd, @EntCaucaoIVAAd
			FROM TAB_RREC WITH(NOLOCK) 
			WHERE RRE_CODI = @CodRubricaIVA) as t
-- atualiza detalhe do anexo de Declaração Sumária da adição
		UPDATE PRO_DURA SET DRA_APDT = @DataApresentacao
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso and DUA_CODI = @NumAdicao and DRA_CODI = 1
-- remove detalhe da Liquidação da declaração de importação
		DELETE FROM PRO_DULR
		WHERE DUC_PNUM = @NumProcesso and DUC_EANO = @AnoProcesso
-- insere rubricas no detalhe da Liquidação da declaração de importação
		INSERT INTO PRO_DULR(DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, DUL_MONT, DUL_MTAG)
		SELECT DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, SUM((CASE DUO_DEST WHEN 0 THEN ISNULL(DUO_MONT, 0) ELSE 0 END)), SUM((CASE DUO_DEST WHEN 1 THEN DUO_MTAG ELSE 0 END))
		FROM PRO_DUOI WITH(NOLOCK) 
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso
		GROUP BY DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME
		ORDER BY RRE_CODI
-- obtem o valor total liquidação no detalhe da Liquidação da declaração de importação 
		SET @TotalLiquidacao = ISNULL((SELECT SUM(DUL_MONT) FROM PRO_DULR WITH(NOLOCK) WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso), 0)
-- atualiza dados da declaração de importação	
		UPDATE PRO_DUCG SET DUC_VLRC = @TotalLiquidacao, DUC_VLRE = dbo.FNT_Extenso_ValorPorExtenso(@TotalLiquidacao, 'euros', 'cêntimos')
		WHERE DUC_PNUM = @NumProcesso and DUC_EANO = @AnoProcesso
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) + ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheiroDARP] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheiroDARP] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheiroFranquias]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheiroFranquias] @NomeFicheiro varchar(200), @DadosFicheiro varchar(MAX), @Ano int AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @i bigint, @Linha varchar(60), @NumCartaPorte varchar(18), @ArtFranquiaStr varchar(3), @ArtFranquia int, @NIFDestinatario varchar(18), @AnoProcesso int, 
		@NumProcesso int, @CodNatureza varchar(3), @NumErro int, @DescErro varchar(2000), @AProcessar int, @CodNaturezaFich varchar(3), @DataStr varchar(10), @Data datetime
-- cria tabela temporária p/ dados das franquias
	CREATE TABLE #DadosFranquias(ID int IDENTITY, 
		FICHEIRO varchar(200) COLLATE Latin1_General_CI_AI, 
		DUC_EANO int, 
		DUC_PNUM int, 
		NDE_CODI varchar(3) COLLATE Latin1_General_CI_AI, 
		DUC_CPRT varchar(18) COLLATE Latin1_General_CI_AI,
		DUC_ARTI int,
		DUC_DNIF varchar(18) COLLATE Latin1_General_CI_AI,
		NDE_CODI1 varchar(3) COLLATE Latin1_General_CI_AI, 
		DUC_DATA datetime, 
		ERRO int,
		DESC_ERRO varchar(2000) COLLATE Latin1_General_CI_AI,
		PROCESSADO int)		
-- verifica se ficheiro termina c/ final de linha ENTER + LINEFEED
	IF SUBSTRING(REVERSE(@DadosFicheiro), 1, 2) <> CHAR(10) + CHAR(13)
		SET @DadosFicheiro = @DadosFicheiro + CHAR(13) + CHAR(10)	
-- obtem primeiro final de linha ENTER
	SET @i = CHARINDEX(CHAR(13) + CHAR(10), @DadosFicheiro)
-- percorre todas as linhas do ficheiro	
	WHILE @i > 0
	BEGIN
-- lê linha do ficheiro
		SET @Linha = SUBSTRING(@DadosFicheiro, 1, @i - 1)
-- obtem Num. Carta Porte, Artigo Franquia e NIF Destinatário da linha lida
		SET @NumCartaPorte = LTRIM(RTRIM(SUBSTRING(@Linha, 1, 18)))
		SET @ArtFranquiaStr = LTRIM(RTRIM(SUBSTRING(@Linha, 19, 3)))
		SET @NIFDestinatario = LTRIM(RTRIM(SUBSTRING(@Linha, 22, 18)))
		SET @CodNaturezaFich = LTRIM(RTRIM(SUBSTRING(@Linha, 40, 3)))
		SET @DataStr = LTRIM(RTRIM(SUBSTRING(@Linha, 43, 8)))			
-- valida o artigo da franquia lido do ficheiro
		IF ISNUMERIC(@ArtFranquiaStr) = 1
			SET @ArtFranquia = CAST(@ArtFranquiaStr AS int)
		ELSE
			SET @ArtFranquia = 0
-- valida a data lida do ficheiro
		SET @DataStr = SUBSTRING(@DataStr, 1, 2) + '-' + SUBSTRING(@DataStr, 3, 2) + '-' + SUBSTRING(@DataStr, 5, 4)
		IF ISDATE(@DataStr) = 1
			SET @Data = CONVERT(datetime, @DataStr, 105)		
		ELSE
			SET @Data = NULL		
-- ontem dados da declaração de importação
		SELECT @NumProcesso = DUC_PNUM, @AnoProcesso = DUC_EANO, @CodNatureza = NDE_CODI
		FROM PRO_DUCG
		WHERE (DUC_EANO = @Ano or DUC_EANO = (@Ano - 1)) and DUC_CPRT = @NumCartaPorte	
-- processa validações dos dados obtidos 
		IF @NumProcesso IS NULL
		BEGIN
			SET @NumErro = 1
			SET @DescErro = 'Não existe nenhuma Declaração DUI2 c/ Carta de Porte número "' + @NumCartaPorte + '".'
			SET @AProcessar = 0
		END
		ELSE
			IF @ArtFranquia NOT IN (23, 25, 42, 86, 87, 103, 104, 113, 141)
			BEGIN
				SET @NumErro = 2
				SET @DescErro = 'O artigo de franquia especificado na Declaração DUI2 c/ Carta de Porte número "' + @NumCartaPorte + '" não é válido.'
				SET @AProcessar = 0
			END	
			ELSE
				IF @Data IS NULL
				BEGIN
					SET @NumErro = 3
					SET @DescErro = 'A data especificada na Declaração DUI2 c/ Carta de Porte número "' + @NumCartaPorte + '" não é válido.'
					SET @AProcessar = 0
				END	
				ELSE
				BEGIN
					SET @NumErro = 0
					SET @DescErro = NULL
					SET @AProcessar = NULL
				END	
-- insere na tabela temporária os dados obtidos do ficheiro e os dados da respetiva declaração	
		INSERT INTO #DadosFranquias(FICHEIRO, DUC_EANO, DUC_PNUM, NDE_CODI, DUC_CPRT, DUC_ARTI, DUC_DNIF, NDE_CODI1, DUC_DATA, ERRO, DESC_ERRO, PROCESSADO)
		VALUES(@NomeFicheiro, @AnoProcesso, @NumProcesso, @CodNatureza, @NumCartaPorte, @ArtFranquia, @NIFDestinatario, @CodNaturezaFich, @Data, @NumErro, @DescErro, @AProcessar)			
-- remove a linha do ficheiro lida e procura novo final de linha ENTER + LINEFEED
		SET @DadosFicheiro = STUFF(@DadosFicheiro, 1, @i + 1, '')
		SET @i = CHARINDEX(CHAR(13) + CHAR(10), @DadosFicheiro)
	END
-- devolve dados das franquias obtidos do ficheiro
	SELECT *
	FROM #DadosFranquias	
-- remove tabela temporária
	DROP TABLE #DadosFranquias	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheiroFranquias] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheiroFranquias] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheiroOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheiroOGMA] @FicheiroXML xml, @NomeFicheiroXML varchar(100), @Utilizador varchar(30), @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdUtilizador int, @DataAtual datetime, @FicheiroBinario varbinary(MAX), @FicheiroBase64 varchar(MAX), @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin)
	DECLARE @TmpFicheiroOGMA TABLE(
		ID int NOT NULL IDENTITY(1, 1), 	
		ADICAO int NOT NULL, 
		DT_PROCESSO datetime NULL, 
		PROCESSO varchar(100) NULL, 
		BI_LI_ID int NULL, 
		AWB varchar(25) NULL, 		
		ARTIGO varchar(40) NULL, 
		QTD_REC numeric(28, 6) NOT NULL, 
		UOM_REC varchar(3) NULL, 
		VALOR_UNIT_REC numeric(28, 6) NOT NULL,		 
		SERIAL_NUM varchar(100) NULL, 
		NOTAS varchar(100) NULL, 
		DAU varchar(20) NULL, 
		DAU_DATE datetime NULL, 		
		N_VOLUMES int NOT NULL,
		GUIA varchar(20) NULL, 	
		WEIGHT_UNIT numeric(28, 6) NOT NULL, 
		UOM_WEIGHT varchar(12) NULL, 
		PROCESS_TYPE varchar(2) NULL, 
		PAIS_EXP_MERCADORIA varchar(3) NULL, 
		EXPEDIDOR varchar(200) NULL, 		
		DESIGNACAO_MERCADORIA varchar(100) NULL, 		
		TIPO_PROCEDIMENTO varchar(20) NULL)
-- inicia processo de geração da declaração	DUI2
	BEGIN TRY	
		SET @NumErro = 0		
-- obtem o ID do utilizador
		SELECT @IdUtilizador = UTI_IDTY
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_UTIL = @Utilizador
-- obtem a data atual
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- converte ficheiro XML para binário e depois para base64
		SET @FicheiroBinario = CAST(CAST(@FicheiroXML AS varchar(MAX)) AS varbinary(MAX))
		SET @FicheiroBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinario")))', 'varchar(MAX)')
-- obtem do ficheiro XML os valores de todos os elementos necessários para a importação
		INSERT INTO @TmpFicheiroOGMA(ADICAO, DT_PROCESSO, PROCESSO, BI_LI_ID, AWB, ARTIGO, QTD_REC, UOM_REC, VALOR_UNIT_REC, SERIAL_NUM, NOTAS, DAU, DAU_DATE, N_VOLUMES, GUIA, WEIGHT_UNIT, 
			UOM_WEIGHT, PROCESS_TYPE, PAIS_EXP_MERCADORIA, EXPEDIDOR, DESIGNACAO_MERCADORIA, TIPO_PROCEDIMENTO)
		SELECT 
			ROW_NUMBER() OVER(PARTITION BY t.c.value('NOTAS[1]', 'varchar(100)') ORDER BY t.c.value('NOTAS[1]', 'varchar(100)')), 
			CONVERT(varchar(10), NULLIF(t.c.value('DT_PROCESSO[1]', 'varchar(10)'), ''), 127), 
			t.c.value('PROCESSO[1]', 'varchar(100)'), 
			t.c.value('BI_LI_ID[1]', 'int'), 
			t.c.value('AWB[1]', 'varchar(25)'), 
			t.c.value('ARTIGO[1]', 'varchar(40)'), 			
			ISNULL(t.c.value('QTD_REC[1]', 'numeric(28, 6)'), 0), 
			t.c.value('UOM_REC[1]', 'varchar(3)'), 
			ISNULL(t.c.value('VALOR_UNIT_REC[1]', 'numeric(28, 6)'), 0),			
			t.c.value('SERIAL_NUM[1]', 'varchar(100)'), 
			t.c.value('NOTAS[1]', 'varchar(100)'), 
			t.c.value('DAU[1]', 'varchar(20)'), 
			CONVERT(varchar(10), NULLIF(t.c.value('DAU_DATE[1]', 'varchar(10)'), ''), 127), 			
			ISNULL(t.c.value('N_VOLUMES[1]', 'int'), 0), 
			t.c.value('GUIA[1]', 'varchar(20)'), 
			ISNULL(t.c.value('WEIGHT_UNIT[1]', 'numeric(28, 6)'), 0), 
			t.c.value('UOM_WEIGHT[1]', 'varchar(12)'), 
			t.c.value('PROCESS_TYPE[1]', 'varchar(2)'), 
			t.c.value('PAIS_EXP_MERCADORIA[1]', 'varchar(3)'), 
			t.c.value('EXPEDIDOR[1]', 'varchar(200)'), 			
			t.c.value('DESIGNACAO_MERCADORIA[1]', 'varchar(100)'), 			
			t.c.value('TIPO_PROCEDIMENTO[1]', 'varchar(20)')
		FROM @FicheiroXML.nodes('FICH_DESPCHANTE/FICH_DESPCHANTE_LINE') AS t(c)	
-- constroi XML para declaração DUI2 a partir do ficheiro XML no formato OGMA
		SET @DocumentoXML = 
			(SELECT
				(SELECT 'I' AS "@Acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "Data", 
					NULLIF(LEFT(fch.NOTAS, 3), '') AS "CodNatureza", 
					NULLIF(LEFT(fch.AWB, 18), '') AS "NumDocTransporte", 
					(CASE 						
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Incompleta' THEN 
							((CASE 
								WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'EU' 
								ELSE 'IM' 
							END) + 'B')
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Simplificada' THEN 
							((CASE 
								WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'EU' 
								ELSE 'IM' 
							END) + 'C')
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Complementar' THEN 
							((CASE 
								WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'EU' 
								ELSE 'IM' 
							END) + 'Y')
						ELSE (NULLIF(LEFT(fch.NOTAS, 3), '') + (CASE 
																	WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'E' 
																	ELSE 'I' 
																END))
					END) AS "CodTipoDeclaracao", 
					alf.ALF_CODI AS "CodEstancia", 
					(CASE ISNULL(LEFT(fch.NOTAS, 4), '')
						WHEN '7171' THEN NULL
						ELSE frn.FOR_CODI 
					END) AS "CodExpedidor", 
					ISNULL(NULLIF(frn.CLI_CODI, ''), '500792828') AS "CodDestinatario",
					(SELECT TOP 1 DEC_CODI FROM TAB_DECL WITH(NOLOCK) WHERE DEC_INAC = 0) AS "CodDeclarante", 
					NULLIF(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') AS "CodPais15A", 
					(CASE ISNULL(LEFT(fch.NOTAS, 4), '')
						WHEN '7171' THEN '30'
						WHEN '4000' THEN '40'
						ELSE ISNULL(NULLIF(duc.MTR_FT21, ''), ISNULL(NULLIF(alf.MTR_CODI, ''), '30'))
					END) AS "CodMeioTransporte18", 
					(CASE 
						WHEN ISNULL(LEFT(fch.NOTAS, 4), '') IN ('7171', '4000') THEN NULL
						ELSE 'CAMIAO' 
					END) AS "IdMeioTransporte", 
					(CASE ISNULL(LEFT(fch.NOTAS, 4), '')
						WHEN '7171' THEN '10'
						WHEN '4000' THEN '40'
						ELSE '30'
					END) AS "CodMeioTransporte21", 
					(CASE 
						WHEN ISNULL(LEFT(fch.NOTAS, 4), '') = '7171' THEN NULL
						WHEN frn.FOR_CODI IN ('83', '84', '85', '86', '87', '264', '266', '267', '268', '269', '470') THEN 'DE' 
						ELSE 'ES' 
					END) AS "CodPais21", 
					0 AS "TemContentores", 
					ISNULL(NULLIF(frn.CEN_CODI, ''), 'XXX') AS "CodCondEntrega", 		 								
					(CASE 
						WHEN ISNULL(LEFT(fch.NOTAS, 4), '') = '7171' THEN NULL
						WHEN ISNULL(LEFT(fch.NOTAS, 2), '') = '51' THEN '42'
						ELSE '11' 
					END) AS "CodNaturezaTransacao", 
					(CASE alf.ALF_CODI
						WHEN 'PT000088' THEN NULL
						ELSE (CASE alf.ALF_TLOC 
								WHEN 'EA' THEN alf.ALF_CODI
								ELSE NULL 
							END) 
					END) AS "CodEstanciaAduaneira", 
					(CASE alf.ALF_CODI
						WHEN 'PT000088' THEN (CASE ISNULL(LEFT(fch.NOTAS, 4), '')
												WHEN '7171' THEN 'RENT00000442088PT'
												WHEN '4000' THEN 'DTP00000988015PT'
												ELSE 'UENT00000174088PT'
											END)
						ELSE (CASE alf.ALF_TLOC 
								WHEN 'LA' THEN alf.LME_CODI
								ELSE NULL 
							END) 
					END) AS "CodLocalAutorizado",
					(CASE 
						WHEN (alf.ALF_CODI = 'PT000088') AND (ISNULL(LEFT(fch.NOTAS, 4), '') <> '4000') THEN 'ENT00000174088'										
						ELSE NULL 
					END) AS "CodArmazem", 
					ISNULL(NULLIF(frn.PAI_CODI1, ''), 'US') AS "CodPais22", 
					'EU' AS "CodPaisFrete", 
					NULLIF(fch.DAU, '') AS "Referencia1", 	
					NULLIF(fch.GUIA, '') AS "Referencia2", 									
					@NomeFicheiroXML AS "NomeFileUPS", 									
					1 AS "EDeclaracaoImportacao", 	
					0 AS "CodFollowUp",									
					(SELECT
						(SELECT 
							1 AS "NumAdicao", 
							'0000000000' AS "CodArtigoPautal",  
							NULLIF(MIN(fch.DESIGNACAO_MERCADORIA), '') AS "Designacao", 														
							CAST(SUM(fch.WEIGHT_UNIT) AS numeric(28, 6)) AS "MassaBruta",							
							CAST(SUM(ROUND((fch.WEIGHT_UNIT * 0.95), 3)) AS numeric(28, 6)) AS "MassaLiquida",							
							CAST(SUM(fch.VALOR_UNIT_REC) AS numeric(28, 6)) AS "PrecoAdicao",														
							(SELECT									
								(SELECT 									
									CAST(SUM(fch.N_VOLUMES) AS numeric(28, 6)) AS "QtdVolumes",
									'CT' AS "CodUnidMedida", 
									0 AS "P", 
									0 AS "R", 
									0 AS "C"																
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE)							
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE), 
					(SELECT 
						(SELECT
							@NomeFicheiroXML AS "Nome", 
							'Ficheiro OGMA AWB/CMR' AS "Descricao", 							
							3 AS "Origem", 
							@FicheiroBase64 AS "Base64" 
						FOR XML PATH('Ficheiro'), TYPE)
					FOR XML PATH('Arquivos'), TYPE)
				FROM @TmpFicheiroOGMA AS fch	
					LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON NULLIF(fch.DAU, '') = duc.DUC_NORD
					LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON FOR_INAC = 0 AND FOR_DESP = 1 AND frn.FOR_CODI = (CASE ISNULL(LEFT(fch.NOTAS, 4), '')
																														WHEN '7171' THEN NULL
																														ELSE ISNULL((SELECT TOP 1 FOR_CODI
																																	FROM TAB_FORN WITH(NOLOCK) 
																																	WHERE FOR_NOME = NULLIF(fch.EXPEDIDOR, '')), '999999999')					
																													END)
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON alf.ALF_CODI = ISNULL(NULLIF(frn.ALF_CODI, ''), 'PT000088')	
				GROUP BY fch.NOTAS, fch.AWB, fch.DAU, fch.GUIA, fch.TIPO_PROCEDIMENTO, fch.PAIS_EXP_MERCADORIA, duc.MTR_FT21, frn.FOR_CODI, frn.CLI_CODI, frn.CEN_CODI, frn.PAI_CODI1, alf.ALF_CODI, 
					alf.MTR_CODI, alf.ALF_TLOC, alf.LME_CODI
				FOR XML PATH('Declaracao'), TYPE)				
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)
-- processa a geração da declaração DUI2
		SET @Erro = ''
		EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @Erro OUTPUT
-- senão houver erros na geração, insere as linhas constantes do ficheiro OGMA
		IF @NumErro = 0
		BEGIN
			INSERT INTO tb_TBL_LinhasOGMA(id_declaracaoIMP, numeroLinha, dataProcesso, numeroProcesso, idBILote, artigo, quantidade, unidadeMedidaQtd, valorUnitario, numeroSerie, observacoes, 
				numeroOrdem, dataOrdem, numeroVolumes, guia, pesoUnitario, unidadeMedidaPeso, tipoProcesso, expedidor, designacaoMercadoria, id_utilizadorControlo, dataControlo)
			SELECT duc.DUC_IDTY, fch.ADICAO, fch.DT_PROCESSO, fch.PROCESSO, fch.BI_LI_ID, fch.ARTIGO, fch.QTD_REC, fch.UOM_REC, fch.VALOR_UNIT_REC, fch.SERIAL_NUM, fch.NOTAS, 
				fch.DAU, fch.DAU_DATE, fch.N_VOLUMES, fch.GUIA, fch.WEIGHT_UNIT, fch.UOM_WEIGHT, fch.PROCESS_TYPE, fch.EXPEDIDOR, fch.DESIGNACAO_MERCADORIA, @IdUtilizador, @DataAtual
			FROM @TmpFicheiroOGMA AS fch	
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON YEAR(@DataAtual) = duc.DUC_EANO AND LEFT(fch.NOTAS, 3) = duc.NDE_CODI AND LEFT(fch.AWB, 18) = duc.DUC_CPRT AND @NomeFicheiroXML = duc.DUC_FUPS
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheiroOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheiroOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheirosCTT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheirosCTT] @FicheiroXML xml, @Utilizador varchar(30), @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @i int, @XMLNumDocTransporte varchar(18), @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin), @Acao varchar(1)
-- cria tabela temporária p/ lista de regiões
	CREATE TABLE #Regioes(CODPOSTAL_DE int, CODPOSTAL_A int, CODREGIAO int)	
-- insere mapeamento de códigos postais c/ regiões respetivas
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(2000, 2399, 36)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(2400, 2599, 92)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3000, 3099, 91)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3100, 3199, 92)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3200, 3499, 91)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3500, 3699, 93)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3700, 3899, 90)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(4000, 4699, 81)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(4700, 4999, 10)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5000, 5199, 84)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5200, 5399, 85)	
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5400, 5499, 84)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(6000, 6199, 94)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(6200, 6499, 95)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7000, 7099, 44)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7100, 7199, 45)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7200, 7499, 44)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7500, 7599, 40)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7600, 7999, 43)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(8000, 8999, 50)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(9000, 9499, 70)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(9500, 9999, 60)	
-- inicia processo de geração da declaração	DUI2
	BEGIN TRY	
		SET @NumErro = 0		
-- obtem o Nº. Doc. Transporte definido no ficheiro XML			
		SELECT @XMLNumDocTransporte = NULLIF(XML_DECL.DCL_DATA.value('NumDocTransporte[1]', 'varchar(18)'), '')				
		FROM @FicheiroXML.nodes('DeclaracoesImpToGIDWin/Declaracao') AS XML_DECL(DCL_DATA)
-- verifica se o Nº. Doc. Transporte definido no ficheiro XML já existe
		IF EXISTS(SELECT DUC_PNUM FROM PRO_DUCG WITH(NOLOCK) WHERE (DUC_EANO = YEAR(GETDATE()) OR DUC_EANO = (YEAR(GETDATE()) - 1)) AND DUC_CPRT = @XMLNumDocTransporte)		
			RETURN @NumErro			
		ELSE
			SET @Acao = 'I'										
-- constroi XML para declaração DUI2 a partir do ficheiro XML no formato CTT 
		SELECT @DocumentoXML = 
			(SELECT
				(SELECT @Acao "@Acao", 
					(CONVERT(varchar(10), XML_DECL.DCL_DATA.value('Data[1]', 'datetime'), 127) + 'Z') "Data", 
					NULLIF(XML_DECL.DCL_DATA.value('CodNatureza[1]', 'varchar(3)'), '') "CodNatureza", 
					@XMLNumDocTransporte "NumDocTransporte", 
					(CASE WHEN (NULLIF(XML_DECL.DCL_DATA.value('CodNatureza[1]', 'varchar(3)'), '') = '40') AND (NULLIF(XML_DECL.DCL_DATA.value('CodTipoDeclaracao[1]', 'varchar(4)'), '') IN ('FREU', 'FRIM')) THEN (CASE WHEN XML_DECL.DCL_DATA.value('CodPais15A[1]', 'varchar(2)') in ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'GB') THEN 'FREU' ELSE 'FRIM' END) WHEN (NULLIF(XML_DECL.DCL_DATA.value('CodNatureza[1]', 'varchar(3)'), '') = '40') AND (NULLIF(XML_DECL.DCL_DATA.value('CodTipoDeclaracao[1]', 'varchar(4)'), '') NOT IN ('FREU', 'FRIM')) THEN (CASE WHEN XML_DECL.DCL_DATA.value('CodPais15A[1]', 'varchar(2)') in ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'GB', 'UA') THEN 'RPEU' ELSE 'RPIM' END) WHEN XML_DECL.DCL_DATA.value('CodPais15A[1]', 'varchar(2)') in ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'GB', 'UA') THEN 'RPEU' ELSE 'RPIM' END) "CodTipoDeclaracao", 
					XML_DECL.DCL_DATA.value('CodEstancia[1]', 'varchar(8)') "CodEstancia",		
					(SELECT TOP 1 CLI_CODI FROM TAB_CLIE WHERE CLI_NIF = NULLIF(XML_DECL.DCL_DATA.value('NIFDestinatario[1]', 'varchar(18)'), '')) "CodDestinatario", 				
					XML_DECL.DCL_DATA.value('CodDeclarante[1]', 'varchar(6)') "CodDeclarante", 
					NULLIF(XML_DECL.DCL_DATA.value('CodPais15A[1]', 'varchar(2)'), '') "CodPais15A", 
					NULLIF(XML_DECL.DCL_DATA.value('CodPais16[1]', 'varchar(2)'), '') "CodPais16",	
					NULLIF(XML_DECL.DCL_DATA.value('CodPais17[1]', 'varchar(2)'), '') "CodPais17",
					NULLIF(XML_DECL.DCL_DATA.value('CodMeioTransporte18[1]', 'varchar(2)'), '') "CodMeioTransporte18", 						
					NULLIF(XML_DECL.DCL_DATA.value('CodMeioTransporte21[1]', 'varchar(2)'), '') "CodMeioTransporte21", 
					XML_DECL.DCL_DATA.value('TemContentores[1]', 'int') "TemContentores", 
					NULLIF(XML_DECL.DCL_DATA.value('CodCondEntrega[1]', 'varchar(3)'), '') "CodCondEntrega", 		 								
					'99' "CodNaturezaTransacao", 
					'DTP00000969236PT' "CodLocalAutorizado",
					XML_DECL.DCL_DATA.value('CodPais22[1]', 'varchar(2)') "CodPais22", 
					NULLIF(XML_DECL.DCL_DATA.value('MoedaFrete[1]', 'varchar(2)'), '') "CodPaisFrete",
					NULLIF(XML_DECL.DCL_DATA.value('MoedaSeguro[1]', 'varchar(2)'), '') "CodPaisSeguro", 
					NULLIF(XML_DECL.DCL_DATA.value('NomeExpedidor[1]', 'varchar(70)'), '') "NomeExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('MoradaExpedidor[1]', 'varchar(70)'), '') "MoradaExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('LocalidadeExpedidor[1]', 'varchar(35)'), '') "LocalidadeExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('CodPostalExpedidor[1]', 'varchar(12)'), '') "CodPostalExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('LocPostalExpedidor[1]', 'varchar(35)'), '') "LocPostalExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('CodPaisExpedidor[1]', 'varchar(2)'), '') "CodPaisExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('NomeDestinatario[1]', 'varchar(70)'), '') "NomeDestinatario", 
					NULLIF(XML_DECL.DCL_DATA.value('MoradaDestinatario[1]', 'varchar(70)'), '') "MoradaDestinatario", 	
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('LocalidadeDestinatario[1]', 'varchar(35)'), ''), '.') "LocalidadeDestinatario",					
					NULLIF(XML_DECL.DCL_DATA.value('CodPostalDestinatario[1]', 'varchar(12)'), '') "CodPostalDestinatario", 						
					NULLIF(XML_DECL.DCL_DATA.value('NIFDestinatario[1]', 'varchar(18)'), '') "NIFDestinatario", 
					(CASE WHEN (NULLIF(XML_DECL.DCL_DATA.value('CodPaisDestinatario[1]', 'varchar(2)'), '') = 'PT') and (SUBSTRING(NULLIF(XML_DECL.DCL_DATA.value('NIFDestinatario[1]', 'varchar(18)'), ''), 1, 1) in ('1', '2', '3')) THEN 1 WHEN (NULLIF(XML_DECL.DCL_DATA.value('CodPaisDestinatario[1]', 'varchar(2)'), '') = 'PT') and (SUBSTRING(NULLIF(XML_DECL.DCL_DATA.value('NIFDestinatario[1]', 'varchar(18)'), ''), 1, 1) in ('5', '6', '8', '9')) THEN 0 WHEN (NULLIF(XML_DECL.DCL_DATA.value('CodPaisDestinatario[1]', 'varchar(2)'), '') <> 'PT') THEN 3 ELSE NULL END) "TipoDestinatario", 
					NULLIF(XML_DECL.DCL_DATA.value('CodPaisDestinatario[1]', 'varchar(2)'), '') "CodPaisDestinatario",	
					(CASE ISNUMERIC(SUBSTRING(XML_DECL.DCL_DATA.value('CodPostalDestinatario[1]', 'varchar(12)'), 1, 4)) WHEN 1 THEN ISNULL((SELECT CODREGIAO FROM #Regioes WHERE CAST(SUBSTRING(XML_DECL.DCL_DATA.value('CodPostalDestinatario[1]', 'varchar(12)'), 1, 4) as int) BETWEEN CODPOSTAL_DE AND CODPOSTAL_A), 35) ELSE NULL END) "CodRegiaoDestinatario",
					XML_DECL.DCL_DATA.value('EDeclaracaoImportacao[1]', 'int') "EDeclaracaoImportacao", 
					XML_DECL.DCL_DATA.value('CodFollowUp[1]', 'int') "CodFollowUp", 				
					(SELECT
						(SELECT XML_ADIC.ADI_DATA.value('NumAdicao[1]', 'int') "NumAdicao", 
							XML_ADIC.ADI_DATA.value('CodArtigoPautal[1]', 'varchar(22)') "CodArtigoPautal", 
							NULLIF(XML_ADIC.ADI_DATA.value('CodPaisOrigem[1]', 'varchar(2)'), '') "CodPaisOrigem",
							NULLIF(XML_ADIC.ADI_DATA.value('C37B[1]', 'varchar(6)'), '') "RegimeB",
							XML_ADIC.ADI_DATA.value('MassaBruta[1]', 'numeric(28, 6)') "MassaBruta",							
							XML_ADIC.ADI_DATA.value('MassaLiquida[1]', 'numeric(28, 6)') "MassaLiquida",
							XML_ADIC.ADI_DATA.value('QtdUnidades[1]', 'numeric(28, 6)') "QtdUnidades",
							XML_ADIC.ADI_DATA.value('PrecoAdicao[1]', 'numeric(28, 6)') "PrecoAdicao",
							XML_ADIC.ADI_DATA.value('ValorFrete[1]', 'numeric(28, 6)') "Frete", 
							XML_ADIC.ADI_DATA.value('ValorSeguro[1]', 'numeric(28, 6)') "Seguro", 								
							XML_ADIC.ADI_DATA.value('MetodoAvaliacao[1]', 'int') "MetodoAvaliacao",
							(SELECT									
								(SELECT NULLIF(XML_MVOL.MVL_DATA.value('Marca[1]', 'varchar(20)'), '') "Marca", 
									NULLIF(XML_MVOL.MVL_DATA.value('Numero[1]', 'varchar(20)'), '') "Numero", 								
									XML_MVOL.MVL_DATA.value('QtdVolumes[1]', 'numeric(28, 6)') "QtdVolumes",
									XML_MVOL.MVL_DATA.value('CodUnidadeMedida[1]', 'varchar(3)') "CodUnidMedida", 
									XML_MVOL.MVL_DATA.value('P[1]', 'bit') "P", 
									XML_MVOL.MVL_DATA.value('R[1]', 'bit') "R", 
									XML_MVOL.MVL_DATA.value('C[1]', 'bit') "C", 
									XML_MVOL.MVL_DATA.value('Loptica[1]', 'varchar(30)') "LOptica"
								FROM XML_ADIC.ADI_DATA.nodes('MarcasEVolumes/MarcaEVolume/.') as XML_MVOL(MVL_DATA)
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE), 
							(SELECT
								(SELECT TOP 1 'X' "Tipo",
									'750' "CodDocumento",
									(dsu.DAT_NUME + REPLICATE('0', 12 - LEN(dsu.DAT_NUME))) "NumeroDeclSumaria",
									(CONVERT(varchar(10), ISNULL(XML_DECL.DCL_DATA.value('DataPrevVoo[1]', 'datetime'), GETDATE()), 127) + 'Z') "DataApresentacao"
								FROM (SELECT NULLIF(XML_MVOL.MVL_DATA.value('Numero[1]', 'varchar(20)'), '') DAT_NUME
									FROM XML_ADIC.ADI_DATA.nodes('MarcasEVolumes/MarcaEVolume/.') as XML_MVOL(MVL_DATA)) as dsu
								FOR XML PATH('DeclaracaoSumaria'), TYPE)
							FOR XML PATH('DeclaracoesSumaria'), TYPE), 								
							(SELECT
								(SELECT XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)') "CodDocumento",
									XML_DOCS.DOC_DATA.value('NumeroReferencia[1]', 'varchar(35)') "NumeroDocumento",
									(CONVERT(varchar(10), ISNULL(XML_DOCS.DOC_DATA.value('DataEmissao[1]', 'datetime'), GETDATE()), 127) + 'Z') "DataEmissao"
								FROM XML_ADIC.ADI_DATA.nodes('Documentos/Documento/.') as XML_DOCS(DOC_DATA)
								FOR XML PATH('Documento'), TYPE)
							FOR XML PATH('Documentos'), TYPE)								
						FROM XML_DECL.DCL_DATA.nodes('Adicoes/Adicao/.') as XML_ADIC(ADI_DATA) 
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE)						
				FROM @FicheiroXML.nodes('DeclaracoesImpToGIDWin/Declaracao') as XML_DECL(DCL_DATA)					
				FOR XML PATH('Declaracao'), TYPE)				
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)										
-- processa a geração da declaração DUI2
		SET @Erro = ''
		EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @Erro OUTPUT				
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH		
-- remove a tabela temporária
	DROP TABLE #Regioes		
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheirosCTT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheirosCTT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheirosDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheirosDHL] @FicheiroXML xml, @Gateway varchar(3), @MsgDate datetime, @XMLDadosRestricao xml, @Utilizador varchar(30), @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
-- declaração de variáveis
	DECLARE @NumErro int, @NumDocTransporte varchar(12), @NumVolumes int, @i int, @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin)
	DECLARE @numeroAdicao int, @documentoTransporte varchar(18), @totalMassaBruta numeric(28, 6), @codigoArtigo varchar(22), @designacao varchar(150), @codPaisOrigem varchar(2), 
		@regimeB varchar(6), @unidades decimal(18, 6), @montante decimal(18, 3), @documentos xml, @idAdicao int
	DECLARE @TblID table(ID int NOT NULL)
	DECLARE @TblAdicoes table(
		id int NOT NULL IDENTITY(1, 1), 	
		documentoTransporte varchar(18) NOT NULL, 	
		totalAdicoes int NOT NULL,
		totalMassaBruta decimal(18, 6) NOT NULL,		
		numeroAdicao int NOT NULL, 
		codigoArtigo varchar(22) NULL, 
		designacao varchar(260) NULL, 
		codPaisOrigem varchar(2) NULL, 
		regimeB varchar(6) NULL, 
		unidades decimal(18, 6) NOT NULL,
		massaBruta decimal(18, 6) NOT NULL, 
		montante decimal(18, 6) NOT NULL)
	DECLARE @TblDocumentosAdicao table(
		id int NOT NULL IDENTITY(1, 1), 	
		idAdicao int NOT NULL, 	
		codigoDocumento varchar(5) NOT NULL, 	
		numerodocumento varchar(70) NULL, 	
		dataDocumento datetime NULL)
-- cria tabela temporária p/ lista de regiões
	CREATE TABLE #Regioes(CODPOSTAL_DE int, CODPOSTAL_A int, CODREGIAO int)	
-- insere mapeamento de códigos postais c/ regiões respetivas
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(2000, 2399, 36)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(2400, 2599, 92)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3000, 3099, 91)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3100, 3199, 92)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3200, 3499, 91)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3500, 3699, 93)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(3700, 3899, 90)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(4000, 4699, 81)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(4700, 4999, 10)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5000, 5199, 84)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5200, 5399, 85)	
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(5400, 5499, 84)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(6000, 6199, 94)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(6200, 6499, 95)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7000, 7099, 44)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7100, 7199, 45)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7200, 7499, 44)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7500, 7599, 40)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(7600, 7999, 43)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(8000, 8999, 50)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(9000, 9499, 70)
	INSERT INTO #Regioes(CODPOSTAL_DE, CODPOSTAL_A, CODREGIAO) VALUES(9500, 9999, 60)	
-- cria tabela temporária p/ detalhe de AWB decompostos em função do Nº. Vols de cada declaração DHL
	CREATE TABLE #AWBs(HAWB varchar(18) COLLATE Latin1_General_CI_AI, HAWB_DETALHE varchar(35) COLLATE Latin1_General_CI_AI)	
-- obtem a lista de declarações a importar que tenham N.º Volumes maior que 1
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), ''), (XML_DECL.DCL_DATA.value('SDPieces[1]', 'int') - 1)
		FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp') as XML_DECL(DCL_DATA)
		WHERE XML_DECL.DCL_DATA.value('SDPieces[1]', 'int') > 1
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @NumDocTransporte, @NumVolumes
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @i = 1
		WHILE @i <= @NumVolumes
		BEGIN
			INSERT INTO #AWBs(HAWB, HAWB_DETALHE)
			VALUES(@NumDocTransporte, (@NumDocTransporte + '_' + CAST(@i as varchar(5))))
			SET @i = @i + 1
		END
		FETCH NEXT FROM Declaracoes INTO @NumDocTransporte, @NumVolumes
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
-- inicia processo de geração da declaração	DUI2
	BEGIN TRY	
		SET @NumErro = 0
		SET @numeroAdicao = 0
-- obtem as adições do ficheiro XML
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
			SELECT 
				l.c.value('(../../HAWB)[1]', 'varchar(18)'), ISNULL(l.c.value('(../../GrossWgt)[1]', 'numeric(28, 6)'), 0), 							
				NULLIF((CASE 
						WHEN r.c.value('numero[1]', 'int') IS NOT NULL THEN r.c.value('../artigoPautal[1]', 'varchar(22)')					
						ELSE ISNULL(NULLIF(art.APA_CODI, ''), '0000000000') 
					END), ''),
				NULLIF((CASE 
						WHEN r.c.value('numero[1]', 'int') IS NOT NULL THEN (NULLIF(r.c.value('../designacaoPautal[1]', 'varchar(150)'), '') + ' - ' + ISNULL(NULLIF(l.c.value('TariffCdNo[1]', 'varchar(12)'), ''), '0000000000'))
						ELSE ISNULL(ISNULL(NULLIF(art.APA_DESG, ''), NULLIF(l.c.value('DescOfGoods[1]', 'varchar(150)'), '')), 'NÃO CLASSIFICADO') 
					END), ''), 
				NULLIF((CASE 
						WHEN EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = NULLIF(ISNULL(NULLIF(l.c.value('CtryMfctrerOrgn[1]', 'varchar(2)'), ''), l.c.value('CtryOrgnCd[1]', 'varchar(2)')), '') AND PAI_ZEUR = 1) THEN 'EU' 
						ELSE ISNULL(NULLIF(l.c.value('CtryMfctrerOrgn[1]', 'varchar(2)'), ''), l.c.value('CtryOrgnCd[1]', 'varchar(2)')) 
					END), ''), 
				NULLIF(l.c.value('(LineItemCustom/CustomAtt[Name_Eng="Special Code"]/Val)[1]', 'varchar(6)'), ''), 
				ISNULL(CAST(NULLIF(l.c.value('TariffQnty[1]', 'varchar(20)'), '') AS decimal(18, 6)), 0), ISNULL(l.c.value('InvLineVal[1]', 'decimal(18, 6)'), 0), 				
				l.c.query('AddDocInfo')
			FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp/LineItems/LineItem') AS l(c)								
				LEFT OUTER JOIN @XMLDadosRestricao.nodes('DadosRestricao/AdicaoRestrita') AS r(c) ON l.c.value('GoodsItemNo[1]', 'int') = r.c.value('numero[1]', 'int')
				OUTER APPLY (SELECT TOP 1 APA_CODI, APA_DESG FROM TAB_APAU WITH(NOLOCK) WHERE APA_CPAU = NULLIF(l.c.value('TariffCdNo[1]', 'varchar(12)'), '')) AS art
		OPEN Adicoes
		FETCH NEXT from Adicoes INTO @documentoTransporte, @totalMassaBruta, @codigoArtigo, @designacao, @codPaisOrigem, @regimeB, @unidades, @montante, @documentos
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			DELETE FROM @TblID
			SET @idAdicao = NULL
-- obtem ID da adição por código artigo
			SELECT @idAdicao = id 
			FROM @TblAdicoes 
			WHERE documentoTransporte = @documentoTransporte AND totalMassaBruta = @totalMassaBruta AND ISNULL(codigoArtigo, '') = ISNULL(@codigoArtigo, '') 
				AND ISNULL(designacao, '') = ISNULL(@designacao, '') AND ISNULL(codPaisOrigem, '') = ISNULL(@codPaisOrigem, '') AND ISNULL(regimeB, '') = ISNULL(@regimeB, '')
-- insere ou atualiza a adição na tabela tmp
			IF @idAdicao IS NULL
			BEGIN
				SET @numeroAdicao = @numeroAdicao + 1
				INSERT INTO @TblAdicoes(	
					documentoTransporte, 	
					totalAdicoes, 
					totalMassaBruta, 			
					numeroAdicao, 
					codigoArtigo, 
					designacao, 
					codPaisOrigem, 
					regimeB, 
					unidades,
					massaBruta, 
					montante)	
				OUTPUT inserted.id INTO @TblID	
				VALUES(
					@documentoTransporte, 	
					0, 
					@totalMassaBruta, 			
					@numeroAdicao, 
					@codigoArtigo, 
					@designacao, 
					@codPaisOrigem, 
					@regimeB, 
					@unidades,
					0, 
					@montante
				)
				SELECT @idAdicao = ID
				FROM @TblID
			END
			ELSE
			BEGIN
				UPDATE @TblAdicoes SET 
					unidades = unidades + @unidades, 
					montante = montante + @montante
				WHERE id = @idAdicao
			END
-- processa a inserção dos documentos "N380", "N325", "N955", "N041", "N954", "N865", "N851", "N853" referenciados na adição se ainda não existirem na adição
			INSERT INTO @TblDocumentosAdicao(
				idAdicao, 	
				codigoDocumento, 	
				numerodocumento, 	
				dataDocumento)
			SELECT 
				@idAdicao, 
				(CASE NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') WHEN 'INV' THEN 'N380' WHEN 'PFI' THEN 'N325' WHEN 'ATA' THEN 'N955' WHEN 'ATR' THEN 'N041' WHEN 'EU1' THEN 'N954' WHEN 'FMA' THEN 'N865' WHEN 'PHY' THEN 'N851' WHEN 'VET' THEN 'N853' ELSE NULL END), 
				ISNULL(NULLIF(d.c.value('DocRefNo[1]', 'varchar(70)'), ''), 'SN'), 
				d.c.value('DocIssueDt[1]', 'datetime') 					
			FROM @documentos.nodes('AddDocInfo/.') AS d(c)
				LEFT OUTER JOIN @TblDocumentosAdicao AS dad ON dad.idAdicao = @idAdicao AND dad.codigoDocumento = (CASE NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') WHEN 'INV' THEN 'N380' WHEN 'PFI' THEN 'N325' WHEN 'ATA' THEN 'N955' WHEN 'ATR' THEN 'N041' WHEN 'EU1' THEN 'N954' WHEN 'FMA' THEN 'N865' WHEN 'PHY' THEN 'N851' WHEN 'VET' THEN 'N853' ELSE NULL END) AND ISNULL(dad.numerodocumento, '') = ISNULL(NULLIF(d.c.value('DocRefNo[1]', 'varchar(70)'), ''), 'SN')
			WHERE NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') IN ('INV', 'PFI', 'ATA', 'ATR', 'EU1', 'FMA', 'PHY', 'VET') AND dad.id IS NULL
			FETCH NEXT from Adicoes INTO @documentoTransporte, @totalMassaBruta, @codigoArtigo, @designacao, @codPaisOrigem, @regimeB, @unidades, @montante, @documentos
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
-- processa a atualização do campo de total de adições
		UPDATE @TblAdicoes SET totalAdicoes = @numeroAdicao
-- processa calculos para o campo de massa bruta de cada adição em função do total de adições apurado
		UPDATE @TblAdicoes SET 			
			massaBruta = (ROUND((ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) / totalAdicoes), 3, 1) + (CASE 
																													WHEN (totalAdicoes > 1) AND (numeroAdicao = totalAdicoes) THEN (ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) - ROUND((ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) / totalAdicoes), 3, 1) * numeroAdicao)
																													ELSE 0
																												END))
-- obtem lista das declarações de importação do ficheiro em formato XML 
		SET @DocumentoXML = 
			(SELECT
				(SELECT 'I' "@Acao", 
					(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 127) + 'Z') "Data", 
					(CASE WHEN ISNULL(XML_REST.RES_DATA.value('natureza[1]', 'varchar(3)'), '') <> '' THEN XML_REST.RES_DATA.value('natureza[1]', 'varchar(3)') WHEN NULLIF(XML_DECL.DCL_DATA.value('(FlexFields[Name_Eng="MSC - Manifest Split Code"]/Val)[1]', 'varchar(255)'), '') IN ('ACH5', 'CASH', 'DDP5', 'FRQ', 'FRQP','DECLA','DECLC','DECLD') THEN 'PRE' ELSE 'CDS' END) "CodNatureza", 
					NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') "NumDocTransporte", 
					(CASE WHEN NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') in ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'EUA' ELSE 'IMA' END) "CodTipoDeclaracao", 
					(CASE @Gateway WHEN 'LIS' THEN 'PT000015' ELSE 'PT000020' END) "CodEstancia", 
					(SELECT TOP 1 CLI_CODI FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_NIF = NULLIF(ISNULL(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(18)'), ''), '')) "CodDestinatario", 				
					'00' "CodDeclarante", 
					(CASE ISNULL(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') WHEN 'IC' THEN 'ES' WHEN 'RS' THEN 'XS' WHEN 'XM' THEN 'SX' WHEN 'XB' THEN 'BQ' ELSE NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') END) "CodPais15A", 
					NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') "CodPais16",					
					'40' "CodMeioTransporte18",  
					'40' "CodMeioTransporte21", 
					0 "TemContentores", 					 
					XML_DECL.DCL_DATA.value('Incoterms[1]', 'varchar(3)') "CodCondEntrega", 
					NULLIF(XML_DECL.DCL_DATA.value('(CustomAtts/CustomAtt[Name_Eng="IncTrmPlcNm"]/Val)[1]', 'varchar(30)'), '') "DescricaoCondEntrega", 															
					(CASE WHEN (ISNULL(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(18)'), '') = '514365455') THEN '41' WHEN (ISNULL(XML_DECL.DCL_DATA.value('(DatElGrp[@Cd="ShpClss"]/DatEl[Cd="Clss"]/Val)[1]', 'varchar(255)'), '') IN ('C2C', 'C2B', 'B2C')) THEN '12' WHEN (ISNULL(XML_DECL.DCL_DATA.value('ReasonForExpt[1]', 'varchar(1)'), '') = 'U') THEN '21' WHEN (ISNULL(XML_DECL.DCL_DATA.value('ReasonForExpt[1]', 'varchar(1)'), '') = 'G') THEN '34' ELSE '11' END) "CodNaturezaTransacao", 					
					(CASE @Gateway WHEN 'LIS' THEN 'DTP00000487015PT' ELSE 'DTP00000473020PT' END) "CodLocalAutorizado",
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') "CodPais22", 					
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/CoName)[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCntctDtls/PreferredName)[1]', 'varchar(70)'), '')) "NomeExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), '') "MoradaExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)'), '') "LocalidadeExpedidor", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0') "CodPostalExpedidor", 
					NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)'), '') "LocPostalExpedidor", 						
					(CASE ISNULL(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') WHEN 'IC' THEN 'ES' WHEN 'RS' THEN 'XS' WHEN 'XM' THEN 'SX' WHEN 'XB' THEN 'BQ' ELSE NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') END) "CodPaisExpedidor", 												
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCntctDtls/PreferredName)[1]', 'varchar(70)'), ''))) "NomeDestinatario", 
					ISNULL(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), '')), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''))) "MoradaDestinatario", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) "LocalidadeDestinatario", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0')) "CodPostalDestinatario", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) "LocPostalDestinatario", 					
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="TEL"]/DeviceDtls)[1]', 'varchar(14)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="TEL"]/DeviceDtls)[1]', 'varchar(14)'), '')) "TelefoneDestinatario", 					
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="EML"]/DeviceDtls)[1]', 'varchar(200)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="EML"]/DeviceDtls)[1]', 'varchar(200)'), '')) "EmailDestinatario", 						
					NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/VATNo)[1]', 'varchar(18)'), '') "NIFDestinatario", 					
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '')) "CodPaisDestinatario",					
					(CASE ISNUMERIC(NULLIF(SUBSTRING(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0')), 1, 4), '.')) WHEN 1 THEN ISNULL((SELECT CODREGIAO FROM #Regioes WHERE CAST(SUBSTRING(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0')), 1, 4) as int) BETWEEN CODPOSTAL_DE AND CODPOSTAL_A), 35) ELSE NULL END) "CodRegiaoDestinatario",					
					NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/DHLAcctNo)[1]', 'varchar(10)'), '') "NumContaExpedidor",	
					NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/DutyAcct)[1]', 'varchar(10)'), '') "NumContaDestinatario",				
					NULLIF(XML_DECL.DCL_DATA.value('ShpOrgn[1]', 'varchar(6)'), '') "Aeroporto", 					
					NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') "MiniCPA",
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(50)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(50)'), '')) "Referencia1",
					ISNULL(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(50)'), '')), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(50)'), ''))) "Referencia2",
					NULLIF(XML_DECL.DCL_DATA.value('ProdContentCd[1]', 'varchar(3)'), '') "ShipID", 					
					NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') "Tracking",	
					NULLIF(XML_DECL.DCL_DATA.value('ShpOrgn[1]', 'varchar(6)'), '') "PosicaoAviao",								
					NULLIF(XML_DECL.DCL_DATA.value('ShpOrgn[1]', 'varchar(6)'), '') "NomeFileUPS",
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(70)'), '')) "NomeDestinatario2", 
					ISNULL(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), '')), ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(45)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''))) "MoradaDestinatario2", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) "LocalidadeDestinatario2", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), '')) "CodPostalDestinatario2", 
					ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) "LocPostalDestinatario2", 					
					1 "EDeclaracaoImportacao", 
					0 "CodFollowUp",
					(CONVERT(varchar(10), @MsgDate, 127) + 'Z') "DataDocCPA", 
					(SELECT
						(SELECT 
							adi.numeroAdicao AS "NumAdicao", 
							adi.codigoArtigo AS "CodArtigoPautal", 							
							adi.designacao AS "Designacao",  
							(CASE ISNULL(adi.codPaisOrigem, '') WHEN 'IC' THEN 'ES' WHEN 'RS' THEN 'XS' WHEN 'XM' THEN 'SX' WHEN 'XB' THEN 'BQ' ELSE ISNULL(adi.codPaisOrigem, '') END) AS "CodPaisOrigem", 							
							adi.regimeB AS "RegimeB", 
							CAST(adi.massaBruta AS numeric(28, 6)) AS "MassaBruta",							
							CAST(ROUND((adi.massaBruta * 95 / 100), 3) AS numeric(28, 6)) AS "MassaLiquida",																												
							CAST(adi.unidades AS numeric(28, 6)) AS "QtdUnidades",
							CAST(adi.montante AS numeric(28, 6)) AS "PrecoAdicao",							
							1 AS "MetodoAvaliacao",
							(SELECT
								(SELECT 
									'LETREIRO' AS "Marca", 									
									CAST(XML_DECL.DCL_DATA.value('SDPieces[1]', 'int') AS numeric(28, 6)) AS "QtdVolumes",
									'CT' AS "CodUnidMedida", 
									(CASE WHEN (adi.totalAdicoes > 1) AND (adi.numeroAdicao < adi.totalAdicoes) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "P", 
									(CASE WHEN (adi.totalAdicoes > 1) AND (adi.numeroAdicao = adi.totalAdicoes) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "R", 
									CAST(0 AS bit) AS "C"						
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE),
							(SELECT								
								t.codigoDocumento AS "CodDocumento", 									
								NULLIF(t.numeroDocumento, '') AS "NumeroDocumento",
								(CONVERT(varchar(10), t.dataDocumento, 127) + 'Z') AS "DataEmissao"
							FROM (SELECT 
									'N740' AS codigoDocumento, 									
									XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)') AS numeroDocumento,
									@MsgDate AS dataDocumento	
								HAVING adi.numeroAdicao = 1							
								UNION
								SELECT 
									codigoDocumento, 
									numeroDocumento,
									dataDocumento
								FROM @TblDocumentosAdicao
								WHERE idAdicao = adi.id) AS t														
							FOR XML PATH('Documento'), ROOT('Documentos'), TYPE)
						FROM @TblAdicoes AS adi	
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE),
					(SELECT
						(SELECT 
							NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') "CodPais",
							NULLIF(XML_DECL.DCL_DATA.value('(LineItems/LineItem/DescOfGoods)[1]', 'varchar(104)'), '') "Descricao",							
							ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') "Moeda",							
							CAST(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsVal)[1]', 'numeric(28, 6)') as numeric(28, 6)) "TotalFatura",
							NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') "NumeroCPA",
							CAST(ISNULL(NULLIF(ROUND(XML_DECL.DCL_DATA.value('GrossWgt[1]', 'numeric(28, 6)'), 1, 1), 0), 0.1) as numeric(28, 6)) "Peso",
							0 "Tipo"
						FOR XML PATH('DadosManifesto'), TYPE),
						(SELECT 
							NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') "CodPais",
							NULLIF(XML_DECL.DCL_DATA.value('(LineItems/LineItem/DescOfGoods)[1]', 'varchar(104)'), '') "Descricao",							
							ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') "Moeda",							
							CAST(XML_DECL.DCL_DATA.value('(TxAndDty/CstmsVal)[1]', 'numeric(28, 6)') as numeric(28, 6)) "TotalFatura",
							HAWB_DETALHE "NumeroCPA",
							CAST(ISNULL(NULLIF(ROUND(XML_DECL.DCL_DATA.value('GrossWgt[1]', 'numeric(28, 6)'), 1, 1), 0), 0.1) as numeric(28, 6)) "Peso",
							0 "Tipo"
						FROM #AWBs
						WHERE HAWB = NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '')
						FOR XML PATH('DadosManifesto'), TYPE)
					FOR XML PATH('Manifestos'), TYPE)
				FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp') as XML_DECL(DCL_DATA)
					OUTER APPLY @XMLDadosRestricao.nodes('DadosRestricao') AS XML_REST(RES_DATA)
				WHERE NOT EXISTS(SELECT DUC_PNUM FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_EANO = YEAR(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) AND DUC_CPRT = NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), ''))						
				FOR XML PATH('Declaracao'), TYPE)				
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)							
-- processa a geração da declaração DUI2	
		SET @Erro = ''		
		EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @Erro OUTPUT
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH	
-- remove as tabelas temporárias
	DROP TABLE #AWBs	
	DROP TABLE #Regioes				
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro			
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheirosDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheirosDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_DeclImportacao_ImportaFicheirosDHLPortal]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_DeclImportacao_ImportaFicheirosDHLPortal] @FicheiroXML xml, @Utilizador varchar(30), @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLNIFCliente varchar(18), @XMLNomeCliente varchar(70), @XMLMoradaCliente varchar(70), @XMLLocalidadeCliente varchar(35), 
		@XMLCodPostalCliente varchar(12), @XMLLocPostalCliente varchar(35), @XMLCodPaisCliente varchar(2), @XMLCodEANCliente varchar(13), @XMLTelefoneCliente varchar(14), 
		@XMLEmailCliente varchar(200), @XMLDeclaracao xml(XMLSC_DeclaracoesImpToGIDWin)
-- inicia processo de geração da declaração	DUI2
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- verifica se NIF de cliente não existe para inserir
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT 
				NULLIF(t.c.value('(importador/nif)[1]', 'varchar(18)'), ''), 
				NULLIF(t.c.value('(importador/nome)[1]', 'varchar(70)'), ''), 
				NULLIF(t.c.value('(importador/morada)[1]', 'varchar(70)'), ''), 
				NULLIF(t.c.value('(importador/localidade)[1]', 'varchar(35)'), ''), 
				NULLIF(t.c.value('(importador/codPostal)[1]', 'varchar(12)'), ''), 
				NULLIF(t.c.value('(importador/locPostal)[1]', 'varchar(35)'), ''), 
				NULLIF(t.c.value('(importador/pais)[1]', 'varchar(2)'), ''), 
				NULLIF(t.c.value('(importador/codigoEAN)[1]', 'varchar(13)'), ''), 
				NULLIF(t.c.value('(importador/telefone)[1]', 'varchar(14)'), ''), 
				NULLIF(t.c.value('(importador/email)[1]', 'varchar(200)'), '')
			FROM @FicheiroXML.nodes('DeclaracoesIMPPortalDHLToGIDWin/declaracao') AS t(c)
				INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON ddg.DUC_DUNO = 1 AND ddg.DUC_EANO = YEAR(@DataAtual) AND ddg.DUC_CPRT = NULLIF(t.c.value('documentoTransporte[1]', 'varchar(18)'), '')					
				LEFT OUTER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON NULLIF(t.c.value('(importador/nif)[1]', 'varchar(18)'), '') = cli.CLI_NIF									
			WHERE t.c.value('(importador/nif)[1]', 'varchar(18)') <> '' AND ddg.DUC_DENV IS NULL AND cli.CLI_IDTY IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLLocalidadeCliente, @XMLCodPostalCliente, @XMLLocPostalCliente, @XMLCodPaisCliente, 
			@XMLCodEANCliente, @XMLTelefoneCliente, @XMLEmailCliente
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			EXEC @NumErro = SP_Clientes_InsereOuEdita 0, @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLNIFCliente, NULL, NULL, @XMLLocalidadeCliente, @XMLCodPostalCliente, @XMLLocPostalCliente, @XMLCodPaisCliente, @XMLEmailCliente, @XMLTelefoneCliente, @XMLCodEANCliente, @Utilizador, @Erro OUTPUT					
			IF @NumErro <> 0
				RAISERROR('Erro na inserção do cliente "%s": "%s".', 16, 1, @XMLNIFCliente, @Erro)
			FETCH NEXT FROM Declaracoes INTO @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLLocalidadeCliente, @XMLCodPostalCliente, @XMLLocPostalCliente, @XMLCodPaisCliente, 
				@XMLCodEANCliente, @XMLTelefoneCliente, @XMLEmailCliente
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- constroi XML para declaração DUI2 a partir do ficheiro XML no formato portal DHL
		SET @XMLDeclaracao = 
			(SELECT
				(SELECT 'U' AS "@Acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "Data",						
					ISNULL(NULLIF(t.c.value('natureza[1]', 'varchar(3)'), ''), ddg.NDE_CODI) AS "CodNatureza", 
					ISNULL(NULLIF(t.c.value('documentoTransporte[1]', 'varchar(18)'), ''), ddg.DUC_CPRT) AS "NumDocTransporte",							
					ddg.TDE_CODI AS "CodTipoDeclaracao", 									
					ddg.ALF_CODI AS "CodEstancia", 
					NULLIF(ddg.DUC_EXP2, '') AS "CodExpedidor", 
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DST8 ELSE cli.CLI_CODI END) AS "CodDestinatario", 
					ddg.DEC_CO14 AS "CodDeclarante", 
					NULLIF(ddg.PAI_PA15, '') AS "CodPais15A",
					NULLIF(ddg.PAI_PA16, '') AS "CodPais16", 
					NULLIF((CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.PAI_PA17 ELSE cli.PAI_CODI END), '') AS "CodPais17",
					NULLIF(ddg.MTR_PT18, '') AS "CodMeioTransporte18", 
					NULLIF(ddg.DUC_MT18, '') AS "IdMeioTransporte", 
					NULLIF(ddg.MTR_FT21, '') AS "CodMeioTransporte21", 
					NULLIF(ddg.PAI_PA21, '') AS "CodPais21", 
					ddg.DUC_CT19 AS "TemContentores", 
					ISNULL(NULLIF(t.c.value('condicaoEntrega[1]', 'varchar(3)'), ''), ddg.CEN_CO20) AS "CodCondEntrega", 					
					NULLIF(ddg.NTR_CO24, '') AS "CodNaturezaTransacao", 
					NULLIF(ddg.ALF_CODI1, '') AS "CodEstanciaAduaneira", 
					NULLIF(ddg.LME_CO30, '') AS "CodLocalAutorizado", 					
					NULLIF(ddg.ARM_CODI, '') AS "CodArmazem", 
					ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN NULL ELSE NULLIF(t.c.value('paisMoedaFatura[1]', 'varchar(2)'), '') END), ddg.PAI_PR22) AS "CodPais22", 	
					ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN NULL ELSE NULLIF(t.c.value('paisMoedaFrete[1]', 'varchar(2)'), '') END), ddg.PAI_FRET) AS "CodPaisFrete", 
					NULLIF(ddg.PAI_SEGU, '') AS "CodPaisSeguro",
					NULLIF(ddg.DUC_ENOM, '') AS "NomeExpedidor",
					NULLIF(ddg.DUC_EMOR, '') AS "MoradaExpedidor",
					NULLIF(ddg.DUC_ELOC, '') AS "LocalidadeExpedidor",
					NULLIF(ddg.DUC_ECPO, '') AS "CodPostalExpedidor",
					NULLIF(ddg.DUC_ELPO, '') AS "LocPostalExpedidor",
					NULLIF(ddg.DUC_ENIF, '') AS "NIFExpedidor",
					NULLIF(ddg.PAI_ELIV, '') AS "CodPaisExpedidor",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DNOM ELSE NULLIF(cli.CLI_NOME, '') END) AS "NomeDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DMOR ELSE NULLIF(cli.CLI_MORA, '') END) AS "MoradaDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DLOC ELSE NULLIF(cli.CLI_LOCA, '') END) AS "LocalidadeDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DCPO ELSE NULLIF(cli.CLI_CPOS, '') END) AS "CodPostalDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DLPO ELSE NULLIF(cli.CLI_LPOS, '') END) AS "LocPostalDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DTEL ELSE NULLIF(cli.CLI_TELF, '') END) AS "TelefoneDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DEMA ELSE NULLIF(cli.CLI_EMAI, '') END) AS "EmailDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DNIF ELSE NULLIF(cli.CLI_NIF, '') END) AS "NIFDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_TPDS ELSE cli.CLI_TNIF END) AS "TipoDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.PAI_DLIV ELSE NULLIF(cli.PAI_CODI, '') END) AS "CodPaisDestinatario",
					(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.PAI_P17B ELSE cli.RES_CODI END) AS "CodRegiaoDestinatario",
					NULLIF(ddg.DUC_NVRF, '') AS "NumVossaReferencia", 
					NULLIF(ddg.DUC_FUPS, '') AS "NomeFileUPS", 
					1 AS "EDeclaracaoImportacao", 
					ddg.DUC_VFRC AS "ValorFreteCompanhia", 
					NULLIF(ddg.DUC_MFRC, '') AS "MoedaFreteCompanhia", 
					ddg.DUC_NVSR AS "NivelServico", 
					(CASE WHEN ISNULL(t.c.value('natureza[1]', 'varchar(3)'), '') <> ddg.NDE_CODI THEN nde.FUP_CODI ELSE NULL END) AS "CodFollowUp", 
					(SELECT 						
						'UPDATE' AS "CodigoCampoExtra",
						'DHL-PORTAL' AS "ValorCampoExtra"				
					FOR XML PATH('CampoExtra'), ROOT('CamposExtra'), TYPE),																								
					(SELECT 
						a.c.value('numeroAdicao[1]', 'int') AS "NumAdicao", 						
						ISNULL(NULLIF(apa.APA_CODI, ''), ISNULL(NULLIF(dad.APA_CO33, ''), '9999999999')) AS "CodArtigoPautal", 							
						ISNULL(NULLIF(apa.APA_DESG, ''), ISNULL(NULLIF(dad.DUA_DESG, ''), 'NÃO CLASSIFICADO')) AS "Designacao", 															
						CAST(dad.DUA_MB35 AS decimal(18, 6)) AS "MassaBruta",
						CAST(dad.DUA_ML38 AS decimal(18, 6)) AS "MassaLiquida", 												
						CAST(dad.DUA_US41 AS decimal(18, 6)) AS "QtdUnidades", 																				
						CAST(ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN dad.DUA_VA42 ELSE a.c.value('montante[1]', 'decimal(18, 2)') END), 0) AS decimal(18, 3)) AS "PrecoAdicao", 
						CAST(ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN dad.DUA_VFRE ELSE a.c.value('frete[1]', 'decimal(18, 2)') END), 0) AS decimal(18, 3)) AS "Frete", 
						(SELECT 						
							NULLIF(D31_MARC, '') AS "Marca", 
							NULLIF(D31_NUME, '') AS "Numero",
							CAST(D31_QNTD AS decimal(18, 6)) AS "QtdVolumes", 							
							NULLIF(UME_CODI, '') AS "CodUnidMedida", 
							D31_CASP AS "P", 
							D31_CASR AS "R", 
							D31_CASC AS "C"									
						FROM PRO_DU31 WITH(NOLOCK)
						WHERE DUC_EANO = dad.DUC_EANO AND DUC_PNUM = dad.DUC_PNUM AND DUA_CODI = dad.DUA_CODI
						FOR XML PATH('MarcaEVolume'), ROOT('MarcasEVolumes'), TYPE), 							
						(SELECT 													
							NULLIF(d.c.value('codigoDocumento[1]', 'varchar(5)'), '') AS "CodDocumento",
							NULLIF(d.c.value('numeroDocumento[1]', 'varchar(70)'), '') AS "NumeroDocumento", 							
							(CONVERT(varchar(10), d.c.value('dataDocumento[1]', 'datetime'), 127) + 'Z') AS "DataEmissao"											
						FROM t.c.nodes('documentos/documento') AS d(c)	
						FOR XML PATH('Documento'), ROOT('Documentos'), TYPE)
					FROM t.c.nodes('adicoes/adicao') AS a(c) 		
						INNER JOIN PRO_DUAD AS dad WITH(NOLOCK) ON ddg.DUC_EANO = dad.DUC_EANO AND ddg.DUC_PNUM = dad.DUC_PNUM AND a.c.value('numeroAdicao[1]', 'int') = dad.DUA_CODI
						LEFT OUTER JOIN TAB_APAU AS apa WITH(NOLOCK) ON NULLIF(a.c.value('codigoArtigo[1]', 'varchar(22)'), '') = apa.APA_CODI
					FOR XML PATH('Adicao'), ROOT('Adicoes'), TYPE),
					(SELECT 
						nde.SIN_CODI AS "CodStatusIncidencia"
					HAVING ISNULL(nde.SIN_CODI, '') <> ''
					FOR XML PATH('DadosIncidencia'), ROOT('Incidencias'), TYPE)
				FROM @FicheiroXML.nodes('DeclaracoesIMPPortalDHLToGIDWin/declaracao') AS t(c)
					INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON ddg.DUC_DUNO = 1 AND ddg.DUC_EANO = YEAR(@DataAtual) AND ddg.DUC_CPRT = NULLIF(t.c.value('documentoTransporte[1]', 'varchar(18)'), '')					
					OUTER APPLY (SELECT TOP 1 CLI_CODI, CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_TELF, CLI_EMAI, CLI_NIF, CLI_TNIF, PAI_CODI, RES_CODI, CLI_IDTY
								FROM TAB_CLIE WITH(NOLOCK)
								WHERE CLI_INAC = 0 AND CLI_DESP = 1 AND CLI_NIF = NULLIF(t.c.value('(importador/nif)[1]', 'varchar(18)'), '')
								ORDER BY CLI_CACC DESC, CLI_IDTY DESC) AS cli
					LEFT OUTER JOIN TAB_NDES AS nde WITH(NOLOCK) ON NULLIF(t.c.value('natureza[1]', 'varchar(3)'), '') = nde.NDE_CODI
				WHERE ddg.DUC_DENV IS NULL
				FOR XML PATH('Declaracao'), TYPE)
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)
-- processa a geração da(s) declaração(ões) DUI2
		EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @XMLDeclaracao, @Utilizador, @Erro OUTPUT	
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_DeclImportacao_ImportaFicheirosDHLPortal] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_DeclImportacao_ImportaFicheirosDHLPortal] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheirosKHUNENAGEL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheirosKHUNENAGEL] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @ComandoDOS varchar(1000), @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml, @ListaErros varchar(MAX), 
		@i int, @XMLNumDocTransporte varchar(18), @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin), @Acao varchar(1)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'
-- cria tabela temporária p/ lista de ficheiros
	CREATE TABLE #ListaFicheiros (ID int IDENTITY, FICHEIRO varchar(500) COLLATE Latin1_General_CI_AI)
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- constroi comando DOS para listar na directoria especificada os ficheiros
	SET @ComandoDOS =  'DIR "' + @DirOrigemFicheiros + '" /A-D /T:C /O:D'
-- executa o comando DOS e insere resultado da lista de ficheiros obtida na tabela temporaria
	INSERT INTO #ListaFicheiros
	EXEC master..xp_cmdshell @ComandoDOS						
-- remove da lista de ficheiros obtida as linhas que não são de ficheiro
	DELETE FROM #ListaFicheiros 
	WHERE ((FICHEIRO not like '[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] %') and (FICHEIRO not like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] %')) or (FICHEIRO like '%<DIR>%') or (FICHEIRO is null)
-- obtem lista de ficheiros Khune&Nagel a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE FicheirosKHUNE CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT (@DirOrigemFicheiros + REVERSE(LEFT(REVERSE(FICHEIRO), CHARINDEX(' ', REVERSE(FICHEIRO)) - 1))), REVERSE(LEFT(REVERSE(FICHEIRO), CHARINDEX(' ', REVERSE(FICHEIRO)) - 1))
		FROM #ListaFicheiros		
		WHERE RIGHT(FICHEIRO, 4) = '.xml'
	OPEN FicheirosKHUNE
	FETCH NEXT from FicheirosKHUNE into @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''				
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'
			EXEC (@ComandoSQL)
-- constroi comando DOS para mover ficheiro importado
			SET @ComandoDOS =  'MOVE /Y "' + @PathFicheiro + '" "' + @DirDestinoFicheiros + '"'
			EXEC master..xp_cmdshell @ComandoDOS, NO_OUTPUT
-- obtem o xml do ficheiro xml importado						
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro	
-- obtem o Nº. Doc. Transporte definido no ficheiro XML			
			SELECT @XMLNumDocTransporte = NULLIF(XML_DECL.DCL_DATA.value('TransportDocumentNumber[1]', 'varchar(18)'), '')				
			FROM @FicheiroXML.nodes('Customs_Declaration/Declaration/Header') as XML_DECL(DCL_DATA)
-- verifica se o Nº. Doc. Transporte definido no ficheiro XML já existe
			IF EXISTS(SELECT DUC_PNUM FROM PRO_DUCG WITH(NOLOCK) WHERE (DUC_EANO = YEAR(GETDATE()) or DUC_EANO = (YEAR(GETDATE()) - 1)) and DUC_CPRT = @XMLNumDocTransporte)
				BREAK			
			ELSE
				SET @Acao = 'I'										
-- obtem lista das declarações de importação do ficheiro em formato XML 
			SELECT @DocumentoXML = 
				(SELECT
					(SELECT @Acao "@Acao", 
						(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 127) + 'Z') "Data", 
						'XML' "CodNatureza", 
						@XMLNumDocTransporte "NumDocTransporte", 
						'IMA' "CodTipoDeclaracao", 
						'PT000020' "CodEstancia", /*É necessário mapear a Estância em função de alguma tag do ficheiro XML*/								
						'01' "CodDeclarante", 
						NULLIF(XML_DECL.DCL_DATA.value('CountryOfDispatch[1]', 'varchar(2)'), '') "CodPais15A", 
						NULLIF(XML_DECL.DCL_DATA.value('CountryOfDispatch[1]', 'varchar(2)'), '') "CodPais16",	
						NULLIF(XML_DECL.DCL_DATA.value('CountryOfDestination[1]', 'varchar(2)'), '') "CodPais17",
						(NULLIF(XML_DECL.DCL_DATA.value('ModeOfTransportBorder[1]', 'varchar(2)'), '') + '0') "CodMeioTransporte18", 
						NULLIF(XML_DECL.DCL_DATA.value('ModeOfTransportBorderIdentity[1]', 'varchar(30)'), '') "IdMeioTransporte", 
						(NULLIF(XML_DECL.DCL_DATA.value('ModeOfTransportBorder[1]', 'varchar(2)'), '') + '0') "CodMeioTransporte21", 
						NULLIF(XML_DECL.DCL_DATA.value('ModeOfTransportBorderNationality[1]', 'varchar(2)'), '') "CodPais21", 
						XML_DECL.DCL_DATA.value('ContainerFlag[1]', 'int') "TemContentores", 
						NULLIF(XML_DECL.DCL_DATA.value('IncotermCode[1]', 'varchar(3)'), '') "CodCondEntrega", 	
						NULLIF(XML_DECL.DCL_DATA.value('IncotermPlace[1]', 'varchar(30)'), '') "DescricaoCondEntrega", 	 								
						'11' "CodNaturezaTransacao", 
						'DTP00000473020PT' "CodLocalAutorizado", /*É necessário mapear o Local Autorizado em função de alguma tag do ficheiro XML*/
						NULLIF(XML_DECL.DCL_DATA.value('InvoiceCurrency[1]', 'varchar(2)'), '') "CodPais22", 
						NULLIF(XML_DECL.DCL_DATA.value('(../Position/TransportCurrency)[1]', 'varchar(2)'), '') "CodPaisFrete",
						NULLIF(XML_DECL.DCL_DATA.value('(../Position/TransportInsuranceCurrency)[1]', 'varchar(2)'), '') "CodPaisSeguro", 
						NULLIF(XML_DECL.DCL_DATA.value('(Shipper/Name)[1]', 'varchar(70)'), '') "NomeExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Shipper/Street)[1]', 'varchar(70)'), '') "MoradaExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Shipper/Place)[1]', 'varchar(35)'), '') "LocalidadeExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Shipper/PostCode)[1]', 'varchar(12)'), '') "CodPostalExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Shipper/Place)[1]', 'varchar(35)'), '') "LocPostalExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Shipper/Country)[1]', 'varchar(2)'), '') "CodPaisExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Name)[1]', 'varchar(70)'), '') "NomeDestinatario", 
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Street)[1]', 'varchar(70)'), '') "MoradaDestinatario", 	
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Place)[1]', 'varchar(35)'), '') "LocalidadeDestinatario",					
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/PostCode)[1]', 'varchar(12)'), '') "CodPostalDestinatario", 
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Place)[1]', 'varchar(35)'), '') "LocPostalDestinatario", 												
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Country)[1]', 'varchar(2)'), '') "CodPaisDestinatario",	
						NULLIF(XML_DECL.DCL_DATA.value('IdentificationNumber[1]', 'varchar(50)'), '') "NumVossaReferencia",
						NULLIF(XML_DECL.DCL_DATA.value('(Shipper/Code)[1]', 'varchar(10)'), '') "NumContaExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Code)[1]', 'varchar(10)'), '') "NumContaDestinatario", 
						NULLIF(XML_DECL.DCL_DATA.value('ShipmentNumber[1]', 'varchar(11)'), '') "ShipID", 
						1 "EDeclaracaoImportacao", 
						1 "CodFollowUp", 				
						(SELECT
							(SELECT XML_ADIC.ADI_DATA.value('Line[1]', 'int') "NumAdicao", 
								ISNULL((SELECT TOP 1 APA_CODI FROM TAB_APAU WHERE SUBSTRING(APA_CPAU, 1, 10) = NULLIF(SUBSTRING(XML_ADIC.ADI_DATA.value('CommodityCodeImport[1]', 'varchar(22)'), 1, 10), '')), '0') "CodArtigoPautal", 
								NULLIF(XML_ADIC.ADI_DATA.value('CountryOfOrigin[1]', 'varchar(2)'), '') "CodPaisOrigem",								
								CAST(REPLACE(XML_ADIC.ADI_DATA.value('TotalGrossWeight[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) "MassaBruta",							
								CAST(REPLACE(XML_ADIC.ADI_DATA.value('TotalNetWeight[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) "MassaLiquida",								
								CAST(REPLACE(XML_ADIC.ADI_DATA.value('InvoicePrice[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) "PrecoAdicao",
								(CASE WHEN NULLIF(XML_DECL.DCL_DATA.value('IncotermCode[1]', 'varchar(3)'), '') IN ('FCA', 'FOB', 'FAS', 'DAT', 'EXW') THEN CAST(REPLACE(XML_ADIC.ADI_DATA.value('TransportPrice[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) ELSE 0.000000 END) "Frete", 
								(CASE WHEN NULLIF(XML_DECL.DCL_DATA.value('IncotermCode[1]', 'varchar(3)'), '') IN ('FCA', 'FOB', 'FAS', 'DAT', 'EXW') THEN CAST(REPLACE(XML_ADIC.ADI_DATA.value('TransportInsurancePrice[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) ELSE 0.000000 END) "Seguro", 								
								1 "MetodoAvaliacao",
								(SELECT									
									(SELECT XML_MVOL.MVL_DATA.value('Quantity[1]', 'numeric(28, 6)') "QtdVolumes",
										XML_MVOL.MVL_DATA.value('Type[1]', 'varchar(3)') "CodUnidMedida", 
										CAST(0 AS bit) "P", 
										CAST(0 AS bit) "R", 
										CAST(0 AS bit) "C"										
									FROM XML_ADIC.ADI_DATA.nodes('Package/.') as XML_MVOL(MVL_DATA)
									FOR XML PATH('MarcaEVolume'), TYPE)
								FOR XML PATH('MarcasEVolumes'), TYPE), 								
								(SELECT
									(SELECT XML_DOCS.DOC_DATA.value('Type[1]', 'varchar(5)') "CodDocumento",
										XML_DOCS.DOC_DATA.value('Reference[1]', 'varchar(35)') "NumeroDocumento",
										(CONVERT(varchar(10), XML_DOCS.DOC_DATA.value('IssueDate[1]', 'datetime'), 127) + 'Z') "DataEmissao"
									FROM XML_ADIC.ADI_DATA.nodes('Document/.') as XML_DOCS(DOC_DATA)
									FOR XML PATH('Documento'), TYPE)
								FOR XML PATH('Documentos'), TYPE)								
							FROM XML_DECL.DCL_DATA.nodes('../Position/.') as XML_ADIC(ADI_DATA) 
							FOR XML PATH('Adicao'), TYPE)
						FOR XML PATH('Adicoes'), TYPE)						
					FROM @FicheiroXML.nodes('Customs_Declaration/Declaration/Header') as XML_DECL(DCL_DATA)					
					FOR XML PATH('Declaracao'), TYPE)				
				FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)										
-- processa a geração das Declarações de Importação carregadas no XML
			EXEC SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @ListaErros OUTPUT								
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Nome Ficheiro KHUNE_NAGEL:  ' + @NomeFicheiro + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @ComandoDOS =  'ECHO ' + SUBSTRING(@ListaErros, 1, @i - 1) + ' >> "' + (@DirDestinoFicheiroErros + '/' + @NomeFicheiro) + '.err' + '"'									
				EXEC master..xp_cmdshell @ComandoDOS, NO_OUTPUT
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END		
		FETCH NEXT from FicheirosKHUNE into @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosKHUNE
	DEALLOCATE FicheirosKHUNE
-- remove as tabelas temporárias
	DROP TABLE #ListaFicheiros
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheirosKHUNENAGEL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheirosKHUNENAGEL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheirosRoadKHUNENAGEL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheirosRoadKHUNENAGEL] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @ComandoDOS varchar(1000), @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml, @ListaErros varchar(MAX), @i int, @XMLNumDocTransporte varchar(18), 
		@DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin), @Acao varchar(1)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'
-- cria tabela temporária p/ lista de ficheiros
	CREATE TABLE #ListaFicheiros (ID int IDENTITY, FICHEIRO varchar(500) COLLATE Latin1_General_CI_AI)
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- constroi comando DOS para listar na directoria especificada os ficheiros
	SET @ComandoDOS =  'DIR "' + @DirOrigemFicheiros + '" /A-D /T:C /O:D'
-- executa o comando DOS e insere resultado da lista de ficheiros obtida na tabela temporaria
	INSERT INTO #ListaFicheiros
	EXEC master..xp_cmdshell @ComandoDOS						
-- remove da lista de ficheiros obtida as linhas que não são de ficheiro
	DELETE FROM #ListaFicheiros 
	WHERE ((FICHEIRO not like '[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] %') and (FICHEIRO not like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] %')) or (FICHEIRO like '%<DIR>%') or (FICHEIRO is null)
-- obtem lista de ficheiros road Khune&Nagel a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE FicheirosKHUNE CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT (@DirOrigemFicheiros + REVERSE(LEFT(REVERSE(FICHEIRO), CHARINDEX(' ', REVERSE(FICHEIRO)) - 1))), REVERSE(LEFT(REVERSE(FICHEIRO), CHARINDEX(' ', REVERSE(FICHEIRO)) - 1))
		FROM #ListaFicheiros		
		WHERE RIGHT(FICHEIRO, 4) = '.xml'
	OPEN FicheirosKHUNE
	FETCH NEXT from FicheirosKHUNE into @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''				
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'
			EXEC (@ComandoSQL)
-- constroi comando DOS para mover ficheiro importado
			SET @ComandoDOS =  'MOVE /Y "' + @PathFicheiro + '" "' + @DirDestinoFicheiros + '"'
			EXEC master..xp_cmdshell @ComandoDOS, NO_OUTPUT
-- obtem o xml do ficheiro xml importado						
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro	
-- obtem o Nº. Doc. Transporte definido no ficheiro XML			
			SELECT @XMLNumDocTransporte = NULLIF(XML_DECL.DCL_DATA.value('IdentificationNumber[1]', 'varchar(18)'), '')				
			FROM @FicheiroXML.nodes('Customs_Declaration/Declaration/Header') as XML_DECL(DCL_DATA)
-- verifica se o Nº. Doc. Transporte definido no ficheiro XML já existe
			IF EXISTS(SELECT DUC_PNUM FROM PRO_DUCG WITH(NOLOCK) WHERE (DUC_EANO = YEAR(GETDATE()) or DUC_EANO = (YEAR(GETDATE()) - 1)) and DUC_CPRT = @XMLNumDocTransporte)
				BREAK			
			ELSE
				SET @Acao = 'I'										
-- obtem lista das declarações de importação do ficheiro em formato XML 
			SELECT @DocumentoXML = 
				(SELECT
					(SELECT @Acao "@Acao", 
						(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 127) + 'Z') "Data", 
						'XML' "CodNatureza", 
						@XMLNumDocTransporte "NumDocTransporte", 
						'EUA' "CodTipoDeclaracao", 
						'PT000284' "CodEstancia", 
						(SELECT TOP 1 CLI_CODI FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_NIF = NULLIF(XML_DECL.DCL_DATA.value('(Supplier/Code)[1]', 'varchar(18)'), '')) "CodDestinatario", 				
						'01' "CodDeclarante", 
						NULLIF(XML_DECL.DCL_DATA.value('CountryOfDispatch[1]', 'varchar(2)'), '') "CodPais15A", 
						NULLIF(XML_DECL.DCL_DATA.value('CountryOfDispatch[1]', 'varchar(2)'), '') "CodPais16",	
						NULLIF(XML_DECL.DCL_DATA.value('CountryOfDestination[1]', 'varchar(2)'), '') "CodPais17",
						'30' "CodMeioTransporte18", 
						'CAMIAO' "IdMeioTransporte",
						'30' "CodMeioTransporte21", 
						'PT' "CodPais21", 
						0 "TemContentores", 
						'DAP' "CodCondEntrega",
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Place)[1]', 'varchar(30)'), '') "DescricaoCondEntrega", 
						'11' "CodNaturezaTransacao", 
						'DTP00000848284PT' "CodLocalAutorizado", 
						NULLIF(XML_DECL.DCL_DATA.value('InvoiceCurrency[1]', 'varchar(2)'), '') "CodPais22", 
						NULLIF(XML_DECL.DCL_DATA.value('(../Position/TransportCurrency)[1]', 'varchar(2)'), '') "CodPaisFrete",
						NULLIF(XML_DECL.DCL_DATA.value('(../Position/TransportInsuranceCurrency)[1]', 'varchar(2)'), '') "CodPaisSeguro", 
						NULLIF(XML_DECL.DCL_DATA.value('(Supplier/Name)[1]', 'varchar(70)'), '') "NomeExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Supplier/Street)[1]', 'varchar(70)'), '') "MoradaExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Supplier/Place)[1]', 'varchar(35)'), '') "LocalidadeExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Supplier/PostCode)[1]', 'varchar(12)'), '') "CodPostalExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Supplier/Place)[1]', 'varchar(35)'), '') "LocPostalExpedidor", 
						NULLIF(XML_DECL.DCL_DATA.value('(Supplier/Country)[1]', 'varchar(2)'), '') "CodPaisExpedidor",
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Name)[1]', 'varchar(70)'), '') "NomeDestinatario", 
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Street)[1]', 'varchar(70)'), '') "MoradaDestinatario", 	
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Place)[1]', 'varchar(35)'), '') "LocalidadeDestinatario",					
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/PostCode)[1]', 'varchar(12)'), '') "CodPostalDestinatario", 
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Place)[1]', 'varchar(35)'), '') "LocPostalDestinatario", 												
						NULLIF(XML_DECL.DCL_DATA.value('(Consignee/Country)[1]', 'varchar(2)'), '') "CodPaisDestinatario",	
						NULLIF(XML_DECL.DCL_DATA.value('IdentificationNumber[1]', 'varchar(50)'), '') "NumVossaReferencia",						
						1 "EDeclaracaoImportacao", 
						1 "CodFollowUp", 				
						(SELECT
							(SELECT XML_ADIC.ADI_DATA.value('Line[1]', 'int') "NumAdicao", 
								ISNULL((SELECT TOP 1 APA_CODI FROM TAB_APAU WITH(NOLOCK) WHERE APA_CPAU = NULLIF(XML_ADIC.ADI_DATA.value('CommodityCode[1]', 'varchar(22)'), '')), '0') "CodArtigoPautal", 
								NULLIF(XML_ADIC.ADI_DATA.value('CountryOfOrigin[1]', 'varchar(2)'), '') "CodPaisOrigem",
								CAST(REPLACE(XML_ADIC.ADI_DATA.value('TotalGrossWeight[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) "MassaBruta",							
								CAST(REPLACE(XML_ADIC.ADI_DATA.value('TotalNetWeight[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) "MassaLiquida",
								CAST(REPLACE(XML_ADIC.ADI_DATA.value('InvoicePrice[1]', 'varchar(28)'), ',', '.') AS numeric(28, 6)) "PrecoAdicao",
								1 "MetodoAvaliacao",
								(SELECT									
									(SELECT XML_MVOL.MVL_DATA.value('Quantity[1]', 'numeric(28, 6)') "QtdVolumes",
										XML_MVOL.MVL_DATA.value('Type[1]', 'varchar(3)') "CodUnidMedida", 
										CAST(0 AS bit) "P", 
										CAST(0 AS bit) "R", 
										CAST(0 AS bit) "C"										
									FROM XML_ADIC.ADI_DATA.nodes('Package/.') as XML_MVOL(MVL_DATA)
									FOR XML PATH('MarcaEVolume'), TYPE)
								FOR XML PATH('MarcasEVolumes'), TYPE), 								
								(SELECT TOP 1
									(SELECT (CASE XML_DOCS.DOC_DATA.value('Type[1]', 'varchar(5)') WHEN '380' THEN 'N380' ELSE XML_DOCS.DOC_DATA.value('Type[1]', 'varchar(5)') END) "CodDocumento", 
										XML_DECL.DCL_DATA.value('InvoiceNumber[1]', 'varchar(35)') "NumeroDocumento"										
									FROM XML_ADIC.ADI_DATA.nodes('Document/.') as XML_DOCS(DOC_DATA)
									WHERE XML_ADIC.ADI_DATA.value('Line[1]', 'int') = 1 AND XML_DOCS.DOC_DATA.value('Type[1]', 'varchar(5)') IN ('380', 'N380')
									FOR XML PATH('Documento'), TYPE)
								FROM XML_ADIC.ADI_DATA.nodes('Document/.') as XML_DOCS(DOC_DATA)
								WHERE XML_ADIC.ADI_DATA.value('Line[1]', 'int') = 1 AND XML_DOCS.DOC_DATA.value('Type[1]', 'varchar(5)') IN ('380', 'N380')
								FOR XML PATH('Documentos'), TYPE)								
							FROM XML_DECL.DCL_DATA.nodes('../Position/.') as XML_ADIC(ADI_DATA) 
							FOR XML PATH('Adicao'), TYPE)
						FOR XML PATH('Adicoes'), TYPE)						
					FROM @FicheiroXML.nodes('Customs_Declaration/Declaration/Header') as XML_DECL(DCL_DATA)					
					FOR XML PATH('Declaracao'), TYPE)				
				FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)										
-- processa a geração das Declarações de Importação carregadas no XML
			EXEC SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @ListaErros OUTPUT								
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Nome Ficheiro ROAD KHUNE_NAGEL:  ' + @NomeFicheiro + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @ComandoDOS =  'ECHO ' + SUBSTRING(@ListaErros, 1, @i - 1) + ' >> "' + (@DirDestinoFicheiroErros + '/' + @NomeFicheiro) + '.err' + '"'									
				EXEC master..xp_cmdshell @ComandoDOS, NO_OUTPUT
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END		
		FETCH NEXT from FicheirosKHUNE into @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosKHUNE
	DEALLOCATE FicheirosKHUNE
-- remove as tabelas temporárias
	DROP TABLE #ListaFicheiros
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheirosRoadKHUNENAGEL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheirosRoadKHUNENAGEL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheirosSAMSUNG]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheirosSAMSUNG] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @ComandoDOS varchar(1000), @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml, @ListaErros varchar(MAX), @i int, @XMLMessageNumber varchar(35), 
		@XMLNumDocTransporte varchar(18), @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin), @Acao varchar(1), @DirFicheiroACKANS varchar(150), @PathFicheiroACKANS nvarchar(250)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'
-- cria tabela temporária p/ lista de ficheiros
	CREATE TABLE #ListaFicheiros (ID int IDENTITY, FICHEIRO varchar(500) COLLATE Latin1_General_CI_AI)
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- constroi comando DOS para listar na directoria especificada os ficheiros
	SET @ComandoDOS =  'DIR "' + @DirOrigemFicheiros + '" /A-D /T:C /O:D'
-- executa o comando DOS e insere resultado da lista de ficheiros obtida na tabela temporaria
	INSERT INTO #ListaFicheiros
	EXEC master..xp_cmdshell @ComandoDOS						
-- remove da lista de ficheiros obtida as linhas que não são de ficheiro
	DELETE FROM #ListaFicheiros 
	WHERE ((FICHEIRO not like '[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] %') and (FICHEIRO not like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] %')) or (FICHEIRO like '%<DIR>%') or (FICHEIRO is null)
-- obtem lista de ficheiros Samsung a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE FicheirosSAMSUNG CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT (@DirOrigemFicheiros + REVERSE(LEFT(REVERSE(FICHEIRO), CHARINDEX(' ', REVERSE(FICHEIRO)) - 1))), REVERSE(LEFT(REVERSE(FICHEIRO), CHARINDEX(' ', REVERSE(FICHEIRO)) - 1))
		FROM #ListaFicheiros		
		WHERE RIGHT(FICHEIRO, 4) = '.xml'
	OPEN FicheirosSAMSUNG
	FETCH NEXT from FicheirosSAMSUNG into @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''				
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'
			EXEC (@ComandoSQL)
-- constroi comando DOS para mover ficheiro importado
			SET @ComandoDOS =  'MOVE /Y "' + @PathFicheiro + '" "' + @DirDestinoFicheiros + '"'
			EXEC master..xp_cmdshell @ComandoDOS, NO_OUTPUT
-- obtem o xml do ficheiro xml importado						
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro	
-- remove o namespace existente na raiz <SHPNOT> do XML 				
			SET @FicheiroXML = REPLACE(CAST(@FicheiroXML as nvarchar(MAX)), 'nr1:', '')						
			SET @FicheiroXML = STUFF(CAST(@FicheiroXML as nvarchar(MAX)), 1, CHARINDEX('>', CAST(@FicheiroXML as nvarchar(MAX))), '<SHPNOT>')						
-- obtem o Nº. Doc. Transporte definido no ficheiro XML			
			SELECT @XMLMessageNumber = NULLIF(XML_DECL.DCL_DATA.value('MessageNumber[1]', 'varchar(35)'), ''), @XMLNumDocTransporte = NULLIF(XML_DECL.DCL_DATA.value('HouseBillofLadingNumber[1]', 'varchar(18)'), '')				
			FROM @FicheiroXML.nodes('SHPNOT') as XML_DECL(DCL_DATA)
-- verifica se o Nº. Doc. Transporte definido no ficheiro XML já existe
			IF EXISTS(SELECT DUC_PNUM FROM PRO_DUCG WITH(NOLOCK) WHERE (DUC_EANO = YEAR(GETDATE()) or DUC_EANO = (YEAR(GETDATE()) - 1)) and DUC_CPRT = @XMLNumDocTransporte)
				BREAK			
			ELSE
				SET @Acao = 'I'								
-- obtem lista das declarações de importação do ficheiro em formato XML 
			SELECT @DocumentoXML = 
				(SELECT
					(SELECT @Acao "@Acao", 
						(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 127) + 'Z') "Data", 
						'01' "CodNatureza", 
						@XMLNumDocTransporte "NumDocTransporte", 
						'IMA' "CodTipoDeclaracao", 
						(CASE XML_DECL.DCL_DATA.value('(TransportationType/Code)[1]', 'varchar(1)') WHEN 'P' THEN 'PT000015' ELSE 'PT000040' END) "CodEstancia", 
						(SELECT FOR_CODI FROM TAB_FORN WHERE FOR_CEAN = XML_DECL.DCL_DATA.value('(OrgList/OrgItem/RelatedOrganization/Code)[3]', 'varchar(4)')) "CodExpedidor", 
						'05026' "CodDestinatario", 								
						'2' "CodDeclarante", 
						NULLIF(XML_DECL.DCL_DATA.value('(LocList/LocItem/RoutingInformation/CountryCode)[2]', 'varchar(2)'), '') "CodPais15A", 
						NULLIF(XML_DECL.DCL_DATA.value('(LocList/LocItem/RoutingInformation/CountryCode)[2]', 'varchar(2)'), '') "CodPais16",	
						'PT' "CodPais17",
						(CASE XML_DECL.DCL_DATA.value('(TransportationType/Code)[1]', 'varchar(1)') WHEN 'P' THEN '40' ELSE '10' END) "CodMeioTransporte18", 
						NULLIF(XML_DECL.DCL_DATA.value('VesselFlightTruckName2[1]', 'varchar(30)'), '') "IdMeioTransporte", 
						(CASE XML_DECL.DCL_DATA.value('(TransportationType/Code)[1]', 'varchar(1)') WHEN 'P' THEN '40' ELSE '10' END) "CodMeioTransporte21", 
						(CASE XML_DECL.DCL_DATA.value('(TransportationType/Code)[1]', 'varchar(1)') WHEN 'P' THEN 'EA' ELSE 'AG' END) "CodPais21", 
						(CASE XML_DECL.DCL_DATA.value('(TransportationType/Code)[1]', 'varchar(1)') WHEN 'P' THEN 0 ELSE 1 END) "TemContentores", 
						NULLIF(XML_DECL.DCL_DATA.value('(LinList/LinItem/IncotermsCode)[1]', 'varchar(3)'), '') "CodCondEntrega", 	
						NULLIF(XML_DECL.DCL_DATA.value('(LinList/LinItem/IncotermsPlace)[1]', 'varchar(30)'), '') "DescricaoCondEntrega", 	 								
						'11' "CodNaturezaTransacao", 
						(CASE XML_DECL.DCL_DATA.value('(TransportationType/Code)[1]', 'varchar(1)') WHEN 'P' THEN 'DTP00000127015PT' ELSE 'DTP00000075040PT' END) "CodLocalAutorizado", 
						NULLIF(XML_DECL.DCL_DATA.value('(InvoiceAmount/CurrencyCode)[1]', 'varchar(2)'), '') "CodPais22", 
						(CONVERT(varchar(10), CAST(XML_DECL.DCL_DATA.value('EstimateDateofArrival[1]', 'varchar(8)') AS datetime), 120) + 'Z') "DataPrevVoo",	
						@XMLMessageNumber "Referencia1", 					
						1 "EDeclaracaoImportacao", 
						1 "CodFollowUp", 				
						(SELECT
							(SELECT ROW_NUMBER() OVER(ORDER BY t.ART_CPAU) "NumAdicao", 
								(SELECT TOP 1 APA_CODI FROM TAB_APAU WHERE SUBSTRING(APA_CPAU, 1, 10) = t.ART_CPAU) "CodArtigoPautal", 
								NULLIF(XML_DECL.DCL_DATA.value('(LocList/LocItem/RoutingInformation/CountryCode)[2]', 'varchar(2)'), '') "CodPaisOrigem",								
								CAST(SUM(t.ART_MBRT) AS numeric(28, 6)) "MassaBruta",							
								CAST(SUM(t.ART_MLIQ) AS numeric(28, 6)) "MassaLiquida",	
								CAST((CASE ISNULL((SELECT TOP 1 USU_CODI FROM TAB_APAU WHERE SUBSTRING(APA_CPAU, 1, 10) = t.ART_CPAU), '') WHEN '' THEN 0 ELSE SUM(t.ART_QTDE) END) AS numeric(28, 6)) "QtdUnidades", 							
								CAST(SUM(t.ART_PREC) AS numeric(28, 6)) "PrecoAdicao",								
								(SELECT									
									(SELECT 1 "QtdVolumes",
										'CT' "CodUnidMedida", 
										CAST(0 AS bit) "P", 
										CAST(0 AS bit) "R", 
										CAST(0 AS bit) "C"															
									FOR XML PATH('MarcaEVolume'), TYPE)
								FOR XML PATH('MarcasEVolumes'), TYPE), 								
								(SELECT
									(SELECT d.DOC_CODI "CodDocumento",
										d.DOC_NUME "NumeroDocumento",
										d.DOC_DATA "DataEmissao"
									FROM (SELECT 'N380' AS DOC_CODI,
										t.DOC_NUME AS DOC_NUME,
										t.DOC_DATA AS DOC_DATA
										UNION
										SELECT (CASE XML_DECL.DCL_DATA.value('(TransportationType/Code)[1]', 'varchar(1)') WHEN 'P' THEN 'N740' ELSE 'N704' END) AS DOC_CODI,
											@XMLNumDocTransporte AS DOC_NUME,
											t.DOC_DATA AS DOC_DATA) AS d
									FOR XML PATH('Documento'), TYPE)
								FOR XML PATH('Documentos'), TYPE)								
							FROM (SELECT NULLIF(XML_ADIC.ADI_DATA.value('CommodityCode[1]', 'varchar(10)'), '') AS ART_CPAU, 									
									XML_ADIC.ADI_DATA.value('(CargoInformation/GrossWeight)[1]', 'decimal(18, 6)') AS ART_MBRT,							
									ROUND(XML_ADIC.ADI_DATA.value('(CargoInformation/GrossWeight)[1]', 'decimal(18, 6)') * 0.95, 3) AS ART_MLIQ,	
									XML_ADIC.ADI_DATA.value('(CargoInformation/Quantity)[1]', 'decimal(18, 6)') AS ART_QTDE, 							
									XML_ADIC.ADI_DATA.value('(Amount/Amount)[1]', 'decimal(18, 6)') AS ART_PREC,								
									NULLIF(XML_ADIC.ADI_DATA.value('(ReferenceNumber/ReferenceNumber)[1]', 'varchar(35)'), '') AS DOC_NUME,
									(CONVERT(varchar(10), XML_ADIC.ADI_DATA.value('(ReferenceNumber/ReferenceDate)[1]', 'datetime'), 120) + 'Z') AS DOC_DATA							
								FROM XML_DECL.DCL_DATA.nodes('MatList/MatItem/.') as XML_ADIC(ADI_DATA)) AS t 
							GROUP BY t.ART_CPAU, t.DOC_NUME, t.DOC_DATA
							FOR XML PATH('Adicao'), TYPE)
						FOR XML PATH('Adicoes'), TYPE)						
					FROM @FicheiroXML.nodes('SHPNOT') as XML_DECL(DCL_DATA)					
					FOR XML PATH('Declaracao'), TYPE)				
				FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)										
-- processa a geração das Declarações de Importação carregadas no XML
			EXEC SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @ListaErros OUTPUT	
-- senão existir erros na geração da Declaração de Importação, processa geração da mensagem ACKANS
			IF ISNULL(@ListaErros, '') = ''										
			BEGIN
-- obtem diretoria de geração do ficheiro XML da mensagem ACKANS
				SELECT @DirFicheiroACKANS = PFC_PEPA
				FROM TAB_PFCT WITH (NOLOCK)
-- verifica se diretoria tem backslash no final
				IF SUBSTRING(REVERSE(@DirFicheiroACKANS), 1, 1) <> '\'
					SET @DirFicheiroACKANS = @DirFicheiroACKANS + '\'				
-- constroi XML para ficheiro ACKANS
				;WITH XMLNAMESPACES ('http://edi.sec.samsung.com/GLS_ECC_LE/ELEM' AS nr1)
				SELECT @FicheiroXML = 				
					(SELECT 	
						'C4E0E0T1' AS "MessageSenderIdentifier", 						
						'C4E0' AS "MessageReceiverIdentifier", 						
						'ACKANS' AS "MessageTypeIdentifier",
						'S' AS "MessageFunctionCode",
						'SHPNOT' AS "ReferenceMessageTypeIdentifier", 
						DUC_REF1 AS "MessageNumber",
						CONVERT(varchar(10), DUC_DTCR, 112) AS "MessageReceiveDate",
						REPLACE(CONVERT(varchar(8), DUC_DTCR, 108), ':', '') AS "MessageReceiveTime",
						CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 112) AS "AckSendDate", 
						REPLACE(CONVERT(varchar(8), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 108), ':', '') AS "AckSendTime", 
						'SUCCESS' AS "HandlingInformation"			
					FROM PRO_DUCG WITH (NOLOCK)
					WHERE (DUC_EANO = YEAR(GETDATE()) or DUC_EANO = (YEAR(GETDATE()) - 1)) and DUC_CPRT = @XMLNumDocTransporte			
					FOR XML PATH('nr1:ACKANS'), ELEMENTS)
-- constroi full path para geração do ficheiro XML
				SET @PathFicheiroACKANS = @DirFicheiroACKANS + 'ACKANS-' + @XMLMessageNumber + '.xml'	
-- gera o ficheiro XML ACKANS c/ encoding UTF-8
				EXEC GIDWIN..SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroACKANS
			END
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Nome Ficheiro SAMSUNG:  ' + @NomeFicheiro + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @ComandoDOS =  'ECHO ' + SUBSTRING(@ListaErros, 1, @i - 1) + ' >> "' + (@DirDestinoFicheiroErros + '/' + @NomeFicheiro) + '.err' + '"'									
				EXEC master..xp_cmdshell @ComandoDOS, NO_OUTPUT
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END		
		FETCH NEXT from FicheirosSAMSUNG into @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosSAMSUNG
	DEALLOCATE FicheirosSAMSUNG
-- remove as tabelas temporárias
	DROP TABLE #ListaFicheiros
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheirosSAMSUNG] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheirosSAMSUNG] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheirosUPS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheirosUPS] @FicheiroXML xml, @Utilizador varchar(30), @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
-- declaração de variáveis
	DECLARE  @NumErro int, @DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin)
-- inicia processo de geração da declaração	DUI2
	BEGIN TRY	
		SET @NumErro = 0	
-- obtem lista das declarações de importação do ficheiro em formato XML 	
		SET @DocumentoXML = 
			(SELECT
				(SELECT (CASE (SELECT COUNT(*) FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_CPRT = RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))) AND CAST(CONVERT(varchar(10), DUC_DTVO, 110) as datetime) = CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 13, 6))) as datetime)) WHEN 0 THEN 'I' ELSE 'U' END) "@Acao", 					
					(CONVERT(varchar(10), GETDATE(), 127) + 'Z') "Data", 
					(CASE 
						WHEN (SELECT COUNT(*) FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_DPRO = 1 AND CLI_NIF = RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9)))) > 0 AND SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '/', ''), 1, 2) <> 'FD' THEN '90' 
						ELSE '25' 
					END) "CodNatureza", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') "NumDocTransporte", 
					'IMA' "CodTipoDeclaracao", 
					'PT000020' "CodEstancia", 
					(SELECT TOP 1 CLI_CODI FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_NIF = RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9)))) "CodDestinatario", 
					'0137I4' "CodDeclarante", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '') "CodPais15A", 
					NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))), '') 
								WHEN '' THEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
								ELSE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))) 
							END), '') "CodPais16",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') "CodPais17", 
					(CASE 
						WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN '30' 
						ELSE '40' 
					END) "CodMeioTransporte18", 
					(CASE 
						WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN 'CAMIAO' 
						ELSE 'OY-SRO' 
					END) "IdMeioTransporte", 
					(CASE 
						WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN '30' 
						ELSE '40' 
					END) "CodMeioTransporte21", 
					(CASE 
						WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN 'PT' 
						ELSE 'DK' 
					END) "CodPais21", 
					0 "TemContentores", 
					'FCA' "CodCondEntrega", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') "DescricaoCondEntrega", 
					'11' "CodNaturezaTransacao", 
					'DTP00000117020PT' "CodLocalAutorizado",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 176, 2))), '') "CodPais22", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') "NomeExpedidor", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 104, 35))), '') "MoradaExpedidor", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') "LocalidadeExpedidor", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 9))), '') "CodPostalExpedidor", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') "LocPostalExpedidor", 												
					NULLIF((CASE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
								WHEN 'GB' THEN (CASE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 2))) 
													WHEN 'BT' THEN 'XI' 
													ELSE 'XU' 
												END) 
								ELSE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
							END), '') "CodPaisExpedidor", 						
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') "NomeDestinatario", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '') "MoradaDestinatario", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') "LocalidadeDestinatario", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') "CodPostalDestinatario", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') "LocPostalDestinatario", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9))), '') "NIFDestinatario", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') "CodPaisDestinatario",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 25))), '') "ObsDesalfandegamento",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') "NumRequerimento",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 20))), '') "NumDURetorno",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 30))), '') "T1Retorno",
					(CONVERT(varchar(10), CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 13, 6))) as datetime), 127) + 'Z') "DataPrevVoo",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') "NumContaExpedidor",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') "NumContaDestinatario",
					NULLIF(ISNULL((SELECT PAE_CODI FROM TAB_IATA WITH(NOLOCK) WHERE IAT_CODI = RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 3, 4)))), RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 3, 4)))), '') "Aeroporto", 
					NULLIF(SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '/', ''), 1, 2), '') "PPouFC", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))), '') "NumVoo",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 34, 11))), '') "MiniCPA",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 296, 12))), '') "Referencia2",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 51, 11))), '') "ShipID",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 35))), '') "Tracking",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 133, 2))), '') "DType",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') "PosicaoAviao",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 260, 5))), '') "TipoCarga",
					NULLIF(XML_DECL.DCL_DATA.value('nomeFicheiro[1]', 'varchar(500)'), '') "NomeFileUPS",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') "NomeDestinatario2", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '') "MoradaDestinatario2", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') "LocalidadeDestinatario2", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') "CodPostalDestinatario2", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') "LocPostalDestinatario2", 
					1 "EDeclaracaoImportacao",
					CAST(((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 207, 9))), ''), 0) as numeric(28, 6)) / 100) - (CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 119, 13))) as numeric(28, 6)) / 100)) as numeric(28, 6)) "ValorFreteCompanhia",
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 216, 3))), '') "MoedaFreteCompanhia",
					CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 137, 2))) as int) "NivelServico",
					(CASE 
						WHEN (SELECT COUNT(*) FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_DPRO = 1 and CLI_NIF = RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9)))) > 0 AND SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '/', ''), 1, 2) <> 'FD' THEN 3 
						ELSE 0 
					END) "CodFollowUp",
					(CONVERT(varchar(10), CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 192, 9))) as datetime), 127) + 'Z') "DataDocCPA", 
					(SELECT
						(SELECT 1 "NumAdicao", 
							'0000000000' "CodArtigoPautal", 
							NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))), '') 
										WHEN '' THEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
										ELSE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))) 
									END), '') "CodPaisOrigem",
							CAST((CASE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))) 
									WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS numeric(28, 6)) * 0.4536), 3) 
									ELSE (CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS numeric(28, 6)) / 10) 
								END) AS numeric(28, 6)) "MassaBruta",							
							ROUND(CAST(((CASE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))) 
											WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS numeric(28, 6)) * 0.4536), 3) 
											ELSE (CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS numeric(28, 6)) / 10) 
										END) * 0.95) AS numeric(28, 6)), 3) "MassaLiquida",
							0.000000 "QtdUnidades",
							CAST((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))) AS numeric(28, 6)) / 100) AS numeric(28, 6)) "PrecoAdicao",
							1 "MetodoAvaliacao",
							(SELECT
								(SELECT 'ADD' "Marca", 									
									CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 100, 3))) as numeric(28, 6)) "QtdVolumes",
									'CT' "CodUnidMedida", 
									CAST(0 as bit) "P", CAST(0 as bit) "R", CAST(0 as bit) "C"						
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE)
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE),
					(SELECT
						(SELECT NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
											WHEN '' THEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
											ELSE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))) 
										END), '') "CodPais",
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') "Descricao",
							CAST((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))) AS numeric(28, 6)) / 100) AS numeric(28, 6)) "Valor",
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 3))), '') "Moeda",							
							CAST((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))) AS numeric(28, 6)) / 100) AS numeric(28, 6)) "TotalFatura",
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') "NumeroCPA",
							CAST((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS numeric(28, 6)) / 10) AS numeric(28, 6)) "Peso",
							0 "Tipo"
						FOR XML PATH('DadosManifesto'), TYPE),
						(SELECT NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
											WHEN '' THEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
											ELSE RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))) 
										END), '') "CodPais",
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') "Descricao",
							CAST((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))) AS numeric(28, 6)) / 100) AS numeric(28, 6)) "Valor",
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 3))), '') "Moeda",							
							CAST((CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))) AS numeric(28, 6)) / 100) AS numeric(28, 6)) "TotalFatura",
							NULLIF(RTRIM(LTRIM(SUBSTRING(XML_MANI.MAN_DATA.value('linha[1]', 'varchar(MAX)'), 167, 35))), '') "NumeroCPA",
							CAST((CAST(RTRIM(LTRIM(SUBSTRING(XML_MANI.MAN_DATA.value('linha[1]', 'varchar(MAX)'), 66, 3))) AS numeric(28, 6)) / 10) AS numeric(28, 6)) "Peso",
							0 "Tipo"
						FROM XML_DECL.DCL_DATA.nodes('b600xxx/.') AS XML_MANI(MAN_DATA)						
						FOR XML PATH('DadosManifesto'), TYPE)
					FOR XML PATH('Manifestos'), TYPE)
				FROM @FicheiroXML.nodes('declaracaoUPS') AS XML_DECL(DCL_DATA)
				WHERE (CASE ISNULL((SELECT NDE_CODI FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_CPRT = RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))) AND CAST(CONVERT(varchar(10), DUC_DTVO, 110) AS datetime) = CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b100000/linha)[1]', 'varchar(MAX)'), 13, 6))) AS datetime)), '') 
						WHEN '' THEN 1 
						WHEN '25' THEN 1 
						ELSE 0 
					END) = 1
				FOR XML PATH('Declaracao'), TYPE)				
			FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)		
-- processa a geração da declaração DUI2	
		SET @Erro = ''	
		EXEC @NumErro = SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @Erro OUTPUT						
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheirosUPS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheirosUPS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheirosUPSDeSFTP]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheirosUPSDeSFTP] @psFTPAppPath varchar(1000), @ServidorSFTP varchar(100), @UtilizadorSFTP varchar(100), @PasswordSFTP varchar(100), 
	@PortaSFTP int, @HostKeyServidorSFTP varchar(100), @DirOrigemFicheirosSFTP varchar(100), @DirDestinoFicheirosSFTP varchar(100), @DirFicheirosTmpLocal varchar(250), 
	@DirDestinoFicheiroErros varchar(500), @DataReferencia datetime, @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @psFPTAppArgs varchar(2000), @PathFicheiroComandosFTP varchar(1000), @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @i int, @ListaErros varchar(MAX), 
		@Erros varchar(MAX), @PathFicheiroErro varchar(500), @Linha varchar(MAX), @ComandoSQL varchar(1500), @Conteudo varchar(MAX), @MascaraFicheirosUPS varchar(10), 
		@DocumentoXML xml(XMLSC_DeclaracoesImpToGIDWin)
-- define a máscara de ficheiros UPS a importar
	SET @MascaraFicheirosUPS = 'd3999*.*'		
-- cria tabela temporária p/ conteudo de cada ficheiro
	CREATE TABLE #ConteudoFicheiro(CONTEUDO varchar(MAX))	
-- cria tabela temporária p/ dados parcialmente descodificados por processo de cada ficheiro
	CREATE TABLE #InfoProcessosUPS(PAIS_ORIGEM varchar(2) COLLATE Latin1_General_CI_AI, AEROPORTO_ORIGEM varchar(4) COLLATE Latin1_General_CI_AI, 
		PAIS_DESTINO varchar(2) COLLATE Latin1_General_CI_AI, AEROPORTO_DESTINO varchar(4) COLLATE Latin1_General_CI_AI, 
		DATA_UPS varchar(6) COLLATE Latin1_General_CI_AI, TIPO_CLIENTE varchar(1) COLLATE Latin1_General_CI_AI, 
		CODIGO_CLIENTE varchar(11) COLLATE Latin1_General_CI_AI, TIPO_LINHA int, DADOS_LINHA varchar(2000) COLLATE Latin1_General_CI_AI)
-- valida se a aplicação p/ sFTP é a correta
	IF REVERSE(SUBSTRING(REVERSE(@psFTPAppPath), 1, CHARINDEX('\', REVERSE(@psFTPAppPath)) - 1)) <> 'psftp.exe'
	BEGIN
		RAISERROR('A aplicação de envio de ficheiros p/ sFTP especificada não é válida!', 16, 1)
		RETURN 1
	END
-- substitui caracteres especiais p/ utilização no comando "echo"
	SET @ServidorSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@ServidorSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @UtilizadorSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@UtilizadorSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @PasswordSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@PasswordSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirOrigemFicheirosSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@DirOrigemFicheirosSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirDestinoFicheirosSFTP = REPLACE(REPLACE(REPLACE(REPLACE(@DirDestinoFicheirosSFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
-- verifica se diretorias SFTP tem separador no início
	IF SUBSTRING(@DirOrigemFicheirosSFTP, 1, 1) <> '/'
		SET @DirOrigemFicheirosSFTP = '/' + @DirOrigemFicheirosSFTP
	IF SUBSTRING(@DirDestinoFicheirosSFTP, 1, 1) <> '/'
		SET @DirDestinoFicheirosSFTP = '/' + @DirDestinoFicheirosSFTP
-- verfica se diretorias locais tem backslash no final
	IF SUBSTRING(REVERSE(@DirFicheirosTmpLocal), 1, 1) <> '\'
		SET @DirFicheirosTmpLocal = @DirFicheirosTmpLocal + '\'		
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'					
-- constroi nome p/ diretoria local tmp
	SET @DirFicheirosTmpLocal = @DirFicheirosTmpLocal + REPLACE(CAST(CONVERT(numeric(38, 12), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) as varchar(20)), '.', ',') + '\'	
-- processa a criação da diretoria local tmp 
	EXEC GIDWIN..SP_Externo_CriaDiretoria @DirFicheirosTmpLocal, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível criar a diretoria "%s"! ERRO: "%s".', 16, 1, @DirFicheirosTmpLocal, @Erros)
-- gera o ficheiro de comandos SFTP na diretoria local tmp p/ download de ficheiros UPS
	SET @PathFicheiroComandosFTP = @DirFicheirosTmpLocal + 'comandosSFTP.txt'			
	SET @Linha = 'cd ' + @DirOrigemFicheirosSFTP
	EXEC GIDWIN..SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroComandosFTP, @Erros)	
	SET @Linha = 'lcd ' + @DirFicheirosTmpLocal
	EXEC GIDWIN..SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroComandosFTP, @Erros)					
	SET @Linha = 'mget ' + @MascaraFicheirosUPS
	EXEC GIDWIN..SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroComandosFTP, @Erros)			
	SET @Linha = 'mv ' + @MascaraFicheirosUPS + ' ' + @DirDestinoFicheirosSFTP
	EXEC GIDWIN..SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroComandosFTP, @Erros)									
	SET @Linha = 'quit'
	EXEC GIDWIN..SP_Externo_EscreveLinhaFicheiro @PathFicheiroComandosFTP, @Linha, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroComandosFTP, @Erros)				
-- constroi os argumentos p/ a aplicação sFTP
	SET @psFPTAppArgs = @ServidorSFTP
	IF @PortaSFTP IS NOT NULL
		SET @psFPTAppArgs = @psFPTAppArgs + ' -P ' + CAST(@PortaSFTP as varchar(5)) 
	SET @psFPTAppArgs = @psFPTAppArgs + ' -l ' + @UtilizadorSFTP + ' -pw ' + @PasswordSFTP + ' -b "' + @PathFicheiroComandosFTP + '" -batch' 
	IF ISNULL(@HostKeyServidorSFTP, '') <> ''
		SET @psFPTAppArgs = @psFPTAppArgs + ' -hostkey ' + @HostKeyServidorSFTP
-- processa o download dos ficheiros UPS do SFTP p/ diretoria local tmp 
	EXEC GIDWIN..SP_Externo_ExecutaPrograma @psFTPAppPath, @psFPTAppArgs, @Erros OUTPUT		
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível efetuar o download dos ficheiros "%s" do servidor SFTP "%s"! ERRO: "%s".', 16, 1, @MascaraFicheirosUPS, @ServidorSFTP, @Erros)
-- remove o ficheiro de comandos SFTP na diretoria local tmp
	EXEC GIDWIN..SP_Externo_RemoveFicheiro @PathFicheiroComandosFTP, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroComandosFTP, @Erros)	
-- obtem lista de ficheiros UPS a integrar
	DECLARE FicheirosUPS CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirFicheirosTmpLocal, @MascaraFicheirosUPS)
		WHERE SUBSTRING(RIGHT([fileName], 4), 1, 1) = '.' and ISNUMERIC(RIGHT([fileName], 3)) = 1 and [lastWriteTime] >= @DataReferencia
		ORDER BY [lastWriteTime]			
	OPEN FicheirosUPS
	FETCH NEXT from FicheirosUPS into @PathFicheiro, @NomeFicheiro			
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''		
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária
			SET @ComandoSQL = 'BULK INSERT #ConteudoFicheiro FROM ''' + @PathFicheiro + ''''
			EXEC (@ComandoSQL)
-- remove o ficheiro UPS da diretoria local tmp
			EXEC GIDWIN..SP_Externo_RemoveFicheiro @PathFicheiro, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)										
-- insere dados parcialmente descodificados por processo/tipo linha de cada ficheiro 
			INSERT INTO #InfoProcessosUPS(PAIS_ORIGEM, AEROPORTO_ORIGEM, PAIS_DESTINO, AEROPORTO_DESTINO, DATA_UPS, TIPO_CLIENTE, CODIGO_CLIENTE, TIPO_LINHA, DADOS_LINHA)
			SELECT SUBSTRING(CONTEUDO, 1, 2), SUBSTRING(CONTEUDO, 3, 4), SUBSTRING(CONTEUDO, 7, 2), SUBSTRING(CONTEUDO, 9, 4), SUBSTRING(CONTEUDO, 13, 6), 
				SUBSTRING(CONTEUDO, 33, 1), SUBSTRING(CONTEUDO, 34, 11), CAST(SUBSTRING(CONTEUDO, 45, 6) as int), dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(CONTEUDO)
			FROM #ConteudoFicheiro
-- obtem lista das declarações de importação do ficheiro em formato XML 	
			SET @DocumentoXML = 
				(SELECT
					(SELECT (CASE (SELECT COUNT(*) FROM PRO_DUCG WHERE DUC_CPRT = RTRIM(LTRIM(SUBSTRING(blc202000.DADOS_LINHA, 51, 18))) and CAST(CONVERT(varchar(10), DUC_DTVO, 110) as datetime) = CAST(RTRIM(LTRIM(SUBSTRING(blc100000.DADOS_LINHA, 13, 6))) as datetime)) WHEN 0 THEN 'I' ELSE 'U' END) "@Acao", 					
						(CONVERT(varchar(10), GETDATE(), 127) + 'Z') "Data", 
						(CASE WHEN (SELECT COUNT(*) FROM TAB_CLIE WHERE CLI_DPRO = 1 and CLI_NIF = RTRIM(LTRIM(SUBSTRING(blc701000.DADOS_LINHA, 107, 9)))) > 0 and SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 319, 3))), '/', ''), 1, 2) <> 'FD' THEN '90' ELSE '25' END) "CodNatureza", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc202000.DADOS_LINHA, 51, 18))), '') "NumDocTransporte", 
						'IMA' "CodTipoDeclaracao", 'PT000020' "CodEstancia", 
						(SELECT TOP 1 CLI_CODI FROM TAB_CLIE WHERE CLI_NIF = RTRIM(LTRIM(SUBSTRING(blc701000.DADOS_LINHA, 107, 9)))) "CodDestinatario", 
						'0137I4' "CodDeclarante", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 240, 2))), '') "CodPais15A", 
						NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 86, 2))), '') WHEN '' THEN RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 240, 2))) ELSE RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 86, 2))) END), '') "CodPais16",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 265, 2))), '') "CodPais17", 
						'40' "CodMeioTransporte18", 'OY-SRO' "IdMeioTransporte", '40' "CodMeioTransporte21", 'DK' "CodPais21", 0 "TemContentores", 'FCA' "CodCondEntrega", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 174, 35))), '') "DescricaoCondEntrega", 
						'11' "CodNaturezaTransacao", 'DTP00000117020PT' "CodLocalAutorizado",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 176, 2))), '') "CodPais22", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 69, 35))), '') "NomeExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 104, 35))), '') "MoradaExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 174, 35))), '') "LocalidadeExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 231, 9))), '') "CodPostalExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 174, 35))), '') "LocPostalExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 240, 2))), '') "CodPaisExpedidor", 					
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 69, 35))), '') "NomeDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 129, 35))), '') "MoradaDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 199, 35))), '') "LocalidadeDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 256, 9))), '') "CodPostalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 199, 35))), '') "LocPostalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc701000.DADOS_LINHA, 107, 9))), '') "NIFDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 265, 2))), '') "CodPaisDestinatario",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 69, 25))), '') "ObsDesalfandegamento",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 220, 1))), '') "NumRequerimento",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 129, 20))), '') "NumDURetorno",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 199, 30))), '') "T1Retorno",
						(CONVERT(varchar(10), CAST(RTRIM(LTRIM(SUBSTRING(blc100000.DADOS_LINHA, 13, 6))) as datetime), 127) + 'Z') "DataPrevVoo",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 59, 10))), '') "NumContaExpedidor",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 59, 10))), '') "NumContaDestinatario",
						NULLIF(ISNULL((SELECT PAE_CODI FROM TAB_IATA WHERE IAT_CODI = RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 3, 4)))), RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 3, 4)))), '') "Aeroporto", 
						NULLIF(SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 319, 3))), '/', ''), 1, 2), '') "PPouFC", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 353, 8))), '') "NumVoo",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 34, 11))), '') "MiniCPA",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 296, 12))), '') "Referencia2",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 51, 11))), '') "ShipID",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc202000.DADOS_LINHA, 51, 35))), '') "Tracking",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 133, 2))), '') "DType",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 256, 9))), '') "PosicaoAviao",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 260, 5))), '') "TipoCarga",
						@NomeFicheiro "NomeFileUPS",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 69, 35))), '') "NomeDestinatario2", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 129, 35))), '') "MoradaDestinatario2", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 199, 35))), '') "LocalidadeDestinatario2", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 256, 9))), '') "CodPostalDestinatario2", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc400000.DADOS_LINHA, 199, 35))), '') "LocPostalDestinatario2", 
						1 "EDeclaracaoImportacao",
						CAST(((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 207, 9))), ''), 0) as numeric(28, 6)) / 100) - (CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 119, 13))) as numeric(28, 6)) / 100)) as numeric(28, 6)) "ValorFreteCompanhia",
						NULLIF(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 216, 3))), '') "MoedaFreteCompanhia",
						CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 137, 2))) as int) "NivelServico",
						(CASE WHEN (SELECT COUNT(*) FROM TAB_CLIE WHERE CLI_DPRO = 1 and CLI_NIF = RTRIM(LTRIM(SUBSTRING(blc701000.DADOS_LINHA, 107, 9)))) > 0 and SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 319, 3))), '/', ''), 1, 2) <> 'FD' THEN 3 ELSE 0 END) "CodFollowUp",
						(CONVERT(varchar(10), CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 192, 9))) as datetime), 127) + 'Z') "DataDocCPA", 
						(SELECT
							(SELECT 1 "NumAdicao", '0000000000' "CodArtigoPautal", 
								NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 86, 2))), '') WHEN '' THEN RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 240, 2))) ELSE RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 86, 2))) END), '') "CodPaisOrigem",
								CAST((CASE RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 82, 3))) WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 77, 5))) as numeric(28, 6)) * 0.4536), 3) ELSE (CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 77, 5))) as numeric(28, 6)) / 10) END) as numeric(28, 6)) "MassaBruta",							
								ROUND(CAST(((CASE RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 82, 3))) WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 77, 5))) as numeric(28, 6)) * 0.4536), 3) ELSE (CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 77, 5))) as numeric(28, 6)) / 10) END) * 0.95) as numeric(28, 6)), 3) "MassaLiquida",
								0.000000 "QtdUnidades",
								CAST((CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 166, 10))) as numeric(28, 6)) / 100) as numeric(28, 6)) "PrecoAdicao",
								1 "MetodoAvaliacao",
								(SELECT
									(SELECT 'ADD' "Marca", 									
										CAST(RTRIM(LTRIM(SUBSTRING(blc202000.DADOS_LINHA, 100, 3))) as numeric(28, 6)) "QtdVolumes",
										'CT' "CodUnidMedida", CAST(0 as bit) "P", CAST(0 as bit) "R", CAST(0 as bit) "C"						
									FOR XML PATH('MarcaEVolume'), TYPE)
								FOR XML PATH('MarcasEVolumes'), TYPE)
							FOR XML PATH('Adicao'), TYPE)
						FOR XML PATH('Adicoes'), TYPE),
						(SELECT
							(SELECT NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 195, 2))), '') WHEN '' THEN RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 240, 2))) ELSE RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 195, 2))) END), '') "CodPais",
								NULLIF(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 58, 104))), '') "Descricao",
								CAST((CAST(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 162, 10))) as numeric(28, 6)) / 100) as numeric(28, 6)) "Valor",
								NULLIF(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 172, 3))), '') "Moeda",							
								CAST((CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 166, 10))) as numeric(28, 6)) / 100) as numeric(28, 6)) "TotalFatura",
								NULLIF(RTRIM(LTRIM(SUBSTRING(blc202000.DADOS_LINHA, 51, 18))), '') "NumeroCPA",
								CAST((CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 77, 5))) as numeric(28, 6)) / 10) as numeric(28, 6)) "Peso",
								0 "Tipo"
							FOR XML PATH('DadosManifesto'), TYPE),
							(SELECT NULLIF((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 195, 2))), '') WHEN '' THEN RTRIM(LTRIM(SUBSTRING(blc300000.DADOS_LINHA, 240, 2))) ELSE RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 195, 2))) END), '') "CodPais",
								NULLIF(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 58, 104))), '') "Descricao",
								CAST((CAST(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 162, 10))) as numeric(28, 6)) / 100) as numeric(28, 6)) "Valor",
								NULLIF(RTRIM(LTRIM(SUBSTRING(blc500000.DADOS_LINHA, 172, 3))), '') "Moeda",							
								CAST((CAST(RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 166, 10))) as numeric(28, 6)) / 100) as numeric(28, 6)) "TotalFatura",
								NULLIF(RTRIM(LTRIM(SUBSTRING(blc600xxx.DADOS_LINHA, 167, 35))), '') "NumeroCPA",
								CAST((CAST(RTRIM(LTRIM(SUBSTRING(blc600xxx.DADOS_LINHA, 66, 3))) as numeric(28, 6)) / 10) as numeric(28, 6)) "Peso",
								0 "Tipo"
							FROM #InfoProcessosUPS as blc600xxx
							WHERE blc600xxx.TIPO_LINHA >= 600000 and blc600xxx.TIPO_LINHA < 700000 and blc600xxx.PAIS_ORIGEM = blc100000.PAIS_ORIGEM and blc600xxx.AEROPORTO_ORIGEM = blc100000.AEROPORTO_ORIGEM 
								and blc600xxx.PAIS_DESTINO = blc100000.PAIS_DESTINO and blc600xxx.AEROPORTO_DESTINO = blc100000.AEROPORTO_DESTINO and blc600xxx.DATA_UPS = blc100000.DATA_UPS 
								and blc600xxx.TIPO_CLIENTE = blc100000.TIPO_CLIENTE and blc600xxx.CODIGO_CLIENTE = blc100000.CODIGO_CLIENTE 
							FOR XML PATH('DadosManifesto'), TYPE)
						FOR XML PATH('Manifestos'), TYPE)
					FROM #InfoProcessosUPS as blc100000 LEFT OUTER JOIN #InfoProcessosUPS as blc200000 ON blc100000.PAIS_ORIGEM = blc200000.PAIS_ORIGEM and blc100000.AEROPORTO_ORIGEM = blc200000.AEROPORTO_ORIGEM and blc100000.PAIS_DESTINO = blc200000.PAIS_DESTINO and blc100000.AEROPORTO_DESTINO = blc200000.AEROPORTO_DESTINO and blc100000.DATA_UPS = blc200000.DATA_UPS and blc100000.TIPO_CLIENTE = blc200000.TIPO_CLIENTE and blc100000.CODIGO_CLIENTE = blc200000.CODIGO_CLIENTE and blc200000.TIPO_LINHA = 200000
						LEFT OUTER JOIN #InfoProcessosUPS as blc202000 ON blc100000.PAIS_ORIGEM = blc202000.PAIS_ORIGEM and blc100000.AEROPORTO_ORIGEM = blc202000.AEROPORTO_ORIGEM and blc100000.PAIS_DESTINO = blc202000.PAIS_DESTINO and blc100000.AEROPORTO_DESTINO = blc202000.AEROPORTO_DESTINO and blc100000.DATA_UPS = blc202000.DATA_UPS and blc100000.TIPO_CLIENTE = blc202000.TIPO_CLIENTE and blc100000.CODIGO_CLIENTE = blc202000.CODIGO_CLIENTE and blc202000.TIPO_LINHA = 202000
						LEFT OUTER JOIN #InfoProcessosUPS as blc300000 ON blc100000.PAIS_ORIGEM = blc300000.PAIS_ORIGEM and blc100000.AEROPORTO_ORIGEM = blc300000.AEROPORTO_ORIGEM and blc100000.PAIS_DESTINO = blc300000.PAIS_DESTINO and blc100000.AEROPORTO_DESTINO = blc300000.AEROPORTO_DESTINO and blc100000.DATA_UPS = blc300000.DATA_UPS and blc100000.TIPO_CLIENTE = blc300000.TIPO_CLIENTE and blc100000.CODIGO_CLIENTE = blc300000.CODIGO_CLIENTE and blc300000.TIPO_LINHA = 300000
						LEFT OUTER JOIN #InfoProcessosUPS as blc400000 ON blc100000.PAIS_ORIGEM = blc400000.PAIS_ORIGEM and blc100000.AEROPORTO_ORIGEM = blc400000.AEROPORTO_ORIGEM and blc100000.PAIS_DESTINO = blc400000.PAIS_DESTINO and blc100000.AEROPORTO_DESTINO = blc400000.AEROPORTO_DESTINO and blc100000.DATA_UPS = blc400000.DATA_UPS and blc100000.TIPO_CLIENTE = blc400000.TIPO_CLIENTE and blc100000.CODIGO_CLIENTE = blc400000.CODIGO_CLIENTE and blc400000.TIPO_LINHA = 400000
						LEFT OUTER JOIN #InfoProcessosUPS as blc500000 ON blc100000.PAIS_ORIGEM = blc500000.PAIS_ORIGEM and blc100000.AEROPORTO_ORIGEM = blc500000.AEROPORTO_ORIGEM and blc100000.PAIS_DESTINO = blc500000.PAIS_DESTINO and blc100000.AEROPORTO_DESTINO = blc500000.AEROPORTO_DESTINO and blc100000.DATA_UPS = blc500000.DATA_UPS and blc100000.TIPO_CLIENTE = blc500000.TIPO_CLIENTE and blc100000.CODIGO_CLIENTE = blc500000.CODIGO_CLIENTE and blc500000.TIPO_LINHA = 500000
						LEFT OUTER JOIN #InfoProcessosUPS as blc701000 ON blc100000.PAIS_ORIGEM = blc701000.PAIS_ORIGEM and blc100000.AEROPORTO_ORIGEM = blc701000.AEROPORTO_ORIGEM and blc100000.PAIS_DESTINO = blc701000.PAIS_DESTINO and blc100000.AEROPORTO_DESTINO = blc701000.AEROPORTO_DESTINO and blc100000.DATA_UPS = blc701000.DATA_UPS and blc100000.TIPO_CLIENTE = blc701000.TIPO_CLIENTE and blc100000.CODIGO_CLIENTE = blc701000.CODIGO_CLIENTE and blc701000.TIPO_LINHA = 701000
					WHERE blc100000.TIPO_LINHA = 100000 and RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 133, 2))) = '01' and RTRIM(LTRIM(SUBSTRING(blc200000.DADOS_LINHA, 260, 5))) in ('T1', 'TD', 'TF')
						and (CASE ISNULL((SELECT NDE_CODI FROM PRO_DUCG WHERE DUC_CPRT = RTRIM(LTRIM(SUBSTRING(blc202000.DADOS_LINHA, 51, 18))) and CAST(CONVERT(varchar(10), DUC_DTVO, 110) as datetime) = CAST(RTRIM(LTRIM(SUBSTRING(blc100000.DADOS_LINHA, 13, 6))) as datetime)), '') WHEN '' THEN 1 WHEN '25' THEN 1 ELSE 0 END) = 1								
					FOR XML PATH('Declaracao'), TYPE)				
				FOR XML PATH('DeclaracoesImpToGIDWin'), ELEMENTS)		
-- processa a geração das Declarações de Importação carregadas no XML			
			EXEC SP_DeclImportacao_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @ListaErros OUTPUT		
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Nome Ficheiro UPS:  ' + @NomeFicheiro + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
				EXEC GIDWIN..SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroErro, @Erros)	
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END		
		FETCH NEXT from FicheirosUPS into @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosUPS
	DEALLOCATE FicheirosUPS	
-- processo a remoção da diretoria local tmp
	EXEC GIDWIN..SP_Externo_RemoveDiretoria @DirFicheirosTmpLocal, @Erros OUTPUT
	IF ISNULL(@Erros, '') <> ''
		RAISERROR ('Não foi possível remover a diretoria "%s"! ERRO: "%s".', 16, 1, @DirFicheirosTmpLocal, @Erros)	
-- remove as tabelas temporárias	
	DROP TABLE #ConteudoFicheiro
	DROP TABLE #InfoProcessosUPS
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheirosUPSDeSFTP] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheirosUPSDeSFTP] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ImportaFicheiroTXTVeiculosRENAULTDACIA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ImportaFicheiroTXTVeiculosRENAULTDACIA] @FicheiroTXT varchar(MAX), @NumFabrica varchar(3) AS
BEGIN
	SET NOCOUNT ON	
-- declaração de variáveis
	DECLARE @Delimiter CHAR(2), @NextPos int, @LastPos int, @Linha varchar(2000)
	DECLARE @tmpTbVeiculos TABLE(ID int IDENTITY NOT NULL, 
							Chassi varchar(25) COLLATE Latin1_General_CI_AI NOT NULL, 
							Homologacao varchar(16) COLLATE Latin1_General_CI_AI NOT NULL, 
							EmissaoCO2 int NOT NULL, 
							Modelo varchar(25) COLLATE Latin1_General_CI_AI NOT NULL, 
							CodTipoVeiculo varchar(3) COLLATE Latin1_General_CI_AI NOT NULL, 
							CodCategoriaVeiculo varchar(2) COLLATE Latin1_General_CI_AI NOT NULL, 
							CodTipoCombustivel varchar(2) COLLATE Latin1_General_CI_AI NOT NULL, 
							Cilindrada int NOT NULL, 
							Particulas decimal(8, 4) NOT NULL, 
							Qualificador varchar(1) COLLATE Latin1_General_CI_AI NOT NULL,
							Fabrica varchar(3) COLLATE Latin1_General_CI_AI NOT NULL)
-- inicia variáveis
	SET @Delimiter = CHAR(13) + CHAR(10)
	SET @LastPos = 0
	SET @NextPos = CHARINDEX(@Delimiter, @FicheiroTXT, 1)
-- percorre as linhas do ficheiro e insere os respetivos dados na tabela tmp
	WHILE @NextPos > 0
	BEGIN
		SET @Linha = SUBSTRING(@FicheiroTXT, @LastPos, @NextPos - @LastPos)
-- insere dados da linha na tabela tmp
		INSERT INTO @tmpTbVeiculos (Chassi, Homologacao, EmissaoCO2, Modelo, CodTipoVeiculo, CodCategoriaVeiculo, CodTipoCombustivel, Cilindrada, Particulas, Qualificador, Fabrica)
		VALUES (LTRIM(RTRIM(SUBSTRING(@Linha, 9, 25))), LTRIM(RTRIM(SUBSTRING(@Linha, 34, 16))), CAST(LTRIM(RTRIM(SUBSTRING(@Linha, 50, 3))) AS int), LTRIM(RTRIM(SUBSTRING(@Linha, 68, 25))), 
			LTRIM(RTRIM(SUBSTRING(@Linha, 93, 3))), LTRIM(RTRIM(SUBSTRING(@Linha, 96, 2))), LTRIM(RTRIM(SUBSTRING(@Linha, 98, 2))), CAST(LTRIM(RTRIM(SUBSTRING(@Linha, 100, 5))) AS int), 
			CAST(LEFT(LTRIM(RTRIM(SUBSTRING(@Linha, 105, 6))), 2) + '.' + RIGHT(LTRIM(RTRIM(SUBSTRING(@Linha, 105, 6))), 4) AS decimal(8, 4)), LTRIM(RTRIM(SUBSTRING(@Linha, 111, 1))),  
			LTRIM(RTRIM(SUBSTRING(@Linha, 112, 3))))
-- incrementa variáveis
		SET @LastPos = @NextPos + 2
		SET @NextPos = CHARINDEX(@Delimiter, @FicheiroTXT, @NextPos + 1)
	END
-- obtem os dados dos veiculos e a respetiva lista de chassis
	SELECT vei.Homologacao AS FCH_HOMO, vei.Cilindrada AS FCH_CILI, vei.CodTipoVeiculo AS FCH_TVEI, vei.Qualificador AS FCH_QUAL, vei.EmissaoCO2 AS FCH_ECO2, vei.CodCategoriaVeiculo AS FCH_CVEI, 
		vei.CodTipoCombustivel AS FCH_TCOM, 'RENAULT-DACIA' AS FCH_MARC, vei.Modelo AS FCH_MODE, vei.Particulas AS FCH_PART, ISNULL(hte.HTE_VISV, 0) AS HTE_VISV, COUNT(*) AS FCH_NVEI, CAST(0 AS bit) AS FCH_SELE, 
		(SELECT 
			(SELECT Chassi
			FROM @tmpTbVeiculos 
			WHERE Fabrica = vei.Fabrica AND Homologacao = vei.Homologacao AND EmissaoCO2 = vei.EmissaoCO2 AND Modelo = vei.Modelo AND CodTipoVeiculo = vei.CodTipoVeiculo 
				AND CodCategoriaVeiculo = vei.CodCategoriaVeiculo AND CodTipoCombustivel = vei.CodTipoCombustivel AND Cilindrada = vei.Cilindrada AND Particulas = vei.Particulas AND Qualificador = vei.Qualificador
			FOR XML PATH(''), TYPE)
		FOR XML PATH('Chassis'), ELEMENTS) AS FCH_CHAS
	FROM @tmpTbVeiculos AS vei LEFT OUTER JOIN TAB_HTEC AS hte ON vei.Homologacao = hte.HTE_CODI
	WHERE vei.Fabrica = @NumFabrica
	GROUP BY vei.Fabrica, vei.Homologacao, vei.EmissaoCO2, vei.Modelo, vei.CodTipoVeiculo, vei.CodCategoriaVeiculo, vei.CodTipoCombustivel, vei.Cilindrada, vei.Particulas, vei.Qualificador, hte.HTE_VISV
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ImportaFicheiroTXTVeiculosRENAULTDACIA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ImportaFicheiroTXTVeiculosRENAULTDACIA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DeclImportacao_ReplicaNRMParaProcessos]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DeclImportacao_ReplicaNRMParaProcessos] @LstProcessos xml, @NumeroNRM varchar(22), @DataNRM datetime, @CodEstancia varchar(8), 
	@MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoProcesso int, @NumProcesso int, @IdNRM int, @NomeEstancia varchar(35), @Erro int
-- inicia transacção para inserção da linha NRM nas várias Declarações de Importação
	BEGIN TRANSACTION		
	BEGIN TRY
-- obtem nome da estância aduaneira
		SELECT @NomeEstancia = EAD_NOME
		FROM TAB_EADU
		WHERE EAD_CODI = @CodEstancia
-- obtem lista de Numeros Doc. Transporte para inserir a linha NRM
		DECLARE LstNumDocsTransporte CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT duc.DUC_EANO, duc.DUC_PNUM
			FROM @LstProcessos.nodes('LstProcessos/Processo') as XML_PRCS(PRC_CPRT) INNER JOIN PRO_DUCG as duc ON XML_PRCS.PRC_CPRT.value('DUC_CPRT[1]', 'varchar(18)') = duc.DUC_CPRT and XML_PRCS.PRC_CPRT.value('DUC_EANO[1]', 'varchar(18)') = duc.DUC_EANO
			WHERE duc.DUC_DUNO = 1
			GROUP BY duc.DUC_EANO, duc.DUC_PNUM			
		OPEN LstNumDocsTransporte
		FETCH NEXT FROM LstNumDocsTransporte INTO @AnoProcesso, @NumProcesso
		WHILE @@FETCH_STATUS = 0
		BEGIN					
-- obtem proximo número (ID) para nova linha NRM a inserir
			SELECT @IdNRM = ISNULL(MAX(DDA_CODI), 0) + 1
			FROM PRO_DUDA
			WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso	
-- insere linha NRM na declaração de importação			
			INSERT INTO PRO_DUDA(DUC_EANO, DUC_PNUM, DDA_CODI, DDA_NNRM, DDA_DATA, EAD_CODI, EAD_NOME)
			VALUES(@AnoProcesso, @NumProcesso, @IdNRM, @NumeroNRM, @DataNRM, @CodEstancia, @NomeEstancia)
			
			FETCH NEXT from LstNumDocsTransporte into @AnoProcesso, @NumProcesso
		END
		CLOSE LstNumDocsTransporte
		DEALLOCATE LstNumDocsTransporte
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) + ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_DeclImportacao_ReplicaNRMParaProcessos] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DeclImportacao_ReplicaNRMParaProcessos] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_DUImportacao_ConverteParaDeclImportacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_DUImportacao_ConverteParaDeclImportacao] @AnoProcesso int, @NumProcesso int, @Utilizador varchar(30), @MensagemErro varchar(8000) OUTPUT AS
BEGIN
-- declaração de variaveis
	DECLARE @Erro int, @IDInterno1Ad varchar(20)
-- inicia variaveis
	SET @Erro = 0
-- inicia transacção para inserção dados CAB e DET da conta
	BEGIN TRANSACTION		
	BEGIN TRY
-- altera campos do Processo p/ conversão em Declaração Importação
		UPDATE PRO_DUCG SET DUC_DUNO = 1, DUC_TLOC = 'LA', DUC_UALT = @Utilizador, DUC_DTAL = GETDATE()
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso
-- altera campos das Adições
		UPDATE PRO_DUAD SET DUA_MAVA = 1, RRE_NOME1 = ISNULL(NULLIF(RRE_NOME1, ''), (SELECT RRE_NOME FROM TAB_RREC WHERE RRE_CODI = PRO_DUAD.RRE_PREF)), 
			DUA_IMPI = ISNULL(NULLIF(DUA_IMPI, ''),(SELECT RRE_IMPO FROM TAB_RREC WHERE RRE_CODI = PRO_DUAD.RRE_CODI))			
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso
-- calcula ID interno p/ linha de Declaração Sumária da 1ª adição
		SET @IDInterno1Ad = REPLACE(CAST(CONVERT(numeric(38, 12), GETDATE()) as varchar(20)), '.', ',')
-- insere linha de detalhe de Declaração Sumária para a 1ª Adição
		INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APDT, DRA_QUAL, DRA_CODR, DRA_AUTO, DRA_IDCR)
		SELECT DUC_EANO, DUC_PNUM, DUA_CODI, (SELECT ISNULL(MAX(DRA_CODI), 0) + 1 FROM PRO_DURA WHERE DUC_EANO = PRO_DUAD.DUC_EANO and DUC_PNUM = PRO_DUAD.DUC_PNUM and DUA_CODI = PRO_DUAD.DUA_CODI), 
			DOC_CODI, YEAR(DUA_DDAT), (DUA_DNUM + ISNULL(DUA_LINH, '')), 'NP', DUA_DDAT, DUA_QUAL, NULL, 0, @IDInterno1Ad
		FROM PRO_DUAD
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso and DUA_CODI = 1 and DUA_QUAL = 'X' and ISNULL(DUA_DNUM, '') <> '' and DUA_DDAT IS NOT NULL					
-- insere linha de detalhe de Declaração Sumária para as restantes Adições
		INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APDT, DRA_QUAL, DRA_CODR, DRA_AUTO, DRA_IDCR)
		SELECT DUC_EANO, DUC_PNUM, DUA_CODI, (SELECT ISNULL(MAX(DRA_CODI), 0) + 1 FROM PRO_DURA WHERE DUC_EANO = PRO_DUAD.DUC_EANO and DUC_PNUM = PRO_DUAD.DUC_PNUM and DUA_CODI = PRO_DUAD.DUA_CODI), 
			DOC_CODI, YEAR(DUA_DDAT), (DUA_DNUM + ISNULL(DUA_LINH, '')), 'NP', DUA_DDAT, DUA_QUAL, @IDInterno1Ad, 1, 
			REPLACE(CAST(CONVERT(numeric(38, 12), GETDATE()) as varchar(20)), '.', ',')
		FROM PRO_DUAD
		WHERE DUC_EANO = @AnoProcesso and DUC_PNUM = @NumProcesso and DUA_CODI > 1 and DUA_QUAL = 'X' and ISNULL(DUA_DNUM, '') <> '' and DUA_DDAT IS NOT NULL				
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) + ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_DUImportacao_ConverteParaDeclImportacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_DUImportacao_ConverteParaDeclImportacao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaAgrex]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
create proc [SP_duplicaAgrex] @cod int, @ano int as
--declaracoes de variaveis do cabecalho--
declare @maximo int, @gre_data datetime, @gre_stat int, @eof_orem varchar(18), @cli_titu varchar(18), @eof_oeex varchar(18), 
	@pai_pdes varchar(2), @gre_dsim bit, @gre_dnao bit, @gre_fsim bit, @gre_fnao bit, @gre_asim bit, @gre_anao bit,
	@gre_dapr datetime, @gre_mtga numeric(38,6), @pai_moed varchar(2), @gre_ultd datetime, @apa_cnc8 varchar(22), 
	@apa_dcom varchar(50), @apa_dncb varchar(150), @gre_quan numeric(38,6), @ume_umed varchar(3), @gre_tole numeric(38,6),
	@tex_mesp varchar(8000), @tex_cesp varchar(8000), @gre_qext varchar(150)

--busca registo da tabela PRO_DAV
	select @gre_data = GRE_DATA, @gre_stat = GRE_STAT, @eof_orem = EOF_OREM, @cli_titu = CLI_TITU, @eof_oeex = EOF_OEEX, 
	@pai_pdes = PAI_PDES, @gre_dsim = GRE_DSIM, @gre_dnao = GRE_DNAO, @gre_fsim = GRE_FSIM, @gre_fnao = GRE_FNAO, 
	@gre_asim = GRE_ASIM, @gre_anao = GRE_ANAO, @gre_dapr = GRE_DAPR, @gre_mtga = GRE_MTGA, @pai_moed = PAI_MOED, 
	@gre_ultd = GRE_ULTD, @apa_cnc8 = APA_CNC8, @apa_dcom = APA_DCOM, @apa_dncb = APA_DNCB, @gre_quan = GRE_QUAN, 
	@ume_umed = UME_UMED, @gre_tole = GRE_TOLE, @tex_mesp = TEX_MESP, @tex_cesp = TEX_CESP, @gre_qext = GRE_QEXT
	from PRO_GREX
	where gre_codi = @cod AND gre_eano = @ano

--busca o max DAV_CODI
	SELECT @maximo = MAX(GRE_CODI) 
	FROM PRO_GREX 
	WHERE GRE_EANO = @ano
	
select @maximo = @maximo + 1


--insere registo do cabeçalho
	
insert into PRO_GREX(GRE_CODI, GRE_EANO, GRE_DATA, GRE_STAT, EOF_OREM, CLI_TITU, EOF_OEEX, 
	PAI_PDES, GRE_DSIM, GRE_DNAO, GRE_FSIM, GRE_FNAO, GRE_ASIM, GRE_ANAO, GRE_DAPR, 
	GRE_MTGA, PAI_MOED, GRE_ULTD, APA_CNC8, APA_DCOM, APA_DNCB, GRE_QUAN, UME_UMED, 
	GRE_TOLE, TEX_MESP, TEX_CESP, GRE_QEXT)
	values(@maximo, @ano, getdate(), 0, @eof_orem, @cli_titu, @eof_oeex, 
		@pai_pdes, @gre_dsim, @gre_dnao, @gre_fsim, @gre_fnao, @gre_asim, @gre_anao, @gre_dapr, 
		@gre_mtga, @pai_moed, @gre_ultd, @apa_cnc8, @apa_dcom, @apa_dncb, @gre_quan, @ume_umed, 
		@gre_tole, @tex_mesp, @tex_cesp, @gre_qext)



ALTER AUTHORIZATION ON [SP_duplicaAgrex] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaAgrex] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaAgrim]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_duplicaAgrim] @cod int, @ano int AS
BEGIN
--declaracoes de variaveis do cabecalho
	declare @maximo int, @gri_data datetime, @gri_stat int, @eof_orem varchar(18), @cli_titu varchar(18), @eof_oeex varchar(18), @pai_ppro varchar(2), 
		@gri_psim bit, @gri_pnao bit, @pai_pori varchar(2), @gri_osim bit, @gri_onao bit, @gri_dapr datetime, @gri_mtga numeric(38,6), @pai_moed varchar(2), 
		@gri_ultd datetime, @apa_cnc8 varchar(22), @apa_dcom varchar(300), @apa_dncb varchar(300), @gri_quan numeric(38,6), @ume_umed varchar(3), 
		@gri_tole numeric(38,6), @tex_mesp varchar(8000), @tex_cesp varchar(8000), @gri_qext varchar(150)
--busca registo da tabela PRO_DAV
	select @gri_data = GRI_DATA, @gri_stat = GRI_STAT, @eof_orem = EOF_OREM, @cli_titu = CLI_TITU, @eof_oeex = EOF_OEEX, @pai_ppro = PAI_PPRO, 
		@gri_psim = GRI_PSIM, @gri_pnao = GRI_PNAO, @pai_pori = PAI_PORI, @gri_osim = GRI_OSIM, @gri_onao = GRI_ONAO, @gri_dapr = GRI_DAPR, 
		@gri_mtga = GRI_MTGA, @pai_moed = PAI_MOED, @gri_ultd = GRI_ULTD, @apa_cnc8 = APA_CNC8, @apa_dcom = APA_DCOM, @apa_dncb = APA_DNCB, 
		@gri_quan = GRI_QUAN, @ume_umed = UME_UMED, @gri_tole = GRI_TOLE, @tex_mesp = TEX_MESP, @tex_cesp = TEX_CESP, @gri_qext = GRI_QEXT
	from PRO_GRIM
	where gri_codi = @cod AND gri_eano = @ano
--busca o max DAV_CODI
	SELECT @maximo = MAX(GRI_CODI) 
	FROM PRO_GRIM
	WHERE GRI_EANO = @ano	
	select @maximo = @maximo + 1
--insere registo do cabeçalho
	insert into PRO_GRIM(GRI_CODI, GRI_EANO, GRI_DATA, GRI_STAT, EOF_OREM, CLI_TITU, EOF_OEEX, PAI_PPRO, GRI_PSIM, GRI_PNAO, PAI_PORI, GRI_OSIM, GRI_ONAO, 
		GRI_DAPR, GRI_MTGA, PAI_MOED, GRI_ULTD, APA_CNC8, APA_DCOM, APA_DNCB, GRI_QUAN, UME_UMED, GRI_TOLE, TEX_MESP, TEX_CESP, GRI_QEXT)
	values(@maximo, @ano, getdate(), 0, @eof_orem, @cli_titu , @eof_oeex, @pai_ppro, @gri_psim, @gri_pnao, @pai_pori, @gri_osim, @gri_onao, @gri_dapr, 
		@gri_mtga, @pai_moed, @gri_ultd, @apa_cnc8, @apa_dcom, @apa_dncb, @gri_quan, @ume_umed, @gri_tole, @tex_mesp, @tex_cesp, @gri_qext)
END

ALTER AUTHORIZATION ON [SP_duplicaAgrim] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaAgrim] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaConta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_duplicaConta] @iden int, @ano int, @tdoc varchar(4), @natureza varchar(3), @util varchar(30), @AnoDest int, @TipoDocDest varchar(4), @SemDetalhes bit = 0 AS
BEGIN
-- declaracao de variaveis
	DECLARE @DataAtual datetime, @codigo int, @TotalInerentesIsentoIVA numeric(38, 6), @i int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem valor do selo
	IF @SemDetalhes = 0
		SET @TotalInerentesIsentoIVA = ISNULL((SELECT SUM(ISNULL(ICD_VTOT, 0)) FROM FAC_ICDO WITH(NOLOCK) WHERE CDO_EANO = @ano and CDO_TDOC = @tdoc and CDO_IDEN = @iden AND ICD_ISEN = 1), 0)
	ELSE
		SET @TotalInerentesIsentoIVA = 0
-- busca iden para nova conta
	SELECT @codigo = ISNULL(MAX(CDO_IDEN), 0) + 1
	FROM FAC_CDOC
	WHERE CDO_TDOC = @TipoDocDest AND CDO_EANO = @AnoDest
-- copia cabeçalho 
	INSERT INTO FAC_CDOC(CDO_EANO, CDO_TDOC, CDO_IDEN, NDE_CODI, CDO_NPRO, CDO_TCNT, DEC_CODI, ALF_CODI, CDO_NORD, CDO_DTAC, CDO_STAT, CDO_DTAB, CDO_DTIN, CDO_DTFI, CLI_DESP, CLI_CCOR, CLI_ENDC, 
		DIN_HONO, CDO_AGRA, CDO_DESA, CDO_FORH, CDO_TTDC, CDO_TTIN, CDO_TTHO, CDO_TTRF, CDO_BIVA, CDO_IVA, CDO_TXIV, CDO_RTFO, CDO_TTPR, CDO_ISIV, CDO_QUNT, CDO_QUAL, CDO_DESC, CDO_PBRT, 
		CDO_PLIQ, CDO_VADU, CDO_MARC, CDO_NFIA, CDO_CTMR, CDO_VREF, MTR_CODI, CDO_MTRA, PAI_MTRA, CDO_DTEN, CDO_DTSA, CDO_PROC, CDO_UCRI, CDO_DTCR, CDO_UALT, CDO_DTAL, CDO_DEST, CDO_ARQU, 
		CDO_TONE, CDO_OPER, CDO_NREC, CDO_DTRE, CDO_RGPR, CDO_OBSR, CDO_IN01, CDO_IN02, CDO_IN03, CDO_IN04, CDO_VI01, CDO_VI02, CDO_VI03, CDO_VI04, CDO_REGL, CDO_DTRL, CDO_MPAG, CDO_CTIP, 
		CDO_ORID, CDO_ORNR, CDO_ORDT, CDO_CPRT, CDO_CNOM, CDO_CMOR, CDO_CLOC, CDO_CCPO, CDO_CLPO, CDO_CNIF, CDO_CPAI, CDO_CEAN, IIV_CODI, FOR_CODI, FOR_NOME, CDO_IVAA, CCO_CODI, CDO_CPAG, 
		CDO_PANO, CDO_IMEX, id_declaracaoDAR)
	SELECT @AnoDest, @TipoDocDest, @codigo, @natureza, c.CDO_NPRO, c.CDO_TCNT, c.DEC_CODI, c.ALF_CODI, c.CDO_NORD, c.CDO_DTAC, 0, c.CDO_DTAB, c.CDO_DTIN, c.CDO_DTFI, c.CLI_DESP, c.CLI_CCOR, c.CLI_ENDC, 
		c.DIN_HONO, c.CDO_AGRA, c.CDO_DESA, n.NDE_FORM, 
		(CASE @SemDetalhes WHEN 1 THEN 0 ELSE c.CDO_TTDC END), (CASE @SemDetalhes WHEN 1 THEN 0 ELSE c.CDO_TTIN END), c.CDO_TTHO, 
		(CASE @SemDetalhes WHEN 1 THEN ROUND(ISNULL(c.CDO_TTHO, 0) * (ISNULL(c.CDO_RTFO, 0) / 100), 2) ELSE c.CDO_TTRF END), c.CDO_BIVA, 
		ROUND((CASE @SemDetalhes WHEN 1 THEN c.CDO_TTHO ELSE (c.CDO_TTHO + c.CDO_TTIN - @TotalInerentesIsentoIVA) END) * (n.NDE_TIVA / 100), 2), n.NDE_TIVA, c.CDO_RTFO, 
		(CASE @SemDetalhes WHEN 1 THEN (c.CDO_TTHO + ROUND(c.CDO_TTHO  * (n.NDE_TIVA / 100), 2)) ELSE (c.CDO_TTDC + c.CDO_TTIN + c.CDO_TTHO + ROUND((c.CDO_TTHO + c.CDO_TTIN - @TotalInerentesIsentoIVA) * (n.NDE_TIVA / 100), 2)) END), 
		(SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = n.IIV_CODI), c.CDO_QUNT, c.CDO_QUAL, c.CDO_DESC, c.CDO_PBRT, 
		c.CDO_PLIQ, c.CDO_VADU, c.CDO_MARC, c.CDO_NFIA, c.CDO_CTMR, c.CDO_VREF, c.MTR_CODI, c.CDO_MTRA, c.PAI_MTRA, c.CDO_DTEN, c.CDO_DTSA, c.CDO_PROC, @util, @DataAtual, @util, @DataAtual, c.CDO_DEST, c.CDO_ARQU, 
		c.CDO_TONE, c.CDO_OPER, c.CDO_NREC, c.CDO_DTRE, c.CDO_RGPR, c.CDO_OBSR, c.CDO_IN01, c.CDO_IN02, c.CDO_IN03, c.CDO_IN04, c.CDO_VI01, c.CDO_VI02, c.CDO_VI03, c.CDO_VI04, c.CDO_REGL, c.CDO_DTRL, c.CDO_MPAG, c.CDO_CTIP, 
		c.CDO_IDEN, c.CDO_CNUM, c.CDO_DTEM, c.CDO_CPRT, c.CDO_CNOM, c.CDO_CMOR, c.CDO_CLOC, c.CDO_CCPO, c.CDO_CLPO, c.CDO_CNIF, c.CDO_CPAI, c.CDO_CEAN, n.IIV_CODI, c.FOR_CODI, c.FOR_NOME, c.CDO_IVAA, n.CCO_CODI, c.CDO_CPAG, 
		c.CDO_PANO, c.CDO_IMEX, c.id_declaracaoDAR
	FROM FAC_CDOC AS c WITH(NOLOCK) 
		INNER JOIN TAB_NDES AS n WITH(NOLOCK) ON n.NDE_CODI = @natureza
	WHERE c.CDO_EANO = @ano AND c.CDO_TDOC = @tdoc AND c.CDO_IDEN = @iden
-- processa a duplicação dos detalhes
	IF @SemDetalhes = 0
	BEGIN
-- copia despesas documentadas 
		INSERT INTO FAC_DCDO(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DDO_CODI, DCD_DESC, DCD_VTOT, CCO_CODI)
		SELECT @AnoDest, @TipoDocDest, @codigo, DCD_LINH, DDO_CODI, DCD_DESC, DCD_VTOT, CCO_CODI
		FROM FAC_DCDO WITH(NOLOCK) 
		WHERE CDO_EANO = @ano AND CDO_TDOC = @tdoc AND CDO_IDEN = @iden
-- copia detalhe das despesas documentadas 
		INSERT INTO FAC_DDCD(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DDC_ADIC, DDC_DORI, DDC_DATA, DDC_IVA, DDC_TIVA, DDC_VALO)
		SELECT @AnoDest, @TipoDocDest, @codigo, DCD_LINH, DDC_ADIC, DDC_DORI, DDC_DATA, DDC_IVA, DDC_TIVA, DDC_VALO
		FROM FAC_DDCD WITH(NOLOCK) 
		WHERE CDO_EANO = @ano AND CDO_TDOC = @tdoc AND CDO_IDEN = @iden
-- copia despesas inerentes 
		INSERT INTO FAC_ICDO(CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, DIN_CODI, ICD_DESC, ICD_VTOT, CCO_CODI, ICD_ISEN, IIV_CODI, IIV_MENC)
		SELECT @AnoDest, @TipoDocDest, @codigo, ICD_LINH, DIN_CODI, ICD_DESC, ICD_VTOT, CCO_CODI, ICD_ISEN, IIV_CODI, IIV_MENC
		FROM FAC_ICDO WITH(NOLOCK) 
		WHERE CDO_EANO = @ano AND CDO_TDOC = @tdoc AND CDO_IDEN = @iden
-- copia detalhe das despesas inerentes 
		INSERT INTO FAC_DICD(CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, DIC_ADIC, DIC_DORI, DIC_DATA, DIC_IVA, DIC_TIVA, DIC_VALO)
		SELECT @AnoDest, @TipoDocDest, @codigo, ICD_LINH, DIC_ADIC, DIC_DORI, DIC_DATA, DIC_IVA, DIC_TIVA, DIC_VALO
		FROM FAC_DICD WITH(NOLOCK) 
		WHERE CDO_EANO = @ano AND CDO_TDOC = @tdoc AND CDO_IDEN = @iden
	END
	ELSE
	BEGIN
-- insere as linhas para as despesas documentadas 
		SET @i = 1
		WHILE (@i < 10)
		BEGIN
			INSERT INTO FAC_DCDO(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DCD_VTOT) 
			VALUES(@AnoDest, @TipoDocDest, @codigo, @i, 0)			
			SET @i = @i + 1
		END
-- insere as linhas para as despesas inerentes
		SELECT @i = 1
		WHILE (@i < 13)
		BEGIN
			INSERT INTO FAC_ICDO(CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, ICD_VTOT) 
			VALUES(@AnoDest, @TipoDocDest, @codigo, @i, 0)
			SET @i = @i + 1
		END
	END
END

ALTER AUTHORIZATION ON [SP_duplicaConta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaConta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaDAV]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_duplicaDAV] @cod int, @ano int AS
BEGIN
-- declaracoes de variaveis
declare @maximo int
set dateformat dmy	
-- busca o max DAV_CODI
select @maximo = isnull(max(DAV_CODI), 0) + 1
from PRO_DAVE 
where DAV_EANO = @ano
-- insere registo do cabeçalho
insert into PRO_DAVE(DAV_CODI, DAV_EANO, DAV_DATA, DAV_STAT, ALF_CODI, CLI_SUJP, DAV_REGI, DAV_CDAV, DAV_CPL, DAV_VUSN, DAV_DEST, DAV_RGIA,
	HTE_ACOD, CAT_ACAT, TVE_ATIP, MAR_AMAR, DAV_AMOD, DAV_AMBT, DAV_ATAR, TCO_ACMB, COR_ACOR, TCX_ACXA, DAV_ANQD, DAV_ANMT, DAV_ANLG, 
	DAV_ACLD, DAV_ACO2, DAV_ANKM, DAV_AEMT, DAV_ACCX, DAV_AACX, DAV_AATP, PAI_BPRV, DAV_BD1M, DAV_BMTA, DAV_BSBC, DAV_BDFV, DAV_BDTR, 
	DAV_CDUN, DAV_CDDU,ALF_CALD , DEC_DCOD, DEC_DNOM, DEC_DMOR, DEC_DNIF, DEC_DTIP, DEC_DQLD, DAV_DSBC, CLI_ECOD, CLI_EECV, CLI_EDNA, 
	CLI_ENID, CLI_ESBC, CLI_EMOR, CLI_ECPS, CLI_ELPS, CLI_ENIF, CLI_ETIP, EJU_FRES, EJU_FDLE, EJU_FCNV, CLI_FNOM, CLI_FEEC, CLI_FDNA, 
	CLI_FNID, CLI_FSBC, CLI_FMOR, CLI_FCPS, CLI_FLPS, CLI_FNIF, CLI_FTIP, TIA_GCOD, TIA_GTAX, DAV_GPAB, DAV_GPRD, DAV_GMTR, DAV_GTIA, 
	DAV_HBTR, DAV_HMIA, DAV_HTTL, DAV_HTXI, DAV_HTLI, DAV_HISE, DAV_HOPT, DAV_IMPA, DAV_IGAN, DAV_IGNU, DAV_IFLG, CSE_JDGV, DAV_PNOM, 
	DAV_PMOR, DAV_PLOC, DAV_PCPO, DAV_PLPO, DAV_PNIF, PAI_PLIV, CLI_ENOM, DAV_EMPC, DAV_PVPR, DAV_ISVR, DAV_VAVL, DAV_LCAV)
select @maximo, DAV_EANO, convert(datetime, convert(varchar(10), getdate(), 105), 105), 0, ALF_CODI, CLI_SUJP, DAV_REGI, DAV_CDAV, DAV_CPL, 
	DAV_VUSN, DAV_DEST, DAV_RGIA, HTE_ACOD, CAT_ACAT, TVE_ATIP, MAR_AMAR, DAV_AMOD, DAV_AMBT, DAV_ATAR, TCO_ACMB, COR_ACOR, TCX_ACXA, 
	DAV_ANQD, DAV_ANMT, DAV_ANLG, DAV_ACLD, DAV_ACO2, DAV_ANKM, DAV_AEMT, DAV_ACCX, DAV_AACX, DAV_AATP, PAI_BPRV, DAV_BD1M, DAV_BMTA, 
	DAV_BSBC, DAV_BDFV, DAV_BDTR, DAV_CDUN, DAV_CDDU, ALF_CALD, DEC_DCOD, DEC_DNOM, DEC_DMOR, DEC_DNIF, DEC_DTIP, DEC_DQLD, DAV_DSBC, 
	CLI_ECOD, CLI_EECV, CLI_EDNA, CLI_ENID, CLI_ESBC, CLI_EMOR, CLI_ECPS, CLI_ELPS, CLI_ENIF, CLI_ETIP, EJU_FRES, EJU_FDLE, EJU_FCNV, 
	CLI_FNOM, CLI_FEEC, CLI_FDNA, CLI_FNID, CLI_FSBC, CLI_FMOR, CLI_FCPS, CLI_FLPS, CLI_FNIF, CLI_FTIP, TIA_GCOD, TIA_GTAX, DAV_GPAB, 
	DAV_GPRD, DAV_GMTR, DAV_GTIA, DAV_HBTR, DAV_HMIA, DAV_HTTL, DAV_HTXI, DAV_HTLI, DAV_HISE, DAV_HOPT, DAV_IMPA, DAV_IGAN, DAV_IGNU, 
	DAV_IFLG, CSE_JDGV, DAV_PNOM, DAV_PMOR, DAV_PLOC, DAV_PCPO, DAV_PLPO, DAV_PNIF, PAI_PLIV, CLI_ENOM, DAV_EMPC, DAV_PVPR, DAV_ISVR, 
	DAV_VAVL, DAV_LCAV
from PRO_DAVE
where DAV_CODI = @cod and DAV_EANO = @ano
END

ALTER AUTHORIZATION ON [SP_duplicaDAV] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaDAV] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaDocExp]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_duplicaDocExp] @cod int, @ano int AS
BEGIN
-- declaracoes de variaveis
declare @maximo int
set dateformat dmy
-- busca o max DEX_CODI
select @maximo = isnull(max(DEX_CODI), 0) + 1
from PRO_DEXP
where DEX_EANO = @ano
-- insere registo do cabeçalho
insert into PRO_DEXP(DEX_CODI, DEX_EANO, DEX_DATA, DEX_STAT, ALF_CODI, CLI_EXPE, DEX_CAPL, DEX_CNOM, DEX_CMOR, DEX_CCPO, DEX_CLPO, 
	DEX_CNIF, DEX_CTIP, DEX_NFAC, DEX_DTFC, FOR_DEST, DEX_DNOM, DEX_DMOR, DEX_DPAI, TVE_CODI, MAR_CODI, DEX_MODE, HTE_CODI, DEX_NQDR, 
	DEX_NMTR, DEX_CLDD,	DEX_MATD, DEX_DTCL, DEX_NDVL, DEX_LANO, DEX_NMDU, DEX_UANO, DEX_MATE, DEX_DTVM, DEX_DADC, DEX_ESCE, DEX_ESSD, 
	DEX_DTSD, DEX_DAPL, DEX_PCNO, DEX_PCMO, DEX_PCLO, DEX_PCCP, DEX_PCLP, DEX_PCNF, PAI_PCPL, DEX_PDNO, DEX_PDMO, DEX_PDLO, DEX_PDCP, 
	DEX_PDLP, DEX_PDNF,	PAI_PDPL)
select @maximo, DEX_EANO, convert(datetime, convert(varchar(10), getdate(), 105), 105), 0, ALF_CODI, CLI_EXPE, DEX_CAPL, DEX_CNOM, 
	DEX_CMOR, DEX_CCPO, DEX_CLPO, DEX_CNIF, DEX_CTIP, DEX_NFAC, DEX_DTFC, FOR_DEST, DEX_DNOM, DEX_DMOR, DEX_DPAI, TVE_CODI, MAR_CODI, 
	DEX_MODE, HTE_CODI, DEX_NQDR, DEX_NMTR, DEX_CLDD, DEX_MATD, DEX_DTCL, DEX_NDVL, DEX_LANO, DEX_NMDU, DEX_UANO, DEX_MATE, DEX_DTVM, 
	DEX_DADC, DEX_ESCE, DEX_ESSD, DEX_DTSD, DEX_DAPL, DEX_PCNO, DEX_PCMO, DEX_PCLO, DEX_PCCP, DEX_PCLP, DEX_PCNF, PAI_PCPL, DEX_PDNO, 
	DEX_PDMO, DEX_PDLO, DEX_PDCP, DEX_PDLP, DEX_PDNF, PAI_PDPL
from PRO_DEXP
where DEX_CODI = @cod and DEX_EANO = @ano
END

ALTER AUTHORIZATION ON [SP_duplicaDocExp] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaDocExp] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaDocVenda]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_duplicaDocVenda] @AnoDoc int, @TipoDoc varchar(4), @NumDoc int, @Utilizador varchar(30) AS
BEGIN
-- declaracao de variaveis
	declare @NumDocDest int, @SerieDest varchar(20)
-- busca novo numero para documento 
	select @NumDocDest = ISNULL(NUM_NUME, 0) + 1, @SerieDest = ISNULL(NULLIF(NUM_SERI, ''), '1')
	from TAB_NUMD
	where TDO_DOCU = @TipoDoc and NUM_EANO = @AnoDoc and NUM_TDOC = 1
-- insere cabeçalho do documento 
	insert into FAC_DVEN(DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_CTXT, DVE_DATA, CLI_CODI, DVE_CNOM, DVE_CMOR, DVE_CLOC, DVE_CCPO, DVE_CLPO, DVE_CNIF, PAI_CLIV, NDE_CODI, DVE_NPRO, 
		DVE_OBSV, DVE_UTIC, DVE_DTCR, DVE_UTIA, DVE_DTAL, DVE_IN01, DVE_IN02, DVE_IN03, DVE_IN04, DVE_VI01, DVE_VI02, DVE_VI03, DVE_VI04, DVE_VLIQ, DVE_VIVA, DVE_VTOT, DVE_STAT, 
		DVE_DIPS, DVE_DFPS, DVE_NDOR, DVE_CPRT, DVE_SERI)
	select DVE_TDOC, @NumDocDest, DVE_EANO, DVE_CTXT, getdate(), CLI_CODI, DVE_CNOM, DVE_CMOR, DVE_CLOC, DVE_CCPO, DVE_CLPO, DVE_CNIF, PAI_CLIV, NDE_CODI, DVE_NPRO, DVE_OBSV, 
		@Utilizador, getdate(), @Utilizador, getdate(), DVE_IN01, DVE_IN02, DVE_IN03, DVE_IN04, DVE_VI01, DVE_VI02, DVE_VI03, DVE_VI04, DVE_VLIQ, DVE_VIVA, DVE_VTOT, 0, getdate(), 
		getdate(), @NumDoc, DVE_CPRT, @SerieDest
	from FAC_DVEN
	where DVE_TDOC = @TipoDoc and DVE_NDOC = @NumDoc and DVE_EANO = @AnoDoc
-- actualiza numerador do documento 
	update TAB_NUMD SET NUM_NUME = @NumDocDest, NUM_DATA = getdate()
	where TDO_DOCU = @TipoDoc and NUM_EANO = @AnoDoc and NUM_TDOC = 1
-- insere linhas de detalhe do documento 
	insert into FAC_DVDT(DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_CTXT, DVD_FORN, DVD_LHON, CCO_CODI)
	select DVE_TDOC, @NumDocDest, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_CTXT, DVD_FORN, DVD_LHON, CCO_CODI
	from FAC_DVDT
	where DVE_TDOC = @TipoDoc and DVE_NDOC = @NumDoc and DVE_EANO = @AnoDoc
END

ALTER AUTHORIZATION ON [SP_duplicaDocVenda] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaDocVenda] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaDocVig]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
create proc [SP_duplicaDocVig] @cod int, @ano int as
--declaracoes de variaveis do cabecalho--
declare @maximo int, @dvi_data datetime, @dvi_stat int, @dvi_nemi varchar(20), @dvi_lodt varchar(20),
	@eof_autc varchar(18), @cli_dest varchar(18), @dvi_pval varchar(30), @pai_ppro varchar(2), 
	@pai_pdes varchar(2), @apa_cnc8 varchar(22), @apa_dmer varchar(50), @dvi_quan varchar(40),
	@dvi_vcif varchar(30), @dec_codi varchar(6), @tex_mesp varchar(8000)

--busca registo da tabela PRO_DAV
	select @dvi_data = DVI_DATA, @dvi_stat = DVI_STAT, @dvi_nemi = DVI_NEMI, @dvi_lodt = DVI_LODT,
	@eof_autc = EOF_AUTC, @cli_dest = CLI_DEST, @dvi_pval = DVI_PVAL, @pai_ppro = PAI_PPRO, 
	@pai_pdes = PAI_PDES, @apa_cnc8 = APA_CNC8, @apa_dmer = APA_DMER, @dvi_quan = DVI_QUAN,
	@dvi_vcif = DVI_VCIF, @dec_codi = DEC_CODI, @tex_mesp = TEX_MESP
	from PRO_DVIG
	where dvi_codi = @cod AND dvi_eano = @ano

--busca o max DAV_CODI
	SELECT @maximo = MAX(DVI_CODI) 
	FROM PRO_DVIG 
	WHERE DVI_EANO = @ano
	
select @maximo = @maximo + 1


--insere registo do cabeçalho
	
insert into PRO_DVIG(DVI_CODI, DVI_EANO, DVI_DATA, DVI_STAT, DVI_NEMI, DVI_LODT, EOF_AUTC, CLI_DEST, DVI_PVAL, PAI_PPRO, 
	PAI_PDES, APA_CNC8, APA_DMER, DVI_QUAN,	DVI_VCIF, DEC_CODI, TEX_MESP)
	values(@maximo, @ano, getdate(), 0, @dvi_nemi, @dvi_lodt, @eof_autc, @cli_dest, @dvi_pval, @pai_ppro, 
	@pai_pdes, @apa_cnc8, @apa_dmer, @dvi_quan, @dvi_vcif, @dec_codi, @tex_mesp)



ALTER AUTHORIZATION ON [SP_duplicaDocVig] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaDocVig] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaDUExportacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_duplicaDUExportacao] @iden int, @ano int, @oper varchar(6), @util varchar(30) AS
BEGIN
	SET DATEFORMAT DMY
	DECLARE @DataAtual datetime, @codigo int, @chaveVelha int, @chaveNova int, @linha int, @nifCedula varchar(18), @refLocal varchar(22), @tamanho int, @AnoNovoProc int, @Numero int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- busca nº. do documento exportação / XML -------------------------------------------------
	SELECT @codigo = ISNULL(DEC_NPRO, 0), 
		@nifCedula = (CASE DEC_NIF WHEN NULL THEN 'PT' + DEC_CEDU ELSE 'PT' + DEC_NIF END), 
		@Numero = (CASE DEC_XNRA WHEN 1 THEN ISNULL(DEC_NPRO, 0) ELSE 0 END)
	FROM TAB_DECL
	WHERE DEC_CODI = @oper 
-- obtem Ano para nova declaração em função da data atual
	IF (@ano < YEAR(@DataAtual)) and (EXISTS(SELECT EMP_CODI FROM GIDWIN.dbo.FAP_EANO WHERE EMP_CODI = DB_NAME() and EAN_ANO = YEAR(@DataAtual)))		
		SET @AnoNovoProc = YEAR(@DataAtual)
	ELSE
		SET @AnoNovoProc = @ano		
	-- trata referencia local ------------------------------------------------------------------
	SELECT @tamanho = 22 - len(@AnoNovoProc) - len(@nifCedula) - len(@codigo) 
	IF @tamanho < 0 
	BEGIN
		SELECT @TAMANHO = 0 
	END
	SELECT @refLocal = cast(@AnoNovoProc as varchar(4)) + @nifCedula + replicate('0', @tamanho) + cast(@codigo as varchar(22))

	UPDATE TAB_DECL SET DEC_NPRO = @codigo + 1
	WHERE DEC_CODI = @oper 
	-- copia cabeçalho -------------------------------------------------------------------------
	INSERT INTO PRO_EXML (EXM_EANO, EXM_CODI, DEC_CODI, EXM_CODO, EXM_TOPE, NDE_CODI, NDE_NOME, DEC_NOME, EXM_DATA, EXM_NRIN, EXM_NRLO, EXM_STAT, EAD_CODA, EAD_NOMA, 
		TDE_COD1, TDE_NOM1, CLI_COD2, CLI_NOM2, CLI_MOR2, CLI_LOC2, CLI_CPO2, CLI_LPO2, CLI_NIF2, CLI_PAI2, EXM_TP2A, EXM_TI2B, EXM_TAD5, EXM_TVL6, FOR_COD8, FOR_NOM8, 
		FOR_MOR8, FOR_LOC8, FOR_CPO8, FOR_LPO8, FOR_NIF8, FOR_PAI8, EXM_IROR, DEC_CO14, DEC_NO14, EXM_TP14, EXM_P15A, EXM_P17A, EXM_C17C, EAD_C17C, EAD_N17C, EXM_D17C, 
		EXM_CT19, MTR_CO18, MTR_NO18, EXM_TP18, EXM_MT18, MTR_C18A, MTR_N18A, EXM_M18A, EXM_T18B, EXM_I18B, EXM_P18C, EXM_I18C, MTR_CO21, MTR_NO21, EXM_TP21, EXM_MT21, 
		PAI_CO21, PAI_NO21, MTR_CO25, MTR_CO26, MTR_C26A, CEN_CO20, CEN_NO20, EXM_FR20, EXM_LG20, NTR_CO24, NTR_NO24, PAI_CO22, PAI_MO22, EXM_MT22, EXM_UFOB, EXM_VFOB, 
		EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, EXM_TREM, EXM_VEUR, EXM_VATT, EAD_CO29, EAD_NO29, EAD_C29A, EAD_N29A, EXM_DTIN, EXM_HRIN, EXM_DTFI, EXM_HRFI, 
		EAD_CO30, EAD_NO30, LEM_CO30, LEM_NO30, LME_CO30, LME_NO30, EXM_MR30, EXM_CP30, EXM_LP30, LEM_C30A, LEM_N30A, EXM_NC48, EXM_AC48, EXM_TC48, ARM_CO49, ARM_NO49, 
		TAR_CO49, TAR_DE49, EXM_ESTM, AGE_CO50, AGE_NO50, EXM_Q30C, EXM_UCRI, EXM_DTCR, EXM_UALT, EXM_DTAL, EXM_NRII, EXM_TPRO, EXM_INCE, EXM_NCMR, EXM_DTMP)
	SELECT  @AnoNovoProc, @codigo, @oper, EXM_CODO, EXM_TOPE, NDE_CODI, NDE_NOME, DEC_NOME, CAST(CONVERT(varchar(10), @DataAtual, 105) as datetime), @codigo, @refLocal, 0, 
		EAD_CODA, EAD_NOMA, TDE_COD1, TDE_NOM1, CLI_COD2, CLI_NOM2, CLI_MOR2, CLI_LOC2, CLI_CPO2, CLI_LPO2, CLI_NIF2, CLI_PAI2, EXM_TP2A, EXM_TI2B, EXM_TAD5, EXM_TVL6, 
		FOR_COD8, FOR_NOM8, FOR_MOR8, FOR_LOC8, FOR_CPO8, FOR_LPO8, FOR_NIF8, FOR_PAI8, EXM_IROR, DEC_CO14, DEC_NO14, EXM_TP14, EXM_P15A, EXM_P17A, EXM_C17C, EAD_C17C, 
		EAD_N17C, EXM_D17C, EXM_CT19, MTR_CO18, MTR_NO18, EXM_TP18, EXM_MT18, MTR_C18A, MTR_N18A, EXM_M18A, EXM_T18B, EXM_I18B, EXM_P18C, EXM_I18C, MTR_CO21, MTR_NO21, 
		EXM_TP21, EXM_MT21, PAI_CO21, PAI_NO21, MTR_CO25, MTR_CO26, MTR_C26A, CEN_CO20, CEN_NO20, EXM_FR20, EXM_LG20, NTR_CO24, NTR_NO24, PAI_CO22, PAI_MO22, EXM_MT22, 
		EXM_UFOB, EXM_VFOB, EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, EXM_TREM, EXM_VEUR, EXM_VATT, EAD_CO29, EAD_NO29, EAD_C29A, EAD_N29A, EXM_DTIN, EXM_HRIN, 
		EXM_DTFI, EXM_HRFI, EAD_CO30, EAD_NO30, LEM_CO30, LEM_NO30, LME_CO30, LME_NO30, EXM_MR30, EXM_CP30, EXM_LP30, LEM_C30A, LEM_N30A, EXM_NC48, EXM_AC48, EXM_TC48, 
		ARM_CO49, ARM_NO49, TAR_CO49, TAR_DE49, EXM_ESTM, AGE_CO50, AGE_NO50, EXM_Q30C, @util, @DataAtual, @util, @DataAtual, @Numero, EXM_TPRO, EXM_INCE, EXM_NCMR, EXM_DTMP
	FROM PRO_EXML
	WHERE EXM_EANO = @ano AND DEC_CODI = @oper AND EXM_CODI = @iden
	-- copia certificados comprovativos de exportacao ------------------------------------------
	INSERT INTO PRO_EXCE (EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_FNIF, EXC_NFAC, EXC_DFAC, EXC_QNTD, UME_CODI, UME_NOME, EXC_DCOM, EXC_PLIQ, EXC_PBRT, EXC_VALO)
	SELECT @AnoNovoProc, @codigo, @oper, EXC_LINH, EXC_FNIF, EXC_NFAC, EXC_DFAC, EXC_QNTD, UME_CODI, UME_NOME, EXC_DCOM, EXC_PLIQ, EXC_PBRT, EXC_VALO
	FROM PRO_EXCE
	WHERE EXM_EANO = @ano AND EXM_COPE = @oper AND EXM_CODI = @iden
	-- copia detalhes de certificados comprovativos de exportacao 
	INSERT INTO PRO_EXCD (EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXD_QTDE, TEM_CODI, TEM_NOME, EXD_PART, EXD_REST)
	SELECT @AnoNovoProc, @codigo, @oper, EXC_LINH, EXD_QTDE, TEM_CODI, TEM_NOME, EXD_PART, EXD_REST
	FROM PRO_EXCD
	WHERE EXM_EANO = @ano AND EXM_COPE = @oper AND EXM_CODI = @iden
	-- copia pedidos anexos a declaracao -------------------------------------------------------
	INSERT INTO PRO_EXPA (EXM_EANO, EXM_CODI, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC)
	SELECT @AnoNovoProc, @codigo, @oper, EXP_LINH, TXM_CODI, TXM_DESC
	FROM PRO_EXPA
	WHERE EXM_EANO = @ano AND EXM_COPE = @oper AND EXM_CODI = @iden
	-- copia contentores -----------------------------------------------------------------------
	INSERT INTO PRO_EXCT (EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_CONT)
	SELECT @AnoNovoProc, @codigo, @oper, EXC_LINH, EXC_CONT
	FROM PRO_EXCT
	WHERE EXM_EANO = @ano AND EXM_COPE = @oper AND EXM_CODI = @iden
	-- copia países itinerario -----------------------------------------------------------------
	INSERT INTO PRO_EXPI (EXM_EANO, EXM_CODI, EXM_COPE, PAI_CODI, PAI_NOME)
	SELECT @AnoNovoProc, @codigo, @oper, PAI_CODI, PAI_NOME
	FROM PRO_EXPI
	WHERE EXM_EANO = @ano AND EXM_COPE = @oper AND EXM_CODI = @iden
	-- copia detalhes das adicoes --------------------------------------------------------------
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EXA_CHVE, EXA_LINH 
		FROM PRO_EXAD
		WHERE EXM_EANO = @ano AND EXM_COPE = @oper AND EXM_CODI = @iden
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @chaveVelha, @linha
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- copia adicoes -------------------------------------------------------------------
		INSERT INTO PRO_EXAD (EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CO33, APA_CP33, APA_DESG, PAI_CODI, PAI_NOME, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU,
			USU_CODI, USU_SIGL, EXA_VALO, EXA_VFRE, EXA_VSEG, EXA_VEST, EXA_PRAZ, EXA_DSOP, GPA_CODI, GPA_DESC, EXA_DTLM, EXA_IVEI, EXA_IRES, EXA_ANXC, EXA_ANXD, 
			EXA_CPMV, TDE_REGI, EXA_ATAR)
		SELECT @AnoNovoProc, @codigo, @oper, EXA_LINH, APA_CO33, APA_CP33, APA_DESG, PAI_CODI, PAI_NOME, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, USU_CODI, USU_SIGL, 
			EXA_VALO, EXA_VFRE, EXA_VSEG, EXA_VEST, EXA_PRAZ, EXA_DSOP, GPA_CODI, GPA_DESC, EXA_DTLM, EXA_IVEI, EXA_IRES, EXA_ANXC, EXA_ANXD, EXA_CPMV, TDE_REGI,
			EXA_ATAR
		FROM PRO_EXAD
		WHERE EXM_EANO = @ano AND EXM_COPE = @oper AND EXM_CODI = @iden AND EXA_CHVE = @chaveVelha
		-- busca chave da nova adicao ------------------------------------------------------	
		SELECT @chaveNova = EXA_CHVE
		FROM PRO_EXAD
		WHERE EXM_EANO = @AnoNovoProc AND EXM_COPE = @oper AND EXM_CODI = @codigo AND EXA_LINH = @linha

		------------------------------------------------------------------------------------
		-- detalhes ------------------------------------------------------------------------
		------------------------------------------------------------------------------------

		-- copia base de tributacao --------------------------------------------------------
		INSERT INTO PRO_EXBT (EXA_CHVE, EXB_BTRI, UME_CODI, UME_NOME, EXB_QUAL)
		SELECT @chaveNova, EXB_BTRI, UME_CODI, UME_NOME, EXB_QUAL
		FROM PRO_EXBT
		WHERE EXA_CHVE = @chaveVelha
		-- copia pedido simplificado -------------------------------------------------------
		INSERT INTO PRO_EXPS (EXA_CHVE, MIA_CODI, MIA_DESC, MIA_OBRI)
		SELECT @chaveNova, MIA_CODI, MIA_DESC, MIA_OBRI
		FROM PRO_EXPS
		WHERE EXA_CHVE = @chaveVelha
		-- copia entrada em entreposto aduaneiro -------------------------------------------
		INSERT INTO PRO_EXEE (EXA_CHVE, APA_CODI, APA_CPAU, APA_DESG, UME_CODI, UME_NOME, EXE_QNTD, EXE_TXRE)
		SELECT @chaveNova, APA_CODI, APA_CPAU, APA_DESG, UME_CODI, UME_NOME, EXE_QNTD, EXE_TXRE
		FROM PRO_EXEE
		WHERE EXA_CHVE = @chaveVelha
		-- copia declaracao sumaria / documento precedente ---------------------------------
		INSERT INTO PRO_EXDS (EXA_CHVE, EXD_TIMP, DOC_CODI, EXD_DESC, PAI_CODI, PAI_NOME, EXD_DATA)
		SELECT @chaveNova, EXD_TIMP, DOC_CODI, EXD_DESC, PAI_CODI, PAI_NOME, EXD_DATA
		FROM PRO_EXDS
		WHERE EXA_CHVE = @chaveVelha
		-- copia controlo de regimes economicos / calculo de imposicoes --------------------
		INSERT INTO PRO_EXCR (EXA_CHVE, APA_CODI, APA_DESG, EXC_QNTD, UME_CODI, UME_NOME, EXC_VCIF, PRE_CODI, PRE_NOME, PAI_CODI, PAI_NOME, DOC_CODI, DOC_NOME, 
			RRE_CODI, RRE_NOME, EXC_BTRI, UME_CTRI, UME_NTRI, EXC_QUAL, EXC_TAXA, EXC_MONT, EXC_LINH)
		SELECT @chaveNova, APA_CODI, APA_DESG, EXC_QNTD, UME_CODI, UME_NOME, EXC_VCIF, PRE_CODI, PRE_NOME, PAI_CODI, PAI_NOME, DOC_CODI, DOC_NOME, RRE_CODI,
			RRE_NOME, EXC_BTRI, UME_CTRI, UME_NTRI,	EXC_QUAL, EXC_TAXA, EXC_MONT, EXC_LINH
		FROM PRO_EXCR
		WHERE EXA_CHVE = @chaveVelha
		-- copia documentos e autorizacoes -------------------------------------------------
		INSERT INTO PRO_EXDA (EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EXD_DTFV, EEM_CODI, EEM_DESC, PAI_CODI, PAI_MOED, PAI_NOME, EXD_MONT, EXD_QNTD, 
			UME_CODI, UME_NOME, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH)
		SELECT @chaveNova, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EXD_DTFV, EEM_CODI, EEM_DESC, PAI_CODI, PAI_MOED, PAI_NOME, EXD_MONT, EXD_QNTD, UME_CODI, 
			UME_NOME, EXD_AUTO, @AnoNovoProc, @codigo, @oper, @linha
		FROM PRO_EXDA
		WHERE EXA_CHVE = @chaveVelha
		-- copia mencoes especiais ---------------------------------------------------------
		INSERT INTO PRO_EXME (EXA_CHVE, INF_CODI, INF_DESI)
		SELECT @chaveNova, INF_CODI, INF_DESI
		FROM PRO_EXME
		WHERE EXA_CHVE = @chaveVelha
		-- copia marcas e volumes ----------------------------------------------------------
		INSERT INTO PRO_EXMV (EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_REST, EXM_TVOL, EXM_IDST, EXM_IDSO)
		SELECT @chaveNova, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_REST, EXM_TVOL, EXM_IDST, EXM_IDSO
		FROM PRO_EXMV
		WHERE EXA_CHVE = @chaveVelha
		-- copia informacoes sobre veiculos ------------------------------------------------
		INSERT INTO PRO_EXIV (EXA_CHVE, EXI_NCHA, EXI_DTPM)
		SELECT @chaveNova, EXI_NCHA, EXI_DTPM
		FROM PRO_EXIV
		WHERE EXA_CHVE = @chaveVelha
		-- copia restituicoes - teores -----------------------------------------------------
		INSERT INTO PRO_EXRT (EXA_CHVE, CTE_CODI, CTE_DESC, EXR_VALO)
		SELECT @chaveNova, CTE_CODI, CTE_DESC, EXR_VALO
		FROM PRO_EXRT
		WHERE EXA_CHVE = @chaveVelha
		-- copia restituicoes - codigos de restituicao -------------------------------------
		INSERT INTO PRO_EXRR (EXA_CHVE, APA_CODI, APA_DESG, EXR_QNTD, UME_CODI, UME_NOME)
		SELECT @chaveNova, APA_CODI, APA_DESG, EXR_QNTD, UME_CODI, UME_NOME
		FROM PRO_EXRR
		WHERE EXA_CHVE = @chaveVelha
		-- copia restituicoes - produtos de composicao -------------------------------------
		INSERT INTO PRO_EXRC (EXA_CHVE, APA_CODI, APA_DESG, EXR_QNTD, UME_CODI, UME_NOME)
		SELECT @chaveNova, APA_CODI, APA_DESG, EXR_QNTD, UME_CODI, UME_NOME
		FROM PRO_EXRC
		WHERE EXA_CHVE = @chaveVelha
		-- copia restituicoes - formulas fabrico -------------------------------------------
		INSERT INTO PRO_EXRF (EXA_CHVE, FFA_CODI, FFA_DESC, EXR_QNTD, UME_CODI, UME_NOME)
		SELECT @chaveNova, FFA_CODI, FFA_DESC, EXR_QNTD, UME_CODI, UME_NOME
		FROM PRO_EXRF
		WHERE EXA_CHVE = @chaveVelha
		-- copia restituicoes - pesos e teores ---------------------------------------------
		INSERT INTO PRO_EXRP (EXA_CHVE, CTE_CODI, CTE_DESC, CPE_CODI, CPE_DESC, EXR_TEOR, EXR_PESO)
		SELECT @chaveNova, CTE_CODI, CTE_DESC, CPE_CODI, CPE_DESC, EXR_TEOR, EXR_PESO
		FROM PRO_EXRP
		WHERE EXA_CHVE = @chaveVelha
		-- copia restituicoes - mencoes especiais ------------------------------------------
		INSERT INTO PRO_EXRM (EXA_CHVE, INF_CODI, INF_DESI)
		SELECT @chaveNova, INF_CODI, INF_DESI
		FROM PRO_EXRM
		WHERE EXA_CHVE = @chaveVelha
		-- copia controlo de mercadorias IECS ----------------------------------------------
		INSERT INTO PRO_EXIE (EXA_CHVE, EXI_NUME, MIE_CODI, MIE_DESC, EXI_QNTD, EXI_TIMP, EXI_MPAG, EXI_MONT, APA_CODI, APA_DESG, EXI_TART, TEM_CODI, TEM_NOME, 
			EXI_CAPE, UME_CODI, UME_NOME, EXI_TEOR)
		SELECT @chaveNova, EXI_NUME, MIE_CODI, MIE_DESC, EXI_QNTD, EXI_TIMP, EXI_MPAG, EXI_MONT, APA_CODI, APA_DESG, EXI_TART, TEM_CODI, TEM_NOME, EXI_CAPE, 
			UME_CODI, UME_NOME, EXI_TEOR
		FROM PRO_EXIE
		WHERE EXA_CHVE = @chaveVelha
		-- copia informacoes complementares da pauta
		INSERT INTO PRO_EXIC (EXA_CHVE, EXC_ICMP, EXC_AUTO)
		SELECT @chaveNova, EXC_ICMP, EXC_AUTO
		FROM PRO_EXIC
		WHERE EXA_CHVE = @chaveVelha

		FETCH NEXT FROM Adicoes INTO @chaveVelha, @linha
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes
END

ALTER AUTHORIZATION ON [SP_duplicaDUExportacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaDUExportacao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaLicImp]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
create proc [SP_duplicaLicImp] @cod int, @ano int as
--declaracoes de variaveis do cabecalho--
declare @maximo int, @lim_data datetime, @lim_stat int, @lim_nemi varchar(20), @lim_pcon varchar(20),
	@eof_autc varchar(18), @cli_dest varchar(18), @lim_pval varchar(30), @pai_ppro varchar(2), 
	@pai_pdes varchar(2), @apa_cnc8 varchar(22), @apa_dmer varchar(50), @lim_quan varchar(40),
	@lim_cauc varchar(30), @dec_codi varchar(6), @tex_mesp varchar(8000)

--busca registo da tabela PRO_DAV
	select @lim_data = LIM_DATA, @lim_stat = LIM_STAT, @lim_nemi = LIM_NEMI, @lim_pcon = LIM_PCON,
	@eof_autc = EOF_AUTC, @cli_dest = CLI_DEST, @lim_pval = LIM_PVAL, @pai_ppro = PAI_PPRO, 
	@pai_pdes = PAI_PDES, @apa_cnc8 = APA_CNC8, @apa_dmer = APA_DMER, @lim_quan = LIM_QUAN,
	@lim_cauc = LIM_CAUC, @dec_codi = DEC_CODI, @tex_mesp = TEX_MESP
	from PRO_LIMP
	where lim_codi = @cod AND lim_eano = @ano

--busca o max DAV_CODI
	SELECT @maximo = MAX(LIM_CODI) 
	FROM PRO_LIMP 
	WHERE LIM_EANO = @ano
	
select @maximo = @maximo + 1


--insere registo do cabeçalho
	
insert into PRO_LIMP(LIM_CODI, LIM_EANO, LIM_DATA, LIM_STAT, LIM_NEMI, LIM_PCON, EOF_AUTC, CLI_DEST,
		 LIM_PVAL, PAI_PPRO, PAI_PDES, APA_CNC8, APA_DMER, LIM_QUAN, LIM_CAUC, DEC_CODI, TEX_MESP)
	values(@maximo, @ano, getdate(), 0, @lim_nemi, @lim_pcon, @eof_autc, @cli_dest, @lim_pval,
		@pai_ppro, @pai_pdes, @apa_cnc8, @apa_dmer, @lim_quan, @lim_cauc, @dec_codi, @tex_mesp)



ALTER AUTHORIZATION ON [SP_duplicaLicImp] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaLicImp] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaNotificacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE proc [SP_duplicaNotificacao] @cod int, @ano int as
--declaracoes de variaveis do cabecalho--
declare @maximo int, @not_data datetime, @ndes_codi varchar(3), @not_stat int,  @not_dten datetime,
	@not_nord varchar(15), @not_dtno datetime, @not_ncon int, @ead_codi varchar(8), 
	@cli_noti varchar(18), @pai_pori varchar(2), @pai_ppro varchar(2), @pai_pdes varchar(2),
	@lme_codi varchar(17), @lme_nome varchar(70), @tex_texp varchar(8000), @not_decs bit, 
	@not_docp bit, @not_desc varchar(60), @not_reex bit, @not_tint bit, @not_pdno varchar(70),
	@not_pdmo varchar(70), @not_pdlo varchar(35), @not_pdcp varchar(12), @not_pdlp varchar(35),
	@not_pdnf varchar(18), @pai_pdpl varchar(2),
	--declara variaveis das adicoes
	@ad_noa_codi int, @ad_apa_codi varchar(22), @ad_noa_mbrt numeric(38,6), @ad_noa_vadi numeric(38,6),
	@ad_tex_mnum varchar(8000), @ad_noa_desg varchar(150), @ad_noa_cpau varchar(22)

--busca registo da tabela PRO_NOTI
	select @not_data = NOT_DATA, @ndes_codi = NDES_CODI, @not_stat = NOT_STAT, @not_dten = NOT_DTEN,
	@not_nord = NOT_NORD, @not_dtno = NOT_DTNO, @not_ncon = NOT_NCON, @ead_codi =EAD_CODI , 
	@cli_noti = CLI_NOTI, @pai_pori = PAI_PORI, @pai_ppro = PAI_PPRO, @pai_pdes = PAI_PDES,
	@lme_codi = LME_CODI, @lme_nome = LME_NOME, @tex_texp = TEX_RESP, @not_decs = NOT_DECS, 
	@not_docp = NOT_DOCP, @not_desc = NOT_DESC, @not_reex = NOT_REEX, @not_tint = NOT_TINT, @not_pdno = NOT_PDNO,
	@not_pdmo = NOT_PDMO, @not_pdlo = NOT_PDLO, @not_pdcp = NOT_PDCP, @not_pdlp = NOT_PDLP,
	@not_pdnf = NOT_PDNF, @pai_pdpl = PAI_PDPL
	from PRO_NOTI
	where not_codi = @cod AND not_eano = @ano

--busca o max DAV_CODI
	SELECT @maximo = MAX(NOT_CODI) 
	FROM PRO_NOTI
	WHERE NOT_EANO = @ano
	
select @maximo = @maximo + 1


--insere registo do cabeçalho
set dateformat dmy	
insert into PRO_NOTI(NOT_CODI, NOT_EANO, NOT_DATA, NOT_STAT, NDES_CODI, EAD_CODI , CLI_NOTI, 
		PAI_PORI, PAI_PPRO, PAI_PDES, LME_CODI, LME_NOME, TEX_RESP, NOT_DECS, 
		NOT_DOCP, NOT_DESC, NOT_REEX, NOT_TINT, NOT_PDNO, NOT_PDMO, NOT_PDLO, 
		NOT_PDCP, NOT_PDLP, NOT_PDNF, PAI_PDPL)
	values(@maximo, @ano, cast(DATENAME(dd, getdate()) + '/'+ cast(DATEpart(mm, getdate()) as varchar) +'/'+DATENAME(yy, getdate()) as datetime),
		0, @ndes_codi, @ead_codi, @cli_noti, @pai_pori, 
		@pai_ppro, @pai_pdes, @lme_codi, @lme_nome, @tex_texp, @not_decs, @not_docp, 
		@not_desc, @not_reex, @not_tint, @not_pdno, @not_pdmo, @not_pdlo, @not_pdcp, 
		@not_pdlp, @not_pdnf , @pai_pdpl)

	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT NOA_CODI, APA_CODI, NOA_MBRT, NOA_VADI, TEX_MNUM, NOA_DESG, NOA_CPAU
		FROM PRO_NOAD
		WHERE NOT_CODI=@cod AND NOT_EANO = @ano
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @ad_noa_codi, @ad_apa_codi, @ad_noa_mbrt, @ad_noa_vadi, 
		@ad_tex_mnum, @ad_noa_desg, @ad_noa_cpau
	WHILE @@FETCH_STATUS = 0
	BEGIN
		insert into PRO_NOAD(NOA_CODI, NOT_CODI, NOT_EANO, APA_CODI, NOA_MBRT, NOA_VADI,
				 TEX_MNUM, NOA_DESG, NOA_CPAU)
			values(@ad_noa_codi, @maximo, @ano, @ad_apa_codi, @ad_noa_mbrt, @ad_noa_vadi, 
			@ad_tex_mnum, @ad_noa_desg, @ad_noa_cpau)
		

		FETCH NEXT FROM Adicoes INTO @ad_noa_codi, @ad_apa_codi, @ad_noa_mbrt, @ad_noa_vadi, 
			@ad_tex_mnum, @ad_noa_desg, @ad_noa_cpau 
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes

ALTER AUTHORIZATION ON [SP_duplicaNotificacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaNotificacao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaT5]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE proc [SP_duplicaT5] @cod int, @ano int as
--declaracoes de variaveis do cabecalho--
declare @maximo int, @t5t_data datetime, @nde_codi varchar(3), @t5t_stat int,
	@t5t_nord varchar(15), @t5t_dtno datetime, @t5t_ncon int, @tde_codi varchar(4), @ead_codi varchar(8), 
	@t5t_lcrg varchar(6), @t5t_adic int, @t5t_tvol int, @t5t_ref7 varchar(30), @cli_expe varchar(18),
	@for_dest varchar(18), @dec_codi varchar(6), @pai_expe varchar(2), @pai_dest varchar(2),
	@mtr_codi varchar(2), @t5t_matr varchar(30), @pai_naci varchar(2), @t5t_cont int, 
	@t5t_mlto numeric(38,6), @t5t_mbto numeric(38,6), @t5t_pdno varchar(70), @t5t_pdmo varchar(70),
	@t5t_pdlo varchar(35), @t5t_pdcp varchar(12), @t5t_pdlp varchar(35), @t5t_pdnf varchar(18),
	@pai_pdpl varchar(2), @t5t_peno varchar(70), @t5t_pemo varchar(70), @t5t_pelo varchar(35), 
	@t5t_pecp varchar(12), @t5t_pelp varchar(35), @t5t_penf varchar(18), @pai_pepl varchar(2),
	--declara variaveis das adicoes
	@ad_t5a_codi int, @ad_apa_codi varchar(22), @ad_t5a_desg varchar(150), @ad_t5a_cpau varchar(22), 
	@ad_t5a_mbrt numeric(38,6), @ad_t5a_mliq numeric(38,6), @ad_t5a_mlex varchar(120), 
	@ad_t5a_dpre varchar(50), @ad_t5a_unsq numeric(38,6), @ad_usu_codi varchar(10), @ad_t5a_marc varchar(20),
	@ad_t5a_nume varchar(20), @ad_t5a_quan int, @ad_ume_natu varchar(2), @ad_tex_utin varchar(8000),
	@ad_tex_utid varchar(8000), @ad_tex_cert varchar(8000), @ad_t5a_stad bit, @ad_t5a_forp bit,
	@ad_t5a_forb bit, @ad_t5a_ffar bit, @ad_t5a_outr bit, @ad_t5a_dout varchar(50), 
	@ad_t5a_rega varchar(60), @ad_t5a_docj varchar(40), @ad_t5a_doca varchar(40), 
	--variaveis do detalhe das adicoes CONTENTORES
	@con_t5c_codi int, @con_t5c_cnum varchar(20)

--busca registo da tabela PRO_T5TR
	select @t5t_data = T5T_DATA, @nde_codi = NDE_CODI, @t5t_stat = T5T_STAT,
	@t5t_nord = T5T_NORD, @t5t_dtno = T5T_DTNO, @t5t_ncon = T5T_NCON, @tde_codi = TDE_CODI, @ead_codi = EAD_CODI, 
	@t5t_lcrg = T5T_LCRG, @t5t_adic = T5T_ADIC, @t5t_tvol = T5T_TVOL, @t5t_ref7 = T5T_REF7, @cli_expe = CLI_EXPE,
	@for_dest = FOR_DEST, @dec_codi = DEC_CODI, @pai_expe = PAI_EXPE, @pai_dest = PAI_DEST,
	@mtr_codi = MTR_CODI, @t5t_matr = T5T_MATR, @pai_naci = PAI_NACI, @t5t_cont = T5T_CONT, 
	@t5t_mlto = T5T_MLTO, @t5t_mbto = T5T_MBTO, @t5t_pdno = T5T_PDNO, @t5t_pdmo = T5T_PDMO,
	@t5t_pdlo = T5T_PDLO, @t5t_pdcp = T5T_PDCP, @t5t_pdlp = T5T_PDLP, @t5t_pdnf = T5T_PDNF,
	@pai_pdpl = PAI_PDPL, @t5t_peno = T5T_PENO, @t5t_pemo = T5T_PEMO, @t5t_pelo = T5T_PELO, 
	@t5t_pecp = T5T_PECP, @t5t_pelp = T5T_PELP, @t5t_penf = T5T_PENF, @pai_pepl = PAI_PEPL
	from PRO_T5TR
	where t5t_codi = @cod AND t5t_eano = @ano

--busca o max DAV_CODI
	SELECT @maximo = MAX(T5T_CODI) 
	FROM PRO_T5TR
	WHERE T5T_EANO = @ano
	
select @maximo = @maximo + 1


--insere registo do cabeçalho
set dateformat dmy	
insert into PRO_T5TR(T5T_CODI, T5T_EANO, T5T_DATA, NDE_CODI, T5T_STAT, TDE_CODI, EAD_CODI, 
	T5T_LCRG, T5T_ADIC, T5T_TVOL, T5T_REF7, CLI_EXPE, FOR_DEST, DEC_CODI, PAI_EXPE, 
	PAI_DEST, MTR_CODI, T5T_MATR, PAI_NACI, T5T_CONT, T5T_MLTO, T5T_MBTO, T5T_PDNO, 
	T5T_PDMO, T5T_PDLO, T5T_PDCP, T5T_PDLP, T5T_PDNF, PAI_PDPL, T5T_PENO, T5T_PEMO, 
	T5T_PELO, T5T_PECP, T5T_PELP, T5T_PENF, PAI_PEPL)
	values(@maximo, @ano, cast(DATENAME(dd, getdate()) + '/'+ cast(DATEpart(mm, getdate()) as varchar) +'/'+DATENAME(yy, getdate()) as datetime),
	 @nde_codi, 0, @tde_codi , @ead_codi, 
	@t5t_lcrg, @t5t_adic, @t5t_tvol, @t5t_ref7, @cli_expe, @for_dest, @dec_codi, 
	@pai_expe, @pai_dest, @mtr_codi, @t5t_matr, @pai_naci, @t5t_cont, @t5t_mlto, 
	@t5t_mbto, @t5t_pdno, @t5t_pdmo, @t5t_pdlo, @t5t_pdcp, @t5t_pdlp, @t5t_pdnf,
	@pai_pdpl, @t5t_peno, @t5t_pemo, @t5t_pelo, @t5t_pecp, @t5t_pelp, @t5t_penf, 
	@pai_pepl)

	-----------------------------------------cria cursor para os dados do detalhe ADICOES
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT T5A_CODI, APA_CODI, T5A_DESG, T5A_CPAU, T5A_MBRT, T5A_MLIQ, T5A_MLEX,
			T5A_DPRE, T5A_UNSQ, USU_CODI, T5A_MARC, T5A_NUME, T5A_QUAN, UME_NATU, 
			TEX_UTIN, TEX_UTID, TEX_CERT, T5A_STAD, T5A_FORP,
			T5A_FORB, T5A_FFAR, T5A_OUTR, T5A_DOUT, T5A_REGA, T5A_DOCJ, T5A_DOCA
		FROM PRO_T5AD
		WHERE T5T_CODI=@cod AND T5T_EANO = @ano
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @ad_t5a_codi, @ad_apa_codi, @ad_t5a_desg, @ad_t5a_cpau, 
	@ad_t5a_mbrt, @ad_t5a_mliq, @ad_t5a_mlex, @ad_t5a_dpre, @ad_t5a_unsq, @ad_usu_codi, 
	@ad_t5a_marc, @ad_t5a_nume, @ad_t5a_quan, @ad_ume_natu, @ad_tex_utin, @ad_tex_utid, 
	@ad_tex_cert, @ad_t5a_stad, @ad_t5a_forp, @ad_t5a_forb, @ad_t5a_ffar, @ad_t5a_outr, 
	@ad_t5a_dout, @ad_t5a_rega, @ad_t5a_docj, @ad_t5a_doca 

	WHILE @@FETCH_STATUS = 0
	BEGIN
		insert into PRO_T5AD(T5A_CODI, T5T_CODI, T5T_EANO, APA_CODI, T5A_DESG, T5A_CPAU, 
			T5A_MBRT, T5A_MLIQ, T5A_MLEX, T5A_DPRE, T5A_UNSQ, USU_CODI, T5A_MARC, 
			T5A_NUME, T5A_QUAN, UME_NATU, TEX_UTIN, TEX_UTID, TEX_CERT, T5A_STAD, 
			T5A_FORP, T5A_FORB, T5A_FFAR, T5A_OUTR, T5A_DOUT, T5A_REGA, T5A_DOCJ, T5A_DOCA)
			values(@ad_t5a_codi, @maximo, @ano, @ad_apa_codi, @ad_t5a_desg, @ad_t5a_cpau, 
				@ad_t5a_mbrt, @ad_t5a_mliq, @ad_t5a_mlex, @ad_t5a_dpre, @ad_t5a_unsq, @ad_usu_codi, 
				@ad_t5a_marc, @ad_t5a_nume, @ad_t5a_quan, @ad_ume_natu, @ad_tex_utin, @ad_tex_utid, 
				@ad_tex_cert, @ad_t5a_stad, @ad_t5a_forp, @ad_t5a_forb, @ad_t5a_ffar, @ad_t5a_outr, 
				@ad_t5a_dout, @ad_t5a_rega, @ad_t5a_docj, @ad_t5a_doca)
		

			-----------------------------------------cria cursor para os dados do detalhe CONTENTORES
		DECLARE Cont CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT T5C_CODI, T5C_CNUM
			FROM PRO_T5CO
			WHERE T5T_CODI=@cod AND T5A_CODI=@ad_t5a_codi AND T5T_EANO = @ano
		OPEN Cont
		FETCH NEXT FROM Cont INTO @con_t5c_codi, @con_t5c_cnum
	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			insert into PRO_T5CO(T5T_CODI, T5T_EANO, T5A_CODI, T5C_CODI, T5C_CNUM)
				values(@maximo, @ano, @ad_t5a_codi, @con_t5c_codi, @con_t5c_cnum)
			FETCH NEXT FROM Cont INTO @con_t5c_codi, @con_t5c_cnum
		END
		CLOSE Cont
		DEALLOCATE Cont


		FETCH NEXT FROM Adicoes INTO @ad_t5a_codi, @ad_apa_codi, @ad_t5a_desg, @ad_t5a_cpau, 
		@ad_t5a_mbrt, @ad_t5a_mliq, @ad_t5a_mlex, @ad_t5a_dpre, @ad_t5a_unsq, @ad_usu_codi, 
		@ad_t5a_marc, @ad_t5a_nume, @ad_t5a_quan, @ad_ume_natu, @ad_tex_utin, @ad_tex_utid, 
		@ad_tex_cert, @ad_t5a_stad, @ad_t5a_forp, @ad_t5a_forb, @ad_t5a_ffar, @ad_t5a_outr, 
		@ad_t5a_dout, @ad_t5a_rega, @ad_t5a_docj, @ad_t5a_doca  
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes

ALTER AUTHORIZATION ON [SP_duplicaT5] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaT5] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_duplicaTMANUAL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_duplicaTMANUAL] @cod int, @ano int AS
BEGIN
--declaracoes de variaveis do cabecalho--
	declare @maximo int, @tma_data datetime, @nde_codi varchar(3), @tma_stat int, @tma_nord varchar(15), @tma_dtno datetime, @tma_ncon int, 
		@tde_codi varchar(4), @ead_codi varchar(8), @tma_lcrg varchar(6), @tma_adic int, @tma_tvol int, @tma_ref7 varchar(30), @tma_expe varchar(18), 
		@tma_dest varchar(18), @dec_codi varchar(6), @pai_expe varchar(2), @pai_dest varchar(2), @mtr_codi varchar(2), @tma_matr varchar(30), 
		@pai_naci varchar(2), @mtr_tfro varchar(2),	@tma_mtrf varchar(30), @pai_mtrn varchar(2), @tma_cont int, @mtr_c25 varchar(2), @lme_codi varchar(17), 
		@tma_mlto numeric(38,6), @tma_mbto numeric(38,6), @arm_codi varchar(17), @cli_rpri varchar(18), @ead_pas1 varchar(8), @ead_pas2 varchar(8), 
		@ead_pas3 varchar(8), @ead_pas4 varchar(8), @ead_dest varchar(8), @ead_part varchar(8), @tma_pdno varchar(70), @tma_pdmo varchar(70), 
		@tma_pdlo varchar(35), @tma_pdcp varchar(12), @tma_pdlp varchar(35), @tma_pdnf varchar(18), @pai_pdpl varchar(2), @tma_peno varchar(70), 
		@tma_pemo varchar(70), @tma_pelo varchar(35), @tma_pecp varchar(12), @tma_pelp varchar(35), @tma_penf varchar(18), @pai_pepl varchar(2),
--declara variaveis das Garantias	
		@gar_pai_codi varchar(2), @gar_pai_nome varchar(50),
--declara variaveis das adicoes
		@ad_tad_codi int, @ad_apa_codi varchar(22), @ad_tad_desg varchar(150), @ad_tad_cpau varchar(22), @ad_tad_mbrt numeric(38,6), 
		@ad_tad_mliq numeric(38,6), @ad_tad_dsum bit, @ad_tad_dpre bit, @ad_tad_desc varchar(60), @ad_tad_marc varchar(20), @ad_tad_nume varchar(20), 
		@ad_tad_quan int, @ad_ume_natu varchar(2), 
--variaveis do detalhe das adicoes CONTENTORES
		@con_tac_codi int, @con_tac_cnum varchar(20),
--variaveis do detalhe das adicoes DOCUMENTOS
		@doc_tmd_codi int, @doc_doc_codi varchar(5), @doc_tmd_nume varchar(35), @doc_tmd_dini datetime, @doc_tmd_dfim datetime
--busca registo da tabela PRO_TMAN
	select @tma_data = TMA_DATA, @nde_codi = NDE_CODI, @tma_stat = TMA_STAT, @tma_nord = TMA_NORD, @tma_dtno = TMA_DTNO, @tma_ncon = TMA_NCON, 
		@tde_codi = TDE_CODI, @ead_codi = EAD_CODI, @tma_lcrg = TMA_LCRG, @tma_adic = TMA_ADIC, @tma_tvol = TMA_TVOL, @tma_ref7 = TMA_REF7, 
		@tma_expe = TMA_EXPE, @tma_dest = TMA_DEST, @dec_codi = DEC_CODI, @pai_expe = PAI_EXPE, @pai_dest = PAI_DEST, @mtr_codi = MTR_CODI, 
		@tma_matr = TMA_MATR, @pai_naci = PAI_NACI, @mtr_tfro = MTR_TFRO, @tma_mtrf = TMA_MTRF, @pai_mtrn = PAI_MTRN, @tma_cont = TMA_CONT, 
		@mtr_c25 = MTR_C25, @lme_codi = LME_CODI, @tma_mlto = TMA_MLTO, @tma_mbto = TMA_MBTO, @arm_codi = ARM_CODI, @cli_rpri = CLI_RPRI, 
		@ead_pas1 = EAD_PAS1, @ead_pas2 = EAD_PAS2, @ead_pas3 = EAD_PAS3, @ead_pas4 = EAD_PAS4, @ead_dest = EAD_DEST, @ead_part = EAD_PART, 
		@tma_pdno = TMA_PDNO, @tma_pdmo = TMA_PDMO, @tma_pdlo = TMA_PDLO, @tma_pdcp = TMA_PDCP, @tma_pdlp = TMA_PDLP, @tma_pdnf = TMA_PDNF,
		@pai_pdpl = PAI_PDPL, @tma_peno = TMA_PENO, @tma_pemo = TMA_PEMO, @tma_pelo = TMA_PELO, @tma_pecp = TMA_PECP, @tma_pelp = TMA_PELP, 
		@tma_penf = TMA_PENF, @pai_pepl = PAI_PEPL
	from PRO_TMAN
	where tma_codi = @cod AND tma_eano = @ano
--busca o max DAV_CODI
	SELECT @maximo = MAX(TMA_CODI) 
	FROM PRO_TMAN
	WHERE TMA_EANO = @ano
	select @maximo = @maximo + 1
--insere registo do cabeçalho
	set dateformat dmy	
	insert into PRO_TMAN(TMA_CODI, TMA_EANO, TMA_DATA, NDE_CODI, TMA_STAT, TDE_CODI, EAD_CODI, TMA_LCRG, TMA_ADIC, TMA_TVOL, TMA_REF7, TMA_EXPE , TMA_DEST, 
		DEC_CODI, PAI_EXPE, PAI_DEST, MTR_CODI, TMA_MATR, PAI_NACI, MTR_TFRO, TMA_MTRF, PAI_MTRN, TMA_CONT, MTR_C25, LME_CODI, TMA_MLTO, TMA_MBTO, ARM_CODI, 
		CLI_RPRI, EAD_PAS1, EAD_PAS2, EAD_PAS3, EAD_PAS4, EAD_DEST, EAD_PART, TMA_PDNO, TMA_PDMO, TMA_PDLO, TMA_PDCP, TMA_PDLP, TMA_PDNF, PAI_PDPL, TMA_PENO, 
		TMA_PEMO, TMA_PELO, TMA_PECP, TMA_PELP, TMA_PENF, PAI_PEPL)
	values(@maximo, @ano, cast(DATENAME(dd, getdate()) + '/'+ cast(DATEpart(mm, getdate()) as varchar) +'/'+DATENAME(yy, getdate()) as datetime),
		@nde_codi, 0, @tde_codi, @ead_codi, @tma_lcrg, @tma_adic, @tma_tvol, @tma_ref7, @tma_expe, @tma_dest, @dec_codi, @pai_expe, @pai_dest, @mtr_codi, 
		@tma_matr, @pai_naci, @mtr_tfro, @tma_mtrf, @pai_mtrn, @tma_cont, @mtr_c25, @lme_codi, @tma_mlto, @tma_mbto, @arm_codi, @cli_rpri, @ead_pas1, 
		@ead_pas2, @ead_pas3, @ead_pas4, @ead_dest, @ead_part, @tma_pdno, @tma_pdmo, @tma_pdlo, @tma_pdcp, @tma_pdlp, @tma_pdnf, @pai_pdpl, @tma_peno, 
		@tma_pemo, @tma_pelo, @tma_pecp, @tma_pelp, @tma_penf, @pai_pepl)
	------------------------------cria cursor para os dados do detalhe tipos garantia
	DECLARE TGarantia CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT PAI_CODI, PAI_NOME
		FROM PRO_TMGT
		WHERE TMA_CODI=@cod AND TMA_EANO = @ano
	OPEN TGarantia
	FETCH NEXT FROM TGarantia INTO @gar_pai_codi, @gar_pai_nome 
	WHILE @@FETCH_STATUS = 0
	BEGIN
		insert into PRO_TMGT(TMA_CODI, TMA_EANO, PAI_CODI, PAI_NOME)
		values(@maximo, @ano, @gar_pai_codi, @gar_pai_nome)
		FETCH NEXT FROM TGarantia INTO @gar_pai_codi, @gar_pai_nome  
	END
	CLOSE TGarantia
	DEALLOCATE TGarantia
	-----------------------------------------cria cursor para os dados do detalhe ADICOES
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT TAD_CODI, APA_CODI, TAD_DESG, TAD_CPAU, TAD_MBRT, TAD_MLIQ, TAD_DSUM, TAD_DPRE, TAD_DESC, TAD_MARC, TAD_NUME, TAD_QUAN, UME_NATU  
		FROM PRO_TADI
		WHERE TMA_CODI=@cod AND TMA_EANO = @ano
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @ad_tad_codi, @ad_apa_codi, @ad_tad_desg, @ad_tad_cpau, @ad_tad_mbrt, @ad_tad_mliq, @ad_tad_dsum, @ad_tad_dpre, @ad_tad_desc, 
		@ad_tad_marc, @ad_tad_nume, @ad_tad_quan, @ad_ume_natu
	WHILE @@FETCH_STATUS = 0
	BEGIN
		insert into PRO_TADI(TMA_CODI, TMA_EANO, TAD_CODI, APA_CODI, TAD_DESG, TAD_CPAU, TAD_MBRT, TAD_MLIQ, TAD_DSUM, TAD_DPRE, TAD_DESC, TAD_MARC, 
			TAD_NUME, TAD_QUAN, UME_NATU)
		values(@maximo, @ano, @ad_tad_codi, @ad_apa_codi, @ad_tad_desg, @ad_tad_cpau, @ad_tad_mbrt, @ad_tad_mliq, @ad_tad_dsum, @ad_tad_dpre, @ad_tad_desc, 
			@ad_tad_marc, @ad_tad_nume, @ad_tad_quan, @ad_ume_natu )
		-----------------------------------------cria cursor para os dados do detalhe CONTENTORES
		DECLARE Cont CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT TAC_CODI, TAC_CNUM
			FROM PRO_TACO
			WHERE TMA_CODI=@cod AND TAD_CODI=@ad_tad_codi AND TMA_EANO = @ano
		OPEN Cont
		FETCH NEXT FROM Cont INTO @con_tac_codi, @con_tac_cnum
		WHILE @@FETCH_STATUS = 0
		BEGIN
			insert into PRO_TACO(TMA_CODI, TMA_EANO, TAD_CODI, TAC_CODI, TAC_CNUM)
			values(@maximo, @ano, @ad_tad_codi, @con_tac_codi, @con_tac_cnum)
			FETCH NEXT FROM Cont INTO @con_tac_codi, @con_tac_cnum
		END
		CLOSE Cont
		DEALLOCATE Cont
		-----------------------------------------cria cursor para os dados do detalhe DOCUMENTOS
		DECLARE Doc CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT TMD_CODI, DOC_CODI, TMD_NUME, TMD_DINI, TMD_DFIM
			FROM PRO_TMDO
			WHERE TMA_CODI=@cod AND TAD_CODI=@ad_tad_codi AND TMA_EANO = @ano
		OPEN Doc
		FETCH NEXT FROM Doc INTO @doc_tmd_codi, @doc_doc_codi, @doc_tmd_nume, @doc_tmd_dini, @doc_tmd_dfim
		WHILE @@FETCH_STATUS = 0
		BEGIN
			insert into PRO_TMDO(TMA_CODI, TMA_EANO, TAD_CODI, TMD_CODI, DOC_CODI, TMD_NUME, TMD_DINI, TMD_DFIM)
			values(@maximo, @ano, @ad_tad_codi, @doc_tmd_codi, @doc_doc_codi, @doc_tmd_nume, @doc_tmd_dini, @doc_tmd_dfim)
			FETCH NEXT FROM Doc INTO @doc_tmd_codi, @doc_doc_codi, @doc_tmd_nume, @doc_tmd_dini, @doc_tmd_dfim
		END
		CLOSE Doc
		DEALLOCATE Doc

		FETCH NEXT FROM Adicoes INTO @ad_tad_codi, @ad_apa_codi, @ad_tad_desg, @ad_tad_cpau, @ad_tad_mbrt, @ad_tad_mliq, @ad_tad_dsum, @ad_tad_dpre, 
			@ad_tad_desc, @ad_tad_marc, @ad_tad_nume, @ad_tad_quan, @ad_ume_natu  
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes
END

ALTER AUTHORIZATION ON [SP_duplicaTMANUAL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_duplicaTMANUAL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_encerramentoAno]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_encerramentoAno] @AnoAtual int, @Contas int, @IdUtilizador int, @NumeracaoContinua bit AS
BEGIN	
	SET DATEFORMAT dmy
-- declaração de variáveis
	DECLARE @AnoNovo int, @CDO_EANO int, @CDO_TDOC varchar(4), @CDO_IDEN int, @TDO_DOCU varchar(4), @NUM_TDOC int, @ProxNumeroDAR int
-- inicia variáveis
	SET @AnoNovo = @AnoAtual + 1
-- processa a passagem das contas para o novo ano
	IF @contas < 2
	BEGIN
 		-- busca todas as contas cdo do ano -----------------------------------------------------
		IF @contas = 0 
		BEGIN
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT CDO_EANO, CDO_TDOC, CDO_IDEN
				FROM FAC_CDOC WITH(NOLOCK)
				WHERE CDO_EANO = @AnoAtual AND CDO_CNUM IS NULL AND CDO_STAT < 3
		END
 		-- busca apenas as conta seleccionadas para transferir ----------------------------------
		ELSE 
			IF @contas = 1
			BEGIN
				DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
					SELECT CDO_EANO, CDO_TDOC, CDO_IDEN
					FROM FAC_CDOC WITH(NOLOCK)
					WHERE CDO_EANO = @AnoAtual AND CDO_CNUM IS NULL AND CDO_STAT IN (10, 11, 12)
			END			
		OPEN Detalhe
		FETCH NEXT from Detalhe into @CDO_EANO, @CDO_TDOC, @CDO_IDEN 
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- actualiza documentadas contas cdo --------------------------------------------
			UPDATE FAC_DCDO SET CDO_EANO = @AnoNovo
			WHERE CDO_EANO = @CDO_EANO AND CDO_TDOC = @CDO_TDOC AND CDO_IDEN = @CDO_IDEN
			-- actualiza detalhe documentadas contas cdo ------------------------------------
			UPDATE FAC_DDCD SET CDO_EANO = @AnoNovo
			WHERE CDO_EANO = @CDO_EANO AND CDO_TDOC = @CDO_TDOC AND CDO_IDEN = @CDO_IDEN	
			-- actualiza inerentes contas cdo -----------------------------------------------
			UPDATE FAC_ICDO SET CDO_EANO = @AnoNovo
			WHERE CDO_EANO = @CDO_EANO AND CDO_TDOC = @CDO_TDOC AND CDO_IDEN = @CDO_IDEN
			-- actualiza detalhe inerentes contas cdo ---------------------------------------
			UPDATE FAC_DICD SET CDO_EANO = @AnoNovo
			WHERE CDO_EANO = @CDO_EANO AND CDO_TDOC = @CDO_TDOC AND CDO_IDEN = @CDO_IDEN
			-- actualiza contas cdo ---------------------------------------------------------
			UPDATE FAC_CDOC SET CDO_EANO = @AnoNovo, CDO_STAT = CDO_STAT - 10
			WHERE CDO_EANO = @CDO_EANO AND CDO_TDOC = @CDO_TDOC AND CDO_IDEN = @CDO_IDEN	
			FETCH NEXT from Detalhe into @CDO_EANO, @CDO_TDOC, @CDO_IDEN 
		END
		CLOSE Detalhe
		DEALLOCATE Detalhe
	END
-- cria numeradores dos tipos de documentos para o novo ano
	INSERT INTO TAB_NUMD(TDO_DOCU, NUM_EANO, NUM_TDOC, NUM_NUME, NUM_DATA, NUM_CVAT, NUM_NVAT, NUM_DVAT, NUM_UVAT, NUM_TVAT, NUM_SERI)
	SELECT TDO_DOCU, @AnoNovo, NUM_TDOC, (CASE @NumeracaoContinua WHEN 1 THEN NUM_NUME ELSE 0 END), CAST(('01-01-' + STR(@AnoNovo , 4)) AS datetime), 
		(CASE @NumeracaoContinua WHEN 1 THEN NUM_CVAT ELSE NULL END), (CASE @NumeracaoContinua WHEN 1 THEN NUM_NVAT ELSE NULL END), (CASE @NumeracaoContinua WHEN 1 THEN NUM_DVAT ELSE NULL END), 
		(CASE @NumeracaoContinua WHEN 1 THEN NUM_UVAT ELSE NULL END), (CASE @NumeracaoContinua WHEN 1 THEN NUM_TVAT ELSE NULL END), (CASE @NumeracaoContinua WHEN 1 THEN NUM_SERI ELSE NULL END)
	FROM TAB_NUMD WITH(NOLOCK)
	WHERE NUM_EANO = @AnoAtual
-- obtem o proximo número para novo exercício nas declarações DAR em função se o tipo de empresa é "FEDEX/TNT", "UPS", "DHL", "TNT" ou "CTT"
	IF EXISTS(SELECT PDE_CODI FROM TAB_PDES WHERE PDE_CADI IN (1, 2, 3, 4, 5))
		SET @ProxNumeroDAR = ISNULL((SELECT proximoNumero FROM tb_ConfiguracoesDARNumeradores WHERE ano = @AnoAtual), 1)
	ELSE
		SET @ProxNumeroDAR = 1
-- cria numerador para novo exercício nas declarações DAR
	INSERT INTO tb_ConfiguracoesDARNumeradores(ano, proximoNumero, id_utilizadorControlo, dataControlo)
	VALUES(@AnoNovo, @ProxNumeroDAR, @IdUtilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())
-- coloca exercicio como encerrado na empresa 
	UPDATE GIDWIN.dbo.FAP_EANO SET EAN_FECH = 1
	WHERE EMP_CODI = DB_NAME() AND EAN_ANO = @AnoAtual
-- cria novo exercício na empresa 
	INSERT INTO GIDWIN.dbo.FAP_EANO(EMP_CODI, EAN_ANO, EAN_FECH)
	VALUES(DB_NAME(), @AnoNovo, 0)
END

ALTER AUTHORIZATION ON [SP_encerramentoAno] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_encerramentoAno] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_EntradasAEX_ExportaParaFicheiroXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_EntradasAEX_ExportaParaFicheiroXML] @NomeSPAGerarXML varchar(100), @CodAgenteTrafego varchar(18), @DirGeracaoFicheiro varchar(500) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Ano int, @CodLocMercadorias varchar(17), @Numero int, @NumeroRefInterna varchar(30), @FicheiroXML xml, @LinhaXMLEncoding varchar(200), @PathFicheiroTmpXML nvarchar(4000), @SQLString nvarchar(500), 
		@SQLParams nvarchar(500)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirGeracaoFicheiro), 1, 1) <> '\'
		SET @DirGeracaoFicheiro = @DirGeracaoFicheiro + '\'
-- inicia variaveis para executar o SQL dinamicamente
	SET @SQLString = N'EXEC ' + @NomeSPAGerarXML + ' @INAno, @INCodLocMercadorias, @INNumero, @OUTFicheiroXML OUTPUT, @OUTLinhaXMLEncoding OUTPUT'
	SET @SQLParams = N'@INAno int, @INCodLocMercadorias varchar(17), @INNumero int, @OUTFicheiroXML xml OUTPUT, @OUTLinhaXMLEncoding varchar(200) OUTPUT'
-- obtem a lista de Entradas AEX ainda não exportadas e pertencentes ao agente de tráfego especificado
	DECLARE EntradasAEX CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EDG_EANO, LME_CODI, EDG_NUME, EDG_REFI
		FROM AEX_ENDG WITH(NOLOCK)
		WHERE EDG_EXPO = 0 AND ISNULL(AGE_CODI, '') = ISNULL(@CodAgenteTrafego, ISNULL(AGE_CODI, ''))
	OPEN EntradasAEX
	FETCH NEXT FROM EntradasAEX INTO @Ano, @CodLocMercadorias, @Numero, @NumeroRefInterna
	WHILE @@FETCH_STATUS = 0
	BEGIN			
-- constroi XML para gerar o ficheiro
		EXECUTE sp_executesql @SQLString, @SQLParams, @INAno = @Ano, @INCodLocMercadorias = @CodLocMercadorias, @INNumero = @Numero, @OUTFicheiroXML = @FicheiroXML OUTPUT, @OUTLinhaXMLEncoding = @LinhaXMLEncoding OUTPUT		
-- constroi full path para geração do ficheiro XML produzido
		SET @PathFicheiroTmpXML = @DirGeracaoFicheiro + '\' + @NumeroRefInterna + '_' + @CodLocMercadorias + '.' + CAST(@Numero AS varchar(10)) + '.' + CAST(@Ano AS varchar(4)) + '.XML'
-- gera o ficheiro XML produzido c/ encoding UTF-8
		EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroTmpXML				
-- atualiza Entrada AEX p/ sinalizar como exportada
		UPDATE AEX_ENDG SET EDG_EXPO = 1
		WHERE EDG_EANO = @Ano AND LME_CODI = @CodLocMercadorias AND EDG_NUME = @Numero			
		FETCH NEXT FROM EntradasAEX INTO @Ano, @CodLocMercadorias, @Numero, @NumeroRefInterna
	END
	CLOSE EntradasAEX
	DEALLOCATE EntradasAEX	
END

ALTER AUTHORIZATION ON [SP_EntradasAEX_ExportaParaFicheiroXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_EntradasAEX_ExportaParaFicheiroXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_EntradasAEX_GeraDeclaracoesDeXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_EntradasAEX_GeraDeclaracoesDeXML] @XMLDeclaracoes xml, @XMLRelacaoTiposEmbalagem xml, @Utilizador varchar(30), @MensagemErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis	
	DECLARE @CodAgente varchar(18), @NumExterno varchar(20), @NomeDestinatario varchar(75), @MoradaDestinatario varchar(100), @LocalidadeDestinatario varchar(35), @PaisDestinatario varchar(2), 
		@NomeExpedidor varchar(75), @MoradaExpedidor varchar(100), @CodPostalExpedidor varchar(12), @LocalidadeExpedidor varchar(35), @NIFExpedidor varchar(50), @CodLocMercadorias varchar(17), 
		@PreTransporte varchar(20), @TransportePartida varchar(20), @TotalVolumes int, @tmpCodTipoEmbalagem varchar(50), @CodTipoEmbalagem varchar(2), @DesignacaoMercadoria varchar(150), 
		@TotalPesoBrt numeric(38, 6), @TotalValor numeric(38, 6), @RefInterna varchar(20), @Observacoes varchar(150)
	DECLARE @Data datetime, @NumeroAEX int, @AnoAEX int, @CodPaisExpedidor varchar(2), @Localizacao varchar(31), @EstAduaneiro varchar(3)
-- carrega declarações XML p/ INSERT
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT NULLIF(XML_DECL.DCL_DATA.value('Agente[1]', 'varchar(18)'), ''), NULLIF(XML_DECL.DCL_DATA.value('NumDoc[1]', 'varchar(20)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('(InfoDestinatario/NomeDestinatario)[1]', 'varchar(75)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(InfoDestinatario/MoradaDestinatario)[1]', 'varchar(100)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('(InfoDestinatario/LocalidadeDestinatario)[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(InfoDestinatario/PaisDestinatario)[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('(InfoRemetente/NomeRemetente)[1]', 'varchar(75)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(InfoRemetente/MoradaRemetente)[1]', 'varchar(100)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('(InfoRemetente/CpostalRemetente)[1]', 'varchar(12)'), ''), NULLIF(XML_DECL.DCL_DATA.value('(InfoRemetente/LocalidadeRemetente)[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('(InfoRemetente/NIFRemetente)[1]', 'varchar(50)'), ''), NULLIF(XML_DECL.DCL_DATA.value('codigoEstancia[1]', 'varchar(17)'), ''),  
			NULLIF(XML_DECL.DCL_DATA.value('idTransporte[1]', 'varchar(20)'), ''), NULLIF(XML_DECL.DCL_DATA.value('tipTransporte[1]', 'varchar(20)'), ''), XML_DECL.DCL_DATA.value('volumes[1]', 'int'), 
			NULLIF(XML_DECL.DCL_DATA.value('tipoEmbalagem[1]', 'varchar(50)'), ''),  NULLIF(XML_DECL.DCL_DATA.value('descricaoMercadoria[1]', 'varchar(150)'), ''), 
			XML_DECL.DCL_DATA.value('peso[1]', 'numeric(38, 6)'), XML_DECL.DCL_DATA.value('valorMercadoria[1]', 'numeric(38, 6)'), NULLIF(XML_DECL.DCL_DATA.value('Notas[1]', 'varchar(20)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Observacoes[1]', 'varchar(150)'), '')			
		FROM @XMLDeclaracoes.nodes('RequestDocumento') as XML_DECL(DCL_DATA)		
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @CodAgente, @NumExterno, @NomeDestinatario, @MoradaDestinatario, @LocalidadeDestinatario, @PaisDestinatario, @NomeExpedidor, @MoradaExpedidor, @CodPostalExpedidor, 
		@LocalidadeExpedidor, @NIFExpedidor, @CodLocMercadorias, @PreTransporte, @TransportePartida, @TotalVolumes, @tmpCodTipoEmbalagem, @DesignacaoMercadoria, @TotalPesoBrt, @TotalValor, @RefInterna, 
		@Observacoes
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- inicia transacção para inserção dados da declaração
		BEGIN TRANSACTION	
		BEGIN TRY	
-- obtem dados em falta
			SET @Data =	GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
			SELECT @AnoAEX = YEAR(@Data), @CodPaisExpedidor = 'PT', @Localizacao = 'CHAO', @EstAduaneiro = 'X'
-- valida se "Ref. Interna" já existe	
			IF EXISTS(SELECT EDG_NUME FROM AEX_ENDG WITH(NOLOCK) WHERE EDG_EANO = @AnoAEX AND EDG_REFI = @RefInterna)
				RAISERROR('A referência interna "%s" já se encontra inserida!', 16, 1, @RefInterna)		
-- obtem o código do tipo de embalagem associado, caso a relação de códigos exista
			IF @XMLRelacaoTiposEmbalagem IS NOT NULL
			BEGIN
				SELECT @CodTipoEmbalagem = XML_DECL.DCL_DATA.value('codigoGIDWIN[1]', 'varchar(2)')
				FROM @XMLRelacaoTiposEmbalagem.nodes('RelacaoTiposEmbalagem/TipoEmbalagem') as XML_DECL(DCL_DATA)				
				WHERE XML_DECL.DCL_DATA.value('codigoFicheiro[1]', 'varchar(50)') = @tmpCodTipoEmbalagem				
			END
			ELSE
				SET @CodTipoEmbalagem = @tmpCodTipoEmbalagem
-- obtem numero da entrada da localização de mercadorias
			SELECT @NumeroAEX = LME_PNRE
			FROM TAB_LMER
			WHERE LME_CODI = @CodLocMercadorias
-- insere Dados Gerais da declaração de Entrada AEX			
			INSERT INTO AEX_ENDG(EDG_EANO, LME_CODI, EDG_NUME, EDG_IDST, EDG_DATA, EDG_TVOL, EDG_TPBR, EDG_TVAL, EDG_PTRN, EDG_TRNP, EDG_REFI, EDG_SVOL, EDG_SPBR, EDG_ENOM, EDG_EMOR, EDG_ELOC, EDG_ECPO, EDG_ELPO, 
				EDG_ENIF, PAI_CODI, EDG_DNOM, EDG_DMOR, EDG_DLOC, PAI_CODI1, EDG_OBSE, EDG_ORIG, EDG_UCRI, EDG_DCRI, EDG_UALT, EDG_DALT, EDG_NEXT, AGE_CODI)
			VALUES(@AnoAEX, @CodLocMercadorias, @NumeroAEX, REPLACE(CONVERT(numeric(38, 10), @Data), '.', ','), @Data, @TotalVolumes, @TotalPesoBrt, @TotalValor, @PreTransporte, @TransportePartida, @RefInterna, 
				@TotalVolumes, @TotalPesoBrt, @NomeExpedidor, @MoradaExpedidor, @LocalidadeExpedidor, @CodPostalExpedidor, @LocalidadeExpedidor, @NIFExpedidor, @CodPaisExpedidor, @NomeDestinatario, 
				@MoradaDestinatario, @LocalidadeDestinatario, @PaisDestinatario, @Observacoes, 4, @Utilizador, @Data, @Utilizador, @Data, @NumExterno, @CodAgente)				
-- incrementa nº. proxima entrada na localização de mercadorias
			UPDATE TAB_LMER SET LME_PNRE = LME_PNRE + 1
			WHERE LME_CODI = @CodLocMercadorias	
-- insere adição nas Mercadorias na Entrada AEX	
			INSERT INTO AEX_ENLN(EDG_EANO, LME_CODI, EDG_NUME, ELN_NLIN, ELN_VOLS, TEM_CODI, ELN_DMER, ELN_PBRT, ELN_VALO, ELN_LOCA, ELN_EADU, ELN_UCRI, ELN_DCRI, ELN_UALT, ELN_DALT)
			VALUES(@AnoAEX, @CodLocMercadorias, @NumeroAEX, 1, @TotalVolumes, @CodTipoEmbalagem, @DesignacaoMercadoria, @TotalPesoBrt, @TotalValor, @Localizacao, @EstAduaneiro, @Utilizador, @Data, 
				@Utilizador, @Data)														
		END TRY
		BEGIN CATCH				
-- constroi mensagem de erro detalhada
			SELECT @MensagemErro = ISNULL(@MensagemErro, '') + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '** ERRO DE DECLARACAO NAO INSERIDA ***********************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.N.º Externo: ' + ISNULL(ISNULL(@NumExterno, @RefInterna), 'n.d.') + CHAR(12) +
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
-- em caso de erro faz rollback da transacção iniciada						           
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION	
		END CATCH	
-- se sucesso faz commit da transacção iniciada
		IF @@TRANCOUNT > 0
			COMMIT TRANSACTION			
		FETCH NEXT FROM Declaracoes INTO @CodAgente, @NumExterno, @NomeDestinatario, @MoradaDestinatario, @LocalidadeDestinatario, @PaisDestinatario, @NomeExpedidor, @MoradaExpedidor, @CodPostalExpedidor, 
			@LocalidadeExpedidor, @NIFExpedidor, @CodLocMercadorias, @PreTransporte, @TransportePartida, @TotalVolumes, @tmpCodTipoEmbalagem, @DesignacaoMercadoria, @TotalPesoBrt, @TotalValor, @RefInterna, 
			@Observacoes
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes		
END

ALTER AUTHORIZATION ON [SP_EntradasAEX_GeraDeclaracoesDeXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_EntradasAEX_GeraDeclaracoesDeXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_EntradasAEX_ImportaFicheirosSTANDARD]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_EntradasAEX_ImportaFicheirosSTANDARD] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @PathReportPDF varchar(250), 
	@PathGIDWinPDFExportTool varchar(250), @PwLoginGIDWin varchar(30), @XMLRelacaoTiposEmbalagem xml, @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml, @ListaErros varchar(MAX), @i int, @XMLNumExterno varchar(20), @XMLCodLocMercadorias varchar(17), 
		@XMLDiretorioPDF varchar(500), @PathFicheiroPDF varchar(500), @ArgsGIDWinPDFExportTool varchar(2000), @GeraPDF bit, @AnoAEX int, @NumeroAEX int, @DataHoraImpressao datetime, @Erros varchar(MAX), 
		@PathFicheiroErro varchar(500), @Linha varchar(MAX)
-- coloca caracter '"' nas paths
	SET @PathReportPDF = QUOTENAME(@PathReportPDF, '"')
	SET @PathGIDWinPDFExportTool = QUOTENAME(@PathGIDWinPDFExportTool, '"')		
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'			
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros a importar (considera apenas ficheiros cuja extensão é ".xml")
	DECLARE FicheirosXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]		
	OPEN FicheirosXML
	FETCH NEXT from FicheirosXML into @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN				
		SET @ListaErros = ''		
		SET @GeraPDF = 0		
		SET @AnoAEX = YEAR(GETDATE())
		SET @PathFicheiroPDF = ''
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)	
-- obtem o xml do ficheiro xml importado						
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- remove o namespace existente na raiz <RequestDocumento> do XML 
			SET @FicheiroXML = STUFF(CAST(@FicheiroXML as varchar(MAX)), 1, CHARINDEX('>', CAST(@FicheiroXML as varchar(MAX))), '<RequestDocumento>')		
-- obtem o Nº. Externo definido no ficheiro XML			
			SELECT @XMLNumExterno = NULLIF(XML_DECL.DCL_DATA.value('NumDoc[1]', 'varchar(20)'), ''), @XMLCodLocMercadorias = NULLIF(XML_DECL.DCL_DATA.value('codigoEstancia[1]', 'varchar(17)'), ''),
				@XMLDiretorioPDF = NULLIF(XML_DECL.DCL_DATA.value('pastaArquivo[1]', 'varchar(500)'), '')		
			FROM @FicheiroXML.nodes('RequestDocumento') as XML_DECL(DCL_DATA)
-- verifica se o Nº. Externo definido no ficheiro XML não existe para efetuar a geração da declaração de Entrada AEX carregada no XML
			IF NOT EXISTS(SELECT EDG_NUME FROM AEX_ENDG WITH(NOLOCK) WHERE EDG_EANO = @AnoAEX AND LME_CODI = @XMLCodLocMercadorias AND EDG_NEXT = @XMLNumExterno)
			BEGIN
				SET @GeraPDF = 1																
				EXEC SP_EntradasAEX_GeraDeclaracoesDeXML @FicheiroXML, @XMLRelacaoTiposEmbalagem, @Utilizador, @ListaErros OUTPUT	
			END			
-- se diretorio PDF foi identificado e não há erros, processa obtenção do path do ficheiro PDF e eventual geração do ficheiro PDF
			IF (ISNULL(@XMLDiretorioPDF, '') <> '') AND (ISNULL(@ListaErros, '') = '')
			BEGIN
-- verifica se diretorias tem backslash no final
				IF SUBSTRING(REVERSE(@XMLDiretorioPDF), 1, 1) <> '\'
					SET @XMLDiretorioPDF = @XMLDiretorioPDF + '\'
-- constroi o nome a dar ao ficheiro PDF
				SELECT @NumeroAEX = EDG_NUME, @PathFicheiroPDF = @XMLDiretorioPDF + 'DME_' + CAST(EDG_EANO AS varchar(4)) + '_' + LME_CODI + '_' + CAST(EDG_NUME AS varchar(20)) + '_' + EDG_REFI + '.pdf'
				FROM AEX_ENDG WITH(NOLOCK) 
				WHERE EDG_EANO = @AnoAEX AND LME_CODI = @XMLCodLocMercadorias AND EDG_NEXT = @XMLNumExterno
-- procede à geração do report em PDF para a declaração de Entrada AEX					
				IF @GeraPDF = 1
				BEGIN
					SET @ArgsGIDWinPDFExportTool = '-s' + @@SERVERNAME + ' -p' + @PwLoginGIDWin + ' -b' + DB_NAME() + ' -r' + @PathReportPDF + ' -c274 -a' + CAST(@AnoAEX AS varchar(4)) + ' -t' + @XMLCodLocMercadorias + ' -i' + CAST(@NumeroAEX AS varchar(20)) + ' -f' + QUOTENAME(@PathFicheiroPDF, '"')					
					EXEC GIDWIN.dbo.SP_Externo_ExecutaPrograma @PathGIDWinPDFExportTool, @ArgsGIDWinPDFExportTool, @ListaErros OUTPUT
				END
			END			
-- se existir ficheiro PDF e não há erros, gera 2 pedidos de impressão na impressora definida na tabela de Localização de Mercadorias
			IF (ISNULL(@PathFicheiroPDF, '') <> '') AND (ISNULL(@ListaErros, '') = '')
			BEGIN
				SET @DataHoraImpressao = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
				INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_FICH, IMF_IMPR, IMF_STAT, IMF_DTST)
				SELECT @DataHoraImpressao, @PathFicheiroPDF, LME_IMPR, 0, @DataHoraImpressao
				FROM TAB_LMER WITH(NOLOCK) 
				WHERE LME_CODI = @XMLCodLocMercadorias AND ISNULL(LME_IMPR, '') <> ''
				UNION ALL
				SELECT @DataHoraImpressao, @PathFicheiroPDF, LME_IMPR, 0, @DataHoraImpressao
				FROM TAB_LMER WITH(NOLOCK) 
				WHERE LME_CODI = @XMLCodLocMercadorias AND ISNULL(LME_IMPR, '') <> ''
			END
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Nome Ficheiro XML:  ' + @NomeFicheiro + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END								
		END					
		FETCH NEXT from FicheirosXML into @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosXML
	DEALLOCATE FicheirosXML
-- remove as tabelas temporárias
	DROP TABLE #ConteudoFicheiro	
END

ALTER AUTHORIZATION ON [SP_EntradasAEX_ImportaFicheirosSTANDARD] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_EntradasAEX_ImportaFicheirosSTANDARD] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_EntradasAEX_InsereViaExportacaoXMLouSDSViaAerea]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_EntradasAEX_InsereViaExportacaoXMLouSDSViaAerea] @ViaExportacaoXML bit, @Ano int, @Codigo int, @CodOperador varchar(6) = NULL, @NumLinhaAWB int = NULL, @CodLocMercadorias varchar(17) = NULL, 
	@Utilizador varchar(30), @MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Erro int, @AnoAEX int, @NumeroAEX int, @CamposAdicionais int, @NumLinha int, @NumVols int, @Parte bit, @CodEmbalagem varchar(2), @Marcas varchar(25), @CodArtigo varchar(22), 
		@DesignacaoArtigo varchar(150), @PesoLiquido numeric(38, 6), @PesoBruto numeric(38, 6), @Valor numeric(38, 6), @Localizacao varchar(31), @EstCarga varchar(3)
-- inicia variaveis
	SET @Erro = 0
	SET @AnoAEX = YEAR(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())
	SET @NumLinha = 0
-- inicia transacção para inserção de Entrada AEX
	BEGIN TRANSACTION		
	BEGIN TRY
-- obtem dados dos parâmetros de despachos
		SELECT TOP 1 @CamposAdicionais = PDE_CADI
		FROM TAB_PDES WITH(NOLOCK)
-- obtem 1ª localização de mercadorias configurada como "Gere AEX" caso esta não tenha sido fornecida
		IF ISNULL(@CodLocMercadorias, '') = ''
		BEGIN
			SELECT TOP 1 @CodLocMercadorias = LME_CODI
			FROM TAB_LMER WITH(NOLOCK)
			WHERE LME_GAEX = 1
		END		
-- obtem numero da entrada da localização de mercadorias
		SELECT @NumeroAEX = LME_PNRE
		FROM TAB_LMER
		WHERE LME_CODI = @CodLocMercadorias
-- insere Dados Gerais da Entrada AEX
		IF @ViaExportacaoXML = 1 
		BEGIN			
			INSERT INTO AEX_ENDG(EDG_EANO, LME_CODI, EDG_NUME, EDG_IDST, EDG_DATA, EDG_TRNP, EDG_REFI, CLI_CODI, EDG_ENOM, EDG_EMOR, EDG_ELOC, EDG_ECPO, EDG_ELPO, EDG_ENIF, PAI_CODI, FOR_CODI, EDG_DNOM, 
				EDG_DMOR, EDG_DLOC, PAI_CODI1, EDG_ORIG, EDG_UCRI, EDG_DCRI, EDG_UALT, EDG_DALT, EXM_EANO, EXM_CODI, DEC_CODI)
			SELECT @AnoAEX, @CodLocMercadorias, @NumeroAEX, REPLACE(CONVERT(numeric(38, 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), '.', ','), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), MTR_CO18, EXM_CPRT, 
				NULLIF(CLI_COD2, ''), CLI_NOM2, CLI_MOR2, CLI_LOC2, CLI_CPO2, CLI_LPO2, CLI_NIF2, EXM_P15A, NULLIF(FOR_COD8, ''), FOR_NOM8, FOR_MOR8, FOR_LOC8, EXM_P17A, 1, @Utilizador, 
				GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), EXM_EANO, EXM_CODI, DEC_CODI
			FROM PRO_EXML WITH(NOLOCK)
			WHERE EXM_EANO = @Ano and EXM_CODI = @Codigo and DEC_CODI = @CodOperador
		END
		ELSE
		BEGIN			
			INSERT INTO AEX_ENDG(EDG_EANO, LME_CODI, EDG_NUME, EDG_IDST, EDG_DATA, EDG_REFI, EDG_ENOM, EDG_EMOR, EDG_ENIF, PAI_CODI, EDG_DNOM, EDG_DMOR, PAI_CODI1, EDG_ORIG, EDG_UCRI, EDG_DCRI, EDG_UALT, EDG_DALT)
			SELECT @AnoAEX, @CodLocMercadorias, @NumeroAEX, REPLACE(CONVERT(numeric(38, 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), '.', ','), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), dsd.DSD_NRMH, 
				dsd.DSD_NOOS, dsd.DSD_MOOS, dsd.DSD_IDOS, dsd.PAI_CODI, dsd.DSD_NOMD, dsd.DSD_MORD, pae.PAI_CODI, 2, @Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
			FROM PRO_SDSD as dsd WITH(NOLOCK) INNER JOIN TAB_PAER as pae WITH(NOLOCK) ON dsd.PAE_CODI = pae.PAE_CODI
			WHERE dsd.DSC_EANO = @Ano and dsd.DSC_NPRO = @Codigo and dsd.DSD_NUME = @NumLinhaAWB
		END
-- incrementa nº. proxima entrada na localização de mercadorias
		UPDATE TAB_LMER SET LME_PNRE = LME_PNRE + 1
		WHERE LME_CODI = @CodLocMercadorias	
-- obtem lista de adições da Exportação/XML		
		IF @ViaExportacaoXML = 1 
		BEGIN
			DECLARE LstAdicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT ROUND(SUM(emv.EXM_NVOL), 0), (CASE emv.EXM_PART WHEN 0 THEN emv.EXM_REST ELSE emv.EXM_PART END), emv.TEM_CODI, SUBSTRING(emv.EXM_MARN, 1, 25), ead.APA_CO33, ead.APA_DESG, 
					ISNULL(ead.EXA_MLQD, 0), ISNULL(ead.EXA_MBRT, 0), ISNULL(ead.EXA_VALO, 0), (CASE WHEN @CamposAdicionais > 0 THEN ('R' + RIGHT(eml.EXM_CPRT, 1)) ELSE NULL END), SUBSTRING(eml.EXM_TPCG, 1, 3)
				FROM PRO_EXAD as ead WITH(NOLOCK) INNER JOIN PRO_EXML as eml WITH(NOLOCK) ON ead.EXM_EANO = eml.EXM_EANO and ead.EXM_CODI = eml.EXM_CODI and ead.EXM_COPE = eml.DEC_CODI
					INNER JOIN PRO_EXMV as emv WITH(NOLOCK) ON ead.EXA_CHVE = emv.EXA_CHVE
				WHERE ead.EXM_EANO = @Ano and ead.EXM_CODI = @Codigo and ead.EXM_COPE = @CodOperador
				GROUP BY ead.EXA_LINH, emv.EXM_PART, emv.EXM_REST, emv.TEM_CODI, emv.EXM_MARN, ead.APA_CO33, ead.APA_DESG, ead.EXA_MLQD, ead.EXA_MBRT, ead.EXA_VALO, eml.EXM_CPRT, eml.EXM_TPCG
				ORDER BY ead.EXA_LINH
		END
		ELSE
		BEGIN			
			DECLARE LstAdicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT DSD_VOLS, 0, TEM_CODI, DSD_MRNR, NULL, DSD_DMER, 0, DSD_PESO, DSD_VALO, (CASE WHEN @CamposAdicionais > 0 THEN ('R' + RIGHT(DSD_NRMH, 1)) ELSE NULL END), DSD_EADC
				FROM PRO_SDSD WITH(NOLOCK)
				WHERE DSC_EANO = @Ano and DSC_NPRO = @Codigo and DSD_NUME = @NumLinhaAWB					
		END
		OPEN LstAdicoes
		FETCH NEXT FROM LstAdicoes INTO @NumVols, @Parte, @CodEmbalagem, @Marcas, @CodArtigo, @DesignacaoArtigo, @PesoLiquido, @PesoBruto, @Valor, @Localizacao, @EstCarga			
		WHILE @@FETCH_STATUS = 0
		BEGIN		
-- calcula valores
			SET @NumLinha = @NumLinha + 1					 
-- insere adição nas Mercadorias na Entrada AEX								
			INSERT INTO AEX_ENLN(EDG_EANO, LME_CODI, EDG_NUME, ELN_NLIN, ELN_VOLS, ELN_PART, TEM_CODI, ELN_MARC, APA_CODI, ELN_DMER, ELN_PLIQ, ELN_PBRT, ELN_VALO, ELN_LOCA, ELN_EADU, ELN_UCRI, ELN_DCRI, 
				ELN_UALT, ELN_DALT)
			VALUES(@AnoAEX, @CodLocMercadorias, @NumeroAEX, @NumLinha, @NumVols, @Parte, @CodEmbalagem, @Marcas, @CodArtigo, @DesignacaoArtigo, @PesoLiquido, @PesoBruto, @Valor, @Localizacao, @EstCarga, 
				@Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())
			FETCH NEXT from LstAdicoes INTO @NumVols, @Parte, @CodEmbalagem, @Marcas, @CodArtigo, @DesignacaoArtigo, @PesoLiquido, @PesoBruto, @Valor, @Localizacao, @EstCarga
		END
		CLOSE LstAdicoes
		DEALLOCATE LstAdicoes		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) 
			+ ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_EntradasAEX_InsereViaExportacaoXMLouSDSViaAerea] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_EntradasAEX_InsereViaExportacaoXMLouSDSViaAerea] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EntradasAEX_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EntradasAEX_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das entradas AEX para migração de dados no novo sistema GIDWin
		SELECT edg.EDG_EANO, edg.LME_CODI, edg.EDG_NUME, edg.EDG_DATA, edg.EDG_PTRN, edg.EDG_TRNP, edg.EDG_REFI, edg.CLI_CODI, edg.EDG_ENOM, edg.EDG_EMOR, edg.EDG_ELOC, edg.EDG_ECPO, 
			edg.EDG_ELPO, edg.EDG_ENIF, edg.PAI_CODI, edg.FOR_CODI, edg.EDG_DNOM, edg.EDG_DMOR, edg.EDG_DLOC, edg.PAI_CODI1, edg.EDG_OBSE, edg.EDG_NEXT, edg.AGE_CODI, edg.EDG_EXPO, 
			eln.ELN_VOLS, eln.TEM_CODI, eln.ELN_MARC, eln.APA_CODI, eln.ELN_DMER, eln.ELN_PLIQ, eln.ELN_PBRT, eln.ELN_VALO, eln.ELN_LOCA, eln.ELN_EADU, eln.ELN_ALTU, eln.ELN_COMP, eln.ELN_LARG
		FROM AEX_ENDG AS edg WITH(NOLOCK)
			INNER JOIN AEX_ENLN AS eln WITH(NOLOCK) ON edg.EDG_EANO = eln.EDG_EANO AND edg.LME_CODI = eln.LME_CODI AND edg.EDG_NUME = eln.EDG_NUME AND eln.ELN_NLIN = 1
		ORDER BY edg.EDG_EANO, edg.LME_CODI, edg.EDG_NUME
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EntradasAEX_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EntradasAEX_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_execLiquidacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_execLiquidacao] @tipoEnti int, @codEnti varchar(18), @numCaucao varchar(24), @anoCaucao varchar(4), @tipCaucao varchar(1), @codAlfa varchar(8), @mes varchar(2), @ano varchar(4) AS
BEGIN
-- declaracao de variaveis
	DECLARE @MCA_IDEN int, @MCA_VLTT numeric(38,6), @TOTAL numeric(38,6), @MCA_DBCR int

	SELECT @MCA_DBCR = CAU_DCTR
	FROM TAB_CAUC WITH(NOLOCK)
	WHERE CAU_CODI = 'LIQI'

	IF @MCA_DBCR < 3 
	BEGIN
		SET @TOTAL = 0
	-- busca registos relacionados com a caução ------------------------------------- 
		DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT MCA_IDEN, (CASE MCA_DBCR WHEN 1 THEN MCA_VLTT ELSE (-1) * MCA_VLTT END)
			FROM PRO_MCAU
			WHERE MCA_TENT = @tipoEnti AND MCA_ENTI = @codEnti AND MCA_NCAU = @numCaucao AND MCA_CANO = @anoCaucao AND MCA_CTIP = @tipCaucao AND ALF_ORIG = @codAlfa AND MCA_PROV = 0 AND MCA_LIQD = 1 
				AND MONTH(dateadd(dd, MCA_NDIA, MCA_DORD)) = @mes AND YEAR(dateadd(dd, MCA_NDIA, MCA_DORD)) = @ano AND (MCA_NORD <> NULL OR MCA_NORD <> '') and CAU_CODI = 'DU'
		OPEN Detalhe
		FETCH NEXT from Detalhe into @MCA_IDEN, @MCA_VLTT
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @TOTAL = @TOTAL + @MCA_VLTT
			-- campo anulado a true para que os registo ca conta corrente não sejam removidos 
			UPDATE PRO_MCAU SET MCA_ANUL = 1
			WHERE MCA_IDEN = @MCA_IDEN
			-- remover o registo da tabela moviemntos de caução ---------------------
			DELETE FROM PRO_MCAU
			WHERE MCA_IDEN = @MCA_IDEN 

			FETCH NEXT from Detalhe into @MCA_IDEN, @MCA_VLTT
		END
		CLOSE Detalhe
		DEALLOCATE Detalhe		
		-- inserir registo com o total dos registos liquidados --------------------------
		INSERT INTO PRO_MCAU(MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO, MCA_CTIP, ALF_ORIG, MCA_DATA, CAU_CODI, MCA_VLTT, MCA_DBCR, ALF_DEST)
		VALUES(@tipoEnti, @codEnti, @numCaucao, @anoCaucao, @tipCaucao, @codAlfa, getdate(), 'LIQI', @TOTAL, @MCA_DBCR, '')
	END
END

ALTER AUTHORIZATION ON [SP_execLiquidacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_execLiquidacao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_Adicoes_ContentoresCopia]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_Adicoes_ContentoresCopia] @IdAdicao int, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @Contentor varchar(20), @Tipo varchar(10), @NumAdicaoSup1 int, @NumContentor int
-- inicia transacção para inserção dos contentores
	BEGIN TRANSACTION TspEXPCopiaContentores
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- insere os contentores da adição nas outras adições onde eles ainda não existem
		INSERT INTO tb_EXP_DeclaracoesAdicoesContentores(id_adicao, id_contentor, id_utilizadorControlo, dataControlo)
		SELECT daN.EXA_CHVE, a1c.id_contentor, @IdUtilizador, @DataAtual
		FROM PRO_EXAD AS da1 WITH(NOLOCK) 
			INNER JOIN tb_EXP_DeclaracoesAdicoesContentores AS a1c WITH(NOLOCK) ON da1.EXA_CHVE = a1c.id_adicao
			INNER JOIN PRO_EXAD AS daN WITH(NOLOCK) ON da1.EXM_EANO = daN.EXM_EANO AND da1.EXM_CODI = daN.EXM_CODI AND da1.EXM_COPE = daN.EXM_COPE AND da1.EXA_LINH < daN.EXA_LINH
			LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesContentores AS aNc WITH(NOLOCK) ON daN.EXA_CHVE = aNc.id_adicao AND a1c.id_contentor = aNc.id_contentor
		WHERE da1.EXA_CHVE = @IdAdicao AND aNc.id IS NULL		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspEXPCopiaContentores
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspEXPCopiaContentores
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_Adicoes_ContentoresCopia] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_Adicoes_ContentoresCopia] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_Adicoes_MarcasInsercaoRapida]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_Adicoes_MarcasInsercaoRapida] @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @SQLVariaveis nvarchar(MAX), @SQLAExecutar nvarchar(MAX)
	DECLARE @IdAdicao int, @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @IdMarca int, @Marcas varchar(512), @Volumes numeric(38, 6), @CodTipoEmbalagem varchar(2), 
		@NomeTipoEmbalagem varchar(35), @VolsAZero bit, @IdStrRegisto varchar(20)
	DECLARE @TblTmpMarcas TABLE(Estado int NOT NULL, IdAdicao int NOT NULL, Marcas varchar(512) NULL, Volumes numeric(38, 6) NOT NULL, CodTipoEmbalagem varchar(2) NULL, IdMarcas int NULL)
-- inicia transacção para a inserção das marcas e volumes
	BEGIN TRANSACTION TspEXPInsercaoRapidaMarcas
	BEGIN TRY	
		SET @NumErro = 0
-- constroi a lista de variáveis
		SET @SQLVariaveis = '@INMarcas varchar(512), @INVolumes numeric(38, 6), @INCodTipoEmbalagem varchar(2), @INNomeTipoEmbalagem varchar(35), @INVolsAZero bit, @INIdMarca int'
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- insere todos os dados das marcas e volumes na tabela tmp
		INSERT INTO @TblTmpMarcas(Estado, IdAdicao, Marcas, Volumes, CodTipoEmbalagem, IdMarcas)
		SELECT t.c.value('ESTADO[1]', 'int'), t.c.value('DUA_IDEN[1]', 'int'), t.c.value('D31_MARC[1]', 'varchar(512)'), ISNULL(t.c.value('D31_QNTD[1]', 'numeric(38, 6)'), 0), 
			t.c.value('UME_CODI[1]', 'varchar(2)'), t.c.value('D31_IDEN[1]', 'int')
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
-- obtem as marcas e volumes removidas
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT IdMarcas
			FROM @TblTmpMarcas
			WHERE Estado = 3			
		OPEN Marcas
		FETCH NEXT FROM Marcas INTO @IdMarca
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove a marca e volume
			DELETE FROM PRO_EXMV
			WHERE EXM_CHVE = @IdMarca
			FETCH NEXT FROM Marcas INTO @IdMarca
		END
		CLOSE Marcas
		DEALLOCATE Marcas
-- obtem as marcas e volumes editadas
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT tmp.IdMarcas, tmp.Marcas, tmp.Volumes, tmp.CodTipoEmbalagem, tem.TEM_NOME, tem.TEM_TVOL,  
				((CASE ISNULL(amv.EXM_MARN, '') WHEN ISNULL(tmp.Marcas, '') THEN '' ELSE 'EXM_MARN = @INMarcas, ' END) 					
					+ (CASE amv.EXM_NVOL WHEN tmp.Volumes THEN '' ELSE 'EXM_NVOL = @INVolumes, ' END)
					+ (CASE ISNULL(amv.TEM_CODI, '') WHEN ISNULL(tmp.CodTipoEmbalagem, '') THEN '' ELSE 'TEM_CODI = @INCodTipoEmbalagem, TEM_NOME = @INNomeTipoEmbalagem, EXM_TVOL = @INVolsAZero, ' END))
			FROM @TblTmpMarcas AS tmp 
				INNER JOIN PRO_EXMV AS amv WITH(NOLOCK) ON tmp.IdMarcas = amv.EXM_CHVE
				LEFT OUTER JOIN TAB_TEMB AS tem WITH(NOLOCK) ON tmp.CodTipoEmbalagem = tem.TEM_CODI
			WHERE tmp.Estado = 2			
		OPEN Marcas
		FETCH NEXT FROM Marcas INTO @IdMarca, @Marcas, @Volumes, @CodTipoEmbalagem, @NomeTipoEmbalagem, @VolsAZero, @SQLAExecutar
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove o caracter "," existente no final
			SET @SQLAExecutar = REVERSE(@SQLAExecutar)
			SET @SQLAExecutar = STUFF(@SQLAExecutar, 2, 1, '')
			SET @SQLAExecutar = REVERSE(@SQLAExecutar)
-- constroi o SQL p/ UPDATE
			SET @SQLAExecutar = 'UPDATE PRO_EXMV SET ' + @SQLAExecutar + 'WHERE EXM_CHVE = @INIdMarca'
-- edita a marca e volume
			EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INMarcas = @Marcas, @INVolumes = @Volumes, @INCodTipoEmbalagem = @CodTipoEmbalagem, @INNomeTipoEmbalagem = @NomeTipoEmbalagem, 
				@INVolsAZero = @VolsAZero, @INIdMarca = @IdMarca
			FETCH NEXT FROM Marcas INTO @IdMarca, @Marcas, @Volumes, @CodTipoEmbalagem, @NomeTipoEmbalagem, @VolsAZero, @SQLAExecutar
		END
		CLOSE Marcas
		DEALLOCATE Marcas
-- obtem as marcas e volumes inseridas
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT tmp.IdAdicao, tmp.Marcas, tmp.Volumes, tmp.CodTipoEmbalagem, tem.TEM_NOME, tem.TEM_TVOL, adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE
			FROM @TblTmpMarcas AS tmp 				
				INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON tmp.IdAdicao = adi.EXA_CHVE
				LEFT OUTER JOIN TAB_TEMB AS tem WITH(NOLOCK) ON tmp.CodTipoEmbalagem = tem.TEM_CODI
			WHERE tmp.Estado = 1			
		OPEN Marcas
		FETCH NEXT FROM Marcas INTO  @IdAdicao, @Marcas, @Volumes, @CodTipoEmbalagem, @NomeTipoEmbalagem, @VolsAZero, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			SET @IdStrRegisto = REPLACE(LTRIM(STR(CAST(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT() AS numeric(20, 10)) + (CAST(@IdAdicao AS numeric(20, 10)) / 10000000000), 20, 10)), '.', ',')
-- insere a marca e volume
			INSERT INTO PRO_EXMV(EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_TVOL, EXM_IDST, EXM_EANO, EXM_CODI, EXM_COPE)
			VALUES(@IdAdicao, @Marcas, @CodTipoEmbalagem, @NomeTipoEmbalagem, @Volumes, @VolsAZero, @IdStrRegisto, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao)
			FETCH NEXT FROM Marcas INTO @IdAdicao, @Marcas, @Volumes, @CodTipoEmbalagem, @NomeTipoEmbalagem, @VolsAZero, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		END
		CLOSE Marcas
		DEALLOCATE Marcas
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspEXPInsercaoRapidaMarcas
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspEXPInsercaoRapidaMarcas
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_Adicoes_MarcasInsercaoRapida] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_Adicoes_MarcasInsercaoRapida] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_AdicoesEdita]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_AdicoesEdita] @IdAdicao int, @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @NumAdicao int, @CodArtigo varchar(22), 
	@PesoLiquido numeric(38, 6), @PesoBruto numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), @CodPaisOrigem varchar(2), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @ValorFormatado varchar(40)
	DECLARE @CodUnidSuplementar varchar(10), @Desdobramento1 varchar(3), @ArtigoAlterado bit, @PaisOrigemAlterado bit, @PesoBrutoAlterado bit, @PesoLiquidoAlterado bit, @UnidadesAlterada bit, 
		@MontanteAlterado bit
	DECLARE @FormulaCondEntrega varchar(70), @MontanteTotal numeric(38, 6), @CambioMontante numeric(38, 6), @FreteTotal numeric(38, 6), @CambioFrete numeric(38, 6), @SeguroTotal numeric(38, 6), 
		@CambioSeguro numeric(38, 6), @MassaBrutaTotal numeric(38, 6), @Seguranca tinyint, @AnexoB varchar(2)
	DECLARE @SomaMontantesAdicoes numeric(38, 6), @SomaFretesAdicoes numeric(38, 6), @SomaSegurosAdicoes numeric(38, 6)
	DECLARE @CodigoPautal varchar(22), @Designacao varchar(150), @CodigoATAR varchar(10), @CodigoIC1 varchar(4), @CodigoIC2 varchar(4), @CodigoIC3 varchar(4), @CodigoIC4 varchar(4), 
		@CodigoIC5 varchar(4), @CodigoCCUS varchar(9), @IndicadorRestituicoes varchar(2), @AnexoC bit, @AnexoD bit, @AdicionalTARIC1 varchar(4), @AdicionalTARIC2 varchar(4), 
		@AdicionalTARIC3 varchar(4)
	DECLARE @NomePaisOrigem varchar(35)
	DECLARE @NomeUnidSuplementar varchar(10)
	DECLARE @Frete numeric(38, 6), @Seguro numeric(38, 6), @ValorEUR numeric(38, 6), @Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6)
-- inicia processo de inserção da adição
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem dados atuais da adição e verifica que colunas da adição é para editar		
		SELECT @CodUnidSuplementar = USU_CODI, @Desdobramento1 = EXA_DESD, 
			@ArtigoAlterado = (CASE ISNULL(APA_CO33, '') WHEN ISNULL(@CodArtigo, '') THEN 0 ELSE 1 END), 
			@PaisOrigemAlterado = (CASE ISNULL(PAI_CODI, '') WHEN ISNULL(@CodPaisOrigem, '') THEN 0 ELSE 1 END), 
			@PesoBrutoAlterado = (CASE ISNULL(EXA_MBRT, 0) WHEN ISNULL(@PesoBruto, 0) THEN 0 ELSE 1 END), 			
			@PesoLiquidoAlterado = (CASE ISNULL(EXA_MLQD, 0) WHEN ISNULL(@PesoLiquido, 0) THEN 0 ELSE 1 END), 
			@UnidadesAlterada = (CASE ISNULL(EXA_QUSU, 0) WHEN ISNULL(@Unidades, 0) THEN 0 ELSE 1 END), 
			@MontanteAlterado = (CASE ISNULL(EXA_VALO, 0) WHEN ISNULL(@Montante, 0) THEN 0 ELSE 1 END)
		FROM PRO_EXAD WITH(NOLOCK)			
		WHERE EXA_CHVE = @IdAdicao
-- valida artigo
		IF (@ArtigoAlterado = 1) AND (NOT EXISTS(SELECT 1 FROM TAB_APAU WITH(NOLOCK) WHERE APA_CODI = @CodArtigo AND APA_INAC = 0 AND APA_FLUX IN (0, 2)))
			RAISERROR ('Código do artigo "%s" inexistente ou não está devidamente configurado.', 16, 1, @CodArtigo)
-- valida país de origem
		IF (@PaisOrigemAlterado = 1) AND (ISNULL(@CodPaisOrigem, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem))
			RAISERROR ('Código do país de origem "%s" inexistente.', 16, 3, @CodPaisOrigem)
-- valida peso líquido
		IF (@PesoLiquidoAlterado = 1) AND (ISNULL(@PesoLiquido, 0) < 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoLiquido, 38, 6))
			RAISERROR ('Peso líquido "%s" inválido.', 16, 4, @ValorFormatado)
		END
-- valida peso bruto
		IF (@PesoBrutoAlterado = 1) AND (ISNULL(@PesoBruto, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoBruto, 38, 6))
			RAISERROR ('Peso bruto "%s" inválido.', 16, 5, @ValorFormatado)
		END
-- valida montante
		IF (@MontanteAlterado = 1) AND (ISNULL(@Montante, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR ('Montante "%s" inválido.', 16, 6, @ValorFormatado)
		END
-- obtem dados da declaração
		SELECT @FormulaCondEntrega = ISNULL(EXM_FR20, ''), @MontanteTotal = ISNULL(EXM_MT22, 0), @CambioMontante = ISNULL(EXM_TX23, 0), @FreteTotal = ISNULL(EXM_TFRT, 0), 
			@SeguroTotal = ISNULL(EXM_TSEG, 0), @MassaBrutaTotal = ISNULL(EXM_TMBR, 0), @Seguranca = EXM_SEGU, @CambioFrete = EXM_CFRE, @CambioSeguro = EXM_CSEG, @AnexoB = EXM_ANXB
		FROM PRO_EXML WITH(NOLOCK) 									
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodOperadorDeclaracao 
-- obtem dados das adições já existentes				
		SELECT @SomaMontantesAdicoes = ISNULL(SUM(EXA_VALO), 0), @SomaFretesAdicoes = ISNULL(SUM(ISNULL(EXA_VFRE, 0)), 0), @SomaSegurosAdicoes = ISNULL(SUM(ISNULL(EXA_VSEG, 0)), 0)			
		FROM PRO_EXAD WITH(NOLOCK)
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao AND EXA_CHVE <> @IdAdicao
-- valida se montante é válido na declaração
		IF (@MontanteAlterado = 1) AND ((@MontanteTotal - @SomaMontantesAdicoes - @Montante) < 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR ('Montante "%s" inválido porque é superior ao montante total disponível', 16, 7, @ValorFormatado)
		END
-- valida país origem
		IF (@PaisOrigemAlterado = 1) AND (LEFT(@Desdobramento1, 1) = 'E') AND (ISNULL(@CodPaisOrigem, '') = '') 		
			RAISERROR ('País de origem obrigatório.', 16, 8)
-- obtem dados do artigo
		IF @ArtigoAlterado = 1
		BEGIN
			SELECT @CodigoPautal = apa.APA_CPAU, @CodUnidSuplementar = apa.USU_CODI, @Designacao = ISNULL(NULLIF(@Designacao, ''), apa.APA_DESG), @IndicadorRestituicoes = apa.APA_INDI, 
				@AnexoC = apa.APA_ANXC, @AnexoD = apa.APA_ANXD, @CodigoIC1 = apa.APA_AIC1, @CodigoIC2 = apa.APA_AIC2, @CodigoIC3 = apa.APA_AIC3, @CodigoIC4 = apa.APA_AIC4, 
				@CodigoIC5 = apa.APA_AIC5, @AdicionalTARIC1 = SUBSTRING(apa.APA_CPAU, 11, 4), @AdicionalTARIC2 = SUBSTRING(apa.APA_CPAU, 15, 4), @AdicionalTARIC3 = SUBSTRING(apa.APA_CPAU, 19, 4), 
				@CodigoATAR = (CASE @Seguranca
								WHEN 2 THEN apa.APA_ATAR
								ELSE NULL 
							END),  
				@CodigoCCUS = (CASE @AnexoB
								WHEN 'B1' THEN apa.APA_CCUS
								ELSE NULL 
							END)									
			FROM TAB_APAU AS apa WITH(NOLOCK)
			WHERE APA_CODI = @CodArtigo
-- obtem dados da unidade suplementar
			SELECT @NomeUnidSuplementar = USU_SIGL
			FROM TAB_USUP WITH(NOLOCK)
			WHERE USU_CODI = @CodUnidSuplementar
		END
-- valida unidades
		IF (@UnidadesAlterada = 1) AND (ISNULL(@CodUnidSuplementar, '') <> '') AND (ISNULL(@Unidades, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
			RAISERROR ('Unidades "%s" inválida.', 16, 9, @ValorFormatado)
		END
		ELSE
			IF (@UnidadesAlterada = 1) AND (ISNULL(@CodUnidSuplementar, '') = '') AND (ISNULL(@Unidades, 0) > 0)
			BEGIN
				SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
				RAISERROR ('Unidades "%s" inválida.', 16, 10, @ValorFormatado)
			END			
-- obtem dados do país de origem
		IF @PaisOrigemAlterado = 1
		BEGIN			
			SELECT @NomePaisOrigem = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPaisOrigem
		END
-- calcula os valores da adição				
		SET @Frete = ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
								WHEN 0 THEN (@FreteTotal - @SomaFretesAdicoes) 
								ELSE (@PesoBruto * @FreteTotal / @MassaBrutaTotal) 
							END), 3)
		SET @Seguro = ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
								WHEN 0 THEN (@SeguroTotal - @SomaSegurosAdicoes) 
								ELSE (@Montante * @SeguroTotal / @MontanteTotal) 
							END), 3)		
		SET @ValorEUR = ROUND(@Montante / @CambioMontante, 2)
		SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@FormulaCondEntrega, 0, @CambioFrete, @CambioSeguro, @Frete, @Seguro, 0, 0, 0)
		SET @ValorEstatistico = dbo.fn_IMP_CalculaValorEstatistico(@ValorEUR, @Ajustamento)		
-- constroi a lista de variáveis
		DECLARE @SQLVariaveis nvarchar(MAX), @SQLAExecutar nvarchar(MAX)
		SET @SQLVariaveis = '@INCodArtigo varchar(22), @INCodigoPautal varchar(22), @INDesignacao varchar(150), @INCodUnidSuplementar varchar(10), @INNomeUnidSuplementar varchar(10), '
		SET @SQLVariaveis = @SQLVariaveis + '@INIndicadorRestituicoes varchar(2), @INAnexoC bit, @INAnexoD bit, @INCodigoATAR varchar(10), @INAdicionalTARIC1 varchar(4), '
		SET @SQLVariaveis = @SQLVariaveis + '@INAdicionalTARIC2 varchar(4), @INAdicionalTARIC3 varchar(4), @INCodigoIC1 varchar(4), @INCodigoIC2 varchar(4), @INCodigoIC3 varchar(4), '
		SET @SQLVariaveis = @SQLVariaveis + '@INCodigoIC4 varchar(4), @INCodigoIC5 varchar(4), @INCodigoCCUS varchar(9), @INCodPaisOrigem varchar(2), @INNomePaisOrigem varchar(35), '
		SET @SQLVariaveis = @SQLVariaveis + '@INPesoBruto numeric(38, 6), @INFrete numeric(38, 6), @INPesoLiquido numeric(38, 6), @INMontante numeric(38, 6), @INSeguro numeric(38, 6), '
		SET @SQLVariaveis = @SQLVariaveis + '@INUnidades numeric(38, 6), @INValorEstatistico numeric(38, 6), @INAjustamento numeric(38, 6), @INIdAdicao int'
-- constroi o SQL p/ UPDATE
		SET @SQLAExecutar = 'UPDATE PRO_EXAD SET '
		IF @ArtigoAlterado = 1		
		BEGIN
			SET @SQLAExecutar = @SQLAExecutar + 'APA_CO33 = @INCodArtigo, APA_CP33 = @INCodigoPautal, APA_DESG = @INDesignacao, USU_CODI = @INCodUnidSuplementar, USU_SIGL = @INNomeUnidSuplementar, '
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_IRES = @INIndicadorRestituicoes, EXA_ANXC = @INAnexoC, EXA_ANXD = @INAnexoD, EXA_ATAR = @INCodigoATAR, EXA_ATA1 = @INAdicionalTARIC1, '
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_ATA2 = @INAdicionalTARIC2, EXA_ATA3 = @INAdicionalTARIC3, EXA_AIC1 = @INCodigoIC1, EXA_AIC2 = @INCodigoIC2, EXA_AIC3 = @INCodigoIC3, '
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_AIC4 = @INCodigoIC4, EXA_AIC5 = @INCodigoIC5, EXA_CCUS = @INCodigoCCUS, '			
		END
		IF @PaisOrigemAlterado = 1
			SET @SQLAExecutar = @SQLAExecutar + 'PAI_CODI = @INCodPaisOrigem, PAI_NOME = @INNomePaisOrigem, '				
		IF @PesoBrutoAlterado = 1		
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_MBRT = @INPesoBruto, EXA_VFRE = @INFrete, '		
		IF @PesoLiquidoAlterado = 1
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_MLQD = @INPesoLiquido, '		
		IF @MontanteAlterado = 1		
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_VALO = @INMontante, EXA_VSEG = @INSeguro, '		
		IF @UnidadesAlterada = 1
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_QUSU = @INUnidades, '				
		IF (@PesoBrutoAlterado = 1) OR (@MontanteAlterado = 1) 
			SET @SQLAExecutar = @SQLAExecutar + 'EXA_VEST = @INValorEstatistico, EXA_AJUS = @INAjustamento, '		
		SET @SQLAExecutar = @SQLAExecutar + 'EXA_TSTP = EXA_TSTP '
		SET @SQLAExecutar = @SQLAExecutar + 'WHERE EXA_CHVE = @INIdAdicao'
-- edita a adição
		EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INCodArtigo = @CodArtigo, @INCodigoPautal = @CodigoPautal, @INDesignacao = @Designacao, @INCodUnidSuplementar = @CodUnidSuplementar, 
			@INNomeUnidSuplementar = @NomeUnidSuplementar, @INIndicadorRestituicoes = @IndicadorRestituicoes, @INAnexoC = @AnexoC, @INAnexoD = @AnexoD, @INCodigoATAR = @CodigoATAR, 
			@INAdicionalTARIC1 = @AdicionalTARIC1, @INAdicionalTARIC2 = @AdicionalTARIC2, @INAdicionalTARIC3 = @AdicionalTARIC3, @INCodigoIC1 = @CodigoIC1, @INCodigoIC2 = @CodigoIC2, 
			@INCodigoIC3 = @CodigoIC3, @INCodigoIC4 = @CodigoIC4, @INCodigoIC5 = @CodigoIC5, @INCodigoCCUS = @CodigoCCUS, @INCodPaisOrigem = @CodPaisOrigem, @INNomePaisOrigem = @NomePaisOrigem, 
			@INPesoBruto = @PesoBruto, @INFrete = @Frete, @INPesoLiquido = @PesoLiquido, @INMontante = @Montante, @INSeguro = @Seguro, @INUnidades = @Unidades, 
			@INValorEstatistico = @ValorEstatistico, @INAjustamento = @Ajustamento, @INIdAdicao = @IdAdicao		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_AdicoesEdita] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_AdicoesEdita] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_AdicoesImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_AdicoesImportaXLSX] @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @CodArtigo varchar(22), @PesoLiq numeric(38, 6), @PesoBrt numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), 
		@CodPaisOrigem varchar(2), @Resultado int, @MsgErro varchar(MAX)
	DECLARE @TblTmpAdicoes TABLE(CodArtigo varchar(22) NOT NULL, PesoLiq numeric(38, 6) NOT NULL, PesoBrt numeric(38, 6) NOT NULL, Montante numeric(38, 6) NOT NULL, 
		Unidades numeric(38, 6) NOT NULL, CodPaisOrigem varchar(2) NULL)
-- inicia transacção para a inserção das adições
	BEGIN TRANSACTION TspEXPAdicoesImportaXLSX
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- insere todos os dados das adições do ficheiro na tabela tmp
		INSERT INTO @TblTmpAdicoes(CodArtigo, PesoLiq, PesoBrt, Montante, Unidades, CodPaisOrigem)
		SELECT t.c.value('CODIGO[1]', 'varchar(22)'), ISNULL(t.c.value('PLIQUIDO[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('PBRUTO[1]', 'numeric(38, 6)'), 0), 
			ISNULL(t.c.value('MONTANTE[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('UNIDADES[1]', 'numeric(38, 6)'), 0), NULLIF(t.c.value('PO[1]', 'varchar(2)'), '')
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
-- obtem as adições do ficheiro agrupadas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT CodArtigo, CodPaisOrigem, SUM(PesoLiq), SUM(PesoBrt), SUM(Montante), SUM(Unidades)
			FROM @TblTmpAdicoes
			GROUP BY CodArtigo, CodPaisOrigem
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- insere a adição
			EXEC @Resultado = sp_EXP_Declaracoes_AdicoesInsere @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, NULL, @CodArtigo, @PesoLiq, @PesoBrt, @Montante, @Unidades, @CodPaisOrigem, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, @MsgErro OUTPUT
			IF @Resultado > 0
				RAISERROR ('Erro na inserção da adição! ERRO: "%s".', 16, 1, @MsgErro)	
			FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspEXPAdicoesImportaXLSX
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspEXPAdicoesImportaXLSX
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_AdicoesImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_AdicoesImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_AdicoesInsercaoRapida]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_AdicoesInsercaoRapida] @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @FicheiroXLSX varchar(MAX), @IdUtilizador int, 
	@Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @GlobalizaAdicoes bit, @CodArtigo varchar(22), @PesoLiq numeric(38, 6), @PesoBrt numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), 
		@CodPaisOrigem varchar(2), @NumAdicao int, @IdAdicao int, @Resultado int, @MsgErro varchar(MAX)
	DECLARE @TblTmpAdicoes TABLE(Estado int NOT NULL, CodArtigo varchar(22) NOT NULL, PesoLiq numeric(38, 6) NOT NULL, PesoBrt numeric(38, 6) NOT NULL, Montante numeric(38, 6) NOT NULL, 
		Unidades numeric(38, 6) NOT NULL, CodPaisOrigem varchar(2) NOT NULL, NumAdicao int NULL, IdAdicao int NULL)
-- inicia transacção para a inserção das adições
	BEGIN TRANSACTION TspEXPAdicoesInsercaoRapida
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- obtem se utilizador globaliza as adições
		SELECT @GlobalizaAdicoes = UTI_GLBA
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- insere todos os dados das adições na tabela tmp
		INSERT INTO @TblTmpAdicoes(Estado, CodArtigo, PesoLiq, PesoBrt, Montante, Unidades, CodPaisOrigem, NumAdicao, IdAdicao)
		SELECT t.c.value('ESTADO[1]', 'int'), t.c.value('APA_CO33[1]', 'varchar(22)'), ISNULL(t.c.value('DUA_ML38[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('DUA_MB35[1]', 'numeric(38, 6)'), 0), 
			ISNULL(t.c.value('DUA_VA42[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('DUA_US41[1]', 'numeric(38, 6)'), 0), t.c.value('PAI_CO34[1]', 'varchar(2)'), 
			t.c.value('DUA_CODI[1]', 'int'), t.c.value('DUA_IDEN[1]', 'int')
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
-- obtem as adições removidas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT IdAdicao
			FROM @TblTmpAdicoes
			WHERE Estado = 3			
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- remove a adição
			DELETE FROM PRO_EXAD
			WHERE EXA_CHVE = @IdAdicao			
			FETCH NEXT FROM Adicoes INTO @IdAdicao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem as adições editadas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT IdAdicao, NumAdicao, CodArtigo, CodPaisOrigem, PesoLiq, PesoBrt, Montante, Unidades
			FROM @TblTmpAdicoes
			WHERE Estado = 2			
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumAdicao, @CodArtigo, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- edita a adição
			EXEC @Resultado = sp_EXP_Declaracoes_AdicoesEdita @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodArtigo, @PesoLiq, @PesoBrt, @Montante, @Unidades, @CodPaisOrigem, @MsgErro OUTPUT			
			IF @Resultado > 0
				RAISERROR ('Erro na edição da adição! ERRO: "%s".', 16, 1, @MsgErro)	
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumAdicao, @CodArtigo, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem as adições inseridas agrupadas ou não conforme a configuraçãpo do utilizador
		IF @GlobalizaAdicoes = 1
		BEGIN
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT CodArtigo, CodPaisOrigem, SUM(PesoLiq), SUM(PesoBrt), SUM(Montante), SUM(Unidades)
				FROM @TblTmpAdicoes
				WHERE Estado = 1
				GROUP BY CodArtigo, CodPaisOrigem
		END
		ELSE
		BEGIN
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT CodArtigo, CodPaisOrigem, PesoLiq, PesoBrt, Montante, Unidades
				FROM @TblTmpAdicoes
				WHERE Estado = 1				
		END					
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- insere a adição
			EXEC @Resultado = sp_EXP_Declaracoes_AdicoesInsere @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, NULL, @CodArtigo, @PesoLiq, @PesoBrt, @Montante, @Unidades, @CodPaisOrigem, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, @MsgErro OUTPUT
			IF @Resultado > 0
				RAISERROR ('Erro na inserção da adição! ERRO: "%s".', 16, 2, @MsgErro)	
			FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspEXPAdicoesInsercaoRapida
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspEXPAdicoesInsercaoRapida
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_AdicoesInsercaoRapida] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_AdicoesInsercaoRapida] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_AdicoesInsere]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_AdicoesInsere] @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @NumAdicao int, @CodArtigo varchar(22), @PesoLiquido numeric(38, 6), 
	@PesoBruto numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), @CodPaisOrigem varchar(2), @Designacao varchar(150), @Desdobramento1 varchar(3), @Frete numeric(38, 6), 
	@Seguro numeric(38, 6), @CodNatTransacaoAd varchar(2), @CodFornecedorDestinatarioAd varchar(18), @CodPaisDestinoAd varchar(2), @IdAdicao int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID int NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @ValorFormatado varchar(40)
	DECLARE @TipoDeclaracaoAdicional varchar(1), @TotalAdicoes int, @CodFornDestinatario varchar(18), @CodPaisDestino varchar(2), @FormulaCondEntrega varchar(70), @CodNatTransacao varchar(2), 
		@MontanteTotal numeric(38, 6), @CambioMontante numeric(38, 6), @FreteTotal numeric(38, 6), @CambioFrete numeric(38, 6), @SeguroTotal numeric(38, 6), @CambioSeguro numeric(38, 6), 
		@MassaBrutaTotal numeric(38, 6), @Seguranca tinyint, @AnexoB varchar(2), @Regime varchar(4), @1CasaTipoDeclaracao varchar(5), @DesdobramentoTipoDeclaracao varchar(3), 
		@CodPaisExpedicaoAd varchar(2)	
	DECLARE @SomaMontantesAdicoes numeric(38, 6), @SomaFretesAdicoes numeric(38, 6), @SomaSegurosAdicoes numeric(38, 6)
	DECLARE @IdDesdobramento int
	DECLARE @CodigoPautal varchar(22), @CodUnidSuplementar varchar(10), @CodigoATAR varchar(10), @CodigoIC1 varchar(4), @CodigoIC2 varchar(4), @CodigoIC3 varchar(4), @CodigoIC4 varchar(4), 
		@CodigoIC5 varchar(4), @CodigoCCUS varchar(9), @IndicadorRestituicoes varchar(2), @AnexoC bit, @AnexoD bit, @AdicionalTARIC1 varchar(4), @AdicionalTARIC2 varchar(4), 
		@AdicionalTARIC3 varchar(4)
	DECLARE @NomePaisOrigem varchar(35)
	DECLARE @NomeUnidSuplementar varchar(10)
	DECLARE @NomeFornDestinatario varchar(70), @MoradaFornDestinatario varchar(70), @LocalidadeFornDestinatario varchar(35), @CodigoPostalFornDestinatario varchar(12),  
		@LocalidadePostalFornDestinatario varchar(35), @NIFFornDestinatario varchar(17), @CodPaisFornDestinatario varchar(2)		
	DECLARE @ValorEUR numeric(38, 6), @Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6)
-- inicia processo de inserção da adição
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- valida artigo
		IF NOT EXISTS(SELECT 1 FROM TAB_APAU WITH(NOLOCK) WHERE APA_CODI = @CodArtigo AND APA_INAC = 0 AND APA_FLUX IN (0, 2))
			RAISERROR ('Código do artigo "%s" inexistente ou não está devidamente configurado.', 16, 1, @CodArtigo)
-- valida país de origem
		IF (ISNULL(@CodPaisOrigem, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem))
			RAISERROR ('Código do país de origem "%s" inexistente.', 16, 2, @CodPaisOrigem)
-- valida natureza de transação
		IF (ISNULL(@CodNatTransacaoAd, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_NTRA WITH(NOLOCK) WHERE NTR_CODI = @CodNatTransacaoAd))
			RAISERROR ('Código da natureza de transação "%s" inexistente.', 16, 3, @CodNatTransacaoAd)
-- valida destinatário
		IF (ISNULL(@CodFornecedorDestinatarioAd, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_FORN WITH(NOLOCK) WHERE FOR_CODI = @CodFornecedorDestinatarioAd AND FOR_INAC = 0 AND FOR_DESP = 1))
			RAISERROR ('Código do destinatário "%s" inexistente ou não está devidamente configurado.', 16, 4, @CodFornecedorDestinatarioAd)
-- valida país de destino
		IF (ISNULL(@CodPaisDestinoAd, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisDestinoAd))
			RAISERROR ('Código do país de destino "%s" inexistente.', 16, 5, @CodPaisDestinoAd)
-- valida peso líquido
		IF ISNULL(@PesoLiquido, 0) < 0
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoLiquido, 38, 6))
			RAISERROR ('Peso líquido "%s" inválido.', 16, 6, @ValorFormatado)
		END
-- valida peso bruto
		IF ISNULL(@PesoBruto, 0) <= 0
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoBruto, 38, 6))
			RAISERROR ('Peso bruto "%s" inválido.', 16, 7, @ValorFormatado)
		END
		ELSE
			IF ISNULL(@PesoBruto, 0) < ISNULL(@PesoLiquido, 0)
				RAISERROR ('Peso bruto inferior ao peso líquido.', 16, 8)
-- valida montante
		IF ISNULL(@Montante, 0) <= 0
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR ('Montante "%s" inválido.', 16, 9, @ValorFormatado)
		END
-- obtem dados da declaração		
		SELECT @TipoDeclaracaoAdicional = dex.EXM_TPRO, @TotalAdicoes = ISNULL(dex.EXM_TAD5, 0), @CodFornDestinatario = dex.FOR_COD8, @CodPaisDestino = dex.EXM_P17A, 
			@FormulaCondEntrega = ISNULL(dex.EXM_FR20, ''), @CodNatTransacao = dex.NTR_CO24, @MontanteTotal = ISNULL(dex.EXM_MT22, 0), @CambioMontante = ISNULL(dex.EXM_TX23, 0), 
			@FreteTotal = ISNULL(dex.EXM_TFRT, 0), @SeguroTotal = ISNULL(dex.EXM_TSEG, 0), @MassaBrutaTotal = ISNULL(dex.EXM_TMBR, 0), @Seguranca = dex.EXM_SEGU, @CambioFrete = dex.EXM_CFRE, 
			@CambioSeguro = dex.EXM_CSEG, @AnexoB = dex.EXM_ANXB, @Regime = dex.EXM_REGI, 
			@1CasaTipoDeclaracao = tde.TDE_1CAS, @DesdobramentoTipoDeclaracao = tde.TDE_DESD, 
			@CodPaisExpedicaoAd = (CASE ISNULL(dex.EXM_P15A, '')
									WHEN '' THEN (SELECT PAI_CODI FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = 'PT') 
									ELSE NULL 
								END)
		FROM PRO_EXML AS dex WITH(NOLOCK) 			
			INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON dex.TDE_COD1 = tde.TDE_CODI						
		WHERE dex.EXM_EANO = @AnoDeclaracao AND dex.EXM_CODI = @CodDeclaracao AND dex.DEC_CODI = @CodOperadorDeclaracao 
-- valida natureza transação
		IF (@TipoDeclaracaoAdicional IN ('A', 'D', 'R', 'X', 'Y', 'Z')) AND (LEFT(@Regime, 2) NOT IN ('71', '76')) AND (ISNULL(@CodNatTransacao, '') = '') AND (ISNULL(@CodNatTransacaoAd, '') = '') 		
			RAISERROR ('Natureza de transação obrigatória.', 16, 10)		
		ELSE
			IF ((@TipoDeclaracaoAdicional IN ('B', 'C', 'E', 'F')) OR (ISNULL(@CodNatTransacao, '') <> '')) AND (ISNULL(@CodNatTransacaoAd, '') <> '') 		
				RAISERROR ('Natureza de transação "%s" não pode ser especificada.', 16, 11, @CodNatTransacaoAd)		
-- valida destinatário
		IF (ISNULL(@CodFornDestinatario, '') = '') AND (ISNULL(@CodFornecedorDestinatarioAd, '') = '') 		
			RAISERROR ('Destinatário obrigatório.', 16, 12)
		ELSE
			IF (ISNULL(@CodFornDestinatario, '') <> '') AND (ISNULL(@CodFornecedorDestinatarioAd, '') <> '') 		
				RAISERROR ('Destinatário "%s" não pode ser especificado.', 16, 13, @CodFornecedorDestinatarioAd)
-- obtem dados do fornecedor destinatário
		SELECT @NomeFornDestinatario = NULLIF(FOR_NOME, ''), @MoradaFornDestinatario = NULLIF(FOR_MORA, ''), @LocalidadeFornDestinatario = NULLIF(FOR_LOCA, ''), 
			@CodigoPostalFornDestinatario = NULLIF(FOR_CPOS, ''), @LocalidadePostalFornDestinatario = NULLIF(FOR_LPOS, ''), @NIFFornDestinatario = NULLIF(FOR_NIF, ''), 
			@CodPaisFornDestinatario = PAI_CODI
		FROM TAB_FORN WITH(NOLOCK)
		WHERE FOR_CODI = @CodFornecedorDestinatarioAd
-- inicia país destino
		IF (ISNULL(@CodPaisDestino, '') = '') AND (ISNULL(@CodPaisDestinoAd, '') = '')
			SET @CodPaisDestinoAd = @CodPaisFornDestinatario
-- valida país destino
		IF (ISNULL(@CodPaisDestino, '') = '') AND (ISNULL(@CodPaisDestinoAd, '') = '') 		
			RAISERROR ('País de destino obrigatório.', 16, 14)
		ELSE
			IF (ISNULL(@CodPaisDestino, '') <> '') AND (ISNULL(@CodPaisDestinoAd, '') <> '') 		
				RAISERROR ('País de destino "%s" não pode ser especificado.', 16, 15, @CodPaisDestinoAd)
-- obtem dados das adições já existentes		
		SELECT @SomaMontantesAdicoes = ISNULL(SUM(EXA_VALO), 0), @SomaFretesAdicoes = ISNULL(SUM(ISNULL(EXA_VFRE, 0)), 0), @SomaSegurosAdicoes = ISNULL(SUM(ISNULL(EXA_VSEG, 0)), 0)			
		FROM PRO_EXAD WITH(NOLOCK)
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao
-- valida se montante é válido na declaração
		IF (@MontanteTotal - @SomaMontantesAdicoes - @Montante) < 0
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR ('Montante "%s" inválido porque é superior ao montante total disponível', 16, 16, @ValorFormatado)
		END
-- obtem dados do desdobramento de regime		
		SELECT @IdDesdobramento = id, @Desdobramento1 = desdobramento1
		FROM tb_TBL_Desdobramentos WITH(NOLOCK) 
		WHERE tipoDeclaracao = @1CasaTipoDeclaracao AND regime = @Regime AND desdobramento1 = ISNULL(NULLIF(@Desdobramento1, ''), @DesdobramentoTipoDeclaracao)
-- valida país origem
		IF (LEFT(@Desdobramento1, 1) = 'E') AND (ISNULL(@CodPaisOrigem, '') = '') 		
			RAISERROR ('País de origem obrigatório.', 16, 17)
-- obtem dados do artigo		
		SELECT @CodigoPautal = apa.APA_CPAU, @CodUnidSuplementar = apa.USU_CODI, @Designacao = ISNULL(NULLIF(@Designacao, ''), apa.APA_DESG), @IndicadorRestituicoes = apa.APA_INDI, 
			@AnexoC = apa.APA_ANXC, @AnexoD = apa.APA_ANXD, @CodigoIC1 = apa.APA_AIC1, @CodigoIC2 = apa.APA_AIC2, @CodigoIC3 = apa.APA_AIC3, @CodigoIC4 = apa.APA_AIC4, @CodigoIC5 = apa.APA_AIC5, 
			@AdicionalTARIC1 = SUBSTRING(apa.APA_CPAU, 11, 4), @AdicionalTARIC2 = SUBSTRING(apa.APA_CPAU, 15, 4), @AdicionalTARIC3 = SUBSTRING(apa.APA_CPAU, 19, 4), 
			@CodigoATAR = (CASE @Seguranca
							WHEN 2 THEN apa.APA_ATAR
							ELSE NULL 
						END),  
			@CodigoCCUS = (CASE @AnexoB
							WHEN 'B1' THEN apa.APA_CCUS
							ELSE NULL 
						END)									
		FROM TAB_APAU AS apa WITH(NOLOCK)
		WHERE APA_CODI = @CodArtigo
-- valida unidades
		IF (ISNULL(@CodUnidSuplementar, '') <> '') AND (ISNULL(@Unidades, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
			RAISERROR ('Unidades "%s" inválida.', 16, 18, @ValorFormatado)
		END
		ELSE
			IF (ISNULL(@CodUnidSuplementar, '') = '') AND (ISNULL(@Unidades, 0) > 0)
			BEGIN
				SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
				RAISERROR ('Unidades "%s" não podem ser especificadas.', 16, 18, @ValorFormatado)
			END
-- obtem dados do país de origem		
		SELECT @NomePaisOrigem = PAI_NOME
		FROM TAB_PAIS WITH(NOLOCK)
		WHERE PAI_CODI = @CodPaisOrigem
-- obtem dados da unidade suplementar
		SELECT @NomeUnidSuplementar = USU_SIGL
		FROM TAB_USUP WITH(NOLOCK)
		WHERE USU_CODI = @CodUnidSuplementar
-- calcula os valores da adição		
		IF @NumAdicao IS NULL
			SET @NumAdicao = @TotalAdicoes + 1		
		SET @Frete = ISNULL(@Frete, ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
											WHEN 0 THEN (@FreteTotal - @SomaFretesAdicoes) 
											ELSE (@PesoBruto * @FreteTotal / @MassaBrutaTotal) 
										END), 3))
		SET @Seguro = ISNULL(@Seguro, ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
												WHEN 0 THEN (@SeguroTotal - @SomaSegurosAdicoes) 
												ELSE (@Montante * @SeguroTotal / @MontanteTotal) 
											END), 3))		
		SET @ValorEUR = ROUND(@Montante / @CambioMontante, 2)
		SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@FormulaCondEntrega, 0, @CambioFrete, @CambioSeguro, @Frete, @Seguro, 0, 0, 0)
		SET @ValorEstatistico = dbo.fn_IMP_CalculaValorEstatistico(@ValorEUR, @Ajustamento)		
-- insere a adição
		INSERT INTO PRO_EXAD(EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CO33, APA_CP33, APA_DESG, PAI_CODI, PAI_NOME, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, USU_CODI, USU_SIGL, EXA_VALO, 
			EXA_VFRE, EXA_VSEG, EXA_VEST, EXA_IRES, EXA_ANXC, EXA_ANXD, TDE_REGI, EXA_ATAR, EXA_ATA1, EXA_ATA2, EXA_ATA3, EXA_AIC1, EXA_AIC2, EXA_AIC3, EXA_AIC4, EXA_AIC5, EXA_CCUS, 
			id_desdobramento, NTR_CODI, PAI_CODI2, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, FOR_NIF, PAI_CODI3, PAI_CODI4, EXA_AJUS)
		OUTPUT inserted.EXA_CHVE INTO @TblID
		VALUES(@AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodArtigo, @CodigoPautal, @Designacao, @CodPaisOrigem, @NomePaisOrigem, @PesoBruto, @Desdobramento1, @PesoLiquido, @Unidades, @CodUnidSuplementar, @NomeUnidSuplementar, @Montante, 
			@Frete, @Seguro, @ValorEstatistico, @IndicadorRestituicoes, @AnexoC, @AnexoD, @Regime, @CodigoATAR, @AdicionalTARIC1, @AdicionalTARIC2, @AdicionalTARIC3, @CodigoIC1, @CodigoIC2, @CodigoIC3, @CodigoIC4, @CodigoIC5, @CodigoCCUS, 
			@IdDesdobramento, @CodNatTransacaoAd, @CodPaisExpedicaoAd,  @CodFornecedorDestinatarioAd, @NomeFornDestinatario, @MoradaFornDestinatario, @LocalidadeFornDestinatario, 
			@CodigoPostalFornDestinatario, @LocalidadePostalFornDestinatario, @NIFFornDestinatario, @CodPaisFornDestinatario, @CodPaisDestinoAd, @Ajustamento)			
-- obtem o ID da nova adição
		SELECT @IdAdicao = ID
		FROM @TblID
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_AdicoesInsere] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_AdicoesInsere] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_ContentoresImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_ContentoresImportaXLSX] @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @UltimoNumContentores int
-- inicia transacção para a inserção dos contentores
	BEGIN TRANSACTION TspEXPContentoresImportaXLSX
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- obtem o número de contentores atualmente existentes na declaração EXP-SAE
		SET @UltimoNumContentores = ISNULL((SELECT COUNT(*)
											FROM PRO_EXCT WITH(NOLOCK)
											WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao), 0)
-- insere os contentores do ficheiro na declaração EXP-SAE
		INSERT INTO PRO_EXCT(EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_CONT)
		SELECT @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, (@UltimoNumContentores + ROW_NUMBER() OVER(ORDER BY con.contentor)), con.contentor
		FROM (SELECT t.c.value('CONT[1]', 'varchar(50)') AS contentor 
				FROM @FicheiroXML.nodes('dataset/row') AS t(c) 
				WHERE t.c.value('CONT[1]', 'varchar(50)') <> '') AS con
			LEFT OUTER JOIN PRO_EXCT AS dco WITH(NOLOCK) ON dco.EXM_EANO = @AnoDeclaracao AND dco.EXM_CODI = @CodDeclaracao AND dco.EXM_COPE = @CodOperadorDeclaracao AND con.contentor = dco.EXC_CONT	
		WHERE dco.EXC_CHVE IS NULL		
		GROUP BY con.contentor
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspEXPContentoresImportaXLSX
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspEXPContentoresImportaXLSX
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_ContentoresImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_ContentoresImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_DocumentosImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_DocumentosImportaXLSX] @IdDeclaracao bigint, @DataDeclaracao datetime, @IdDocumento int, @FicheiroXLSX varchar(MAX), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @FicheiroXML xml
-- inicia transacção para a inserção dos documentos
	BEGIN TRANSACTION TspEXPDocumentosImportaXLSX
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX		
-- insere os documentos do ficheiro como "Suporte" na declaração
		INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
		SELECT @IdDeclaracao, 0, @IdDocumento, t.c.value('Numero[1]', 'varchar(70)'), 7, @IdUtilizador, @DataAtual
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 						
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspEXPDocumentosImportaXLSX
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspEXPDocumentosImportaXLSX
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_DocumentosImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_DocumentosImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_Duplica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_Duplica] @Id bigint, @NovoNumero int, @DuplicaContentores bit, @DuplicaSelos bit, @DuplicaMeiosTransportePartida bit, @DuplicaOutrosIntervenientes bit, 
	@DuplicaPaisesRota bit, @DuplicaLocaisTransformacao bit, @DuplicaProdutosTransformados bit, @DuplicaCertificados bit, @DuplicaVolumesCertificados bit, @DuplicaAutorizacoes bit, 
	@DuplicaDocumentos bit, @DuplicaPrecedentes bit, @DuplicaPedidos bit, @DuplicaAdicoes bit, @DuplicaImposicoes bit, @DuplicaTaxasImposicoes bit, @DuplicaMarcasEVolumes bit, 
	@DuplicaDocumentosAdicoes bit, @DuplicaPrecedentesAdicoes bit, @DuplicaPedidosAdicoes bit, @DuplicaContentoresAdicoes bit, @DuplicaAutorizacoesAdicoes bit, 
	@DuplicaOutrosIntervenientesAdicoes bit, @DuplicaVeiculos bit, @DuplicaChassis bit, @IdUtilizador int, @NovoId bigint OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID int NOT NULL, CODIGO int NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @Ano smallint, @Codigo int, @CodDeclOperador varchar(6), @NIFDeclOperador varchar(17), @NovoCodigo int, 
		@NRL varchar(22), @NovoAno smallint, @NumAdicao int, @IdAdicao bigint, @NovoIdAdicao bigint
-- inicia transacção para duplicação da declaração EXP-SAE
	BEGIN TRANSACTION TspEXPDuplicacao
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem dados da declaração EXP-SAE de origem
		SELECT @Ano = dex.EXM_EANO, @Codigo = dex.EXM_CODI, @CodDeclOperador = dex.DEC_CODI, @NIFDeclOperador = dcl.DEC_NIF
		FROM PRO_EXML AS dex WITH(NOLOCK)
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dex.DEC_CODI = dcl.DEC_CODI
		WHERE dex.EXM_IDTY = @Id
-- calcula o ano da nova declaração
		IF (@Ano < YEAR(@DataAtual)) AND (EXISTS(SELECT EMP_CODI FROM GIDWIN.dbo.FAP_EANO WITH(NOLOCK) WHERE EMP_CODI = DB_NAME() and EAN_ANO = YEAR(@DataAtual)))		
			SET @NovoAno = YEAR(@DataAtual)
		ELSE
			SET @NovoAno = @Ano
-- obtem o número para a nova declaração
		SELECT @NovoCodigo = ISNULL(DEC_NPRO, 1), @NovoNumero = (CASE DEC_XNRA WHEN 0 THEN ISNULL(@NovoNumero, 0) ELSE ISNULL(DEC_NPRO, 1) END)
		FROM TAB_DECL		
		WHERE DEC_CODI = @CodDeclOperador
-- verifica se o número é válido
		IF @NovoNumero = 0
			RAISERROR('Número da declaração não foi especificado.', 16, 1)	
-- constroi NRL
		SET @NRL = RIGHT(STR(@NovoAno, 4), 2) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclOperador)) + @NIFDeclOperador + REPLICATE('0', 9 - LEN(LTRIM(STR(@NovoCodigo, 9)))) + LTRIM(STR(@NovoCodigo, 9))
-- insere os dados gerais da nova declaração EXP-SAE
		INSERT INTO PRO_EXML(EXM_EANO, EXM_CODI, DEC_CODI, EXM_TPRO, NDE_CODI, NDE_NOME, DEC_NOME, EXM_DATA, EXM_NRIN, EXM_NRLO, EXM_STAT, EXM_VERS, EXM_REVI, EAD_CODA, EAD_NOMA, TDE_COD1, 
			TDE_NOM1, CLI_COD2, CLI_NOM2, CLI_MOR2, CLI_LOC2, CLI_CPO2, CLI_LPO2, CLI_NIF2, CLI_PAI2, EXM_TP2A, EXM_TI2B, EXM_TAD5, EXM_TVL6, FOR_COD8, FOR_NOM8, FOR_MOR8, FOR_LOC8, FOR_CPO8, 
			FOR_LPO8, FOR_NIF8, FOR_PAI8, EXM_IROR, DEC_CO14, DEC_NO14, EXM_TP14, EXM_P15A, EXM_P17A, EXM_CT19, MTR_CO18, MTR_NO18, EXM_MT18, EXM_P18C, MTR_CO21, MTR_NO21, EXM_MT21, PAI_CO21, 
			PAI_NO21, MTR_CO26, CEN_CO20, CEN_NO20, EXM_FR20, EXM_LG20, NTR_CO24, NTR_NO24, PAI_CO22, PAI_MO22, EXM_MT22, EXM_UFOB, EXM_VFOB, EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, 
			EXM_TREM, EXM_VEUR, EXM_VATT, EAD_CO29, EAD_NO29, EAD_C29A, EAD_N29A, EAD_CO30, EAD_NO30, LEM_CO30, LEM_NO30, LME_CO30, LME_NO30, EXM_MR30, EXM_CP30, EXM_LP30, EXM_NC48, EXM_AC48, 
			EXM_TC48, ARM_CO49, ARM_NO49, TAR_CO49, TAR_DE49, EXM_Q30C, EXM_UCRI, EXM_DTCR, EXM_UALT, EXM_DTAL, EXM_MASC, EXM_VLRC, FIN_CODI, EXM_NRII, EXM_NVRF, EXM_CPRT, EXM_MCPA, EXM_TPCG, 
			EXM_DTVO, EXM_DTYP, EXM_CIEX, EXM_CIDE, EXM_PPFC, EXM_NVOO, EXM_REF1, EXM_REF2, EXM_TRAC, EXM_SHIP, EXM_VDIR, EXM_VCLE, EXM_INCE, EXM_NCMR, EXM_DTMP, EXM_TMSF, CLI_CODI, CLI_NOME, 
			PAE_CODI, PAE_NOME, EXM_ANOT, EXM_HVLV, EXM_CNTX, EXM_SEGU, EXM_DGEN, EXM_DCMP, CLI_CODI1, CLI_NOME1, CLI_MORA1, CLI_LOCA1, CLI_CPOS1, CLI_LPOS1, CLI_NIF1, PAI_CODI1, EXM_NTRP, 
			EAD_CODI, PAI_CODI, PAE_CODI1, EXM_TXTC, PAI_CODI2, EXM_CFRE, PAI_CODI3, EXM_CSEG, EXM_VRBA, PAI_CODI4, EXM_TLOC, EXM_QUAL, PAI_CODI5, EXM_IADI, EXM_NAUT, EXM_ONIF, EAD_CODI1, 
			EXM_PRZA, EXM_ATVP, EXM_INFA, EXM_VSCA, EXM_ANXB, EXM_REGI, EXM_DCEN, EXM_MTIT, EXM_MTFT, CLI_TNIF1)						
		OUTPUT inserted.EXM_IDTY, inserted.EXM_CODI INTO @TblID
		SELECT @NovoAno, @NovoCodigo, DEC_CODI, EXM_TPRO, NDE_CODI, NDE_NOME, DEC_NOME, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), @NovoNumero, @NRL, 0, 0, 0, EAD_CODA, EAD_NOMA, TDE_COD1, 
			TDE_NOM1, CLI_COD2, CLI_NOM2, CLI_MOR2, CLI_LOC2, CLI_CPO2, CLI_LPO2, CLI_NIF2, CLI_PAI2, EXM_TP2A, EXM_TI2B, 0, 0, FOR_COD8, FOR_NOM8, FOR_MOR8, FOR_LOC8, FOR_CPO8, 
			FOR_LPO8, FOR_NIF8, FOR_PAI8, EXM_IROR, DEC_CO14, DEC_NO14, EXM_TP14, EXM_P15A, EXM_P17A, EXM_CT19, MTR_CO18, MTR_NO18, EXM_MT18, EXM_P18C, MTR_CO21, MTR_NO21, EXM_MT21, PAI_CO21, 
			PAI_NO21, MTR_CO26, CEN_CO20, CEN_NO20, EXM_FR20, EXM_LG20, NTR_CO24, NTR_NO24, PAI_CO22, PAI_MO22, EXM_MT22, EXM_UFOB, EXM_VFOB, EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, 
			EXM_TREM, EXM_VEUR, 0, EAD_CO29, EAD_NO29, EAD_C29A, EAD_N29A, EAD_CO30, EAD_NO30, LEM_CO30, LEM_NO30, LME_CO30, LME_NO30, EXM_MR30, EXM_CP30, EXM_LP30, EXM_NC48, EXM_AC48, 
			EXM_TC48, ARM_CO49, ARM_NO49, TAR_CO49, TAR_DE49, EXM_Q30C, @CodUtilizador, @DataAtual, @CodUtilizador, @DataAtual, EXM_MASC, 0, FIN_CODI, @NovoNumero, EXM_NVRF, EXM_CPRT, EXM_MCPA, EXM_TPCG, 
			(CASE WHEN EXM_DTVO IS NULL THEN NULL ELSE CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime) END), EXM_DTYP, EXM_CIEX, EXM_CIDE, EXM_PPFC, EXM_NVOO, EXM_REF1, EXM_REF2, EXM_TRAC, EXM_SHIP, 0, 0, EXM_INCE, EXM_NCMR, EXM_DTMP, EXM_TMSF, CLI_CODI, CLI_NOME, 
			PAE_CODI, PAE_NOME, EXM_ANOT, EXM_HVLV, EXM_CNTX, EXM_SEGU, EXM_DGEN, EXM_DCMP, CLI_CODI1, CLI_NOME1, CLI_MORA1, CLI_LOCA1, CLI_CPOS1, CLI_LPOS1, CLI_NIF1, PAI_CODI1, EXM_NTRP, 
			EAD_CODI, PAI_CODI, PAE_CODI1, EXM_TXTC, PAI_CODI2, EXM_CFRE, PAI_CODI3, EXM_CSEG, EXM_VRBA, PAI_CODI4, EXM_TLOC, EXM_QUAL, PAI_CODI5, EXM_IADI, EXM_NAUT, EXM_ONIF, EAD_CODI1, 
			EXM_PRZA, EXM_ATVP, EXM_INFA, 0, EXM_ANXB, EXM_REGI, EXM_DCEN, EXM_MTIT, EXM_MTFT, CLI_TNIF1						
		FROM PRO_EXML WITH(NOLOCK)
		WHERE EXM_IDTY = @Id
-- obtem o ID da nova declaração EXP-SAE
		SELECT @NovoId = ID, @NovoCodigo = CODIGO
		FROM @TblID
-- gere o detalhe de contentores na nova declaração EXP-SAE
		IF @DuplicaContentores = 1
		BEGIN
-- remove o detalhe de contentores já criado por algum automatismo da nova declaração EXP-SAE
			DELETE FROM PRO_EXCT
			WHERE EXM_EANO = @NovoAno AND EXM_CODI = @NovoCodigo AND EXM_COPE = @CodDeclOperador
-- insere o detalhe de contentores na nova declaração EXP-SAE
			INSERT INTO PRO_EXCT(EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_CONT)
			SELECT @NovoAno, @NovoCodigo, EXM_COPE, EXC_LINH, EXC_CONT
			FROM PRO_EXCT WITH(NOLOCK)
			WHERE EXM_EANO = @Ano AND EXM_CODI = @Codigo AND EXM_COPE = @CodDeclOperador
		END
-- insere o detalhe de selos dos contentores na nova declaração EXP-SAE
		IF @DuplicaSelos = 1
		BEGIN
-- remove o detalhe de selos de contentores já criado por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesContentoresSelos
			WHERE id_contentor IN (SELECT EXC_CHVE
									FROM PRO_EXCT WITH(NOLOCK)
									WHERE EXM_EANO = @NovoAno AND EXM_CODI = @NovoCodigo AND EXM_COPE = @CodDeclOperador)
-- insere o detalhe de selos de contentores na nova declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesContentoresSelos(id_contentor, numeroSelo, id_utilizadorControlo, dataControlo)
			SELECT nco.EXC_CHVE, dcs.numeroSelo, @IdUtilizador, @DataAtual
			FROM tb_EXP_DeclaracoesContentoresSelos AS dcs WITH(NOLOCK)
				INNER JOIN PRO_EXCT AS dco WITH(NOLOCK) ON dcs.id_contentor = dco.EXC_CHVE
				INNER JOIN PRO_EXCT AS nco WITH(NOLOCK) ON nco.EXM_EANO = @NovoAno AND nco.EXM_CODI = @NovoCodigo AND dco.EXM_COPE = nco.EXM_COPE AND dco.EXC_LINH = nco.EXC_LINH
			WHERE dco.EXM_EANO = @Ano AND dco.EXM_CODI = @Codigo AND dco.EXM_COPE = @CodDeclOperador
		END
-- gere o detalhe de meios de transporte partida na nova declaração EXP-SAE
		IF @DuplicaMeiosTransportePartida = 1
		BEGIN
-- remove o detalhe de meios de transporte partida já criados por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesMeiosTransportePartida
			WHERE id_declaracaoEXP = @NovoId
-- insere o detalhe de meios de transporte partida na nova declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesMeiosTransportePartida(id_declaracaoEXP, id_meioTransporte, identificacao, id_pais, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_meioTransporte, identificacao, id_pais, origem, @IdUtilizador, @DataAtual
			FROM tb_EXP_DeclaracoesMeiosTransportePartida WITH(NOLOCK)
			WHERE id_declaracaoEXP = @Id
		END
-- gere o detalhe de outros intervenientes na nova declaração EXP-SAE
		IF @DuplicaOutrosIntervenientes = 1
		BEGIN
-- remove o detalhe de outros intervenientes já criado por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesIntervenientes
			WHERE id_declaracaoEXP = @NovoId
-- insere o detalhe de outros intervenientes na nova declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesIntervenientes(id_declaracaoEXP, funcao, nif, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, funcao, nif, origem, @IdUtilizador, @DataAtual
			FROM tb_EXP_DeclaracoesIntervenientes WITH(NOLOCK)
			WHERE id_declaracaoEXP = @Id
		END
-- gere o detalhe de países da rota na nova declaração EXP-SAE
		IF @DuplicaPaisesRota = 1
		BEGIN
-- remove o detalhe de países da rota já criadas por algum automatismo da nova declaração EXP-SAE
			DELETE FROM PRO_EXPI
			WHERE EXM_EANO = @NovoAno AND EXM_CODI = @NovoCodigo AND EXM_COPE = @CodDeclOperador
-- insere o detalhe de países da rota na nova declaração EXP-SAE
			INSERT INTO PRO_EXPI(EXM_EANO, EXM_CODI, EXM_COPE, PAI_CODI, PAI_NOME, EXP_ORIG)
			SELECT @NovoAno, @NovoCodigo, EXM_COPE, PAI_CODI, PAI_NOME, EXP_ORIG
			FROM PRO_EXPI WITH(NOLOCK)
			WHERE EXM_EANO = @Ano AND EXM_CODI = @Codigo AND EXM_COPE = @CodDeclOperador
		END
-- gere o detalhe de locais de transformação na nova declaração EXP-SAE
		IF @DuplicaLocaisTransformacao = 1
		BEGIN
-- remove o detalhe de locais de transformação já criados por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesLocaisTransformacao
			WHERE id_declaracaoEXP = @NovoId
-- insere o detalhe de locais de transformação na nova declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesLocaisTransformacao(id_declaracaoEXP, tipo, qualificador, id_localAutorizado, morada, localidade, codigoPostal, id_pais, origem, id_utilizadorControlo, 
				dataControlo, texto)
			SELECT @NovoId, tipo, qualificador, id_localAutorizado, morada, localidade, codigoPostal, id_pais, origem, @IdUtilizador, 
				@DataAtual, texto				
			FROM tb_EXP_DeclaracoesLocaisTransformacao WITH(NOLOCK)
			WHERE id_declaracaoEXP = @Id
		END		
-- gere o detalhe de produtos transformados na nova declaração EXP-SAE
		IF @DuplicaProdutosTransformados = 1
		BEGIN
-- remove o detalhe de produtos transformados já criados por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesProdutosTransformados
			WHERE id_declaracaoEXP = @NovoId
-- insere o detalhe de produtos transformados na nova declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesProdutosTransformados(id_declaracaoEXP, id_artigo, codigoPautal, designacao, descricao, taxaRendimento, origem, id_utilizadorControlo, 
				dataControlo, id_meioIdentificacao)
			SELECT @NovoId, id_artigo, codigoPautal, designacao, descricao, taxaRendimento, origem, @IdUtilizador, 
				@DataAtual, id_meioIdentificacao
			FROM tb_EXP_DeclaracoesProdutosTransformados WITH(NOLOCK)
			WHERE id_declaracaoEXP = @Id
		END		
-- gere o detalhe de certificados CCE na nova declaração EXP-SAE
		IF @DuplicaCertificados = 1
		BEGIN
-- remove o detalhe de certificados CCE já criadas por algum automatismo da nova declaração EXP-SAE
			DELETE FROM PRO_EXCE
			WHERE EXM_EANO = @NovoAno AND EXM_CODI = @NovoCodigo AND EXM_COPE = @CodDeclOperador
-- insere o detalhe de certificados CCE na nova declaração EXP-SAE
			INSERT INTO PRO_EXCE(EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_FNIF, EXC_NFAC, EXC_DFAC, EXC_QNTD, EXC_DCOM, EXC_PLIQ, EXC_PBRT, EXC_VALO)
			SELECT @NovoAno, @NovoCodigo, EXM_COPE, EXC_LINH, EXC_FNIF, EXC_NFAC, EXC_DFAC, EXC_QNTD, EXC_DCOM, EXC_PLIQ, EXC_PBRT, EXC_VALO
			FROM PRO_EXCE WITH(NOLOCK)
			WHERE EXM_EANO = @Ano AND EXM_CODI = @Codigo AND EXM_COPE = @CodDeclOperador
		END		
-- insere o detalhe de volumes dos certificados CCE na nova declaração EXP-SAE
		IF @DuplicaVolumesCertificados = 1
		BEGIN
-- remove o detalhe de volumes dos certificados CCE já criado por algum automatismo da nova declaração EXP-SAE
			DELETE FROM PRO_EXCD
			WHERE EXD_CHVE IN (SELECT ncv.EXD_CHVE
									FROM PRO_EXCE AS ncc WITH(NOLOCK)
										INNER JOIN PRO_EXCD AS ncv WITH(NOLOCK) ON ncc.EXM_EANO = ncv.EXM_EANO AND ncc.EXM_CODI = ncv.EXM_CODI AND ncc.EXM_COPE = ncv.EXM_COPE AND ncc.EXC_LINH = ncv.EXC_LINH
									WHERE ncc.EXM_EANO = @NovoAno AND ncc.EXM_CODI = @NovoCodigo AND ncc.EXM_COPE = @CodDeclOperador)
-- insere o detalhe de volumes dos certificados CCE na nova declaração EXP-SAE
			INSERT INTO PRO_EXCD(EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXD_QTDE, TEM_CODI, TEM_NOME)			
			SELECT @NovoAno, @NovoCodigo, EXM_COPE, EXC_LINH, EXD_QTDE, TEM_CODI, TEM_NOME
			FROM PRO_EXCD WITH(NOLOCK)
			WHERE EXM_EANO = @Ano AND EXM_CODI = @Codigo AND EXM_COPE = @CodDeclOperador
		END
-- gere o detalhe de autorizações na nova declaração EXP-SAE
		IF @DuplicaAutorizacoes = 1
		BEGIN
-- remove o detalhe de autorizações já criados por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAutorizacoes
			WHERE id_declaracaoEXP = @NovoId
-- insere o detalhe de autorizações na nova declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesAutorizacoes(id_declaracaoEXP, id_documento, numero, titular, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_documento, numero, titular, origem, @IdUtilizador, @DataAtual
			FROM tb_EXP_DeclaracoesAutorizacoes WITH(NOLOCK)
			WHERE id_declaracaoEXP = @Id
		END		   
-- gere o detalhe de pedidos na nova declaracao EXP-SAE
		IF @DuplicaPedidos = 1
		BEGIN
-- remove o detalhe de pedidos já criado por algum automatismo da nova declaração EXP-SAE
			DELETE FROM PRO_EXPA
			WHERE EXM_EANO = @NovoAno AND EXM_CODI = @NovoCodigo AND EXM_COPE = @CodDeclOperador					
-- insere o detalhe de pedidos na nova declaracao EXP-SAE
			INSERT INTO PRO_EXPA(EXM_EANO, EXM_CODI, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC, EXP_ORIG)
			SELECT @NovoAno, @NovoCodigo, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC, EXP_ORIG
			FROM PRO_EXPA WITH(NOLOCK)				
			WHERE EXM_EANO = @Ano AND EXM_CODI = @Codigo AND EXM_COPE = @CodDeclOperador			
		END		
-- gere o detalhe de documentos e certificados na nova declaracao EXP-SAE
		IF @DuplicaDocumentos = 1
		BEGIN
-- remove o detalhe de documentos e certificados já criado por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos
			WHERE id_declaracaoEXP = @NovoId
-- insere o detalhe de documentos e certificados na nova declaracao EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, dataValidade, entidadeEmissora, numeroAdicao, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, tipo, id_documento, numero, dataValidade, entidadeEmissora, numeroAdicao, origem, @IdUtilizador, @DataAtual
			FROM tb_EXP_DeclaracoesDocumentos WITH(NOLOCK)
			WHERE id_declaracaoEXP = @Id 
		END		
-- gere o detalhe de documentos precedentes na nova declaracao EXP-SAE
		IF @DuplicaPrecedentes = 1
		BEGIN
-- remove o detalhe de documentos precedentes já criado por algum automatismo da nova declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesPrecedentes
			WHERE id_declaracaoEXP = @NovoId
-- insere o detalhe de documentos precedentes na nova declaracao EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesPrecedentes(id_declaracaoEXP, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_documento, numero, origem, @IdUtilizador, @DataAtual
			FROM tb_EXP_DeclaracoesPrecedentes WITH(NOLOCK)
			WHERE id_declaracaoEXP = @Id	
		END			
-- obtem o detalhe de adições na declaracao de origem
		IF @DuplicaAdicoes = 1 
		BEGIN
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT EXA_LINH, EXA_CHVE
				FROM PRO_EXAD WITH(NOLOCK)
				WHERE EXM_EANO = @Ano AND EXM_CODI = @Codigo AND EXM_COPE = @CodDeclOperador
			OPEN Adicoes
			FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdAdicao
			WHILE @@FETCH_STATUS = 0
			BEGIN	
-- remove o ID existente
				DELETE FROM @TblID									
-- insere a adição na nova declaracao EXP-SAE			
				INSERT INTO PRO_EXAD(EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CO33, APA_CP33, APA_DESG, PAI_CODI, PAI_NOME, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, USU_CODI, USU_SIGL, 
					EXA_VALO, EXA_VFRE, EXA_VSEG, EXA_VEST, EXA_IRES, EXA_ANXC, EXA_ANXD, TDE_REGI, EXA_ATAR, EXA_ORIG,	EXA_ATA1, EXA_ATA2, EXA_ATA3, EXA_ATA4, EXA_ATA5, EXA_AIC1, EXA_AIC2, 
					EXA_AIC3, EXA_AIC4, EXA_AIC5, EXA_CCUS, id_desdobramento, NTR_CODI, EXA_NRUR, EXA_MPAG, CLI_CODI, CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_NIF, PAI_CODI1, 
					PAI_CODI2, RES_CODI, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, FOR_NIF, PAI_CODI3, PAI_CODI4, EXA_AJUS, CLI_TNIF)
				OUTPUT inserted.EXA_CHVE, inserted.EXA_LINH INTO @TblID
				SELECT @NovoAno, @NovoCodigo, EXM_COPE, EXA_LINH, APA_CO33, APA_CP33, APA_DESG, PAI_CODI, PAI_NOME, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, USU_CODI, USU_SIGL, 
					EXA_VALO, EXA_VFRE, EXA_VSEG, EXA_VEST, EXA_IRES, EXA_ANXC, EXA_ANXD, TDE_REGI, EXA_ATAR, EXA_ORIG,	EXA_ATA1, EXA_ATA2, EXA_ATA3, EXA_ATA4, EXA_ATA5, EXA_AIC1, EXA_AIC2, 
					EXA_AIC3, EXA_AIC4, EXA_AIC5, EXA_CCUS, id_desdobramento, NTR_CODI, EXA_NRUR, EXA_MPAG, CLI_CODI, CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_NIF, PAI_CODI1, 
					PAI_CODI2, RES_CODI, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, FOR_NIF, PAI_CODI3, PAI_CODI4, EXA_AJUS, CLI_TNIF
				FROM PRO_EXAD WITH(NOLOCK)
				WHERE EXA_CHVE = @IdAdicao				
-- obtem o ID da nova adição
				SELECT @NovoIdAdicao = ID 
				FROM @TblID
-- gere o detalhe de marcas e volumes na nova adição				
				IF @DuplicaMarcasEVolumes = 1 
				BEGIN
-- remove o detalhe de marcas e volumes já criado por algum automatismo da nova adição
					DELETE FROM PRO_EXMV
					WHERE EXA_CHVE = @NovoIdAdicao
-- insere o detalhe de marcas e volumes na nova adição
					INSERT INTO PRO_EXMV(EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_TVOL, EXM_IDST, EXM_AUTO, EXM_EANO, EXM_CODI, EXM_COPE)
					SELECT @NovoIdAdicao, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_TVOL, REPLACE(CONVERT(numeric(38, 10), DATEADD(MS, (ROW_NUMBER() OVER(ORDER BY EXM_CHVE) * 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())), '.', ','), EXM_AUTO, @NovoAno, @NovoCodigo, EXM_COPE
					FROM PRO_EXMV WITH(NOLOCK) 
					WHERE EXA_CHVE = @IdAdicao				
				END
-- gere o detalhe de veículos na nova adição
				/*IF @DuplicaVeiculos = 1 
				BEGIN			
-- remove o detalhe de veículos já criado por algum automatismo da nova adição
					DELETE FROM PRO_DUBT
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao	
-- insere o detalhe de veículos na nova adição						
					INSERT INTO PRO_DUBT(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, 
						DBT_AUTO, DBT_VLIA, DBT_MARC, DBT_MODE, DBT_CODR, DBT_IDCR, HTE_CODI, DBT_HOMO, DBT_TABE, DBT_TCO2, DBT_AUTN, DBT_DIMT)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DBT_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, 
						DBT_AUTO, DBT_VLIA, DBT_MARC, DBT_MODE, DBT_CODR, REPLACE(CONVERT(numeric(38, 10), DATEADD(MS, (DBT_CODI * 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())), '.', ','), HTE_CODI, DBT_HOMO, DBT_TABE, DBT_TCO2, DBT_AUTN, DBT_DIMT
					FROM PRO_DUBT WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
					ORDER BY DBT_CODI
				END
-- gere o detalhe de chassis na nova adição
				IF @DuplicaChassis = 1 
				BEGIN		
-- remove o detalhe de chassis já criado por algum automatismo da nova adição
					DELETE FROM PRO_DUVE
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao	
-- insere o detalhe de chassis na nova adição							
					INSERT INTO PRO_DUVE(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS, DVC_DMAT, DVC_DCHA)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS, DVC_DMAT, DVC_DCHA
					FROM PRO_DUVE WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
					ORDER BY DBT_CODI, DVC_CODI
				END*/
-- gere o detalhe de pedidos na nova adição
				IF @DuplicaPedidosAdicoes = 1
				BEGIN	
-- remove o detalhe de pedidos já criado por algum automatismo da nova adição
					DELETE FROM tb_EXP_DeclaracoesAdicoesPedidos
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de pedidos na nova adição						
					INSERT INTO tb_EXP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, id_pedido, numero, origem, @IdUtilizador, @DataAtual
					FROM tb_EXP_DeclaracoesAdicoesPedidos WITH(NOLOCK)						
					WHERE id_adicao = @IdAdicao
				END
-- gere o detalhe de documentos e certificados na nova adição
				IF @DuplicaDocumentosAdicoes = 1
				BEGIN			
-- remove o detalhe de documentos e certificados já criado por algum automatismo da nova adição
					DELETE FROM PRO_EXDA
					WHERE EXA_CHVE = @NovoIdAdicao							
-- insere o detalhe de documentos e certificados na nova adição
					INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EEM_DESC, PAI_CODI, PAI_MOED, PAI_NOME, EXD_MONT, EXD_QNTD, UME_CODI, UME_NOME, EXD_AUTO, EXM_EANO, 
						EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI)
					SELECT @NovoIdAdicao, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EEM_DESC, PAI_CODI, PAI_MOED, PAI_NOME, EXD_MONT, EXD_QNTD, UME_CODI, UME_NOME, EXD_AUTO, @NovoAno, 
						@NovoCodigo, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI
					FROM PRO_EXDA WITH(NOLOCK)
					WHERE EXA_CHVE = @IdAdicao				
				END
-- gere o detalhe de documentos precedentes na nova adição
				IF @DuplicaPrecedentesAdicoes = 1
				BEGIN		
-- remove o detalhe de documentos precedentes já criado por algum automatismo da nova adição
					DELETE FROM tb_EXP_DeclaracoesAdicoesPrecedentes
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de documentos precedentes na nova adição															
					INSERT INTO tb_EXP_DeclaracoesAdicoesPrecedentes(id_adicao, id_documento, numero, numeroAdicao, id_unidadeMedidaVolumes, volumes, id_unidadeMedidaQualificador, 
						quantidade, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, id_documento, numero, numeroAdicao, id_unidadeMedidaVolumes, volumes, id_unidadeMedidaQualificador, 
						quantidade, origem, @IdUtilizador, @DataAtual
					FROM tb_EXP_DeclaracoesAdicoesPrecedentes WITH(NOLOCK)
					WHERE id_adicao = @IdAdicao						
				END
-- gere o detalhe de contentores na nova adição
				IF @DuplicaContentoresAdicoes = 1 
				BEGIN
-- remove o detalhe de contentores já criado por algum automatismo da nova adição
					DELETE FROM tb_EXP_DeclaracoesAdicoesContentores
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de contentores na nova adição
					INSERT INTO tb_EXP_DeclaracoesAdicoesContentores(id_adicao, id_contentor, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, nco.EXC_CHVE, dac.origem, @IdUtilizador, @DataAtual
					FROM tb_EXP_DeclaracoesAdicoesContentores AS dac WITH(NOLOCK)
						INNER JOIN PRO_EXCT AS dco WITH(NOLOCK) ON dac.id_contentor = dco.EXC_CHVE
						INNER JOIN PRO_EXCT AS nco WITH(NOLOCK) ON nco.EXM_EANO = @NovoAno AND nco.EXM_CODI = @NovoCodigo AND dco.EXM_COPE = nco.EXM_COPE AND dco.EXC_LINH = nco.EXC_LINH
					WHERE dac.id_adicao = @IdAdicao					
				END
-- gere o detalhe de autorizações na nova adição
				IF @DuplicaAutorizacoesAdicoes = 1 
				BEGIN
-- remove o detalhe de autorizações já criado por algum automatismo da nova adição
					DELETE FROM tb_EXP_DeclaracoesAdicoesAutorizacoes
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de autorizações na nova adição
					INSERT INTO tb_EXP_DeclaracoesAdicoesAutorizacoes(id_adicao, id_documento, numero, titular, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, id_documento, numero, titular, origem, @IdUtilizador, @DataAtual
					FROM tb_EXP_DeclaracoesAdicoesAutorizacoes WITH(NOLOCK)
					WHERE id_adicao = @IdAdicao
				END
-- gere o detalhe de outros intervenientes na nova adição
				IF @DuplicaOutrosIntervenientesAdicoes = 1 
				BEGIN
-- remove o detalhe de outros intervenientes já criado por algum automatismo da nova adição
					DELETE FROM tb_EXP_DeclaracoesAdicoesIntervenientes
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de outros intervenientes na nova adição
					INSERT INTO tb_EXP_DeclaracoesAdicoesIntervenientes(id_adicao, funcao, nif, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, funcao, nif, origem, @IdUtilizador, @DataAtual
					FROM tb_EXP_DeclaracoesAdicoesIntervenientes WITH(NOLOCK)
					WHERE id_adicao = @IdAdicao
				END
-- gere o detalhe de imposições na nova adição
				IF @DuplicaImposicoes = 1
				BEGIN				
-- remove o detalhe de imposições já criado por algum automatismo da nova adição					
					DELETE FROM tb_EXP_DeclaracoesAdicoesImposicoes
					WHERE id_adicao = @NovoIdAdicao						
-- insere o detalhe de imposições na nova adição							
					INSERT INTO tb_EXP_DeclaracoesAdicoesImposicoes(id_adicao, id_rubricaReceita, imposicao, montante, metodoPagamento, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, id_rubricaReceita, imposicao, 0, metodoPagamento, origem, @IdUtilizador, @DataAtual
					FROM tb_EXP_DeclaracoesAdicoesImposicoes WITH(NOLOCK)						
					WHERE id_adicao = @IdAdicao					
				END
-- insere o detalhe de taxas das imposições na nova adição
				IF @DuplicaTaxasImposicoes = 1
				BEGIN
-- remove o detalhe de taxas das imposições já criado por algum automatismo da nova adição
					DELETE FROM tb_EXP_DeclaracoesAdicoesImposicoesTaxas
					WHERE id_imposicao IN (SELECT id
											FROM tb_EXP_DeclaracoesAdicoesImposicoes WITH(NOLOCK)
											WHERE id_adicao = @NovoIdAdicao)
-- insere o detalhe de taxas das imposições na nova adição
					INSERT INTO tb_EXP_DeclaracoesAdicoesImposicoesTaxas(id_imposicao, tipoCalculo, taxaValor, id_unidadeMedida, quantidade, valor, montante, origem, id_utilizadorControlo, 
						dataControlo)
					SELECT nai.id, dait.tipoCalculo, dait.taxaValor, dait.id_unidadeMedida, dait.quantidade, dait.valor, dait.montante, dait.origem, @IdUtilizador, 
						@DataAtual
					FROM tb_EXP_DeclaracoesAdicoesImposicoesTaxas AS dait WITH(NOLOCK)
						INNER JOIN tb_EXP_DeclaracoesAdicoesImposicoes AS dai WITH(NOLOCK) ON dait.id_imposicao = dai.id
						INNER JOIN tb_EXP_DeclaracoesAdicoesImposicoes AS nai WITH(NOLOCK) ON nai.id_adicao = @NovoIdAdicao	AND dai.id_rubricaReceita = nai.id_rubricaReceita AND dai.imposicao = nai.imposicao AND dai.metodoPagamento = nai.metodoPagamento AND dai.origem = nai.origem
					WHERE dai.id_adicao = @IdAdicao
				END
				FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdAdicao
			END
			CLOSE Adicoes
			DEALLOCATE Adicoes
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspEXPDuplicacao
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspEXPDuplicacao
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_Duplica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_Duplica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_ImportaFicheiroUPS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_ImportaFicheiroUPS] @FicheiroASCII varchar(MAX), @DataVoo datetime, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
SET NOCOUNT ON	
	SET ARITHABORT ON		
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @XMLFicheiroUPS xml, @XMLDeclaracao xml(XMLSC_DeclaracoesExpToGIDWin)
	DECLARE @TblFicheiroUPS TABLE(id int, valor varchar(MAX))
-- inicia variaveis
	SET @NumErro = 0
-- inicia processo de importação da declaração IMP-CAU
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- carrega o conteúdo do ficheiro ASCII para dentro de tabela tmp
		INSERT INTO @TblFicheiroUPS(id, valor)
		SELECT id, valor
		FROM dbo.FNT_Geral_SeparaTexto(@FicheiroASCII, CHAR(13) + CHAR(10))
-- converte dados do ficheiro ASCII para formato XML dividida nos vários blocos
		SET @XMLFicheiroUPS = 			
			(SELECT 
				(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(cab.valor) AS "linha"
				FOR XML PATH('b200000'), TYPE), 				
				(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.valor) AS "linha"
				FROM @TblFicheiroUPS AS det
				WHERE CAST(SUBSTRING(det.valor, 45, 6) AS int) = 202000 AND SUBSTRING(det.valor, 1, 2) = SUBSTRING(cab.valor, 1, 2) 
					AND SUBSTRING(det.valor, 3, 4) = SUBSTRING(cab.valor, 3, 4) AND SUBSTRING(det.valor, 7, 2) = SUBSTRING(cab.valor, 7, 2) 
					AND SUBSTRING(det.valor, 9, 4) = SUBSTRING(cab.valor, 9, 4) AND SUBSTRING(det.valor, 13, 6) = SUBSTRING(cab.valor, 13, 6) 
					AND SUBSTRING(det.valor, 33, 1) = SUBSTRING(cab.valor, 33, 1) AND SUBSTRING(det.valor, 34, 11) = SUBSTRING(cab.valor, 34, 11) 						
				FOR XML PATH('b202000'), TYPE), 
				(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.valor) AS "linha"
				FROM @TblFicheiroUPS AS det
				WHERE CAST(SUBSTRING(det.valor, 45, 6) AS int) = 300000 AND SUBSTRING(det.valor, 1, 2) = SUBSTRING(cab.valor, 1, 2) 
					AND SUBSTRING(det.valor, 3, 4) = SUBSTRING(cab.valor, 3, 4) AND SUBSTRING(det.valor, 7, 2) = SUBSTRING(cab.valor, 7, 2) 
					AND SUBSTRING(det.valor, 9, 4) = SUBSTRING(cab.valor, 9, 4) AND SUBSTRING(det.valor, 13, 6) = SUBSTRING(cab.valor, 13, 6) 
					AND SUBSTRING(det.valor, 33, 1) = SUBSTRING(cab.valor, 33, 1) AND SUBSTRING(det.valor, 34, 11) = SUBSTRING(cab.valor, 34, 11) 						
				FOR XML PATH('b300000'), TYPE), 
				(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.valor) AS "linha"
				FROM @TblFicheiroUPS AS det
				WHERE CAST(SUBSTRING(det.valor, 45, 6) AS int) = 400000 AND SUBSTRING(det.valor, 1, 2) = SUBSTRING(cab.valor, 1, 2) 
					AND SUBSTRING(det.valor, 3, 4) = SUBSTRING(cab.valor, 3, 4) AND SUBSTRING(det.valor, 7, 2) = SUBSTRING(cab.valor, 7, 2) 
					AND SUBSTRING(det.valor, 9, 4) = SUBSTRING(cab.valor, 9, 4) AND SUBSTRING(det.valor, 13, 6) = SUBSTRING(cab.valor, 13, 6) 
					AND SUBSTRING(det.valor, 33, 1) = SUBSTRING(cab.valor, 33, 1) AND SUBSTRING(det.valor, 34, 11) = SUBSTRING(cab.valor, 34, 11) 						
				FOR XML PATH('b400000'), TYPE), 
				(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.valor) AS "linha"
				FROM @TblFicheiroUPS AS det
				WHERE CAST(SUBSTRING(det.valor, 45, 6) AS int) >= 500000 AND CAST(SUBSTRING(det.valor, 45, 6) AS int) < 600000 AND SUBSTRING(det.valor, 1, 2) = SUBSTRING(cab.valor, 1, 2) 
					AND SUBSTRING(det.valor, 3, 4) = SUBSTRING(cab.valor, 3, 4) AND SUBSTRING(det.valor, 7, 2) = SUBSTRING(cab.valor, 7, 2) 
					AND SUBSTRING(det.valor, 9, 4) = SUBSTRING(cab.valor, 9, 4) AND SUBSTRING(det.valor, 13, 6) = SUBSTRING(cab.valor, 13, 6) 
					AND SUBSTRING(det.valor, 33, 1) = SUBSTRING(cab.valor, 33, 1) AND SUBSTRING(det.valor, 34, 11) = SUBSTRING(cab.valor, 34, 11) 						
				FOR XML PATH('b500xxx'), TYPE), 
				(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.valor) AS "linha"
				FROM @TblFicheiroUPS AS det
				WHERE CAST(SUBSTRING(det.valor, 45, 6) AS int) >= 600000 AND CAST(SUBSTRING(det.valor, 45, 6) AS int) < 700000 AND SUBSTRING(det.valor, 1, 2) = SUBSTRING(cab.valor, 1, 2) 
					AND SUBSTRING(det.valor, 3, 4) = SUBSTRING(cab.valor, 3, 4) AND SUBSTRING(det.valor, 7, 2) = SUBSTRING(cab.valor, 7, 2) 
					AND SUBSTRING(det.valor, 9, 4) = SUBSTRING(cab.valor, 9, 4) AND SUBSTRING(det.valor, 13, 6) = SUBSTRING(cab.valor, 13, 6) 
					AND SUBSTRING(det.valor, 33, 1) = SUBSTRING(cab.valor, 33, 1) AND SUBSTRING(det.valor, 34, 11) = SUBSTRING(cab.valor, 34, 11) 						
				FOR XML PATH('b600xxx'), TYPE)				
			FROM @TblFicheiroUPS AS cab 
			WHERE CAST(SUBSTRING(cab.valor, 45, 6) AS int) = 200000 				
			FOR XML PATH('declaracaoUPS'), TYPE)
-- constroi XML para declaração EXP-CAU a partir do ficheiro XML de blocos do formato UPS
		SET @XMLDeclaracao = 
			(SELECT
				(SELECT 'I' AS "@Acao", 
					'A' AS "TipoProcedimento",
					'1' AS "CodNatureza", 
					(SELECT TOP 1 DEC_CODI FROM TAB_DECL WITH(NOLOCK)) AS "CodOperador", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "Data",					
					'PT000020' AS "CodEstanciaA", 				
					'EXY' AS "CodTipoDeclaracao", 				
					NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AS "NumeroCPA", 				
					'X' AS "TipoCarga",
					(CONVERT(varchar(10), @DataVoo, 127) + 'Z') AS "DataVoo", 
					(SELECT 
						(SELECT TOP 1 CLI_CODI FROM TAB_CLIE WITH(NOLOCK) WHERE SUBSTRING(CLI_NOME, 1, 12) LIKE '%' + SUBSTRING(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 69, 35))), ''), 1, 12) + '%') AS "Codigo", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 69, 35))), '')) AS "Nome",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 104, 35))), '')) AS "Morada",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '')) AS "Localidade",
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 9))), '') AS "CodPostal",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '')) AS "LocPostal",
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 320, 9))), '') AS "NIF",
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '') AS "CodPais"
					FOR XML PATH('Expedidor'), TYPE),					
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '')) AS "Nome",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '')) AS "Morada",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '')) AS "Localidade",
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') AS "CodPostal",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '')) AS "LocPostal",							
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') AS "CodPais"
					FOR XML PATH('Destinatario'), TYPE), 
					NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '') AS "CodPais15A", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') AS "CodPais17A", 					
					(SELECT 
						(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN '30' ELSE NULL END) AS "CodMeioTransporte", 
						(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN 'CAMIAO' ELSE NULL END) AS "MatriculaMT", 
						(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN '30' ELSE '40' END) AS "CodMeioTransporte25", 
						(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN '30' ELSE NULL END) AS "CodMeioTransporte26", 
						NULLIF(ISNULL((SELECT PAE_CODI FROM TAB_IATA WITH(NOLOCK) WHERE IAT_CODI = NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 9, 4))), '')), NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 9, 4))), '')), '') AS "CodAeroporto"
					FOR XML PATH('MeioTransportePartida'), TYPE), 
					(SELECT 
						(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN '30' ELSE '40' END) AS "CodMeioTransporte", 
						(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN 'CAMIAO' ELSE 'SRR6645' END) AS "MatriculaMT", 
						(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN 'PT' ELSE 'DK' END) AS "CodPais"
					FOR XML PATH('MeioTransporteFronteira'), TYPE), 
					(CASE WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') = '{' AND ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') IN ('GB', 'XI', 'XU')) THEN 'FR620001' WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 7, 2))), '') = 'GI' THEN 'ES001167' ELSE 'PT000020' END) AS "CodEstanciaTAC", 
					'AEX00000097020PT' AS "LocalizacaoMercadorias/CodLocalAutorizado", 
					'FCA' AS "CodCondEntrega", 
					'AEROPORTO PORTO' AS "Lugar", 
					'11' AS "CodNaturezaTransacao",
					NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 163, 2))), '') AS "CodPais", 
					CAST(0 AS decimal(28, 6)) AS "TotalFrete", 
					CAST(0 AS decimal(28, 6)) AS "TotalSeguro",					 
					1 AS "Origem",
					(SELECT												
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') AS "CodExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "NomeExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 104, 35))), '') AS "MoradaExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') AS "LocalidadeExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 9))), '') AS "CodPostalExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') AS "LocPostalExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '') AS "CodPaisExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 320, 9))), '') AS "NIFExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') AS "CodDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "NomeDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '') AS "MoradaDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "LocalidadeDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') AS "CodPaisDestinatario", 
						CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(28, 6)) AS "Montante", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 163, 2))), '') AS "CodPais", 
						CAST(ROUND((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(28, 6)) / 10) * 0.9, 3) AS decimal(28, 6)) AS "MassaLiqTotal", 
						CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(28, 6)) / 10) AS decimal(28, 6)) AS "MassaBrtTotal", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 34, 11))), '') AS "MiniCPA",
						(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 33, 2))), '') WHEN 'P3' THEN '01' WHEN 'P4' THEN '02' WHEN 'P5' THEN '03' WHEN 'T5' THEN '04' WHEN 'AC' THEN '05' WHEN 'T3' THEN '06' WHEN 'P2' THEN '07' ELSE NULL END) AS "DutyType", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 210, 6))), '') AS "NomeFicheiro", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '') AS "PPouFC", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))), '') AS "NumeroVoo", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 333, 35))), '') AS "Referencia1", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 296, 12))), '') AS "Referencia2", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 35))), '') AS "Tracking", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 51, 11))), '') AS "Shipping", 
						CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 100, 3))) AS int) AS "VolsDirty"
					FOR XML PATH('DadosManifesto'), TYPE), 
					(SELECT
						(SELECT 
							1 AS "NumeroAdicao", 
							art.APA_CODI AS "CodArtigo", 
							art.APA_DESG AS "DesignacaoArtigo", 
							'PT' AS "CodPaisOrigem", 
							CAST((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))), '')
									WHEN 'LBS' THEN ROUND((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(28, 6)) * 0.4536 * 10), 1) 
									ELSE (CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(28, 6)) / 10) 
								END) AS decimal(28, 6)) AS "MassaBruta", 
							CAST(ROUND(CAST((CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))), '')
									WHEN 'LBS' THEN ROUND((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(28, 6)) * 0.4536 * 10), 1) 
									ELSE (CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(28, 6)) / 10) 
								END) AS decimal(28, 6)) * 0.9, 3) AS decimal(28, 6)) AS "MassaLiquida",						
							'1000' AS "Regime", 
							CAST(0 AS decimal(28, 6)) AS "QtdUnidades", 
							CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(28, 6)) AS "ValorAdicao", 
							CAST(0 AS decimal(28, 6)) AS "ValorFrete", 
							CAST(0 AS decimal(28, 6)) AS "ValorSeguro", 
							(SELECT 
								(SELECT 
									DOC_CODI AS "CodDocumento", 
									DOC_NREF AS "NumeroReferencia", 
									DOC_DTEM AS "DataEmissao"									
								FROM (
									SELECT 'N740' as DOC_CODI, NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AS DOC_NREF, (CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS DOC_DTEM
									UNION															
									SELECT 'N830' as DOC_CODI, NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AS DOC_NREF, (CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS DOC_DTEM
									) AS UNI_DOCS									
								FOR XML PATH('Documento'), TYPE)							
							FOR XML PATH('Documentos'), TYPE), 							
							(SELECT
								(SELECT 
									'LET' AS "Marca", 																			
									'CM' AS "CodNaturezaVols", 
									CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 100, 3))) AS int) AS "NumeroVols", 						
									CAST(0 AS bit) AS "P", 						
									CAST(0 AS bit) AS "R"						
								FOR XML PATH('MarcaEVolume'), TYPE)
							FOR XML PATH('MarcasEVolumes'), TYPE)
						FROM TAB_APAU AS art WITH(NOLOCK)
						WHERE art.APA_CODI = '00000000'					
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE)
				FROM @XMLFicheiroUPS.nodes('declaracaoUPS') AS t(c)
				FOR XML PATH('Declaracao'), TYPE)
			FOR XML PATH('DeclaracoesExpToGIDWin'), ELEMENTS)					
-- processa a geração da declaração EXP-CAU
		EXEC @NumErro = SP_ExportacaoXML_GeraDeclaracoesDeXML @XMLDeclaracao, @CodUtilizador, @Erro OUTPUT	
		IF @NumErro <> 0
			RAISERROR('Erro na importação da declaração EXP-SAE: %s', 16, 1, @Erro)		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_ImportaFicheiroUPS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_ImportaFicheiroUPS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_IntegracaoNSTI_AtribuiID]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_IntegracaoNSTI_AtribuiID] @XMLDeclaracoes xml, @IdDeclaracaoNSTI int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- atribui o ID da declaração NSTI gerada pela integração NSTI nas declarações EXP-SAE
		UPDATE PRO_EXML SET EXM_INST = @IdDeclaracaoNSTI
		WHERE EXM_IDTY IN (SELECT x.d.value('id[1]', 'bigint')
							FROM @XMLDeclaracoes.nodes('DeclaracoesEXPSAE/Declaracao') AS x(d))
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_IntegracaoNSTI_AtribuiID] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_IntegracaoNSTI_AtribuiID] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard] @XMLDeclaracoes xml, @Tipologia tinyint, @TipoDeclaracao tinyint, @Data datetime, @CodNatureza varchar(6), 
	@CodOperadorNSTI varchar(18), @NumOperadorTIR varchar(17), @NomeRepresentante varchar(70), @LocalidadeOperadorNSTI varchar(35), @CodTipoDeclaracao varchar(10), 
	@CodLocalAutorizado varchar(17), @CodEstanciaPassagem1 varchar(8), @CodEstanciaDestino varchar(8), @ResultadoControlo varchar(2), @DataControlo datetime, 
	@MatriculaMeioTranspPartida varchar(27), @CodPaisMeioTranspPartida varchar(2), @NumeroSelo1 varchar(20), @NumeroSelo2 varchar(20), @NumeroSelo3 varchar(20), @NumeroSelo4 varchar(20), 
	@NumeroRUR varchar(35), @FicheiroXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @IdDeclaracaoEXP bigint, @CodEstanciaPartida varchar(8), @DeclaracaoParteResto bit, @TotalVolumesParteResto int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem o ID da 1ª declaração EXP-SAE
		SELECT TOP 1 @IdDeclaracaoEXP = x.d.value('id[1]', 'bigint')
		FROM @XMLDeclaracoes.nodes('DeclaracoesEXPSAE/Declaracao[1]') AS x(d)
-- obtem a estância de partida na 1ª declaração EXP-SAE
		SELECT @CodEstanciaPartida = EAD_CODA
		FROM PRO_EXML WITH(NOLOCK)
		WHERE EXM_IDTY = @IdDeclaracaoEXP
-- obtem se existem declarações EXP-SAE P/R 
		IF @Tipologia = 9 /*TORRESTIR*/
		BEGIN
			IF EXISTS(SELECT 1 
					FROM @XMLDeclaracoes.nodes('DeclaracoesEXPSAE/Declaracao') AS x(d)
						INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON x.d.value('id[1]', 'bigint') = exm.EXM_IDTY
						INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON exm.EXM_EANO = adi.EXM_EANO AND exm.EXM_CODI = adi.EXM_CODI AND exm.DEC_CODI = adi.EXM_COPE
						INNER JOIN PRO_EXMV AS mvl WITH(NOLOCK) ON adi.EXA_CHVE = mvl.EXA_CHVE
					WHERE mvl.EXM_PART = 1)
				SET @DeclaracaoParteResto = 1
			ELSE
				SET @DeclaracaoParteResto = 0
		END
		ELSE
			SET @DeclaracaoParteResto = 0
-- obtem o total de volumes de todas as declarações EXP-SAE
		IF @DeclaracaoParteResto = 1
		BEGIN
			SELECT @TotalVolumesParteResto = SUM(ISNULL(exm.EXM_TVL6, 0))
			FROM @XMLDeclaracoes.nodes('DeclaracoesEXPSAE/Declaracao') AS x(d)
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON x.d.value('id[1]', 'bigint') = exm.EXM_IDTY							
		END
		ELSE
			SET @TotalVolumesParteResto = 0
-- constroi XML para ficheiro NSTI formato STANDARD do GIDWin XE
		SET @FicheiroXML = 				
			(SELECT
				(SELECT 'I' AS "@acao",
					(CONVERT(varchar(10), @Data, 120) + 'Z') AS "data",
					@CodNatureza AS "natureza",
					NULLIF(@NumeroRUR, '') AS "referenciaInterna", 
					(SELECT
						(SELECT
							@CodOperadorNSTI AS "operador",
							NULLIF(@NumOperadorTIR, '') AS "numeroOperadorTIR",
							@NomeRepresentante AS "nomeRepresentante",
							@LocalidadeOperadorNSTI AS "localDeclaracao"
						FOR XML PATH('operadorNSTI'), TYPE),
						(SELECT
							'999999990' AS "nif"						
						FOR XML PATH('expedidor'), TYPE),
						'PT' AS "paisExpedicao",
						(SELECT
							(CASE @Tipologia WHEN 2 THEN '5' ELSE NULL END) AS "fornecedor", /*UPS*/
							(CASE @Tipologia WHEN 9 THEN '999999990' ELSE NULL END) AS "nif" /*TORRESTIR*/		
						FOR XML PATH('destinatario'), TYPE),
						'GB' AS "paisDestino",
						(SELECT
							'UPS' AS "fornecedor"
						HAVING @TipoDeclaracao = 0 AND @Tipologia = 2 /*UPS*/
						FOR XML PATH('operadorAutorizado'), TYPE)
					FOR XML PATH('operadores'), TYPE),
					@CodTipoDeclaracao AS "tipoDeclaracao",
					(SELECT
						'LC' AS "tipo",
						@CodLocalAutorizado AS localAutorizado
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					(SELECT
						@CodEstanciaPartida AS "estanciaPartida",
						@CodEstanciaPassagem1 AS "estanciaPassagem1",
						@CodEstanciaDestino AS "estanciaDestino",
						(CASE @TipoDeclaracao WHEN 0 THEN NULLIF(@ResultadoControlo, '') ELSE NULL END) AS "resultadoControlo",
						(CASE @TipoDeclaracao WHEN 0 THEN (CONVERT(varchar(10), @DataControlo, 120) + 'Z') ELSE NULL END) AS "dataControlo"
					FOR XML PATH('estancias'), TYPE),
					(SELECT
						(SELECT
							'3' AS "meioTransporte",
							NULLIF(@MatriculaMeioTranspPartida, '''') AS "matricula",
							@CodPaisMeioTranspPartida AS "pais"
						FOR XML PATH('partida'), TYPE),
						(SELECT
							'3' AS "meioTransporte",
							NULLIF(@MatriculaMeioTranspPartida, '') AS "matricula",
							@CodPaisMeioTranspPartida AS "pais"						
						FOR XML PATH('fronteira'), TYPE)						
					FOR XML PATH('transporte'), TYPE),
					(SELECT
						(SELECT
							t.numeroSelo AS "numeroSelo"
						FROM (
							SELECT @NumeroSelo1 AS numeroSelo
							UNION ALL
							SELECT @NumeroSelo2 AS numeroSelo
							UNION ALL
							SELECT @NumeroSelo3 AS numeroSelo
							UNION ALL
							SELECT @NumeroSelo4 AS numeroSelo
							) AS t
						WHERE ISNULL(t.numeroSelo, '') <> ''
						FOR XML PATH('selo'), TYPE)
					HAVING (ISNULL(@NumeroSelo1, '') + ISNULL(@NumeroSelo2, '') + ISNULL(@NumeroSelo3, '') + ISNULL(@NumeroSelo4, '')) <> ''
					FOR XML PATH('selos'), TYPE),
					(SELECT
						(SELECT 'I' AS "@acao", 
							t.EXA_NUME AS "numeroAdicao",
							t.APA_CO33 AS "artigo", 
							t.APA_DESG AS "designacao", 
							CAST((CASE @Tipologia
								WHEN 2 THEN t.EXM_TMLQ
								ELSE t.EXA_MLQD
							END) AS decimal(18, 3)) AS "massaLiquida",
							CAST((CASE @Tipologia
								WHEN 2 THEN t.EXM_TMBR
								ELSE t.EXA_MBRT
							END) AS decimal(18, 3)) AS "massaBruta",
							CAST((CASE @TipoDeclaracao 
								WHEN 1 THEN t.EXA_QUSU 
								ELSE NULL 
							END) AS decimal(18, 6)) AS "unidadesSupl", 
							'EU' AS paisMoeda,
							CAST((CASE @Tipologia
								WHEN 2 THEN t.EXM_VEUR
								ELSE t.EXA_VALO
							END) AS decimal(18, 3)) AS "valor",							
							(SELECT TOP 1
								(SELECT
									(CASE @DeclaracaoParteResto
										WHEN 1 THEN 'PARTE'
										ELSE NULLIF(LEFT(emv.EXM_MARN, 42), '')
									END) AS "marcas",
									emv.TEM_CODI AS "tipoEmbalagem",
									(CASE @DeclaracaoParteResto
										WHEN 1 THEN @TotalVolumesParteResto
										ELSE CAST(emv.EXM_NVOL AS int)
									END) AS "volumes",
									0 AS "unidades",
									@DeclaracaoParteResto AS "parte"
								FROM PRO_EXMV AS emv WITH(NOLOCK)
									INNER JOIN TAB_TEMB AS tem WITH(NOLOCK) ON emv.TEM_CODI = tem.TEM_CODI
								WHERE emv.EXA_CHVE = t.EXA_CHVE AND ((t.EXA_NUME = 1) OR (t.EXA_NUME > 1 AND @DeclaracaoParteResto = 0)) AND tem.TEM_NSTI = 1 AND @Tipologia = 9 /*TORRESTIR*/
								FOR XML PATH('marcaEVolume'), TYPE),
								(SELECT TOP 1
									NULLIF(LEFT(emv.EXM_MARN, 42), '') AS "marcas",
									emv.TEM_CODI AS "tipoEmbalagem",
									CAST(t.EXM_TVL6 AS int) AS "volumes",
									0 AS "unidades",
									@DeclaracaoParteResto AS "parte"
								FROM PRO_EXAD AS adi WITH(NOLOCK)
									INNER JOIN PRO_EXMV AS emv WITH(NOLOCK) ON adi.EXA_CHVE = emv.EXA_CHVE
									INNER JOIN TAB_TEMB AS tem WITH(NOLOCK) ON emv.TEM_CODI = tem.TEM_CODI
								WHERE adi.EXM_EANO = t.EXM_EANO AND adi.EXM_CODI = t.EXM_CODI AND adi.EXM_COPE = t.DEC_CODI AND adi.EXA_LINH = 1 AND tem.TEM_NSTI = 1 AND @Tipologia = 2 /*UPS*/
								FOR XML PATH('marcaEVolume'), TYPE)
							HAVING (t.EXA_NUME = 1) OR (t.EXA_NUME > 1 AND @DeclaracaoParteResto = 0)
							FOR XML PATH('marcasEVolumes'), TYPE),
							(SELECT								
								s.RAA_CODI AS "documento",
								NULLIF(t.EXM_NDGA, '') AS "referencia",
								CONVERT(varchar(10), t.EXM_DDGA, 105) AS "complemento"
							FROM (SELECT 'DECEXP' AS RAA_CODI 
								HAVING @TipoDeclaracao = 0
								UNION
								SELECT DOC_CODI AS RAA_CODI
								FROM TAB_DOCU WITH(NOLOCK) 
								WHERE DOC_CODI = 'N830' AND @TipoDeclaracao = 1) AS s
							WHERE ISNULL(t.EXM_NDGA, '') <> '' AND @Tipologia = 2 /*UPS*/														
							FOR XML PATH('referenciaAdministrativa'), ROOT('referenciasAdministrativas'), TYPE),
							(SELECT 
								doc.DOC_CODI AS "documento",
								NULLIF(LEFT(s.EXD_NREF, 35), '') AS "referencia",
								CONVERT(varchar(10), s.EXD_DTEM, 105) AS "complemento"								
							FROM TAB_DOCU AS doc WITH(NOLOCK)
								INNER JOIN (SELECT (CASE @TipoDeclaracao 
														WHEN 1 THEN edo.DOC_CODI 																	
														ELSE (CASE LEFT(edo.DOC_CODI, 1) 
																WHEN 'N' THEN REPLACE(edo.DOC_CODI, 'N', '') 
																ELSE 'ZZZ' 
															END) 
													END) AS DOC_CODI, edo.EXD_NREF, edo.EXD_DTEM
											FROM PRO_EXAD AS adi WITH(NOLOCK)
												INNER JOIN PRO_EXDA AS edo WITH(NOLOCK) ON adi.EXA_CHVE = edo.EXA_CHVE
											WHERE adi.EXM_EANO = t.EXM_EANO AND adi.EXM_CODI = t.EXM_CODI AND adi.EXM_COPE = t.DEC_CODI AND adi.EXA_LINH = 1 AND edo.DOC_CODI IN ('N325', 'N380', 'N740', '9E06')
											UNION ALL
											SELECT 'ZZZ', NULLIF(t.EXM_NDGA, ''), CONVERT(varchar(10), t.EXM_DDGA, 105)
											HAVING @TipoDeclaracao = 0 AND @Tipologia = 9) AS s ON doc.DOC_CODI = s.DOC_CODI
							WHERE doc.DOC_TRAN = 1 AND ISNULL(LEFT(s.EXD_NREF, 35), '') <> ''
							FOR XML PATH('dadosDocumento'), ROOT('documentos'), TYPE)
						FROM (SELECT ROW_NUMBER() OVER(ORDER BY exm.EXM_IDTY, adi.EXA_LINH) AS EXA_NUME, exm.EXM_EANO, exm.EXM_CODI, exm.DEC_CODI, exm.EXM_NDGA, exm.EXM_DDGA,
								ISNULL(exm.EXM_TMLQ, 0) AS EXM_TMLQ, ISNULL(exm.EXM_TMBR, 0) AS EXM_TMBR, ISNULL(exm.EXM_TVL6, 0) AS EXM_TVL6,
								exm.CLI_NIF2, exm.CLI_NOM2, exm.CLI_MOR2, exm.CLI_LOC2, ISNULL(NULLIF(exm.CLI_CPO2, ''), '0000') AS CLI_CPO2, exm.CLI_LPO2, exm.CLI_PAI2,
								exm.FOR_COD8, exm.FOR_NOM8, exm.FOR_MOR8, exm.FOR_LOC8, ISNULL(NULLIF(exm.FOR_CPO8, ''), '0000') AS FOR_CPO8, exm.FOR_LPO8, exm.FOR_PAI8,
								ISNULL(NULLIF(exm.EXM_VEUR, 0), (SELECT SUM(EXA_VEOR) FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI)) AS EXM_VEUR,
								adi.EXA_CHVE, adi.APA_CO33, adi.APA_DESG, ISNULL(adi.EXA_MLQD, 0) AS EXA_MLQD, ISNULL(adi.EXA_MBRT, 0) AS EXA_MBRT, ISNULL(adi.EXA_QUSU, 0) AS EXA_QUSU, 
								ISNULL(NULLIF(ROUND((ISNULL(adi.EXA_VALO, 0) / ISNULL(exm.EXM_TX23, 1)), 3), 0), adi.EXA_VEOR) AS EXA_VALO
								FROM @XMLDeclaracoes.nodes('DeclaracoesEXPSAE/Declaracao') AS x(d)
									INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON x.d.value('id[1]', 'bigint') = exm.EXM_IDTY
									INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON exm.EXM_EANO = adi.EXM_EANO AND exm.EXM_CODI = adi.EXM_CODI AND exm.DEC_CODI = adi.EXM_COPE
										AND adi.EXA_LINH = (CASE @Tipologia
																WHEN 2 THEN (SELECT TOP 1 sad.EXA_LINH
																			FROM PRO_EXAD AS sad WITH(NOLOCK)
																				INNER JOIN TAB_APAU AS sap WITH(NOLOCK) ON sad.APA_CO33 = sap.APA_CODI 
																			WHERE sad.EXM_EANO = exm.EXM_EANO AND sad.EXM_CODI = exm.EXM_CODI and sad.EXM_COPE = exm.DEC_CODI
																			GROUP BY sad.EXA_LINH
																			ORDER BY MAX(ISNULL(sap.APA_TPT, 0)) DESC, MIN(sad.EXA_LINH))
																ELSE adi.EXA_LINH
															END)) AS t
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE) 				
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('TRACAUToGIDWin'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_IntegracaoNSTI_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_IntegracaoNSTI_ObtemDados] @Ano smallint, @Check bit, @CodEstanciaPartida varchar(8), @DataASDe datetime, @DataASA datetime, @CodNatureza varchar(6), 
	@CodPaisDestino varchar(2), @Somente100Primeiros bit, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @TotalRegistos bigint
	BEGIN TRY	
		SET @NumErro = 0
-- obtem a restrição do TOP
		IF @Somente100Primeiros = 1
			SET @TotalRegistos = 100
		ELSE
			SET @TotalRegistos = 9000000000000000000 --valor maximo (arredondado) do tipo bigint
-- obtem as declarações IMP-CAU disponíveis para integração NSTI
		SELECT TOP(@TotalRegistos) EXM_IDTY AS id, EXM_EANO AS ano, EXM_CODI AS codigo, DEC_CODI AS codigoDeclarante, EXM_NRII AS numero, CLI_COD2 AS codigoCliente, 
			CLI_NOM2 AS nomeCliente, FOR_COD8 AS codigoFornecedor, FOR_NOM8 AS nomeFornecedor, EXM_P17A AS codigoPaisDestino, EXM_CPRT AS documentoTransporte, 
			CAST(EXM_TVL6 AS decimal(18, 2)) AS totalVolumes, 
			CAST(EXM_VEUR AS decimal(18, 2)) AS totalMontanteEUR, 			
			@Check AS "S."
		FROM PRO_EXML WITH(NOLOCK)
		WHERE NST_CODI IS NULL AND EXM_INST IS NULL AND EXM_EANO = @Ano AND EAD_CODA = @CodEstanciaPartida			
			AND CAST(CONVERT(varchar(10), EXM_DTAS, 105) AS datetime) >= @DataASDe
			AND CAST(CONVERT(varchar(10), EXM_DTAS, 105) AS datetime) <= @DataASA
			AND (ISNULL(@CodNatureza, '') = '' OR NDE_CODI = @CodNatureza)			
			AND (ISNULL(@CodPaisDestino, '') = '' OR EXM_P17A = @CodPaisDestino)			
		ORDER BY EXM_CPRT
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_IntegracaoNSTI_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_IntegracaoNSTI_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_IntegracaoNSTIAdicoes_ExportaXMLStandard]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_IntegracaoNSTIAdicoes_ExportaXMLStandard] @AnoDeclaracaoEXP smallint, @NumDeclaracaoEXP int, @TipoDeclaracao tinyint, @NumDeclaracaoNSTI int, @Data datetime, 
	@CodNatureza varchar(6), @CodOperadorNSTI varchar(18), @NomeRepresentante varchar(70), @LocalidadeOperadorNSTI varchar(35), @NIFClienteExpedidor varchar(18), 
	@CodFornecedorDestinatario varchar(18), @CodPaisDestino varchar(2), @CodTipoDeclaracao varchar(10), @TipoLocalizacaoMercadorias varchar(2), @CodLocalAutorizado varchar(17), 
	@CodEstanciaPartida varchar(8), @CodEstanciaDestino varchar(8), @FicheiroXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @IdDeclaracaoEXP bigint
	BEGIN TRY	
		SET @NumErro = 0
-- obtem o ID da declaração EXP-SAE
		SELECT TOP 1 @idDeclaracaoEXP = EXM_IDTY
		FROM PRO_EXML WITH(NOLOCK)
		WHERE EXM_EANO = @AnoDeclaracaoEXP AND EXM_NRII = @NumDeclaracaoEXP
		ORDER BY EXM_IDTY DESC
-- verifica se declaração EXP-SAE é válida
		IF @idDeclaracaoEXP IS NULL
			RAISERROR('Declaração EXP-SAE "%d"."%d" inválida.', 16, 1, @AnoDeclaracaoEXP, @NumDeclaracaoEXP)
-- constroi XML para ficheiro NSTI formato STANDARD do GIDWin XE
		SET @FicheiroXML = 				
			(SELECT
				(SELECT 'U' AS "@acao",
					@NumDeclaracaoNSTI AS "numero",
					(CONVERT(varchar(10), @Data, 120) + 'Z') AS "data",
					@CodNatureza AS "natureza",
					(SELECT
						(SELECT
							@CodOperadorNSTI AS "operador",			
							@NomeRepresentante AS "nomeRepresentante",
							@LocalidadeOperadorNSTI AS "localDeclaracao"
						FOR XML PATH('operadorNSTI'), TYPE),
						(SELECT
							@NIFClienteExpedidor AS "nif"
						FOR XML PATH('expedidor'), TYPE),
						(SELECT
							@CodFornecedorDestinatario AS "fornecedor"
						FOR XML PATH('destinatario'), TYPE),
						@CodPaisDestino AS "paisDestino"
					FOR XML PATH('operadores'), TYPE),
					@CodTipoDeclaracao AS "tipoDeclaracao",
					(SELECT
						(CASE @TipoDeclaracao 
							WHEN 1 THEN (CASE @TipoLocalizacaoMercadorias WHEN 'B' THEN 'LU' WHEN 'C' THEN 'LP' WHEN 'A' THEN 'LR' ELSE 'LC' END)
							ELSE @TipoLocalizacaoMercadorias 
						END) AS "tipo",
						@CodLocalAutorizado AS localAutorizado
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					(SELECT
						@CodEstanciaPartida AS "estanciaPartida",
						@CodEstanciaDestino AS "estanciaDestino"
					FOR XML PATH('estancias'), TYPE),
					(SELECT
						(SELECT 'I' AS "@acao",
							adi.EXA_LINH AS "numeroAdicao",
							adi.APA_CO33 AS "artigo",
							adi.APA_DESG AS "designacao",
							CAST(ISNULL(adi.EXA_MLQD, 0) AS decimal(18, 3)) AS "massaLiquida",
							CAST(ISNULL(adi.EXA_MBRT, 0) AS decimal(18, 3)) AS "massaBruta",
							CAST((CASE @TipoDeclaracao 
								WHEN 1 THEN adi.EXA_QUSU 
								ELSE NULL 
							END) AS decimal(18, 6)) AS "unidadesSupl",
							'EU' AS paisMoeda,
							CAST(ROUND((adi.EXA_VALO / exm.EXM_TX23), 3) AS decimal(18, 3)) AS "valor",
							(SELECT TOP 1
								(SELECT
									(CASE
										WHEN (EXM_PART = 1 OR EXM_REST = 1) THEN 'PARTE'
										ELSE NULLIF(LEFT(EXM_MARN, 42), '')
									END) AS "marcas",
									TEM_CODI AS "tipoEmbalagem",
									CAST(EXM_NVOL AS int) AS "volumes",
									0 AS "unidades",
									(CASE
										WHEN (EXM_PART = 1 OR EXM_REST = 1) THEN CAST(1 AS bit)
										ELSE CAST(0 AS bit)
									END) AS "parte"
								FROM PRO_EXMV WITH(NOLOCK)
								WHERE EXA_CHVE = adi.EXA_CHVE AND ((adi.EXA_LINH = 1) OR (adi.EXA_LINH > 1 AND EXM_PART = 0 AND EXM_REST = 0))
								FOR XML PATH('marcaEVolume'), TYPE)
							FROM PRO_EXMV WITH(NOLOCK)
							WHERE EXA_CHVE = adi.EXA_CHVE AND ((adi.EXA_LINH = 1) OR (adi.EXA_LINH > 1 AND EXM_PART = 0 AND EXM_REST = 0))
							FOR XML PATH('marcasEVolumes'), TYPE),
							(SELECT								
								s.RAA_CODI AS "documento",
								NULLIF(exm.EXM_NDGA, '') AS "referencia",
								CONVERT(varchar(10), exm.EXM_DDGA, 105) AS "complemento"
							FROM (SELECT 'DECEXP' AS RAA_CODI 
								HAVING @TipoDeclaracao = 0
								UNION
								SELECT DOC_CODI AS RAA_CODI 
								FROM TAB_DOCU WITH(NOLOCK) 
								WHERE DOC_CODI = 'N337' AND @TipoDeclaracao = 1) AS s
							WHERE ISNULL(exm.EXM_NDGA, '') <> ''
							FOR XML PATH('referenciaAdministrativa'), ROOT('referenciasAdministrativas'), TYPE),							
							(SELECT 
								doc.DOC_CODI AS "documento",
								NULLIF(LEFT(t.EXD_NREF, 35), '') AS "referencia",
								CONVERT(varchar(10), t.EXD_DTEM, 105) AS "complemento"								
							FROM TAB_DOCU AS doc WITH(NOLOCK)
								INNER JOIN (SELECT TOP 1 (CASE @TipoDeclaracao 
															WHEN 1 THEN DOC_CODI 
															ELSE REPLACE(DOC_CODI, 'N', '') 
														END) AS DOC_CODI, EXD_NREF, EXD_DTEM
											FROM PRO_EXDA WITH(NOLOCK)
											WHERE EXA_CHVE = adi.EXA_CHVE AND DOC_CODI IN ('N325', 'N380')) AS t ON doc.DOC_CODI = t.DOC_CODI							
							WHERE doc.DOC_TRAN = 1 AND ISNULL(LEFT(t.EXD_NREF, 35), '') <> '' AND adi.EXA_LINH = 1
							FOR XML PATH('dadosDocumento'), ROOT('documentos'), TYPE), 							
							(SELECT TOP 1
								(SELECT
									LEFT(EXC_CONT, 17) AS "numeroContentor"
								FROM PRO_EXCT WITH(NOLOCK)
								WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI
								FOR XML PATH('contentor'), TYPE)
							FROM PRO_EXCT WITH(NOLOCK)
							WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI
							FOR XML PATH('contentores'), TYPE)
						FROM PRO_EXML AS exm WITH(NOLOCK)
							INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON exm.EXM_EANO = adi.EXM_EANO AND exm.EXM_CODI = adi.EXM_CODI AND exm.DEC_CODI = adi.EXM_COPE
						WHERE exm.EXM_IDTY = @idDeclaracaoEXP
						ORDER BY adi.EXA_LINH
						FOR XML PATH('adicao'), TYPE)					
					FOR XML PATH('adicoes'), TYPE)				
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('TRACAUToGIDWin'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_IntegracaoNSTIAdicoes_ExportaXMLStandard] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_IntegracaoNSTIAdicoes_ExportaXMLStandard] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_Listagens]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_Listagens] @ModoMenu bit, @IDListagem tinyint, @Ano smallint, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @MesAtual tinyint
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
	SET @MesAtual = MONTH(@DataAtual)
	BEGIN TRY	
		SET @NumErro = 0
-- obtem as listagens a apresentar nas declarações EXP-SAE
		IF @ModoMenu = 1
		BEGIN
			SELECT 0 AS id, 'Reduzida (Mensal)' AS titulo, 'Vista Reduzida p/ Mês Atual' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 1 AS id, 'Reduzida (Global)' AS titulo, 'Vista Reduzida Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 2 AS id, 'Standard (Mensal)' AS titulo, 'Vista Standard p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 3 AS id, 'Standard (Global)' AS titulo, 'Vista Standard Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 4 AS id, 'Detalhada (Mensal)' AS titulo, 'Vista Detalhada p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 5 AS id, 'Detalhada (Global)' AS titulo, 'Vista Detalhada Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 6 AS id, 'Adições Reduzida (Mensal)' AS titulo, 'Vista Adições Reduzida p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION
			SELECT 7 AS id, 'Adições Reduzida (Global)' AS titulo, 'Vista Adições Reduzida Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 8 AS id, 'Adições Standard (Mensal)' AS titulo, 'Vista Adições Standard p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION
			SELECT 9 AS id, 'Adições Standard (Global)' AS titulo, 'Vista Adições Standard Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			UNION
			SELECT 10 AS id, 'Documentos (Gerais)' AS titulo, 'Vista Documentos Gerais' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION
			SELECT 11 AS id, 'Documentos (Adições)' AS titulo, 'Vista Documentos das Adições' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			UNION			
			SELECT 12 AS id, 'Documentos Precedentes (Gerais)' AS titulo, 'Vista Documentos Precedentes Gerais' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION	
			SELECT 13 AS id, 'Documentos Precedentes (Adições)' AS titulo, 'Vista Documentos Precedentes das Adições' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			UNION	
			SELECT 14 AS id, 'Chassis/Matriculas' AS titulo, 'Vista Chassis/Matriculas' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo	
			UNION		
			SELECT 15 AS id, 'Contentores' AS titulo, 'Vista Contentores' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo					
			ORDER BY id, titulo			
		END
		ELSE
		BEGIN
-- obtem as declarações EXP-SAE para as listagens "Reduzida (Mensal)" e "Reduzida (Global)"
			IF @IDListagem IN (0, 1)
			BEGIN
				SELECT EXM_IDTY AS id, EXM_NRII AS "Processo", EXM_DATA AS "Data", EXM_DTVO AS "Data Voo", EXM_ANXB AS "Anexo", NDE_CODI AS "Natureza", 
					(CASE EXM_SEGU WHEN 2 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "Segurança", 
					EXM_DCEN AS "DC", TDE_COD1 AS "Tipo Declaração", EXM_TPRO AS "TD Adicional", EXM_REGI AS "Regime", EAD_CODA AS "Estância Exportação", EXM_CPRT AS "Documento Transporte", 
					EXM_NVRF AS "V/ Referência", EXM_NRLO AS "NRL", EXM_NDGA AS "NRM", 
					(CASE EXM_STAT WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Anulado' WHEN 4 THEN 'Finalizado' ELSE 'Por Enviar' END) AS "Status", 
					dbo.fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao(EXM_ESTO) AS "Estado Operação", 
					EXM_DTAS AS "Data AS", CLI_NOM2 AS "Exportador", FOR_NOM8 AS "Destinatário", EXM_TAD5 AS "Adições", EXM_TVL6 AS "Volumes", EXM_CNUM AS "Conta N.º", EXM_CRTA AS "CA", 
					EXM_CRTD AS "CD", EXM_CRTF AS "CF", EXM_UCRI AS "Utilizador", EXM_DTCR AS "Data Criação"
				FROM PRO_EXML WITH(NOLOCK)
				WHERE EXM_CNTX = 1 AND EXM_EANO = @Ano AND (CASE @IDListagem WHEN 0 THEN MONTH(EXM_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY DEC_CODI, EXM_CODI				
			END
			ELSE
-- obtem as declarações EXP-SAE para as listagens "Standard (Mensal)" e "Standard (Global)"
			IF @IDListagem IN (2, 3)
			BEGIN
				SELECT EXM_IDTY AS id, EXM_NRII AS "Processo", EXM_DATA AS "Data", EXM_DTVO AS "Data Voo", EXM_ANXB AS "Anexo", NDE_CODI AS "Natureza", 
					(CASE EXM_SEGU WHEN 2 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "Segurança", 
					EXM_DCEN AS "DC", TDE_COD1 AS "Tipo Declaração", EXM_TPRO AS "TD Adicional", EXM_REGI AS "Regime", EAD_CODA AS "Estância Exportação", EAD_C29A AS "Estância Apresentação", 
					EAD_CO29 AS "Estância Saída", EXM_CPRT AS "Documento Transporte", EXM_NVRF AS "V/ Referência", EXM_NRLO AS "NRL", EXM_NDGA AS "NRM", 
					(CASE EXM_STAT WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Anulado' WHEN 4 THEN 'Finalizado' ELSE 'Por Enviar' END) AS "Status", 
					dbo.fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao(EXM_ESTO) AS "Estado Operação", 
					EXM_DTAS AS "Data AS", CLI_NOM2 AS "Exportador", CLI_NIF2 AS "NIF", FOR_NOM8 AS "Destinatário", CEN_CO20 AS "C.E.", CAST(EXM_CT19 AS bit) AS "Contentor", 
					MTR_CO18 AS "MT Interior", EXM_MT18 AS "Ident. Interior", MTR_CO21 AS "MT Fronteira", EXM_MT21 AS "Ident. Fronteira", PAI_MO22 AS "Moeda", EXM_MT22 AS "Montante", 
					EXM_VATT AS "Valor Aduaneiro", EXM_TAD5 AS "Adições", EXM_TVL6 AS "Volumes", EXM_CNUM AS "Conta N.º", EXM_CRTA AS "CA", EXM_CRTD AS "CD", EXM_CRTF AS "CF", 
					EXM_UCRI AS "Utilizador", EXM_DTCR AS "Data Criação"
				FROM PRO_EXML WITH(NOLOCK)
				WHERE EXM_CNTX = 1 AND EXM_EANO = @Ano AND (CASE @IDListagem WHEN 2 THEN MONTH(EXM_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY DEC_CODI, EXM_CODI				
			END
			ELSE
-- obtem as declarações EXP-SAE para as listagens "Detalhada (Mensal)" e "Detalhada (Global)"
			IF @IDListagem IN (4, 5)
			BEGIN
				SELECT EXM_IDTY AS id, EXM_NRII AS "Processo", EXM_DATA AS "Data", EXM_DTVO AS "Data Voo", EXM_ANXB AS "Anexo", NDE_CODI AS "Natureza", 
					(CASE EXM_SEGU WHEN 2 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) AS "Segurança", 
					EXM_DCEN AS "DC", TDE_COD1 AS "Tipo Declaração", EXM_TPRO AS "TD Adicional", EXM_REGI AS "Regime", EAD_CODA AS "Estância Exportação", EAD_C29A AS "Estância Apresentação", 
					EAD_CO29 AS "Estância Saída", EXM_CPRT AS "Documento Transporte", EXM_NVRF AS "V/ Referência", EXM_NRLO AS "NRL", EXM_NDGA AS "NRM", 
					(CASE EXM_STAT WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Anulado' WHEN 4 THEN 'Finalizado' ELSE 'Por Enviar' END) AS "Status", 
					dbo.fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao(EXM_ESTO) AS "Estado Operação", 
					EXM_DTAS AS "Data AS", EXM_DCMP AS "Data Complementar", CLI_NOM2 AS "Exportador", CLI_NIF2 AS "NIF", FOR_NOM8 AS "Destinatário", EXM_P17A AS "P.D.", CEN_CO20 AS "C.E.", 
					(CASE EXM_TLOC WHEN 'A' THEN 'Local Designado' WHEN 'B' THEN 'Local Autorizado' WHEN 'C' THEN 'Local Aprovado' WHEN 'D' THEN 'Outro Local' END) AS "Tipo Localização", 
					LME_CO30 AS "Local Autorizado", EAD_CO30 AS "Estância", LEM_CO30 AS "UN/LOCODE", ARM_CO49 AS "Armazém", TAR_CO49 AS "Tipo", CAST(EXM_CT19 AS bit) AS "Contentor", 
					MTR_CO18 AS "MT Interior", EXM_MT18 AS "Ident. Interior", MTR_CO21 AS "MT Fronteira", EXM_MT21 AS "Ident. Fronteira", PAI_MO22 AS "Moeda", EXM_MT22 AS "Montante", 
					EXM_VATT AS "Valor Aduaneiro", EXM_TAD5 AS "Adições", EXM_TVL6 AS "Volumes", EXM_TMLQ AS "Massa Líquida", EXM_TMBR AS "Massa Bruta", EXM_CNUM AS "Conta N.º", EXM_CRTA AS "CA", 
					EXM_CRTD AS "CD", EXM_CRTF AS "CF", EXM_UCRI AS "Utilizador", EXM_DTCR AS "Data Criação"
				FROM PRO_EXML WITH(NOLOCK)
				WHERE EXM_CNTX = 1 AND EXM_EANO = @Ano AND (CASE @IDListagem WHEN 4 THEN MONTH(EXM_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY DEC_CODI, EXM_CODI									
			END
			ELSE
-- obtem as adições EXP-SAE para as listagens "Adições Reduzida (Mensal)" e "Adições Reduzida (Global)"
			IF @IDListagem IN (6, 7)
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.EXM_DATA AS "Data", c.EXM_REGI AS "Regime", 
					dbo.fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao(c.EXM_ESTO) AS "Estado Operação", 
					c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", c.EXM_CRTA AS "CA", c.EXM_CRTD AS "CD", c.EXM_CRTF AS "CF",
					a.EXA_LINH AS "N.º", SUBSTRING(a.APA_CP33, 1, 6) AS "Codigo Pautal", SUBSTRING(a.APA_CP33, 7, 2) AS "NC", a.APA_DESG AS "Designação Mercadorias", 
					a.EXA_VEST AS "Valor Estatistico"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN PRO_EXAD AS a WITH(NOLOCK) ON c.EXM_EANO = a.EXM_EANO AND c.EXM_CODI = a.EXM_CODI AND c.DEC_CODI = a.EXM_COPE
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano AND (CASE @IDListagem WHEN 6 THEN MONTH(c.EXM_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY c.DEC_CODI, c.EXM_CODI, a.EXA_LINH				
			END
			ELSE
-- obtem as adições EXP-SAE para as listagens "Adições Standard (Mensal)" e "Adições Standard (Global)"
			IF @IDListagem IN (8, 9)
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.EXM_DATA AS "Data", c.EXM_REGI AS "Regime", 
					dbo.fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao(c.EXM_ESTO) AS "Estado Operação", 
					c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", c.EXM_CRTA AS "CA", c.EXM_CRTD AS "CD", c.EXM_CRTF AS "CF",
					a.EXA_LINH AS "N.º", SUBSTRING(a.APA_CP33, 1, 6) AS "Codigo Pautal", SUBSTRING(a.APA_CP33, 7, 2) AS "NC", a.APA_DESG AS "Designação Mercadorias", 
					a.EXA_DESD AS "Regime Adicional", a.EXA_MLQD AS "Massa Liquida", a.EXA_MBRT AS "Massa Bruta", a.EXA_QUSU AS "Unidades", a.EXA_VALO AS "Valor Adição", 
					a.EXA_VFRE AS "Frete", a.EXA_VSEG AS "Seguro", a.EXA_AJUS AS "Ajustamento", a.EXA_VEST AS "Valor Estatistico"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN PRO_EXAD AS a WITH(NOLOCK) ON c.EXM_EANO = a.EXM_EANO AND c.EXM_CODI = a.EXM_CODI AND c.DEC_CODI = a.EXM_COPE
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano AND (CASE @IDListagem WHEN 8 THEN MONTH(c.EXM_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY c.DEC_CODI, c.EXM_CODI, a.EXA_LINH							
			END
			ELSE
-- obtem os documentos gerais EXP-SAE para a listagem "Documentos (Gerais)"
			IF @IDListagem = 10
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", doc.DOC_CODI AS "Documento", 
					(CASE ddo.tipo WHEN 1 THEN 'Transporte' WHEN 2 THEN 'Ref. Adicional' ELSE 'Suporte' END) AS "Tipo", 
					ddo.numero AS "Número"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON c.EXM_IDTY = ddo.id_declaracaoEXP 
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano 
				ORDER BY c.DEC_CODI, c.EXM_CODI, ddo.id				
			END
			ELSE
-- obtem os documentos das adições EXP-SAE para a listagem "Documentos (Adições)"
			IF @IDListagem = 11
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", a.EXA_LINH AS "N.º Adição", 
					ddo.DOC_CODI AS "Documento", 
					(CASE ddo.EXD_TIPO WHEN 1 THEN 'Transporte' WHEN 2 THEN 'Ref. Adicional' ELSE 'Suporte' END) AS "Tipo", 
					ddo.EXD_NREF AS "Número", ddo.EXD_DTEM AS "Data"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN PRO_EXAD AS a WITH(NOLOCK) ON c.EXM_EANO = a.EXM_EANO AND c.EXM_CODI = a.EXM_CODI AND c.DEC_CODI = a.EXM_COPE
					INNER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON a.EXA_CHVE = ddo.EXA_CHVE
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano 
				ORDER BY c.DEC_CODI, c.EXM_CODI, a.EXA_LINH, ddo.EXD_CHVE					
			END
			ELSE
-- obtem os precedentes gerais EXP-SAE para a listagem "Documentos Precedentes (Gerais)"
			IF @IDListagem = 12
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", doc.DOC_CODI AS "Documento", dpr.numero AS "Número"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN tb_EXP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) ON c.EXM_IDTY = dpr.id_declaracaoEXP 
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano
				ORDER BY c.DEC_CODI, c.EXM_CODI, dpr.id				
			END
			ELSE
-- obtem os precedentes das adições EXP-SAE para a listagem "Documentos Precedentes (Adições)"
			IF @IDListagem = 13
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", a.EXA_LINH AS "N.º Adição",  doc.DOC_CODI AS "Documento", dap.numero AS "Número"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN PRO_EXAD AS a WITH(NOLOCK) ON c.EXM_EANO = a.EXM_EANO AND c.EXM_CODI = a.EXM_CODI AND c.DEC_CODI = a.EXM_COPE
					INNER JOIN tb_EXP_DeclaracoesAdicoesPrecedentes AS dap WITH(NOLOCK) ON a.EXA_CHVE = dap.id_adicao
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dap.id_documento = doc.DOC_IDTY
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano 
				ORDER BY c.DEC_CODI, c.EXM_CODI, a.EXA_LINH, dap.id				
			END
			ELSE
-- obtem os chassis/matrículas de veículos das adições EXP-SAE para a listagem "Chassis/Matriculas"
			IF @IDListagem = 14
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", a.EXA_LINH AS "N.º Adição", 
					dav.EXI_NCHA AS "Chassi"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN PRO_EXAD AS a WITH(NOLOCK) ON c.EXM_EANO = a.EXM_EANO AND c.EXM_CODI = a.EXM_CODI AND c.DEC_CODI = a.EXM_COPE
					INNER JOIN PRO_EXIV AS dav WITH(NOLOCK) ON a.EXA_CHVE = dav.EXA_CHVE					
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano
				ORDER BY c.DEC_CODI, c.EXM_CODI, a.EXA_LINH, dav.EXI_CHVE	
			END
			ELSE
-- obtem os contentores gerais e das adições EXP-SAE para a listagem "Contentores"
			IF @IDListagem = 15
			BEGIN
				SELECT c.EXM_IDTY AS id, c.EXM_NRII AS "Processo", c.CLI_NOM2 AS "Exportador", c.EXM_NVRF AS "V/ Referência", c.EXM_NDGA as "NRM", c.MTR_CO18 AS "Navio", 
					adi.EXA_LINH AS "N.º Adição", dco.EXC_CONT AS "Contentor"
				FROM PRO_EXML AS c WITH(NOLOCK) 
					INNER JOIN PRO_EXCT AS dco WITH(NOLOCK) ON c.EXM_EANO = dco.EXM_EANO AND c.EXM_CODI = dco.EXM_CODI AND c.DEC_CODI = dco.EXM_COPE	
					LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesContentores AS dac WITH(NOLOCK) ON dco.EXC_CHVE = dac.id_contentor
					LEFT OUTER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON dac.id_adicao = adi.EXA_CHVE
				WHERE c.EXM_CNTX = 1 AND c.EXM_EANO = @Ano
				ORDER BY c.DEC_CODI, c.EXM_CODI, dco.EXC_LINH	 			
			END
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_Listagens] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_Listagens] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagemGeraXMLPT511C]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagemGeraXMLPT511C] @IdDeclaracao int, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem PT511C - Notificação de Apresentação das Mercadorias da Declaração de Exportação	
	SET @FicheiroXML = 				
		(SELECT
			NULLIF(dco.DEC_WSUS, '') AS "messageSender", 
			'AT' AS "messageRecipient", 
			CONVERT(varchar(19), @DataAtual, 120) AS "preparationDateAndTime", 
			'EXP-CAU' AS "messageIdentification", 
			'PT511C' AS "messageType", 
			NULLIF(exm.EXM_NRLO, '') AS "correlationIdentifier", 			
			(SELECT								
				NULLIF(exm.EXM_NRLO, '') AS "LRN"
			FOR XML PATH('ExportOperation'), TYPE),			
			(SELECT
				NULLIF(exm.EAD_C29A, '') AS "referenceNumber"
			HAVING exm.EXM_DCEN = 1 AND ISNULL(exm.EAD_C29A, '') <> ''
			FOR XML PATH('CustomsOfficeOfPresentation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_CODA, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExport'), TYPE), 			
			(SELECT 
				NULLIF(exm.EAD_CODI, '') AS "referenceNumber"
			HAVING LEFT(exm.EXM_REGI, 2) IN ('21', '22') AND ISNULL(exm.EAD_CODI, '') <> ''
			FOR XML PATH('SupervisingCustomsOffice'), TYPE), 			
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(dcl.DEC_NIF, '')), '') AS "identificationNumber"				
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(exm.CLI_PAI2, '') + ISNULL(exm.CLI_NIF2, '')), '') AS "identificationNumber",
				exm.EXM_TP14 AS "status"			
			HAVING ISNULL(exm.EXM_TP14, -1) = 2
			FOR XML PATH('Representative'), TYPE), 						
			(SELECT						
				(SELECT
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') THEN exm.EXM_CT19 ELSE NULL END) AS "containerIndicator", 
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND exm.EAD_CODA <> exm.EAD_CO29 THEN NULLIF(LEFT(exm.MTR_CO26, 1), '') ELSE NULL END) AS "inlandModeOfTransport", 					
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dco.EXC_CONT) AS "sequenceNumber",
						NULLIF(dco.EXC_CONT, '') AS "containerIdentificationNumber", 
						(SELECT COUNT(*) FROM tb_EXP_DeclaracoesContentoresSelos WITH(NOLOCK) WHERE id_contentor = dco.EXC_CHVE) AS "numberOfSeals", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber",
							NULLIF(numeroSelo, '') AS "identifier"
						FROM tb_EXP_DeclaracoesContentoresSelos WITH(NOLOCK) 
						WHERE id_contentor = dco.EXC_CHVE AND exm.EXM_SEGU = 2
						FOR XML PATH('Seal'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY dad.EXA_LINH) AS "sequenceNumber",
							dad.EXA_LINH AS "declarationGoodsItemNumber"
						FROM tb_EXP_DeclaracoesAdicoesContentores AS dac WITH(NOLOCK)
							INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON dac.id_adicao = dad.EXA_CHVE
						WHERE dac.id_contentor = dco.EXC_CHVE			
						FOR XML PATH('GoodsReference'), TYPE)
					FROM PRO_EXCT AS dco WITH(NOLOCK)						
					WHERE dco.EXM_EANO = exm.EXM_EANO AND dco.EXM_CODI = exm.EXM_CODI AND dco.EXM_COPE = exm.DEC_CODI AND exm.EXM_CT19 = 1
					FOR XML PATH('TransportEquipment'), TYPE),
					(SELECT 
						NULLIF(exm.EXM_TLOC, '') AS "typeOfLocation", 
						NULLIF(exm.EXM_QUAL, '') AS "qualifierOfIdentification", 
						(CASE ISNULL(exm.EXM_QUAL, '') WHEN 'Y' THEN NULLIF(exm.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
						NULLIF(exm.EXM_IADI, '') AS "additionalIdentifier", 
						(CASE ISNULL(exm.EXM_QUAL, '') WHEN 'U' THEN NULLIF(exm.LEM_CO30, '') ELSE NULL END) AS "UNLocode", 												
						(SELECT 
							NULLIF(exm.EAD_CO30, '') AS "referenceNumber"
						HAVING ISNULL(exm.EXM_QUAL, '') = 'V' AND ISNULL(exm.EAD_CO30, '') <> ''
						FOR XML PATH('CustomsOffice'), TYPE),				 						
						(SELECT 
							NULLIF(exm.EXM_ONIF, '') AS "identificationNumber"
						HAVING ISNULL(exm.EXM_QUAL, '') = 'X' AND ISNULL(exm.EXM_ONIF, '') <> ''
						FOR XML PATH('EconomicOperator'), TYPE),
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_MR30, '')) AS "streetAndNumber", 
							NULLIF(exm.EXM_CP30, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_LP30, '')) AS "city", 
							NULLIF(exm.PAI_CODI5, '') AS "country"					
						HAVING ISNULL(exm.EXM_QUAL, '') = 'Z' AND ISNULL(exm.EXM_MR30, '') <> ''				
						FOR XML PATH('Address'), TYPE)					
					FOR XML PATH('LocationOfGoods'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY t.id) AS "sequenceNumber",
						t.tipoIdentificacao AS "typeOfIdentification", 
						NULLIF(t.numeroIdentificacao, '') AS "identificationNumber", 
						NULLIF(t.codigoPais, '') AS "nationality"
					FROM (SELECT 0 AS id, exm.EXM_MTIT AS tipoIdentificacao, exm.EXM_MT18 AS numeroIdentificacao, exm.PAI_CODI4 AS codigoPais
						UNION ALL
						SELECT dmp.id, mtr.MTR_TIPO, dmp.identificacao, pai.PAI_CODI
						FROM tb_EXP_DeclaracoesMeiosTransportePartida AS dmp WITH(NOLOCK)
							INNER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dmp.id_meioTransporte = mtr.MTR_IDTY
							LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dmp.id_pais = pai.PAI_IDTY
						WHERE dmp.id_declaracaoEXP = exm.EXM_IDTY AND LEFT(exm.MTR_CO18, 1) IN ('2', '3')) AS t
					WHERE exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(exm.EXM_REGI, 2) = '76') AND ISNULL(t.numeroIdentificacao, '') <> '' 					
					FOR XML PATH('DepartureTransportMeans'), TYPE)
				FOR XML PATH('Consignment'), TYPE)				
			FOR XML PATH('GoodsShipment'), TYPE)
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dco WITH(NOLOCK) ON exm.DEC_CODI = dco.DEC_CODI	
			INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON exm.TDE_COD1 = tde.TDE_CODI
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
		WHERE exm.EXM_IDTY = @IdDeclaracao
		FOR XML PATH('PT511C'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagemGeraXMLPT511C] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagemGeraXMLPT511C] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagemGeraXMLPT513C]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagemGeraXMLPT513C] @IdDeclaracao int, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @PeriodoTransitorio bit
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem configuração do periodo transitório EXP-SAE dos Parâmetros de Despachos
	SELECT TOP 1 @PeriodoTransitorio = PDE_PTEX 
	FROM TAB_PDES WITH(NOLOCK)
-- constroi XML para ficheiro XML da mensagem PT513C - Pedido de Alteração da Declaração de Exportação	
	SET @FicheiroXML = 				
		(SELECT
			NULLIF(dco.DEC_WSUS, '') AS "messageSender", 
			'AT' AS "messageRecipient", 
			CONVERT(varchar(19), @DataAtual, 120) AS "preparationDateAndTime", 
			'EXP-CAU' AS "messageIdentification", 
			'PT513C' AS "messageType", 
			NULLIF(exm.EXM_NRLO, '') AS "correlationIdentifier", 			
			(SELECT								
				NULLIF(exm.EXM_NRLO, '') AS "LRN",
				NULLIF(exm.EXM_NDGA, '') AS "MRN",  
				NULLIF(tde.TDE_1CAS, '') AS "declarationType", 
				exm.EXM_TPRO AS "additionalDeclarationType", 
				exm.EXM_SEGU AS "security", 
				(CASE exm.EXM_SEGU WHEN 2 THEN NULLIF((CASE exm.EXM_INCE WHEN 'A' THEN 'A20' ELSE NULL END), '') ELSE NULL END) AS "specificCircumstanceIndicator", 
				(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) <> '76' THEN CAST(ISNULL(exm.EXM_MT22, 0) AS decimal(18, 2)) ELSE NULL END) AS "totalAmountInvoiced", 
				(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) <> '76' AND NOT EXISTS(SELECT 1 FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 0 AND doc.DOC_CODI = '9E06') THEN NULLIF(exm.PAI_MO22, '') ELSE NULL END) AS "invoiceCurrency" 
			FOR XML PATH('ExportOperation'), TYPE),
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
				doc.DOC_CODI AS "type", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dau.numero, '')) AS "referenceNumber", 
				NULLIF(dau.titular, '') AS "holderOfAuthorisation"
			FROM tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK)
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dau.id_documento = doc.DOC_IDTY
			WHERE id_declaracaoEXP = exm.EXM_IDTY
			FOR XML PATH('Authorisation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_C29A, '') AS "referenceNumber"
			HAVING exm.EXM_DCEN = 1 AND exm.EXM_TPRO <> 'R' AND ISNULL(exm.EAD_C29A, '') <> ''
			FOR XML PATH('CustomsOfficeOfPresentation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_CODA, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExport'), TYPE), 
			(SELECT
				NULLIF(exm.EAD_CO29, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExitDeclared'), TYPE), 
			(SELECT 
				NULLIF(exm.EAD_CODI, '') AS "referenceNumber"
			HAVING LEFT(exm.EXM_REGI, 2) IN ('21', '22') AND ISNULL(exm.EAD_CODI, '') <> ''
			FOR XML PATH('SupervisingCustomsOffice'), TYPE), 
			(SELECT 
				(CASE WHEN ISNULL(exm.CLI_PAI2, '') = 'PT' OR exm.EXM_TP2A IN ('C', 'S') THEN NULLIF((ISNULL(exm.CLI_PAI2, '') + ISNULL(exm.CLI_NIF2, '')), '') ELSE NULLIF(exm.CLI_NIF2, '') END) AS "identificationNumber", 
				(CASE WHEN ISNULL(exm.CLI_PAI2, '') <> 'PT' AND exm.EXM_TP2A = 'P' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_NOM2, 35) ELSE exm.CLI_NOM2 END), '')) ELSE NULL END) AS "name", 
				(SELECT
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_MOR2, 35) ELSE exm.CLI_MOR2 END), '')) AS "streetAndNumber", 					
					NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_CPO2, 9) ELSE exm.CLI_CPO2 END), '') AS "postcode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_LOC2, 20) ELSE exm.CLI_LOC2 END), '')) AS "city", 
					NULLIF(exm.CLI_PAI2, '') AS "country"
				HAVING ISNULL(exm.CLI_PAI2, '') <> 'PT' AND exm.EXM_TP2A = 'P'
				FOR XML PATH('Address'), TYPE)			
			FOR XML PATH('Exporter'), TYPE), 
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(dcl.DEC_NIF, '')), '') AS "identificationNumber"				
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(dcl.DEC_NIF, '')), '') AS "identificationNumber",
				exm.EXM_TP14 AS "status"			
			HAVING ISNULL(exm.EXM_TP14, -1) = 2
			FOR XML PATH('Representative'), TYPE), 			
			(SELECT 				
				NULLIF(exm.EXM_NC48, '') AS "deferredPayment"
			HAVING exm.EXM_ANXB NOT IN ('B3', 'B4') AND ISNULL(exm.EXM_NC48, '') <> ''
			FOR XML PATH('DeferredPayment'), TYPE),
			(SELECT		
				1 AS "sequenceNumber", 		
				(CASE WHEN exm.EXM_TPRO IN ('V', 'Z') THEN CONVERT(varchar(10), exm.EXM_DDGA, 120) ELSE NULL END) AS "declarationAcceptanceDate", 
				(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) NOT IN ('71', '76') THEN NULLIF(exm.NTR_CO24, '') ELSE NULL END) AS "natureOfTransaction",
				NULLIF(exm.EXM_P15A, '') AS "countryOfExport", 
				NULLIF(exm.EXM_P17A, '') AS "countryOfDestination", 				 						
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(funcao, '') AS "role", 
					NULLIF(nif, '') AS "identificationNumber"
				FROM tb_EXP_DeclaracoesIntervenientes WITH(NOLOCK) 		
				WHERE id_declaracaoEXP = exm.EXM_IDTY
				FOR XML PATH('AdditionalSupplyChainActor'), TYPE),
				(SELECT
					NULLIF(exm.CEN_CO20, '') AS "incotermCode", 
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE NULLIF(exm.PAE_CODI1, '') END) AS "UNLOCODE", 
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_LG20, '')) END) AS "location",
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE NULLIF(exm.PAI_CODI, '') END) AS "country", 										
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_TXTC, '')) ELSE NULL END) AS "text"
				HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) <> '76' AND ISNULL(exm.CEN_CO20, '') <> ''
				FOR XML PATH('DeliveryTerms'), TYPE), 
				(SELECT
					NULLIF(exm.TAR_CO49, '') AS "type", 
					NULLIF(exm.ARM_CO49, '') AS "identifier"
				HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND ISNULL(exm.TAR_CO49, '') <> ''
				FOR XML PATH('Warehouse'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
					doc.DOC_CODI AS "type", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.numero, '')) AS "referenceNumber"
				FROM tb_EXP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
				WHERE dpr.id_declaracaoEXP = exm.EXM_IDTY AND exm.EXM_TPRO NOT IN ('U', 'V')
				FOR XML PATH('PreviousDocument'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					doc.DOC_CODI AS "type", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 					
					ddo.numeroAdicao AS "documentLineItemNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.entidadeEmissora, '')) AS "issuingAuthorityName", 			
					CONVERT(varchar(10), ddo.dataValidade, 120) AS "validityDate"			
				FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 0 
				FOR XML PATH('SupportingDocument'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					doc.DOC_CODI AS "type", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber"
				FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO'
				FOR XML PATH('AdditionalReference'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY EXP_LINH) AS "sequenceNumber", 
					NULLIF(TXM_CODI, '') AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(TXM_DESC, '')) AS "text"
				FROM PRO_EXPA WITH(NOLOCK) 					
				WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI
				FOR XML PATH('AdditionalInformation'), TYPE),
				(SELECT
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') THEN exm.EXM_CT19 ELSE NULL END) AS "containerIndicator", 
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND exm.EAD_CODA <> exm.EAD_CO29 THEN NULLIF(LEFT(exm.MTR_CO26, 1), '') ELSE NULL END) AS "inlandModeOfTransport", 
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) NOT IN ('21', '22') AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(exm.EXM_REGI, 2) = '76') THEN NULLIF(LEFT(exm.MTR_CO21, 1), '') ELSE NULL END) AS "modeOfTransportAtTheBorder", 		
					(CASE WHEN ISNULL(exm.EXM_TAD5, 0) > 1 THEN ISNULL(exm.EXM_TMBR, 0) ELSE NULL END) AS "grossMass", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_NCMR, '')) AS "referenceNumberUCR", 																		
					(SELECT 
						NULLIF(exm.EXM_NTRP, '') AS "identificationNumber"
					HAVING exm.EXM_SEGU = 2 AND ISNULL(exm.EXM_NTRP, '') <> ''
					FOR XML PATH('Carrier'), TYPE),
					(SELECT 
						(CASE WHEN ISNULL(exm.PAI_CODI1, '') = 'PT' OR exm.CLI_TNIF1 IN ('C', 'S') THEN NULLIF((ISNULL(exm.PAI_CODI1, '') + ISNULL(exm.CLI_NIF1, '')), '') ELSE NULLIF(exm.CLI_NIF1, '') END) AS "identificationNumber", 
						(CASE WHEN ISNULL(exm.PAI_CODI1, '') <> 'PT' AND exm.CLI_TNIF1 = 'P' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_NOME1, '')) ELSE NULL END) AS "name", 					
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_MORA1, '')) AS "streetAndNumber", 					
							NULLIF(exm.CLI_CPOS1, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_LOCA1, '')) AS "city", 
							NULLIF(exm.PAI_CODI1, '') AS "country"
						HAVING ISNULL(exm.PAI_CODI1, '') <> 'PT' AND exm.CLI_TNIF1 = 'P'
						FOR XML PATH('Address'), TYPE)									
					HAVING exm.EXM_SEGU = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO' AND LEFT(exm.EXM_REGI, 2) NOT IN ('21', '22') AND ISNULL(exm.CLI_NOME1, '') <> ''			
					FOR XML PATH('Consignor'), TYPE), 
					(SELECT 						
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_NOM8, 35) ELSE exm.FOR_NOM8 END), '')) AS "name", 			
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_MOR8, 35) ELSE exm.FOR_MOR8 END), '')) AS "streetAndNumber", 							
							NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_CPO8, 9) ELSE exm.FOR_CPO8 END), '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_LOC8, 20) ELSE exm.FOR_LOC8 END), '')) AS "city", 
							NULLIF(exm.FOR_PAI8, '') AS "country"
						FOR XML PATH('Address'), TYPE)
					HAVING ISNULL(exm.FOR_NOM8, '') <> ''
					FOR XML PATH('Consignee'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dco.EXC_CONT) AS "sequenceNumber",
						NULLIF(dco.EXC_CONT, '') AS "containerIdentificationNumber", 
						(SELECT COUNT(*) FROM tb_EXP_DeclaracoesContentoresSelos WITH(NOLOCK) WHERE id_contentor = dco.EXC_CHVE) AS "numberOfSeals", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber",
							NULLIF(numeroSelo, '') AS "identifier"
						FROM tb_EXP_DeclaracoesContentoresSelos WITH(NOLOCK) 
						WHERE id_contentor = dco.EXC_CHVE AND exm.EXM_SEGU = 2
						FOR XML PATH('Seal'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY dad.EXA_LINH) AS "sequenceNumber",
							dad.EXA_LINH AS "declarationGoodsItemNumber"
						FROM tb_EXP_DeclaracoesAdicoesContentores AS dac WITH(NOLOCK)
							INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON dac.id_adicao = dad.EXA_CHVE
						WHERE dac.id_contentor = dco.EXC_CHVE			
						FOR XML PATH('GoodsReference'), TYPE)
					FROM PRO_EXCT AS dco WITH(NOLOCK)						
					WHERE dco.EXM_EANO = exm.EXM_EANO AND dco.EXM_CODI = exm.EXM_CODI AND dco.EXM_COPE = exm.DEC_CODI AND exm.EXM_CT19 = 1
					FOR XML PATH('TransportEquipment'), TYPE),
					(SELECT 
						NULLIF(exm.EXM_TLOC, '') AS "typeOfLocation", 
						NULLIF(exm.EXM_QUAL, '') AS "qualifierOfIdentification", 
						(CASE ISNULL(exm.EXM_QUAL, '') WHEN 'Y' THEN NULLIF(exm.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
						NULLIF(exm.EXM_IADI, '') AS "additionalIdentifier", 
						(CASE ISNULL(exm.EXM_QUAL, '') WHEN 'U' THEN NULLIF(exm.LEM_CO30, '') ELSE NULL END) AS "UNLocode", 												
						(SELECT 
							NULLIF(exm.EAD_CO30, '') AS "referenceNumber"
						HAVING ISNULL(exm.EXM_QUAL, '') = 'V' AND ISNULL(exm.EAD_CO30, '') <> ''
						FOR XML PATH('CustomsOffice'), TYPE),				 						
						(SELECT 
							NULLIF(exm.EXM_ONIF, '') AS "identificationNumber"
						HAVING ISNULL(exm.EXM_QUAL, '') = 'X' AND ISNULL(exm.EXM_ONIF, '') <> ''
						FOR XML PATH('EconomicOperator'), TYPE),
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_MR30, '')) AS "streetAndNumber", 
							NULLIF(exm.EXM_CP30, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_LP30, '')) AS "city", 
							NULLIF(exm.PAI_CODI5, '') AS "country"					
						HAVING ISNULL(exm.EXM_QUAL, '') = 'Z' AND ISNULL(exm.EXM_MR30, '') <> ''				
						FOR XML PATH('Address'), TYPE)
					HAVING exm.EXM_TPRO NOT IN ('D', 'E', 'F') 
					FOR XML PATH('LocationOfGoods'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY t.id) AS "sequenceNumber",
						t.tipoIdentificacao AS "typeOfIdentification", 
						NULLIF(t.numeroIdentificacao, '') AS "identificationNumber", 
						NULLIF(t.codigoPais, '') AS "nationality"
					FROM (SELECT 0 AS id, exm.EXM_MTIT AS tipoIdentificacao, exm.EXM_MT18 AS numeroIdentificacao, exm.PAI_CODI4 AS codigoPais
						UNION ALL
						SELECT dmp.id, mtr.MTR_TIPO, dmp.identificacao, pai.PAI_CODI
						FROM tb_EXP_DeclaracoesMeiosTransportePartida AS dmp WITH(NOLOCK)
							INNER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dmp.id_meioTransporte = mtr.MTR_IDTY
							LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dmp.id_pais = pai.PAI_IDTY
						WHERE dmp.id_declaracaoEXP = exm.EXM_IDTY AND LEFT(exm.MTR_CO18, 1) IN ('2', '3')) AS t
					WHERE exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(exm.EXM_REGI, 2) = '76') AND ISNULL(t.numeroIdentificacao, '') <> '' 					
					FOR XML PATH('DepartureTransportMeans'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXP_CHVE) AS "sequenceNumber",
						NULLIF(PAI_CODI, '') AS "country"
					FROM PRO_EXPI WITH(NOLOCK)
					WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI AND exm.EXM_SEGU = 2
					FOR XML PATH('CountryOfRoutingOfConsignment'), TYPE),
					(SELECT
						exm.EXM_MTFT AS "typeOfIdentification", 
						NULLIF(exm.EXM_MT21, '') AS "identificationNumber", 
						NULLIF(exm.PAI_CO21, '') AS "nationality"
					HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) NOT IN ('21', '22') AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(exm.EXM_REGI, 2) = '76') AND ISNULL(exm.EXM_MT21, '') <> ''
					FOR XML PATH('ActiveBorderTransportMeans'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 						
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber"
					FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 1
					FOR XML PATH('TransportDocument'), TYPE), 
					(SELECT
						NULLIF(exm.EXM_DTMP, '') AS "methodOfPayment" 
					HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND exm.EXM_SEGU = 2 AND ISNULL(exm.EXM_DTMP, '') <> ''
					FOR XML PATH('TransportCharges'), TYPE)
				FOR XML PATH('Consignment'), TYPE), 						
				(SELECT
					ROW_NUMBER() OVER(ORDER BY adi.EXA_LINH) AS "sequenceNumber", 
					adi.EXA_LINH AS "declarationGoodsItemNumber", 					
					(CASE WHEN (@PeriodoTransitorio = 1) OR (exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F')) THEN CAST(ISNULL(adi.EXA_VEST, 0) AS decimal(18, 2)) ELSE NULL END) AS "statisticalValue", 
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') THEN NULLIF(adi.NTR_CODI, '') ELSE NULL END) AS "natureOfTransaction", 					
					NULLIF(adi.PAI_CODI2, '') AS "countryOfExport", 
					NULLIF(adi.PAI_CODI4, '') AS "countryOfDestination", 				 						
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.EXA_NRUR, '')) AS "referenceNumberUCR", 			
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY aau.id) AS "sequenceNumber", 
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(aau.numero, '')) AS "referenceNumber", 	
						NULLIF(aau.titular, '') AS "holderOfAuthorisation"			
					FROM tb_EXP_DeclaracoesAdicoesAutorizacoes AS aau WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON aau.id_documento = doc.DOC_IDTY
					WHERE aau.id_adicao = adi.EXA_CHVE
					FOR XML PATH('Authorisation'), TYPE), 
					(SELECT
						NULLIF(LEFT(adi.TDE_REGI, 2), '') AS "requestedProcedure",
						NULLIF(RIGHT(adi.TDE_REGI, 2), '') AS "previousProcedure",
						(SELECT
							ROW_NUMBER() OVER(ORDER BY t.coluna) AS "sequenceNumber",
							NULLIF(t.desdobramento, '') AS "additionalProcedure"									
						FROM tb_TBL_Desdobramentos AS ddb WITH(NOLOCK)
							UNPIVOT(desdobramento FOR coluna IN (ddb.desdobramento1, ddb.desdobramento2, ddb.desdobramento3, ddb.desdobramento4, ddb.desdobramento5)) AS t
						WHERE t.id = adi.id_desdobramento
						FOR XML PATH('AdditionalProcedure'), TYPE) 
					FOR XML PATH('Procedure'), TYPE), 	
					(SELECT 
						(CASE WHEN ISNULL(adi.PAI_CODI1, '') = 'PT' OR adi.CLI_TNIF IN ('C', 'S') THEN NULLIF((ISNULL(adi.PAI_CODI1, '') + ISNULL(adi.CLI_NIF, '')), '') ELSE NULLIF(adi.CLI_NIF, '') END) AS "identificationNumber", 
						(CASE WHEN ISNULL(adi.PAI_CODI1, '') <> 'PT' AND adi.CLI_TNIF = 'P' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.CLI_NOME, '')) ELSE NULL END) AS "name", 					
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.CLI_MORA, '')) AS "streetAndNumber", 					
							NULLIF(adi.CLI_CPOS, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.CLI_LPOS, '')) AS "city", 
							NULLIF(adi.PAI_CODI1, '') AS "country"
						HAVING ISNULL(adi.PAI_CODI1, '') <> 'PT' AND adi.CLI_TNIF = 'P'
						FOR XML PATH('Address'), TYPE)									
					HAVING exm.EXM_SEGU = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO' AND LEFT(adi.TDE_REGI, 2) NOT IN ('21', '22') AND ISNULL(adi.CLI_NOME, '') <> ''	
					FOR XML PATH('Consignor'), TYPE),		
					(SELECT 						
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME, '')) AS "name", 			
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA, '')) AS "streetAndNumber", 							
							NULLIF(adi.FOR_CPOS, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS, '')) AS "city", 
							NULLIF(adi.PAI_CODI3, '') AS "country"
						FOR XML PATH('Address'), TYPE)
					HAVING ISNULL(adi.FOR_NOME, '') <> ''
					FOR XML PATH('Consignee'), TYPE), 								
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(funcao, '') AS "role", 
						NULLIF(nif, '') AS "identificationNumber"
					FROM tb_EXP_DeclaracoesAdicoesIntervenientes WITH(NOLOCK) 								
					WHERE id_adicao = adi.EXA_CHVE
					FOR XML PATH('AdditionalSupplyChainActor'), TYPE), 
					(SELECT
						NULLIF(adi.PAI_CODI, '') AS "countryOfOrigin", 
						(CASE WHEN (exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND (LEFT(adi.TDE_REGI, 2) <> '76')) THEN NULLIF(res.RES_NUTS, '') ELSE NULL END) AS "regionOfDispatch"
					HAVING ISNULL(adi.PAI_CODI, '') <> ''
					FOR XML PATH('Origin'), TYPE), 
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.APA_DESG, '')) AS "descriptionOfGoods", 
						(CASE WHEN exm.EXM_ANXB = 'B1' THEN NULLIF(adi.EXA_CCUS, '') ELSE NULL END) AS "cusCode", 						
						(SELECT 
							NULLIF(LEFT(adi.APA_CP33, 6), '') AS "harmonizedSystemSubHeadingCode", 
							NULLIF(SUBSTRING(adi.APA_CP33, 7, 2), '') AS "combinedNomenclatureCode", 							
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.EXA_ORDE) AS "sequenceNumber",
								NULLIF(t.EXA_ATAR, '') AS "taricAdditionalCode"
							FROM (
								SELECT 1 AS EXA_ORDE, adi.EXA_ATA1 AS EXA_ATAR
								UNION
								SELECT 2, adi.EXA_ATA2
								UNION
								SELECT 3, adi.EXA_ATA3
								UNION
								SELECT 4, adi.EXA_ATA4
								UNION
								SELECT 5, adi.EXA_ATA5
							) AS t
							WHERE ISNULL(t.EXA_ATAR, '') <> '' AND ISNULL(t.EXA_ATAR, '') <> '0000'
							FOR XML PATH('TARICAdditionalCode'), TYPE),
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.EXA_ORDE) AS "sequenceNumber",
								NULLIF(t.EXA_ANAC, '') AS "nationalAdditionalCode"						
							FROM (
								SELECT 1 AS EXA_ORDE, adi.EXA_AIC1 AS EXA_ANAC
								UNION
								SELECT 2, adi.EXA_AIC2
								UNION
								SELECT 3, adi.EXA_AIC3 
								UNION
								SELECT 4, adi.EXA_AIC4 
								UNION
								SELECT 5, adi.EXA_AIC5 
							) AS t
							WHERE ISNULL(t.EXA_ANAC, '') <> '' AND ISNULL(t.EXA_ANAC, '') <> '0000'
							FOR XML PATH('NationalAdditionalCode'), TYPE) 
						FOR XML PATH('CommodityCode'), TYPE), 
						(SELECT
							1 AS "sequenceNumber", 
							NULLIF(adi.EXA_ATAR, '') AS "UNNumber"
						HAVING exm.EXM_SEGU = 2 AND ISNULL(adi.EXA_ATAR, '') <> ''
						FOR XML PATH('DangerousGoods'), TYPE), 
						(SELECT
							(CASE WHEN EXISTS(SELECT 1 FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = adi.EXA_CHVE GROUP BY EXA_CHVE HAVING SUM(EXM_NVOL) > 0) THEN ISNULL(adi.EXA_MBRT, 0) ELSE NULL END) AS "grossMass", 
							ISNULL(adi.EXA_MLQD, 0) AS "netMass", 
							NULLIF(adi.EXA_QUSU, 0) AS "supplementaryUnits"
						FOR XML PATH('GoodsMeasure'), TYPE), 
						(SELECT
							CAST(ISNULL((SELECT SUM(montante) FROM tb_EXP_DeclaracoesAdicoesImposicoes WITH(NOLOCK) WHERE id_adicao = adi.EXA_CHVE), 0) AS decimal(18, 2)) AS "totalDutiesAndTaxesAmount", 								
							(SELECT
								ROW_NUMBER() OVER(ORDER BY aoi.imposicao, aoi.metodoPagamento) AS "sequenceNumber", 
								NULLIF(aoi.imposicao, '') AS "taxType", 												
								CAST(aoi.montante AS decimal(18, 2)) AS "payableTaxAmount", 
								NULLIF(aoi.metodoPagamento, '') AS "methodOfPayment", 
								(SELECT
									ROW_NUMBER() OVER(ORDER BY itx.id) AS "sequenceNumber", 
									CAST((CASE itx.tipoCalculo WHEN 1 THEN (itx.taxaValor / 100) ELSE itx.taxaValor END) AS decimal(18, 3)) AS "taxRate", 
									ume.UME_CODI AS "measurementUnitAndQualifier", 
									NULLIF(itx.quantidade, 0) AS "quantity", 
									NULLIF(itx.valor, 0) AS "amount", 
									CAST(itx.montante AS decimal(18, 2)) AS "taxAmount"
								FROM tb_EXP_DeclaracoesAdicoesImposicoesTaxas AS itx WITH(NOLOCK)
									LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON itx.id_unidadeMedida = ume.UME_IDTY
								WHERE itx.id_imposicao = aoi.id 
								FOR XML PATH('TaxBase'), TYPE) 
							FROM tb_EXP_DeclaracoesAdicoesImposicoes AS aoi WITH(NOLOCK)
							WHERE aoi.id_adicao = adi.EXA_CHVE								
							FOR XML PATH('DutiesAndTaxes'), TYPE)
						HAVING (SELECT SUM(montante) FROM tb_EXP_DeclaracoesAdicoesImposicoes WITH(NOLOCK) WHERE id_adicao = adi.EXA_CHVE) > 0 
							AND ((exm.EXM_P17A IN ('AD', 'AL', 'BA', 'CL', 'DZ', 'EG', 'FO', 'HR', 'IL', 'JO', 'MA', 'ME', 'MK', 'MX', 'PS', 'TN', 'TR', 'XC', 'XL')) OR (adi.TDE_REGI = '3151'))
						FOR XML PATH('CalculationOfTaxes'), TYPE)						
					FOR XML PATH('Commodity'), TYPE),
					(SELECT
						ROW_NUMBER() OVER(ORDER BY EXM_CHVE) AS "sequenceNumber", 
						NULLIF(TEM_CODI, '') AS "typeOfPackages", 
						CAST(EXM_NVOL AS int) AS "numberOfPackages",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXM_MARN, '')) AS "shippingMarks"
					FROM PRO_EXMV WITH(NOLOCK)
					WHERE EXA_CHVE = adi.EXA_CHVE
					FOR XML PATH('Packaging'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY apr.id) AS "sequenceNumber", 
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(apr.numero, '')) AS "referenceNumber", 										
						apr.numeroAdicao AS "goodsItemNumber", 
						umv.UME_CODI AS "typeOfPackages", 
						apr.volumes AS "numberOfPackages", 
						umq.UME_CODI AS "measurementUnitAndQualifier", 
						apr.quantidade AS "quantity"						 
					FROM tb_EXP_DeclaracoesAdicoesPrecedentes AS apr WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON apr.id_documento = doc.DOC_IDTY
						INNER JOIN TAB_UMED AS umv WITH(NOLOCK) ON apr.id_unidadeMedidaVolumes = umv.UME_IDTY
						LEFT OUTER JOIN TAB_UMED AS umq WITH(NOLOCK) ON apr.id_unidadeMedidaQualificador = umq.UME_IDTY
					WHERE apr.id_adicao = adi.EXA_CHVE AND exm.EXM_TPRO NOT IN ('X', 'Y', 'Z')
					FOR XML PATH('PreviousDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
						NULLIF(DOC_CODI, '') AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXD_NREF, '')) AS "referenceNumber", 	
						EXD_NADI AS "documentLineItemNumber", 									
						NULLIF(EEM_DESC, '') AS "issuingAuthorityName", 
						CONVERT(varchar(10), EXD_DTEM, 120) AS "validityDate", 
						NULLIF(UME_CODI, '') AS "measurementUnitAndQualifier", 
						NULLIF(EXD_QNTD, 0) AS "quantity", 						
						NULLIF(PAI_MOED, '') AS "currency", 						
						CAST(ISNULL(EXD_MONT, 0) AS decimal(18, 2)) AS "amount"
					FROM PRO_EXDA WITH(NOLOCK) 												
					WHERE EXA_CHVE = adi.EXA_CHVE AND EXD_TIPO = 0
					FOR XML PATH('SupportingDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
						NULLIF(DOC_CODI, '') AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXD_NREF, '')) AS "referenceNumber"
					FROM PRO_EXDA WITH(NOLOCK) 						
					WHERE EXA_CHVE = adi.EXA_CHVE AND EXD_TIPO = 1
					FOR XML PATH('TransportDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
						NULLIF(DOC_CODI, '') AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXD_NREF, '')) AS "referenceNumber"									
					FROM PRO_EXDA WITH(NOLOCK) 						
					WHERE EXA_CHVE = adi.EXA_CHVE AND EXD_TIPO = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO'
					FOR XML PATH('AdditionalReference'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ape.id) AS "sequenceNumber", 
						ped.TXM_CODI AS "code", 				
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(numero, '')) AS "text" 				
					FROM tb_EXP_DeclaracoesAdicoesPedidos AS ape WITH(NOLOCK)
						INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ape.id_pedido = ped.TXM_IDTY 					
					WHERE ape.id_adicao = adi.EXA_CHVE
					FOR XML PATH('AdditionalInformation'), TYPE), 															
					(SELECT
						NULLIF(adi.EXA_MPAG, '') AS "methodOfPayment" 					
					HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND exm.EXM_SEGU = 2 AND ISNULL(adi.EXA_MPAG, '') <> ''
					FOR XML PATH('TransportCharges'), TYPE) 
				FROM PRO_EXAD AS adi WITH(NOLOCK) 
					LEFT OUTER JOIN TAB_REST AS res WITH(NOLOCK) ON adi.RES_CODI = res.RES_CODI		
				WHERE adi.EXM_EANO = exm.EXM_EANO AND adi.EXM_CODI = exm.EXM_CODI AND adi.EXM_COPE = exm.DEC_CODI
				FOR XML PATH('GoodsItem'), TYPE)
			FOR XML PATH('GoodsShipment'), TYPE), 
			(SELECT
				NULLIF(exm.EAD_CODI1, '') AS "customsOfficeOfDischargeCode", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_PRZA, '')) AS "dischargeDeadline", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_ATVP, '')) AS "plannedActivitiesDetails", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_INFA, '')) AS "additionalInformation", 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY dlt.id) AS "sequenceNumber", 
					dlt.tipo AS "typeOfLocation", 
					dlt.qualificador AS "qualifierOfLocation",
					(CASE dlt.qualificador WHEN 'U' THEN lau.LME_CODI ELSE NULL END) AS "UNLocode",
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.morada, '')) AS "streetAndNumber", 					
						NULLIF(dlt.codigoPostal, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.localidade, '')) AS "city", 
						pai.PAI_CODI AS "country"
					HAVING dlt.qualificador <> 'U'
					FOR XML PATH('Address'), TYPE)					
				FROM tb_EXP_DeclaracoesLocaisTransformacao AS dlt WITH(NOLOCK)
					LEFT OUTER JOIN TAB_LMER AS lau WITH(NOLOCK) ON dlt.id_localAutorizado = lau.LME_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dlt.id_pais = pai.PAI_IDTY
				WHERE dlt.id_declaracaoEXP = exm.EXM_IDTY
				FOR XML PATH('PlaceOrPlacesOfProcessingOrUse'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpt.id) AS "sequenceNumber", 
					dpt.codigoPautal AS "commodityCode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.designacao, '')) AS "descriptionOfGoods", 
					(SELECT
						1 AS "sequenceNumber", 
						mid.MIA_CODI AS "identificationMeasureCode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.descricao, '')) AS "identificationMeasureDescription"
					FOR XML PATH('GoodsIdentification'), TYPE),
					(SELECT	
						1 AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.taxaRendimento, '')) AS "freeText"					
					HAVING ISNULL(dpt.taxaRendimento, '') <> ''
					FOR XML PATH('YieldRate'), TYPE)
				FROM tb_EXP_DeclaracoesProdutosTransformados AS dpt WITH(NOLOCK)
					INNER JOIN TAB_MIAU AS mid WITH(NOLOCK) ON dpt.id_meioIdentificacao = mid.MIA_IDTY
				WHERE dpt.id_declaracaoEXP = exm.EXM_IDTY
				FOR XML PATH('ProcessedProducts'), TYPE)				
			HAVING exm.EXM_TPRO IN ('A', 'D') AND ISNULL(exm.EAD_C29A, '') = '' AND LEFT(exm.EXM_REGI, 2) IN ('21', '22') AND ISNULL(exm.EAD_CODI1, '') <> ''			
			FOR XML PATH('AuthorizationRequestsOutwardProcessing'), TYPE),
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY dcc.EXC_CHVE) AS "sequenceNumber", 
				NULLIF(dcc.EXC_FNIF, '') AS "supplierVATNumber", 
				NULLIF(dcc.EXC_NFAC, '') AS "invoiceNumber", 
				CONVERT(varchar(10), dcc.EXC_DFAC, 120) AS "invoiceIssueDate", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dcc.EXC_DCOM, '')) AS "goodsDescription", 
				ISNULL(dcc.EXC_PBRT, 0) AS "grossMass", 
				ISNULL(dcc.EXC_PLIQ, 0) AS "netMass", 
				ISNULL(dcc.EXC_VALO, 0) AS "amountInvoiced", 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
					NULLIF(TEM_CODI, '') AS "typeOfPackages", 
					CAST(EXD_QTDE AS int) AS "numberOfPackages"
				FROM PRO_EXCD WITH(NOLOCK)
				WHERE EXM_EANO = dcc.EXM_EANO AND EXM_CODI = dcc.EXM_CODI AND EXM_COPE = dcc.EXM_COPE AND EXC_LINH = dcc.EXC_LINH
				FOR XML PATH('Packaging'), TYPE)
			FROM PRO_EXCE AS dcc WITH(NOLOCK)
			WHERE dcc.EXM_EANO = exm.EXM_EANO AND dcc.EXM_CODI = exm.EXM_CODI AND dcc.EXM_COPE = exm.DEC_CODI AND LEFT(exm.EXM_REGI, 2) = '10'
			FOR XML PATH('CCEElements'), TYPE)
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dco WITH(NOLOCK) ON exm.DEC_CODI = dco.DEC_CODI	
			INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON exm.TDE_COD1 = tde.TDE_CODI
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
		WHERE exm.EXM_IDTY = @IdDeclaracao
		FOR XML PATH('PT513C'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagemGeraXMLPT513C] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagemGeraXMLPT513C] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagemGeraXMLPT514C]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagemGeraXMLPT514C] @IdDeclaracao int, @Motivo varchar(512), @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem PT514C - Anulação da Declaração de Exportação
	SET @FicheiroXML = 				
		(SELECT
			NULLIF(dco.DEC_WSUS, '') AS "messageSender", 
			'AT' AS "messageRecipient", 
			CONVERT(varchar(19), @DataAtual, 120) AS "preparationDateAndTime", 
			'EXP-CAU' AS "messageIdentification", 
			'PT514C' AS "messageType", 
			NULLIF(exm.EXM_NRLO, '') AS "correlationIdentifier", 			
			(SELECT								
				NULLIF(exm.EXM_NRLO, '') AS "LRN",
				NULLIF(exm.EXM_NDGA, '') AS "MRN",  
				CONVERT(varchar(19), @DataAtual, 126) AS "invalidationRequestDateAndTime", 
				NULLIF(@Motivo, '') AS "invalidationReason"				
			FOR XML PATH('ExportOperation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_CODA, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExport'), TYPE), 
			(SELECT 
				(CASE WHEN ISNULL(exm.CLI_PAI2, '') = 'PT' OR exm.EXM_TP2A IN ('C', 'S') THEN NULLIF((ISNULL(exm.CLI_PAI2, '') + ISNULL(exm.CLI_NIF2, '')), '') ELSE NULLIF(exm.CLI_NIF2, '') END) AS "identificationNumber", 
				(CASE WHEN ISNULL(exm.CLI_PAI2, '') <> 'PT' AND exm.EXM_TP2A = 'P' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_NOM2, '')) ELSE NULL END) AS "name", 					
				(SELECT
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_MOR2, '')) AS "streetAndNumber", 					
					NULLIF(exm.CLI_CPO2, '') AS "postcode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_LOC2, '')) AS "city", 
					NULLIF(exm.CLI_PAI2, '') AS "country"
				HAVING ISNULL(exm.CLI_PAI2, '') <> 'PT' AND exm.EXM_TP2A = 'P'
				FOR XML PATH('Address'), TYPE)			
			FOR XML PATH('Exporter'), TYPE), 
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(dcl.DEC_NIF, '')), '') AS "identificationNumber"				
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(exm.CLI_PAI2, '') + ISNULL(exm.CLI_NIF2, '')), '') AS "identificationNumber",
				exm.EXM_TP14 AS "status"			
			HAVING ISNULL(exm.EXM_TP14, -1) = 2
			FOR XML PATH('Representative'), TYPE)																			
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dco WITH(NOLOCK) ON exm.DEC_CODI = dco.DEC_CODI				
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
		WHERE exm.EXM_IDTY = @IdDeclaracao
		FOR XML PATH('PT514C'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagemGeraXMLPT514C] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagemGeraXMLPT514C] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagemGeraXMLPT515C]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagemGeraXMLPT515C] @IdDeclaracao int, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @PeriodoTransitorio bit
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem configuração do periodo transitório EXP-SAE dos Parâmetros de Despachos
	SELECT TOP 1 @PeriodoTransitorio = PDE_PTEX 
	FROM TAB_PDES WITH(NOLOCK)
-- constroi XML para ficheiro XML da mensagem PT515C - Criação da Declaração de Exportação	
	SET @FicheiroXML = 				
		(SELECT
			NULLIF(dco.DEC_WSUS, '') AS "messageSender", 
			'AT' AS "messageRecipient", 
			CONVERT(varchar(19), @DataAtual, 120) AS "preparationDateAndTime", 
			'EXP-CAU' AS "messageIdentification", 
			'PT515C' AS "messageType", 
			NULLIF(exm.EXM_NRLO, '') AS "correlationIdentifier", 			
			(SELECT								
				NULLIF(exm.EXM_NRLO, '') AS "LRN", 
				NULLIF(tde.TDE_1CAS, '') AS "declarationType", 
				exm.EXM_TPRO AS "additionalDeclarationType", 
				exm.EXM_SEGU AS "security", 
				(CASE exm.EXM_SEGU WHEN 2 THEN NULLIF((CASE exm.EXM_INCE WHEN 'A' THEN 'A20' ELSE NULL END), '') ELSE NULL END) AS "specificCircumstanceIndicator", 
				(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) <> '76' THEN CAST(ISNULL(exm.EXM_MT22, 0) AS decimal(18, 2)) ELSE NULL END) AS "totalAmountInvoiced", 
				(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) <> '76' AND NOT EXISTS(SELECT 1 FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 0 AND doc.DOC_CODI = '9E06') THEN NULLIF(exm.PAI_MO22, '') ELSE NULL END) AS "invoiceCurrency" 
			FOR XML PATH('ExportOperation'), TYPE),
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
				doc.DOC_CODI AS "type", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dau.numero, '')) AS "referenceNumber", 
				NULLIF(dau.titular, '') AS "holderOfAuthorisation"
			FROM tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK)
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dau.id_documento = doc.DOC_IDTY
			WHERE id_declaracaoEXP = exm.EXM_IDTY
			FOR XML PATH('Authorisation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_C29A, '') AS "referenceNumber"
			HAVING exm.EXM_DCEN = 1 AND exm.EXM_TPRO <> 'R' AND ISNULL(exm.EAD_C29A, '') <> ''
			FOR XML PATH('CustomsOfficeOfPresentation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_CODA, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExport'), TYPE), 
			(SELECT
				NULLIF(exm.EAD_CO29, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExitDeclared'), TYPE), 
			(SELECT 
				NULLIF(exm.EAD_CODI, '') AS "referenceNumber"
			HAVING LEFT(exm.EXM_REGI, 2) IN ('21', '22') AND ISNULL(exm.EAD_CODI, '') <> ''
			FOR XML PATH('SupervisingCustomsOffice'), TYPE), 
			(SELECT 
				(CASE WHEN ISNULL(exm.CLI_PAI2, '') = 'PT' OR exm.EXM_TP2A IN ('C', 'S') THEN NULLIF((ISNULL(exm.CLI_PAI2, '') + ISNULL(exm.CLI_NIF2, '')), '') ELSE NULLIF(exm.CLI_NIF2, '') END) AS "identificationNumber", 
				(CASE WHEN ISNULL(exm.CLI_PAI2, '') <> 'PT' AND exm.EXM_TP2A = 'P' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_NOM2, 35) ELSE exm.CLI_NOM2 END), '')) ELSE NULL END) AS "name", 					
				(SELECT
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_MOR2, 35) ELSE exm.CLI_MOR2 END), '')) AS "streetAndNumber", 					
					NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_CPO2, 9) ELSE exm.CLI_CPO2 END), '') AS "postcode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.CLI_LOC2, 20) ELSE exm.CLI_LOC2 END), '')) AS "city", 
					NULLIF(exm.CLI_PAI2, '') AS "country"
				HAVING ISNULL(exm.CLI_PAI2, '') <> 'PT' AND exm.EXM_TP2A = 'P'
				FOR XML PATH('Address'), TYPE)			
			FOR XML PATH('Exporter'), TYPE), 
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(dcl.DEC_NIF, '')), '') AS "identificationNumber"				
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(dcl.DEC_NIF, '')), '') AS "identificationNumber",
				exm.EXM_TP14 AS "status"			
			HAVING ISNULL(exm.EXM_TP14, -1) = 2
			FOR XML PATH('Representative'), TYPE), 			
			(SELECT 				
				NULLIF(exm.EXM_NC48, '') AS "deferredPayment"
			HAVING exm.EXM_ANXB NOT IN ('B3', 'B4') AND ISNULL(exm.EXM_NC48, '') <> ''
			FOR XML PATH('DeferredPayment'), TYPE),
			(SELECT		
				1 AS "sequenceNumber", 		
				(CASE WHEN exm.EXM_TPRO IN ('V', 'Z') THEN CONVERT(varchar(10), exm.EXM_DDGA, 120) ELSE NULL END) AS "declarationAcceptanceDate", 
				(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) NOT IN ('71', '76') THEN NULLIF(exm.NTR_CO24, '') ELSE NULL END) AS "natureOfTransaction",
				NULLIF(exm.EXM_P15A, '') AS "countryOfExport", 
				NULLIF(exm.EXM_P17A, '') AS "countryOfDestination", 				 						
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(funcao, '') AS "role", 
					NULLIF(nif, '') AS "identificationNumber"
				FROM tb_EXP_DeclaracoesIntervenientes WITH(NOLOCK) 		
				WHERE id_declaracaoEXP = exm.EXM_IDTY
				FOR XML PATH('AdditionalSupplyChainActor'), TYPE),
				(SELECT
					NULLIF(exm.CEN_CO20, '') AS "incotermCode", 
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE NULLIF(exm.PAE_CODI1, '') END) AS "UNLOCODE", 
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_LG20, '')) END) AS "location",
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE NULLIF(exm.PAI_CODI, '') END) AS "country", 										
					(CASE ISNULL(exm.CEN_CO20, '') WHEN 'XXX' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_TXTC, '')) ELSE NULL END) AS "text"
				HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) <> '76' AND ISNULL(exm.CEN_CO20, '') <> ''
				FOR XML PATH('DeliveryTerms'), TYPE), 
				(SELECT
					NULLIF(exm.TAR_CO49, '') AS "type", 
					NULLIF(exm.ARM_CO49, '') AS "identifier"
				HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND ISNULL(exm.TAR_CO49, '') <> ''
				FOR XML PATH('Warehouse'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
					doc.DOC_CODI AS "type", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.numero, '')) AS "referenceNumber"
				FROM tb_EXP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
				WHERE dpr.id_declaracaoEXP = exm.EXM_IDTY AND exm.EXM_TPRO NOT IN ('U', 'V')
				FOR XML PATH('PreviousDocument'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					doc.DOC_CODI AS "type", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 					
					ddo.numeroAdicao AS "documentLineItemNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.entidadeEmissora, '')) AS "issuingAuthorityName", 			
					CONVERT(varchar(10), ddo.dataValidade, 120) AS "validityDate"			
				FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 0 
				FOR XML PATH('SupportingDocument'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					doc.DOC_CODI AS "type", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber"
				FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO'
				FOR XML PATH('AdditionalReference'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY EXP_LINH) AS "sequenceNumber", 
					NULLIF(TXM_CODI, '') AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(TXM_DESC, '')) AS "text"
				FROM PRO_EXPA WITH(NOLOCK) 					
				WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI
				FOR XML PATH('AdditionalInformation'), TYPE),
				(SELECT
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') THEN exm.EXM_CT19 ELSE NULL END) AS "containerIndicator", 
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND exm.EAD_CODA <> exm.EAD_CO29 THEN NULLIF(LEFT(exm.MTR_CO26, 1), '') ELSE NULL END) AS "inlandModeOfTransport", 
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) NOT IN ('21', '22') AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(exm.EXM_REGI, 2) = '76') THEN NULLIF(LEFT(exm.MTR_CO21, 1), '') ELSE NULL END) AS "modeOfTransportAtTheBorder", 		
					(CASE WHEN ISNULL(exm.EXM_TAD5, 0) > 1 THEN ISNULL(exm.EXM_TMBR, 0) ELSE NULL END) AS "grossMass", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_NCMR, '')) AS "referenceNumberUCR", 																		
					(SELECT 
						NULLIF(exm.EXM_NTRP, '') AS "identificationNumber"
					HAVING exm.EXM_SEGU = 2 AND ISNULL(exm.EXM_NTRP, '') <> ''
					FOR XML PATH('Carrier'), TYPE),
					(SELECT 
						(CASE WHEN ISNULL(exm.PAI_CODI1, '') = 'PT' OR exm.CLI_TNIF1 IN ('C', 'S') THEN NULLIF((ISNULL(exm.PAI_CODI1, '') + ISNULL(exm.CLI_NIF1, '')), '') ELSE NULLIF(exm.CLI_NIF1, '') END) AS "identificationNumber", 
						(CASE WHEN ISNULL(exm.PAI_CODI1, '') <> 'PT' AND exm.CLI_TNIF1 = 'P' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_NOME1, '')) ELSE NULL END) AS "name", 					
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_MORA1, '')) AS "streetAndNumber", 					
							NULLIF(exm.CLI_CPOS1, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.CLI_LOCA1, '')) AS "city", 
							NULLIF(exm.PAI_CODI1, '') AS "country"
						HAVING ISNULL(exm.PAI_CODI1, '') <> 'PT' AND exm.CLI_TNIF1 = 'P'
						FOR XML PATH('Address'), TYPE)									
					HAVING exm.EXM_SEGU = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO' AND LEFT(exm.EXM_REGI, 2) NOT IN ('21', '22') AND ISNULL(exm.CLI_NOME1, '') <> ''			
					FOR XML PATH('Consignor'), TYPE), 
					(SELECT 						
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_NOM8, 35) ELSE exm.FOR_NOM8 END), '')) AS "name", 			
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_MOR8, 35) ELSE exm.FOR_MOR8 END), '')) AS "streetAndNumber", 							
							NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_CPO8, 9) ELSE exm.FOR_CPO8 END), '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF((CASE @PeriodoTransitorio WHEN 1 THEN LEFT(exm.FOR_LOC8, 20) ELSE exm.FOR_LOC8 END), '')) AS "city", 
							NULLIF(exm.FOR_PAI8, '') AS "country"
						FOR XML PATH('Address'), TYPE)
					HAVING ISNULL(exm.FOR_NOM8, '') <> ''
					FOR XML PATH('Consignee'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dco.EXC_CONT) AS "sequenceNumber",
						NULLIF(dco.EXC_CONT, '') AS "containerIdentificationNumber", 
						(SELECT COUNT(*) FROM tb_EXP_DeclaracoesContentoresSelos WITH(NOLOCK) WHERE id_contentor = dco.EXC_CHVE) AS "numberOfSeals", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber",
							NULLIF(numeroSelo, '') AS "identifier"
						FROM tb_EXP_DeclaracoesContentoresSelos WITH(NOLOCK) 
						WHERE id_contentor = dco.EXC_CHVE AND exm.EXM_SEGU = 2
						FOR XML PATH('Seal'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY dad.EXA_LINH) AS "sequenceNumber",
							dad.EXA_LINH AS "declarationGoodsItemNumber"
						FROM tb_EXP_DeclaracoesAdicoesContentores AS dac WITH(NOLOCK)
							INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON dac.id_adicao = dad.EXA_CHVE
						WHERE dac.id_contentor = dco.EXC_CHVE			
						FOR XML PATH('GoodsReference'), TYPE)
					FROM PRO_EXCT AS dco WITH(NOLOCK)						
					WHERE dco.EXM_EANO = exm.EXM_EANO AND dco.EXM_CODI = exm.EXM_CODI AND dco.EXM_COPE = exm.DEC_CODI AND exm.EXM_CT19 = 1
					FOR XML PATH('TransportEquipment'), TYPE),
					(SELECT 
						NULLIF(exm.EXM_TLOC, '') AS "typeOfLocation", 
						NULLIF(exm.EXM_QUAL, '') AS "qualifierOfIdentification", 
						(CASE ISNULL(exm.EXM_QUAL, '') WHEN 'Y' THEN NULLIF(exm.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
						NULLIF(exm.EXM_IADI, '') AS "additionalIdentifier", 
						(CASE ISNULL(exm.EXM_QUAL, '') WHEN 'U' THEN NULLIF(exm.LEM_CO30, '') ELSE NULL END) AS "UNLocode", 												
						(SELECT 
							NULLIF(exm.EAD_CO30, '') AS "referenceNumber"
						HAVING ISNULL(exm.EXM_QUAL, '') = 'V' AND ISNULL(exm.EAD_CO30, '') <> ''
						FOR XML PATH('CustomsOffice'), TYPE),				 						
						(SELECT 
							NULLIF(exm.EXM_ONIF, '') AS "identificationNumber"
						HAVING ISNULL(exm.EXM_QUAL, '') = 'X' AND ISNULL(exm.EXM_ONIF, '') <> ''
						FOR XML PATH('EconomicOperator'), TYPE),
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_MR30, '')) AS "streetAndNumber", 
							NULLIF(exm.EXM_CP30, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_LP30, '')) AS "city", 
							NULLIF(exm.PAI_CODI5, '') AS "country"					
						HAVING ISNULL(exm.EXM_QUAL, '') = 'Z' AND ISNULL(exm.EXM_MR30, '') <> ''				
						FOR XML PATH('Address'), TYPE)
					HAVING exm.EXM_TPRO NOT IN ('D', 'E', 'F') 
					FOR XML PATH('LocationOfGoods'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY t.id) AS "sequenceNumber",
						t.tipoIdentificacao AS "typeOfIdentification", 
						NULLIF(t.numeroIdentificacao, '') AS "identificationNumber", 
						NULLIF(t.codigoPais, '') AS "nationality"
					FROM (SELECT 0 AS id, exm.EXM_MTIT AS tipoIdentificacao, exm.EXM_MT18 AS numeroIdentificacao, exm.PAI_CODI4 AS codigoPais
						UNION ALL
						SELECT dmp.id, mtr.MTR_TIPO, dmp.identificacao, pai.PAI_CODI
						FROM tb_EXP_DeclaracoesMeiosTransportePartida AS dmp WITH(NOLOCK)
							INNER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dmp.id_meioTransporte = mtr.MTR_IDTY
							LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dmp.id_pais = pai.PAI_IDTY
						WHERE dmp.id_declaracaoEXP = exm.EXM_IDTY AND LEFT(exm.MTR_CO18, 1) IN ('2', '3')) AS t
					WHERE exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(exm.EXM_REGI, 2) = '76') AND ISNULL(t.numeroIdentificacao, '') <> '' 					
					FOR XML PATH('DepartureTransportMeans'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXP_CHVE) AS "sequenceNumber",
						NULLIF(PAI_CODI, '') AS "country"
					FROM PRO_EXPI WITH(NOLOCK)
					WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI AND exm.EXM_SEGU = 2
					FOR XML PATH('CountryOfRoutingOfConsignment'), TYPE),
					(SELECT
						exm.EXM_MTFT AS "typeOfIdentification", 
						NULLIF(exm.EXM_MT21, '') AS "identificationNumber", 
						NULLIF(exm.PAI_CO21, '') AS "nationality"
					HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND LEFT(exm.EXM_REGI, 2) NOT IN ('21', '22') AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(exm.EXM_REGI, 2) = '76') AND ISNULL(exm.EXM_MT21, '') <> ''
					FOR XML PATH('ActiveBorderTransportMeans'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 						
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber"
					FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoEXP = exm.EXM_IDTY AND ddo.tipo = 1
					FOR XML PATH('TransportDocument'), TYPE), 
					(SELECT
						NULLIF(exm.EXM_DTMP, '') AS "methodOfPayment" 
					HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND exm.EXM_SEGU = 2 AND ISNULL(exm.EXM_DTMP, '') <> ''
					FOR XML PATH('TransportCharges'), TYPE)
				FOR XML PATH('Consignment'), TYPE), 						
				(SELECT
					ROW_NUMBER() OVER(ORDER BY adi.EXA_LINH) AS "sequenceNumber", 
					adi.EXA_LINH AS "declarationGoodsItemNumber", 					
					(CASE WHEN (@PeriodoTransitorio = 1) OR (exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F')) THEN CAST(ISNULL(adi.EXA_VEST, 0) AS decimal(18, 2)) ELSE NULL END) AS "statisticalValue", 
					(CASE WHEN exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') THEN NULLIF(adi.NTR_CODI, '') ELSE NULL END) AS "natureOfTransaction", 					
					NULLIF(adi.PAI_CODI2, '') AS "countryOfExport", 
					NULLIF(adi.PAI_CODI4, '') AS "countryOfDestination", 				 						
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.EXA_NRUR, '')) AS "referenceNumberUCR", 			
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY aau.id) AS "sequenceNumber", 
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(aau.numero, '')) AS "referenceNumber", 	
						NULLIF(aau.titular, '') AS "holderOfAuthorisation"			
					FROM tb_EXP_DeclaracoesAdicoesAutorizacoes AS aau WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON aau.id_documento = doc.DOC_IDTY
					WHERE aau.id_adicao = adi.EXA_CHVE
					FOR XML PATH('Authorisation'), TYPE), 
					(SELECT
						NULLIF(LEFT(adi.TDE_REGI, 2), '') AS "requestedProcedure",
						NULLIF(RIGHT(adi.TDE_REGI, 2), '') AS "previousProcedure",
						(SELECT
							ROW_NUMBER() OVER(ORDER BY t.coluna) AS "sequenceNumber",
							NULLIF(t.desdobramento, '') AS "type"									
						FROM tb_TBL_Desdobramentos AS ddb WITH(NOLOCK)
							UNPIVOT(desdobramento FOR coluna IN (ddb.desdobramento1, ddb.desdobramento2, ddb.desdobramento3, ddb.desdobramento4, ddb.desdobramento5)) AS t
						WHERE t.id = adi.id_desdobramento
						FOR XML PATH('AdditionalProcedure'), TYPE) 
					FOR XML PATH('Procedure'), TYPE), 	
					(SELECT 
						(CASE WHEN ISNULL(adi.PAI_CODI1, '') = 'PT' OR adi.CLI_TNIF IN ('C', 'S') THEN NULLIF((ISNULL(adi.PAI_CODI1, '') + ISNULL(adi.CLI_NIF, '')), '') ELSE NULLIF(adi.CLI_NIF, '') END) AS "identificationNumber", 
						(CASE WHEN ISNULL(adi.PAI_CODI1, '') <> 'PT' AND adi.CLI_TNIF = 'P' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.CLI_NOME, '')) ELSE NULL END) AS "name", 					
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.CLI_MORA, '')) AS "streetAndNumber", 					
							NULLIF(adi.CLI_CPOS, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.CLI_LPOS, '')) AS "city", 
							NULLIF(adi.PAI_CODI1, '') AS "country"
						HAVING ISNULL(adi.PAI_CODI1, '') <> 'PT' AND adi.CLI_TNIF = 'P'
						FOR XML PATH('Address'), TYPE)									
					HAVING exm.EXM_SEGU = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO' AND LEFT(adi.TDE_REGI, 2) NOT IN ('21', '22') AND ISNULL(adi.CLI_NOME, '') <> ''	
					FOR XML PATH('Consignor'), TYPE),		
					(SELECT 						
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME, '')) AS "name", 			
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA, '')) AS "streetAndNumber", 							
							NULLIF(adi.FOR_CPOS, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS, '')) AS "city", 
							NULLIF(adi.PAI_CODI3, '') AS "country"
						FOR XML PATH('Address'), TYPE)
					HAVING ISNULL(adi.FOR_NOME, '') <> ''
					FOR XML PATH('Consignee'), TYPE), 								
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(funcao, '') AS "role", 
						NULLIF(nif, '') AS "identificationNumber"
					FROM tb_EXP_DeclaracoesAdicoesIntervenientes WITH(NOLOCK) 								
					WHERE id_adicao = adi.EXA_CHVE
					FOR XML PATH('AdditionalSupplyChainActor'), TYPE), 
					(SELECT
						NULLIF(adi.PAI_CODI, '') AS "countryOfOrigin", 
						(CASE WHEN (exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND (LEFT(adi.TDE_REGI, 2) <> '76')) THEN NULLIF(res.RES_NUTS, '') ELSE NULL END) AS "regionOfDispatch"
					HAVING ISNULL(adi.PAI_CODI, '') <> ''
					FOR XML PATH('Origin'), TYPE), 
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.APA_DESG, '')) AS "descriptionOfGoods", 
						(CASE WHEN exm.EXM_ANXB = 'B1' THEN NULLIF(adi.EXA_CCUS, '') ELSE NULL END) AS "cusCode", 						
						(SELECT 
							NULLIF(LEFT(adi.APA_CP33, 6), '') AS "harmonizedSystemSubHeadingCode", 
							NULLIF(SUBSTRING(adi.APA_CP33, 7, 2), '') AS "combinedNomenclatureCode", 							
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.EXA_ORDE) AS "sequenceNumber",
								NULLIF(t.EXA_ATAR, '') AS "taricAdditionalCode"
							FROM (
								SELECT 1 AS EXA_ORDE, adi.EXA_ATA1 AS EXA_ATAR
								UNION
								SELECT 2, adi.EXA_ATA2
								UNION
								SELECT 3, adi.EXA_ATA3
								UNION
								SELECT 4, adi.EXA_ATA4
								UNION
								SELECT 5, adi.EXA_ATA5
							) AS t
							WHERE ISNULL(t.EXA_ATAR, '') <> '' AND ISNULL(t.EXA_ATAR, '') <> '0000'
							FOR XML PATH('TARICAdditionalCode'), TYPE),
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.EXA_ORDE) AS "sequenceNumber",
								NULLIF(t.EXA_ANAC, '') AS "nationalAdditionalCode"						
							FROM (
								SELECT 1 AS EXA_ORDE, adi.EXA_AIC1 AS EXA_ANAC
								UNION
								SELECT 2, adi.EXA_AIC2
								UNION
								SELECT 3, adi.EXA_AIC3 
								UNION
								SELECT 4, adi.EXA_AIC4 
								UNION
								SELECT 5, adi.EXA_AIC5 
							) AS t
							WHERE ISNULL(t.EXA_ANAC, '') <> '' AND ISNULL(t.EXA_ANAC, '') <> '0000'
							FOR XML PATH('NationalAdditionalCode'), TYPE) 
						FOR XML PATH('CommodityCode'), TYPE), 
						(SELECT
							1 AS "sequenceNumber", 
							NULLIF(adi.EXA_ATAR, '') AS "UNNumber"
						HAVING exm.EXM_SEGU = 2 AND ISNULL(adi.EXA_ATAR, '') <> ''
						FOR XML PATH('DangerousGoods'), TYPE), 
						(SELECT
							(CASE WHEN EXISTS(SELECT 1 FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = adi.EXA_CHVE GROUP BY EXA_CHVE HAVING SUM(EXM_NVOL) > 0) THEN ISNULL(adi.EXA_MBRT, 0) ELSE NULL END) AS "grossMass", 
							ISNULL(adi.EXA_MLQD, 0) AS "netMass", 
							NULLIF(adi.EXA_QUSU, 0) AS "supplementaryUnits"
						FOR XML PATH('GoodsMeasure'), TYPE), 
						(SELECT
							CAST(ISNULL((SELECT SUM(montante) FROM tb_EXP_DeclaracoesAdicoesImposicoes WITH(NOLOCK) WHERE id_adicao = adi.EXA_CHVE), 0) AS decimal(18, 2)) AS "totalDutiesAndTaxesAmount", 								
							(SELECT
								ROW_NUMBER() OVER(ORDER BY aoi.imposicao, aoi.metodoPagamento) AS "sequenceNumber", 
								NULLIF(aoi.imposicao, '') AS "taxType", 												
								CAST(aoi.montante AS decimal(18, 2)) AS "payableTaxAmount", 
								NULLIF(aoi.metodoPagamento, '') AS "methodOfPayment", 
								(SELECT
									ROW_NUMBER() OVER(ORDER BY itx.id) AS "sequenceNumber", 
									CAST((CASE itx.tipoCalculo WHEN 1 THEN (itx.taxaValor / 100) ELSE itx.taxaValor END) AS decimal(18, 3)) AS "taxRate", 
									ume.UME_CODI AS "measurementUnitAndQualifier", 
									NULLIF(itx.quantidade, 0) AS "quantity", 
									NULLIF(itx.valor, 0) AS "amount", 
									CAST(itx.montante AS decimal(18, 2)) AS "taxAmount"
								FROM tb_EXP_DeclaracoesAdicoesImposicoesTaxas AS itx WITH(NOLOCK)
									LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON itx.id_unidadeMedida = ume.UME_IDTY
								WHERE itx.id_imposicao = aoi.id 
								FOR XML PATH('TaxBase'), TYPE) 
							FROM tb_EXP_DeclaracoesAdicoesImposicoes AS aoi WITH(NOLOCK)
							WHERE aoi.id_adicao = adi.EXA_CHVE								
							FOR XML PATH('DutiesAndTaxes'), TYPE)
						HAVING (SELECT SUM(montante) FROM tb_EXP_DeclaracoesAdicoesImposicoes WITH(NOLOCK) WHERE id_adicao = adi.EXA_CHVE) > 0 
							AND ((exm.EXM_P17A IN ('AD', 'AL', 'BA', 'CL', 'DZ', 'EG', 'FO', 'HR', 'IL', 'JO', 'MA', 'ME', 'MK', 'MX', 'PS', 'TN', 'TR', 'XC', 'XL')) OR (adi.TDE_REGI = '3151'))
						FOR XML PATH('CalculationOfTaxes'), TYPE)						
					FOR XML PATH('Commodity'), TYPE),
					(SELECT
						ROW_NUMBER() OVER(ORDER BY EXM_CHVE) AS "sequenceNumber", 
						NULLIF(TEM_CODI, '') AS "typeOfPackages", 
						CAST(EXM_NVOL AS int) AS "numberOfPackages",
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXM_MARN, '')) AS "shippingMarks"
					FROM PRO_EXMV WITH(NOLOCK)
					WHERE EXA_CHVE = adi.EXA_CHVE
					FOR XML PATH('Packaging'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY apr.id) AS "sequenceNumber", 
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(apr.numero, '')) AS "referenceNumber", 										
						apr.numeroAdicao AS "goodsItemNumber", 
						umv.UME_CODI AS "typeOfPackages", 
						apr.volumes AS "numberOfPackages", 
						umq.UME_CODI AS "measurementUnitAndQualifier", 
						apr.quantidade AS "quantity"						 
					FROM tb_EXP_DeclaracoesAdicoesPrecedentes AS apr WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON apr.id_documento = doc.DOC_IDTY
						INNER JOIN TAB_UMED AS umv WITH(NOLOCK) ON apr.id_unidadeMedidaVolumes = umv.UME_IDTY
						LEFT OUTER JOIN TAB_UMED AS umq WITH(NOLOCK) ON apr.id_unidadeMedidaQualificador = umq.UME_IDTY
					WHERE apr.id_adicao = adi.EXA_CHVE AND exm.EXM_TPRO NOT IN ('X', 'Y', 'Z')
					FOR XML PATH('PreviousDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
						NULLIF(DOC_CODI, '') AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXD_NREF, '')) AS "referenceNumber", 	
						EXD_NADI AS "documentLineItemNumber", 									
						NULLIF(EEM_DESC, '') AS "issuingAuthorityName", 
						CONVERT(varchar(10), EXD_DTEM, 120) AS "validityDate", 
						NULLIF(UME_CODI, '') AS "measurementUnitAndQualifier", 
						NULLIF(EXD_QNTD, 0) AS "quantity", 						
						NULLIF(PAI_MOED, '') AS "currency", 						
						CAST(ISNULL(EXD_MONT, 0) AS decimal(18, 2)) AS "amount"
					FROM PRO_EXDA WITH(NOLOCK) 												
					WHERE EXA_CHVE = adi.EXA_CHVE AND EXD_TIPO = 0
					FOR XML PATH('SupportingDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
						NULLIF(DOC_CODI, '') AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXD_NREF, '')) AS "referenceNumber"
					FROM PRO_EXDA WITH(NOLOCK) 						
					WHERE EXA_CHVE = adi.EXA_CHVE AND EXD_TIPO = 1
					FOR XML PATH('TransportDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
						NULLIF(DOC_CODI, '') AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(EXD_NREF, '')) AS "referenceNumber"									
					FROM PRO_EXDA WITH(NOLOCK) 						
					WHERE EXA_CHVE = adi.EXA_CHVE AND EXD_TIPO = 2 AND ISNULL(tde.TDE_1CAS, '') <> 'CO'
					FOR XML PATH('AdditionalReference'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ape.id) AS "sequenceNumber", 
						ped.TXM_CODI AS "code", 				
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(numero, '')) AS "text" 				
					FROM tb_EXP_DeclaracoesAdicoesPedidos AS ape WITH(NOLOCK)
						INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ape.id_pedido = ped.TXM_IDTY 					
					WHERE ape.id_adicao = adi.EXA_CHVE
					FOR XML PATH('AdditionalInformation'), TYPE), 															
					(SELECT
						NULLIF(adi.EXA_MPAG, '') AS "methodOfPayment" 					
					HAVING exm.EXM_TPRO NOT IN ('B', 'C', 'E', 'F') AND exm.EXM_SEGU = 2 AND ISNULL(adi.EXA_MPAG, '') <> ''
					FOR XML PATH('TransportCharges'), TYPE) 
				FROM PRO_EXAD AS adi WITH(NOLOCK) 
					LEFT OUTER JOIN TAB_REST AS res WITH(NOLOCK) ON adi.RES_CODI = res.RES_CODI		
				WHERE adi.EXM_EANO = exm.EXM_EANO AND adi.EXM_CODI = exm.EXM_CODI AND adi.EXM_COPE = exm.DEC_CODI
				FOR XML PATH('GoodsItem'), TYPE)
			FOR XML PATH('GoodsShipment'), TYPE), 
			(SELECT
				NULLIF(exm.EAD_CODI1, '') AS "customsOfficeOfDischargeCode", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_PRZA, '')) AS "dischargeDeadline", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_ATVP, '')) AS "plannedActivitiesDetails", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(exm.EXM_INFA, '')) AS "additionalInformation", 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY dlt.id) AS "sequenceNumber", 
					dlt.tipo AS "typeOfLocation", 
					dlt.qualificador AS "qualifierOfLocation",
					(CASE dlt.qualificador WHEN 'U' THEN lau.LME_CODI ELSE NULL END) AS "UNLocode",
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.morada, '')) AS "streetAndNumber", 					
						NULLIF(dlt.codigoPostal, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.localidade, '')) AS "city", 
						pai.PAI_CODI AS "country"
					HAVING dlt.qualificador <> 'U'
					FOR XML PATH('Address'), TYPE)					
				FROM tb_EXP_DeclaracoesLocaisTransformacao AS dlt WITH(NOLOCK)
					LEFT OUTER JOIN TAB_LMER AS lau WITH(NOLOCK) ON dlt.id_localAutorizado = lau.LME_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dlt.id_pais = pai.PAI_IDTY
				WHERE dlt.id_declaracaoEXP = exm.EXM_IDTY
				FOR XML PATH('PlaceOrPlacesOfProcessingOrUse'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpt.id) AS "sequenceNumber", 
					dpt.codigoPautal AS "commodityCode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.designacao, '')) AS "descriptionOfGoods", 
					(SELECT
						1 AS "sequenceNumber", 
						mid.MIA_CODI AS "identificationMeasureCode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.descricao, '')) AS "identificationMeasureDescription"
					FOR XML PATH('GoodsIdentification'), TYPE),
					(SELECT	
						1 AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.taxaRendimento, '')) AS "freeText"					
					HAVING ISNULL(dpt.taxaRendimento, '') <> ''
					FOR XML PATH('YieldRate'), TYPE)
				FROM tb_EXP_DeclaracoesProdutosTransformados AS dpt WITH(NOLOCK)
					INNER JOIN TAB_MIAU AS mid WITH(NOLOCK) ON dpt.id_meioIdentificacao = mid.MIA_IDTY
				WHERE dpt.id_declaracaoEXP = exm.EXM_IDTY
				FOR XML PATH('ProcessedProducts'), TYPE)				
			HAVING exm.EXM_TPRO IN ('A', 'D') AND ISNULL(exm.EAD_C29A, '') = '' AND LEFT(exm.EXM_REGI, 2) IN ('21', '22') AND ISNULL(exm.EAD_CODI1, '') <> ''			
			FOR XML PATH('AuthorizationRequestsOutwardProcessing'), TYPE),
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY dcc.EXC_CHVE) AS "sequenceNumber", 
				NULLIF(dcc.EXC_FNIF, '') AS "supplierVATNumber", 
				NULLIF(dcc.EXC_NFAC, '') AS "invoiceNumber", 
				CONVERT(varchar(10), dcc.EXC_DFAC, 120) AS "invoiceIssueDate", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dcc.EXC_DCOM, '')) AS "goodsDescription", 
				ISNULL(dcc.EXC_PBRT, 0) AS "grossMass", 
				ISNULL(dcc.EXC_PLIQ, 0) AS "netMass", 
				ISNULL(dcc.EXC_VALO, 0) AS "amountInvoiced", 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY EXD_CHVE) AS "sequenceNumber", 
					NULLIF(TEM_CODI, '') AS "typeOfPackages", 
					CAST(EXD_QTDE AS int) AS "numberOfPackages"
				FROM PRO_EXCD WITH(NOLOCK)
				WHERE EXM_EANO = dcc.EXM_EANO AND EXM_CODI = dcc.EXM_CODI AND EXM_COPE = dcc.EXM_COPE AND EXC_LINH = dcc.EXC_LINH
				FOR XML PATH('Packaging'), TYPE)
			FROM PRO_EXCE AS dcc WITH(NOLOCK)
			WHERE dcc.EXM_EANO = exm.EXM_EANO AND dcc.EXM_CODI = exm.EXM_CODI AND dcc.EXM_COPE = exm.DEC_CODI AND LEFT(exm.EXM_REGI, 2) = '10'
			FOR XML PATH('CCEElements'), TYPE)
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dco WITH(NOLOCK) ON exm.DEC_CODI = dco.DEC_CODI	
			INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON exm.TDE_COD1 = tde.TDE_CODI
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
		WHERE exm.EXM_IDTY = @IdDeclaracao
		FOR XML PATH('PT515C'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagemGeraXMLPT515C] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagemGeraXMLPT515C] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagemGeraXMLPT583C]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagemGeraXMLPT583C] @IdDeclaracao int, @InfoRequerida int, @DataSaida datetime, @TransportadorNIF varchar(17), @TransportadorNome varchar(70), 
	@XMLInfoExtra xml, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem PT583C - Resposta ao Pedido de Informação sobre Exportação s/ Saída
	SET @FicheiroXML = 				
		(SELECT
			NULLIF(dco.DEC_WSUS, '') AS "messageSender", 
			'AT' AS "messageRecipient", 
			CONVERT(varchar(19), @DataAtual, 120) AS "preparationDateAndTime", 
			'EXP-CAU' AS "messageIdentification", 
			'PT583C' AS "messageType", 
			NULLIF(exm.EXM_NRLO, '') AS "correlationIdentifier", 			
			(SELECT												
				NULLIF(exm.EXM_NDGA, '') AS "MRN",  
				CONVERT(varchar(10), @DataSaida, 120) AS "exitDate", 
				@InfoRequerida AS "enquiryInformationCode"				
			FOR XML PATH('ExportOperation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_CODA, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExport'), TYPE), 
			(SELECT
				NULLIF(exm.EAD_CO29, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExitActual'), TYPE), 			
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(dcl.DEC_NIF, '')), '') AS "identificationNumber"				
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(exm.CLI_PAI2, '') + ISNULL(exm.CLI_NIF2, '')), '') AS "identificationNumber",
				exm.EXM_TP14 AS "status"			
			HAVING ISNULL(exm.EXM_TP14, -1) = 2
			FOR XML PATH('Representative'), TYPE),
			(SELECT 
				NULLIF(@TransportadorNIF, '') AS "identificationNumber", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(@TransportadorNome, '')) AS "name"					
			HAVING ISNULL(@TransportadorNIF, '') <> ''
			FOR XML PATH('ExitCarrier'), TYPE),
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY t.c.value('id[1]', 'varchar(30)')) AS "sequenceNumber", 
				t.c.value('tipo[1]', 'int') AS "type",
				(SELECT
					ROW_NUMBER() OVER(ORDER BY d.c.value('codigo[1]', 'varchar(5)')) AS "sequenceNumber", 
					NULLIF(d.c.value('codigo[1]', 'varchar(5)'), '') AS "type", 
					NULLIF(d.c.value('numero[1]', 'varchar(70)'), '') AS "referenceNumber"
				FROM @XMLInfoExtra.nodes('provasAlternativas/prova/docTransporte') AS d(c)
				WHERE d.c.value('(../id)[1]', 'varchar(30)') = t.c.value('id[1]', 'varchar(30)')
				FOR XML PATH('TransportEquipment'), TYPE)
			FROM @XMLInfoExtra.nodes('provasAlternativas/prova') AS t(c)
			FOR XML PATH('AlternativeEvidence'), TYPE)														
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dco WITH(NOLOCK) ON exm.DEC_CODI = dco.DEC_CODI				
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
		WHERE exm.EXM_IDTY = @IdDeclaracao
		FOR XML PATH('PT583C'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagemGeraXMLPT583C] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagemGeraXMLPT583C] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagemGeraXMLPTE46C]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagemGeraXMLPTE46C] @IdDeclaracao int, @XMLDocumentos xml, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem PTE46C - Envio de documentos da Declaração de Exportação
	SET @FicheiroXML = 				
		(SELECT
			NULLIF(dco.DEC_WSUS, '') AS "messageSender", 
			'AT' AS "messageRecipient", 
			CONVERT(varchar(19), @DataAtual, 120) AS "preparationDateAndTime", 
			'EXP-CAU' AS "messageIdentification", 
			'PTE46C' AS "messageType", 
			NULLIF(exm.EXM_NRLO, '') AS "correlationIdentifier", 			
			(SELECT												
				NULLIF(exm.EXM_NDGA, '') AS "MRN",  				
				(CASE WHEN EXISTS(SELECT 1 FROM @XMLDocumentos.nodes('documentosAEnviar/documento') AS t(c)) THEN 1 ELSE 0 END) AS "availableDocuments"			
			FOR XML PATH('ExportOperation'), TYPE),											
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY t.adicao, t.id) AS "sequenceNumber", 
				t.DOC_CODI AS "documentType", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(t.numero, '')) AS "referenceNumber", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(t.descricao, '')) AS "description", 
				t.elementosCCE AS "CCEElements", 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY f.c.value('nome[1]', 'varchar(200)')) AS "sequenceNumber",
					NULLIF(UPPER(SUBSTRING(f.c.value('nome[1]', 'varchar(200)'), (CHARINDEX('.', f.c.value('nome[1]', 'varchar(200)')) + 1), (LEN(f.c.value('nome[1]', 'varchar(200)')) - CHARINDEX('.', f.c.value('nome[1]', 'varchar(200)'))))), '') AS "fileType", 
					NULLIF(f.c.value('base64[1]', 'varchar(MAX)'), '') AS "documentImage"
				FROM @XMLDocumentos.nodes('documentosAEnviar/documento/ficheiro') AS f(c)
				WHERE ISNULL(f.c.value('../adicao[1]', 'int'), 0) = t.adicao AND f.c.value('../id[1]', 'bigint') = t.id
				FOR XML PATH('DocumentsImage'), TYPE)
			FROM (SELECT 0 AS adicao, ddo.id, ddo.numero, doc.DOC_CODI, t.c.value('descricao[1]', 'varchar(512)') AS descricao, t.c.value('elementosCCE[1]', 'bit') AS elementosCCE
				FROM @XMLDocumentos.nodes('documentosAEnviar/documento') AS t(c)
					INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON t.c.value('id[1]', 'bigint') = ddo.id
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE t.c.value('adicao[1]', 'int') IS NULL
				UNION ALL
				SELECT dad.EXA_LINH AS adicao, dad.EXD_CHVE, dad.EXD_NREF, dad.DOC_CODI, t.c.value('descricao[1]', 'varchar(512)') AS descricao, t.c.value('elementosCCE[1]', 'bit') AS elementosCCE
				FROM @XMLDocumentos.nodes('documentosAEnviar/documento') AS t(c)
					INNER JOIN PRO_EXDA AS dad WITH(NOLOCK) ON t.c.value('id[1]', 'bigint') = dad.EXD_CHVE
				WHERE t.c.value('adicao[1]', 'int') IS NOT NULL) AS t
			FOR XML PATH('RequestedDocuments'), TYPE)		
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dco WITH(NOLOCK) ON exm.DEC_CODI = dco.DEC_CODI	
		WHERE exm.EXM_IDTY = @IdDeclaracao
		FOR XML PATH('PTE46C'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagemGeraXMLPTE46C] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagemGeraXMLPTE46C] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagemGeraXMLPTE85C]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagemGeraXMLPTE85C] @IdDeclaracao int, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem PTE85C - Comunicação de Saída (Remessas Postais)
	SET @FicheiroXML = 				
		(SELECT
			NULLIF(dco.DEC_WSUS, '') AS "messageSender", 
			'AT' AS "messageRecipient", 
			CONVERT(varchar(19), @DataAtual, 120) AS "preparationDateAndTime", 
			'EXP-CAU' AS "messageIdentification", 
			'PTE85C' AS "messageType", 
			NULLIF(exm.EXM_NRLO, '') AS "correlationIdentifier", 			
			(SELECT												
				NULLIF(exm.EXM_NDGA, '') AS "MRN"
			FOR XML PATH('ExportOperation'), TYPE),
			(SELECT
				NULLIF(exm.EAD_CO29, '') AS "referenceNumber"			
			FOR XML PATH('CustomsOfficeOfExitDeclared'), TYPE), 
			(SELECT 				
				(SELECT					
					NULLIF(exm.EXM_CPRT, '') AS "ObjectCode", 					
					NULLIF(exm.EXM_P17A, '') AS "CountryofDestination", 
					CONVERT(varchar(10), exm.EXM_DPUP, 120) AS "ShippingDate", 
					ISNULL(exm.EXM_TMBR, 0) AS "grossMass"	
				FOR XML PATH('Consignment'), TYPE)			
			FOR XML PATH('GoodsShipment'), TYPE)																		
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dco WITH(NOLOCK) ON exm.DEC_CODI = dco.DEC_CODI				
		WHERE exm.EXM_IDTY = @IdDeclaracao
		FOR XML PATH('PTE85C'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagemGeraXMLPTE85C] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagemGeraXMLPTE85C] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagensObtemResposta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagensObtemResposta] @Ambito tinyint, @Tipo varchar(3), @Id int, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @PassPhrase varchar(50), @DataAtual datetime, @CodUtilizador varchar(30), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), 
		@ProxyPassword varchar(100), @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @NRLDeclaracao varchar(22), @AutorizacaoSaida bit, @EnderecoWS varchar(250), 
		@LoginWS varchar(50), @PwdWS varchar(100), @PathCertificado varchar(250), @PwdCertificado varchar(100), @MensagemSoapAction varchar(250), @PublicKeyCertificadoAT nvarchar(4000), 
		@PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), @RequestXML xml, @Resultado int, @ResponseXML xml, @FaultCode varchar(100), 
		@FaultMessage varchar(MAX), @RespostaXML xml, @FicheirosXML xml, @NomeFicheiro varchar(100), @MensagemXMLBase64 varchar(MAX), @MensagemXML xml, @TipoMensagem varchar(100), 
		@EstadoOperacao varchar(3), @XMLNumeroNRM varchar(25), @XMLDataNRM datetime, @XMLDataLimite datetime, @XMLDataSaida datetime, @XMLDataControlo datetime, @FicheiroBinario varbinary(MAX), 
		@IndiceInicial int, @IndiceFinal int
-- inicia variáveis	
	SET @PassPhrase = '16345678901234567'
-- inicia processo de obtenção de respostas da declaração
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações do Proxy Authentication nos Parâmetros de Despachos
		SELECT TOP 1 @ProxyAuthentication = PDE_PRXA, @ProxyServer = ISNULL(PDE_PRXS, ''), @ProxyPort = ISNULL(PDE_PRXP, 0), @ProxyUser = ISNULL(PDE_PRXU, ''), 
			@ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, PDE_PRXW)), '')
		FROM TAB_PDES WITH(NOLOCK)
-- obtem configurações do Webservice no declarante da declaração
		SELECT @AnoDeclaracao = exm.EXM_EANO, @CodDeclaracao = exm.EXM_CODI, @CodOperadorDeclaracao = exm.DEC_CODI, @NRLDeclaracao = EXM_NRLO, @AutorizacaoSaida = exm.EXM_ASAI, 
			@EnderecoWS = dcl.DEC_WSEX, @LoginWS = dcl.DEC_WSUS, 
			@PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSPW)), 
			@PathCertificado = dcl.DEC_WSPC, @PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSWC))			
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CODI = dcl.DEC_CODI	
		WHERE exm.EXM_IDTY = @Id
-- obtem a chave pública do sistema de autenticação na AT em função se o request é para ambiente de testes ou não (porta 818 = Ambiente de Testes)
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT((CASE WHEN CHARINDEX(':818', @EnderecoWS) > 0 THEN 1 ELSE 0 END))
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- processa obtenção das mensagens de resposta
		IF @Ambito IN (0, 1)
		BEGIN
-- em função do âmbito, assume o respetivo soap action
			IF @Ambito = 0
				SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/obterMensagensNaoEntreguesRequest'				                           
			ELSE
				SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/obterMensagensEntreguesRequest'
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido a enviar à AT		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://pt.atos.expcau.ws' AS web, 'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							(SELECT 
								(SELECT
									NULLIF(@NRLDeclaracao, '') AS "numeroReferenciaLocal"									
								FOR XML PATH('listaNRLs'), TYPE),
								@Tipo AS "tipo"
							FOR XML PATH('obterMensagensNaoEntreguesInput'), TYPE)	
						HAVING @Ambito = 0 -- Mensagens Não Entregues		
						FOR XML PATH('web:obterMensagensNaoEntregues'), TYPE), 
						(SELECT 
							(SELECT 
								NULLIF(@NRLDeclaracao, '') AS "numeroReferenciaLocal",
								@Tipo AS "tipo"
							FOR XML PATH('obterMensagensEntreguesInput'), TYPE)	
						HAVING @Ambito = 1 -- Mensagens Entregues						
						FOR XML PATH('web:obterMensagensEntregues'), TYPE)
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)				
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)					
-- em função do âmbito, obtem o resultado "OK"/"NOK" retornados do WS			
			IF @Ambito = 0
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://pt.atos.expcau.ws' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterMensagensNaoEntreguesResponse/return') AS t(c)								
			END
			ELSE
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://pt.atos.expcau.ws' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterMensagensEntreguesResponse/return') AS t(c)										
			END
			IF @FaultCode <> '0'
				RAISERROR('A obtençao das mensagens gerou o erro "%s".', 16, 4, @FaultMessage)
-- obtem o resultado de sucesso resultante da obtenção dos dados do WS
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)'),
				@FicheirosXML = t.c.query('ficheiroResposta')
			FROM @RespostaXML.nodes('declaracao') AS t(c)							
			IF (@FaultCode <> '100') AND (@FaultCode <> '101')
				RAISERROR('A declaração gerou o erro "%s".', 16, 5, @FaultMessage)	
-- obtem todos os ficheiros de resposta associados à declaração
			DECLARE FicheirosXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT 
					t.c.value('nomeFicheiro[1]', 'varchar(100)'), 
					t.c.value('ficheiro[1]', 'varchar(MAX)')
				FROM @FicheirosXML.nodes('ficheiroResposta') AS t(c)
			OPEN FicheirosXML
			FETCH NEXT FROM FicheirosXML INTO @NomeFicheiro, @MensagemXMLBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN 
				SET @MensagemXML = NULL
				SET @TipoMensagem = NULL
				SET @EstadoOperacao = NULL
-- converte o Base64 para varbinary e depois para xml
				SET @MensagemXML = CAST('' AS XML).value('xs:base64Binary(sql:variable("@MensagemXMLBase64"))', 'varbinary(max)')					
-- obtem da mensagem xml o nome do elemento root como tipo da mensagem obtida
				SELECT @TipoMensagem = t.c.value('local-name(.)', 'varchar(100)')
				FROM @MensagemXML.nodes('*') AS t(c)
-- atualiza declaração em função da mensagem de resposta obtida
				IF @TipoMensagem = 'PT504C'
				BEGIN
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem PT504C - Aceitação da Alteração da Declaração
					SELECT 
						@XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), ''), 
						@XMLDataControlo = t.c.value('(ExportOperation/amendmentAcceptanceDateAndTime)[1]', 'datetime')
					FROM @MensagemXML.nodes('PT504C') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, n.º provisório e n.º NRM 
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_NDGA = ISNULL(@XMLNumeroNRM, EXM_NDGA), 						
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT509C'
				BEGIN					
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem PT509C - Aceitação da Anulação da Declaração
					SELECT 
						@XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), ''), 
						@XMLDataControlo = t.c.value('(ExportOperation/invalidationDecisionDateAndTime)[1]', 'datetime')
					FROM @MensagemXML.nodes('PT509C') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_EXML SET 
						EXM_STAT = 3, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT528C'
				BEGIN					
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem PT528C - Aceitação da Declaração
					SELECT 
						@XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), ''),
						@XMLDataNRM = t.c.value('(ExportOperation/declarationAcceptanceDate)[1]', 'datetime')						
					FROM @MensagemXML.nodes('PT528C') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, n.º NRM e data NRM
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_NDGA = @XMLNumeroNRM,  
						EXM_DDGA = @XMLDataNRM,  
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT529C'
				BEGIN					
					SET @EstadoOperacao = 'AS' 
-- obtem dados da mensagem PT529C - Autorização de Saída da Declaração
					SELECT @XMLDataSaida = t.c.value('(ExportOperation/releaseDate)[1]', 'datetime')
					FROM @MensagemXML.nodes('PT529C') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, AS, data AS e data 6A
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_ASAI = 1, 
						EXM_DTAS = @XMLDataSaida, 
						EXM_DT6A = @DataAtual, 						
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT531C'
				BEGIN					
					SET @EstadoOperacao = 'LDC' 
-- obtem dados da mensagem PT531C - Lembrete de Expiração do Prazo DC da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('PT531C') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT551C'
				BEGIN					
					SET @EstadoOperacao = 'SNA' 
-- obtem dados da mensagem PT551C - Saída Não Autorizada da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('PT551C') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT556C'
				BEGIN					
					SET @EstadoOperacao = 'RE' 
-- obtem dados da mensagem PT556C - Rejeição da Declaração
					SELECT 						
						@XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), ''), 
						@XMLDataControlo = t.c.value('(ExportOperation/rejectionDateAndTime)[1]', 'datetime')			
					FROM @MensagemXML.nodes('PT556C') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação e n.º NRM 
					UPDATE PRO_EXML SET 
						EXM_STAT = (CASE WHEN ISNULL(ISNULL(@XMLNumeroNRM, EXM_NDGA), '') <> '' THEN 2 ELSE 0 END), 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_NDGA = ISNULL(NULLIF(@XMLNumeroNRM, ''), EXM_NDGA), 						
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT560C'
				BEGIN									
-- obtem dados da mensagem PT560C - Notificação de Controlo da Declaração					
					SELECT @EstadoOperacao = (CASE 
												WHEN t.c.value('(ExportOperation/notificationType)[1]', 'int') = 1 THEN 'PDA' 
												WHEN (t.c.value('(ExportOperation/notificationType)[1]', 'int') IN (0, 2)) AND (@AutorizacaoSaida = 1) THEN 'CAP' 
												ELSE 'CA' 
											END), 
						@XMLDataControlo = t.c.value('(ExportOperation/controlNotificationDate)[1]', 'datetime')
					FROM @MensagemXML.nodes('PT560C') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, data do controlo e flags de CD e CAP
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 						
						EXM_DTCD = @XMLDataControlo, 
						EXM_CRTD = (CASE WHEN @EstadoOperacao IN ('PDA', 'CA') THEN 1 ELSE EXM_CRTD END), 				
						EXM_CRTA = (CASE @EstadoOperacao WHEN 'CAP' THEN 1 ELSE EXM_CRTA END), 						
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE				
				IF @TipoMensagem = 'PT582C'
				BEGIN					
					SET @EstadoOperacao = 'PIL' 
-- obtem dados da mensagem PT582C - Pedido Sobre Exportação Sem Saída da Declaração
					SELECT 
						@XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), ''), 
						@XMLDataLimite = t.c.value('(ExportOperation/limitForResponseDate)[1]', 'datetime')
					FROM @MensagemXML.nodes('PT582C') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação e data limite 
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 
						EXM_DTLM = @XMLDataLimite,												
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT599C'
				BEGIN					
					SET @EstadoOperacao = 'CS' 
-- obtem dados da mensagem PT599C - Certificação de Saída da Declaração
					SELECT 
						@XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), ''), 
						@XMLDataSaida = t.c.value('(ExportOperation/releaseDate)[1]', 'datetime')
					FROM @MensagemXML.nodes('PT599C') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, data CS e bloqueio
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 
						EXM_DTCS = @XMLDataSaida,					
						EXM_BLOQ = 1,							
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PTE38C'
				BEGIN					
					SET @EstadoOperacao = 'LED' 
-- obtem dados da mensagem PTE38C - Lembrete p/ Envio de Documentos da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('PTE38C') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END	
				ELSE
				IF @TipoMensagem = 'PTE44C'
				BEGIN					
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem PTE44C - Notificação do Resultado do Controlo da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ExportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('PTE44C') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_EXML SET 
						EXM_STAT = 2, 
						EXM_ESTO = @EstadoOperacao, 												
						EXM_UALT = @CodUtilizador, EXM_DTAL = @DataAtual
					WHERE EXM_IDTY = @Id
				END																
				ELSE
					SET @TipoMensagem = 'PT???C' --Mensagem desconhecida
-- insere no detalhe de mensagens os dados da obtenção da mensagem
				INSERT INTO tb_EXP_DeclaracoesMensagens(id_declaracaoEXP, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, 
					id_utilizadorControlo, dataControlo, nomeFicheiro, ficheiro)
				VALUES(@Id, 0, @TipoMensagem, @IdUtilizador, @DataAtual, @RequestXML, @MensagemXML, 1, @EstadoOperacao, 
					@IdUtilizador, @DataAtual, ISNULL(@NomeFicheiro, 'SemNome.xml'), CAST(@MensagemXML AS varbinary(MAX)))
-- para a mensagem PT560C - Notificação de Controlo e PTE38C - Lembrete p/ Envio de Documentos, processa o envio de emails de notificação de controlo para spool de acordo com as configurações
				IF (@TipoMensagem = 'PT560C') OR (@TipoMensagem = 'PTE38C')
					EXEC sp_EXP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo @id, @Erro OUTPUT
				FETCH NEXT FROM FicheirosXML INTO @NomeFicheiro, @MensagemXMLBase64
			END
			CLOSE FicheirosXML
			DEALLOCATE FicheirosXML
		END
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- insere no detalhe de mensagens os dados da obtenção da declaração
		IF (@RequestXML IS NOT NULL) AND (ISNULL(ISNULL(@MensagemXML, @RespostaXML), @ResponseXML) IS NOT NULL)
		BEGIN
			INSERT INTO tb_EXP_DeclaracoesMensagens(id_declaracaoEXP, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, 
				id_utilizadorControlo, dataControlo, nomeFicheiro, ficheiro)
			VALUES(@Id, 0, ISNULL(@TipoMensagem, 'PT???C'), @IdUtilizador, @DataAtual, @RequestXML, ISNULL(ISNULL(@MensagemXML, @RespostaXML), @ResponseXML), 0, @EstadoOperacao, 
				@IdUtilizador, @DataAtual, ISNULL(@NomeFicheiro, 'Erro.xml'), CAST(ISNULL(ISNULL(@MensagemXML, @RespostaXML), @ResponseXML) AS varbinary(MAX)))				
		END
	END CATCH	
-- processa obtenção dos documentos PDF
	IF @Ambito IN (0, 2)
	BEGIN
-- inicia processo de obtenção de documentos PDF da declaração
		BEGIN TRY	
			SET @FaultCode = NULL
			SET @FaultMessage = NULL
			SET @RespostaXML = NULL
			SET @FicheirosXML = NULL
-- em função do âmbito, assume o respetivo soap action
			IF @Ambito = 0
				SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/obterDocumentosPDFNaoEntreguesRequest'
			ELSE
				SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/obterDocumentosPDFEntreguesRequest'
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido a enviar à AT		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://pt.atos.expcau.ws' AS net, 'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							(SELECT 
								(SELECT
									NULLIF(@NRLDeclaracao, '') AS "numeroReferenciaLocal"								
								FOR XML PATH('listaNRLs'), TYPE),
								@Tipo AS "tipo"
							FOR XML PATH('obterDocumentosPDFNaoEntreguesInput'), TYPE)
						HAVING @Ambito = 0 -- Documentos PDF Não Entregues
						FOR XML PATH('net:obterDocumentosPDFNaoEntregues'), TYPE), 
						(SELECT 
							(SELECT 
								NULLIF(@NRLDeclaracao, '') AS "numeroReferenciaLocal",
								@Tipo AS "tipo"
							FOR XML PATH('obterDocumentosEntreguesInput'), TYPE)
						HAVING @Ambito = 2 -- Documentos PDF Entregues
						FOR XML PATH('net:obterDocumentosPDFEntregues'), TYPE)
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)																											
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 6, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 7, @FaultMessage)					
-- em função do âmbito, obtem o resultado "OK"/"NOK" retornados do WS			
			IF @Ambito = 0
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://pt.atos.expcau.ws' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterDocumentosPDFNaoEntreguesResponse/return') AS t(c)					
			END
			ELSE
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://pt.atos.expcau.ws' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:obterDocumentosPDFEntreguesResponse/return') AS t(c)					
			END
			IF @FaultCode <> '0'
				RAISERROR('A obtençao dos documentos gerou o erro "%s".', 16, 8, @FaultMessage)				
-- obtem o resultado de sucesso resultante da obtenção dos dados do WS			
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)'),
				@FicheirosXML = t.c.query('ficheiroResposta')
			FROM @RespostaXML.nodes('declaracao') AS t(c)							
			IF (@FaultCode <> '100') AND (@FaultCode <> '101')
				RAISERROR('A declaração gerou o erro "%s".', 16, 9, @FaultMessage)		
-- obtem todos os ficheiros de resposta associados à declaração
			DECLARE FicheirosPDF CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT 
					t.c.value('nomeFicheiro[1]', 'varchar(100)'), 
					t.c.value('ficheiro[1]', 'varchar(MAX)')
				FROM @FicheirosXML.nodes('ficheiroResposta') AS t(c)
			OPEN FicheirosPDF
			FETCH NEXT FROM FicheirosPDF INTO @NomeFicheiro, @MensagemXMLBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN 							
-- converte o Base64 para varbinary 
				SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@MensagemXMLBase64"))', 'varbinary(max)')
-- obtem do nome do ficheiro o tipo de mensagem
				IF CHARINDEX('.AUT.', @NomeFicheiro) > 0
					SET @TipoMensagem = 'PT529C'
				ELSE
					IF CHARINDEX('.CSAI.', @NomeFicheiro) > 0
						SET @TipoMensagem = 'PT599C'
					ELSE					
					BEGIN
						SET @IndiceInicial = CHARINDEX('.CC', @NomeFicheiro) + 1
						SET @IndiceFinal = CHARINDEX('A.', @NomeFicheiro, @IndiceInicial) + 1
						SET @TipoMensagem = SUBSTRING(@NomeFicheiro, @IndiceInicial, (@IndiceFinal - @IndiceInicial))
						IF ISNULL(@TipoMensagem, '') = ''
							SET @TipoMensagem = 'OUTRO'
					END									
-- insere no detalhe de arquivos o ficheiro obtido 
				INSERT INTO PRO_EXFI(EXM_EANO, EXM_CODI, DEC_CODI, EXF_DESC, EXF_DATA, EXF_UTIL, EXF_NOMF, EXF_TMSG, EXF_ORIG, EXF_FICH)
				VALUES(@AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @TipoMensagem, @DataAtual, @CodUtilizador, @NomeFicheiro, @TipoMensagem, 1, @FicheiroBinario)
-- processa o envio de emails dos ficheiros das mensagens de PT529C - Autorização de Saída e PT599C - Certificação de Saída para spool de acordo com as configurações
				IF (@TipoMensagem = 'PT529C') OR (@TipoMensagem = 'PT599C')
					EXEC sp_EXP_Declaracoes_ProcessaEnvioEmailArquivosResposta @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @TipoMensagem, @NomeFicheiro, @FicheiroBinario, @Erro OUTPUT
				FETCH NEXT FROM FicheirosPDF INTO @NomeFicheiro, @MensagemXMLBase64
			END
			CLOSE FicheirosPDF
			DEALLOCATE FicheirosPDF
		END TRY
		BEGIN CATCH		
-- constroi mensagem de erro detalhada
			SET @NumErro = 1 
			SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'			
		END CATCH	
	END
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagensObtemResposta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagensObtemResposta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_MensagensSubmetePedido]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_MensagensSubmetePedido] @TipoMensagem varchar(8), @Id int, @Motivo varchar(512), @InfoRequerida int, @DataSaida datetime, 
	@TransportadorNIF varchar(17), @TransportadorNome varchar(70), @XMLInfoExtra xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @PassPhrase varchar(50), @DataAtual datetime, @CodUtilizador varchar(30), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, 
		@ProxyUser varchar(100), @ProxyPassword varchar(100), @NRLDeclaracao varchar(22), @NRMDeclaracao varchar(21), @NumProvisorioDeclaracao varchar(20), 
		@EstadoOperacaoDeclaracao varchar(3), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), @PathCertificado varchar(250), @PwdCertificado varchar(100), 
		@MensagemSoapAction varchar(250), @MensagemXML xml, @MensagemTXT varchar(MAX), @MensagemXMLBinario varbinary(MAX), @MensagemXMLBase64 varchar(MAX), 
		@PublicKeyCertificadoAT nvarchar(4000), @PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), 
		@RequestXML xml, @Resultado int, @ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX)
-- inicia variáveis	
	SET @PassPhrase = '16345678901234567'
-- inicia processo de submissão de pedido da declaração
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações do Proxy Authentication nos Parâmetros de Despachos
		SELECT TOP 1 @ProxyAuthentication = PDE_PRXA, @ProxyServer = ISNULL(PDE_PRXS, ''), @ProxyPort = ISNULL(PDE_PRXP, 0), @ProxyUser = ISNULL(PDE_PRXU, ''), 
			@ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, PDE_PRXW)), '')
		FROM TAB_PDES WITH(NOLOCK)
-- obtem configurações do Webservice no declarante da declaração
		SELECT @NRLDeclaracao = EXM_NRLO, @EstadoOperacaoDeclaracao = exm.EXM_ESTO, @NRMDeclaracao = EXM_NDGA, @NumProvisorioDeclaracao = EXM_NPRO, @EnderecoWS = dcl.DEC_WSEX, 
			@LoginWS = dcl.DEC_WSUS, @PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSPW)), @PathCertificado = dcl.DEC_WSPC, 
			@PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSWC))			
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CODI = dcl.DEC_CODI	
		WHERE exm.EXM_IDTY = @Id
-- obtem a chave pública do sistema de autenticação na AT em função se o request é para ambiente de testes ou não (porta 818 = Ambiente de Testes)
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT((CASE WHEN CHARINDEX(':818', @EnderecoWS) > 0 THEN 1 ELSE 0 END))
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- constroi o XML de acordo com o tipo de mensagem		
		IF @TipoMensagem = 'PT511C' -- Notificação de Apresentação das Mercadorias
		BEGIN
			SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/processaMensagemRequest'
			EXEC sp_EXP_Declaracoes_MensagemGeraXMLPT511C @Id, @MensagemXML OUTPUT			
		END
		ELSE
		IF @TipoMensagem = 'PT513C' -- Alteração da declaração
		BEGIN
			SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/processaMensagemRequest'
			EXEC sp_EXP_Declaracoes_MensagemGeraXMLPT513C @Id, @MensagemXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'PT514C' -- Anulação da declaração
		BEGIN
			SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/processaMensagemRequest'
			EXEC sp_EXP_Declaracoes_MensagemGeraXMLPT514C @Id, @Motivo, @MensagemXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'PT515C' -- Criação da declaração
		BEGIN
			SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/processaMensagemRequest'
			EXEC sp_EXP_Declaracoes_MensagemGeraXMLPT515C @Id, @MensagemXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'PT583C' -- Resposta ao Pedido de Informação sobre Exportação s/ Saída
		BEGIN
			SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/processaMensagemRequest'
			EXEC sp_EXP_Declaracoes_MensagemGeraXMLPT583C @Id, @InfoRequerida, @DataSaida, @TransportadorNIF, @TransportadorNome, @XMLInfoExtra, @MensagemXML OUTPUT
		END
		ELSE			
		IF @TipoMensagem = 'PTE46C' -- Entrega de documentos
		BEGIN
			SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/entregarDocumentosRequest'
			EXEC sp_EXP_Declaracoes_MensagemGeraXMLPTE46C @Id, @XMLInfoExtra, @MensagemXML OUTPUT
		END
		ELSE			
		IF @TipoMensagem = 'PTE85C' -- Comunicação de Saída (Remessas Postais)
		BEGIN
			SET @MensagemSoapAction = 'http://pt.atos.expcau.ws/WebServiceBean/processaMensagemRequest'
			EXEC sp_EXP_Declaracoes_MensagemGeraXMLPTE85C @Id, @MensagemXML OUTPUT
		END
-- converte o XML gerado para varbinary e depois para Base64
		SET @MensagemTXT = '<?xml version="1.0" encoding="UTF-8"?>' + CAST(@MensagemXML AS varchar(MAX))
		SET @MensagemXMLBinario = CONVERT(varbinary(MAX), @MensagemTXT) 
		SET @MensagemXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@MensagemXMLBinario"))', 'varchar(MAX)') 
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
		EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido ao metodo para enviar mensagem à AT
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://pt.atos.expcau.ws' AS web, 'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT
						(SELECT 
							@LoginWS AS "wss:Username", 
							@PwdWSEncriptada AS "wss:Password",
							@ChvSimetricaEncriptada AS "wss:Nonce",
							@DataSistemaEncriptada AS "wss:Created"
						FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem", 
							@TipoMensagem AS "tipo"
						FOR XML PATH('processaMensagemInput'), TYPE)
					HAVING @TipoMensagem IN ('PT511C', 'PT513C', 'PT514C', 'PT515C', 'PT583C', 'PTE85C') -- "Notificação de Apresentação das Mercadorias" OU "Alteração da declaração" OU "Anulação da declaração" OU "Criação da declaração" OU "Resposta ao Pedido de Informação sobre Exportação s/ Saída" OU "Comunicação de Saída (Remessas Postais)"
					FOR XML PATH('web:processaMensagem'), TYPE), 					
					(SELECT 
						(SELECT 
							(SELECT 
								@NRLDeclaracao AS "numeroReferenciaLocal", 
								NULLIF(@NRMDeclaracao, '') AS "mrn", 
								NULLIF(@NumProvisorioDeclaracao, '') AS "numeroProvisorio"
							FOR XML PATH('identificacaoDeclaracao'), TYPE), 
							(SELECT 
								t.DOC_CODI AS "codigoDocumento", 
								t.adicao AS "numeroAdicao", 
								NULLIF(t.nomeFicheiro, '') AS "nomeFicheiro", 
								NULLIF(t.base64Ficheiro, '') AS "conteudoFicheiro"
							FROM (SELECT 0 AS adicao, doc.DOC_CODI, t.c.value('nome[1]', 'varchar(200)') AS nomeFicheiro, t.c.value('base64[1]', 'varchar(MAX)') AS base64Ficheiro
								FROM @XMLInfoExtra.nodes('documentosAEnviar/documento/ficheiro') AS t(c)
									INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON t.c.value('../id[1]', 'bigint') = ddo.id
									INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
								WHERE t.c.value('../adicao[1]', 'int') IS NULL
								UNION ALL
								SELECT dad.EXA_LINH AS adicao, dad.DOC_CODI, t.c.value('nome[1]', 'varchar(200)') AS nomeFicheiro, t.c.value('base64[1]', 'varchar(MAX)') AS base64Ficheiro
								FROM @XMLInfoExtra.nodes('documentosAEnviar/documento/ficheiro') AS t(c)
									INNER JOIN PRO_EXDA AS dad WITH(NOLOCK) ON t.c.value('../id[1]', 'bigint') = dad.EXD_CHVE
								WHERE t.c.value('../adicao[1]', 'int') IS NOT NULL) AS t
							FOR XML PATH('documento'), TYPE)
						FOR XML PATH('entregarDocumentosInput'), TYPE)
					HAVING @TipoMensagem = 'PTE46C' -- "Entrega de Documentos"
					FOR XML PATH('web:entregarDocumentos'), TYPE)
				FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)				
-- obtem o resultado "OK"/"NOK" retornados do WS
		IF @TipoMensagem IN ('PT511C', 'PT513C', 'PT514C', 'PT515C', 'PT583C', 'PTE85C') -- "Notificação de Apresentação das Mercadorias" OU "Alteração da declaração" OU "Anulação da declaração" OU "Criação da declaração" OU "Resposta ao Pedido de Informação sobre Exportação s/ Saída" OU "Comunicação de Saída (Remessas Postais)"
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://pt.atos.expcau.ws' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:processaMensagemResponse/return/resultadoProcessamento') AS t(c)		
		END
		ELSE		
		IF @TipoMensagem = 'PTE46C' -- Entrega de Documentos
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://pt.atos.expcau.ws' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:entregarDocumentosResponse/return/resultadoProcessamento') AS t(c)
		END
-- se resultado não for de sucesso, manda erro
		IF @FaultCode <> '0'
			RAISERROR('A submissão da mensagem gerou o erro "%s".', 16, 4, @FaultMessage)		
-- atualiza declaração p/ alteração do status e utilizador/data
		UPDATE PRO_EXML SET 
			EXM_STAT = (CASE @TipoMensagem WHEN 'PT514C' THEN 3 ELSE 1 END), 			
			EXM_EMMA = (CASE @TipoMensagem WHEN 'PT511C' THEN 1 ELSE EXM_EMMA END), 
			EXM_DTLM = (CASE @TipoMensagem WHEN 'PT583C' THEN NULL ELSE EXM_DTLM END), 
			EXM_DENV = @DataAtual, 
			EXM_UENV = @CodUtilizador, 
			EXM_UALT = @CodUtilizador, 
			EXM_DTAL = @DataAtual 
		WHERE EXM_IDTY = @Id
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH	
-- insere no detalhe de mensagens os dados da submissão da declaração
	IF (@MensagemXML IS NOT NULL) AND (@ResponseXML IS NOT NULL)
	BEGIN
		INSERT INTO tb_EXP_DeclaracoesMensagens(id_declaracaoEXP, fluxo, mensagem, id_utilizadorMensagem, dataMensagem, pedido, resposta, sucesso, estadoOperacao, 
			id_utilizadorControlo, dataControlo, nomeFicheiro, ficheiro)
		VALUES(@Id, 1, @TipoMensagem, @IdUtilizador, @DataAtual, @MensagemXML, @ResponseXML, (CASE @NumErro WHEN 1 THEN 0 ELSE 1 END), @EstadoOperacaoDeclaracao, 
			@IdUtilizador, @DataAtual, (@TipoMensagem + '-' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(25), @DataAtual, 121), '-', ''), ':', ''), ' ', ''), '.', '') + '.xml'), CAST(@MensagemXML AS varbinary(MAX)))	
	END
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_MensagensSubmetePedido] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_MensagensSubmetePedido] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_ProcessaEnvioEmailArquivosResposta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_ProcessaEnvioEmailArquivosResposta] @AnoDeclaracao int, @CodDeclaracao int, @CodDeclaranteOperador varchar(6), @NomeMensagem varchar(50), 
	@NomeFicheiro varchar(200), @FicheiroBinario varbinary(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @IdDeclaracao bigint, @EmailDeclarante varchar(100), @EmailCliente varchar(250), @EmailCliente2 varchar(250), @Assunto varchar(250), 
		@Texto varchar(MAX)
-- inicia processo de envio de email de notificação de controlo para spool
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os dados para envio na declaração
		SELECT @IdDeclaracao = exm.EXM_IDTY, @EmailDeclarante = dcl.DEC_EMAI, @Assunto = per.DER_EASS, @Texto = per.DER_ETXT, @EmailCliente = cli.CLI_EMAI, @EmailCliente2 = cli.CLI_EMA2
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
			INNER JOIN TAB_PDER AS per WITH(NOLOCK) ON per.DER_MENS = @NomeMensagem AND per.DER_ACTI = 1
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON exm.CLI_COD2 = cli.CLI_CODI
		WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CODI = @CodDeclaracao AND exm.DEC_CODI = @CodDeclaranteOperador AND ISNULL(dcl.DEC_EMAI, '') <> '' AND ISNULL(cli.CLI_EMAI, '') <> ''
-- se configurações todas ativas, insere os dados do email do ficheiro da resposta no spool para o email configurado
		IF (ISNULL(@EmailDeclarante, '') <> '') AND (ISNULL(@Assunto, '') <> '') AND (ISNULL(@EmailCliente, '') <> '') 
		BEGIN
-- descodifica assunto e texto do email
			EXEC sp_APL_DescodificaTexto @IdDeclaracao, 'PRO_EXML', 'EXM_IDTY', @Assunto OUTPUT
			EXEC sp_APL_DescodificaTexto @IdDeclaracao, 'PRO_EXML', 'EXM_IDTY', @Texto OUTPUT
-- insere pedido de envio de email no spool
			INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_IMPR, IMF_STAT, IMF_DTST, IMF_FBIN, IMF_TIPO, IMF_FROM, IMF_PARA, IMF_ASSU, IMF_TEXT, IMF_NFIC, IMF_CCOP)
			VALUES(@DataAtual, 'SMTP', 0, @DataAtual, @FicheiroBinario, 1, @EmailDeclarante, @EmailCliente, @Assunto, @Texto, @NomeFicheiro, @EmailCliente2)
		END
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_ProcessaEnvioEmailArquivosResposta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_ProcessaEnvioEmailArquivosResposta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo] @Id int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @EstadoOperacao varchar(3), @EmailDeclarante varchar(50), @Assunto varchar(250), @Texto varchar(MAX)
-- inicia processo de envio de email de notificação de controlo para spool
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os dados para envio na declaração
		SELECT @EstadoOperacao = exm.EXM_ESTO, @EmailDeclarante = dcl.DEC_EMAI, 
			@Assunto = 'Aviso de ' + dbo.fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao(exm.EXM_ESTO), 
			@Texto = 'Dados da declaração EXP-SAE:' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) +
			         '		.Declaração N.º....: ' + CAST(exm.EXM_NRII AS varchar(10)) + CHAR(13) + CHAR(10) +
					 '		.NRL.....................: ' + exm.EXM_NRLO + CHAR(13) + CHAR(10) +
					 '		.NRM....................: ' + ISNULL(exm.EXM_NDGA, '') + CHAR(13) + CHAR(10) +
					 '		.Cliente.................: ' + ISNULL(exm.CLI_NOM2, '') + CHAR(13) + CHAR(10) +
					 '		.Doc. Transporte...: ' + ISNULL(exm.EXM_CPRT, '') + CHAR(13) + CHAR(10) +
					 '		.Tipo de Controlo..: ' + dbo.fn_EXP_Declaracoes_ObtemDescricaoEstadoOperacao(exm.EXM_ESTO) + CHAR(13) + CHAR(10) 
		FROM PRO_EXML AS exm WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
		WHERE exm.EXM_IDTY = @Id
-- insere os dados do email de notificação de controlo no spool para os emails configurados
		INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_IMPR, IMF_STAT, IMF_DTST, IMF_TIPO, IMF_FROM, IMF_PARA, IMF_ASSU, IMF_TEXT)
		SELECT @DataAtual, 'SMTP', 0, @DataAtual, 1, @EmailDeclarante, DCA_EMAI, @Assunto, @Texto
		FROM TAB_PDCA WITH(NOLOCK)
		WHERE (@EstadoOperacao = 'CAP' AND DCA_ECAE = 1) OR (@EstadoOperacao = 'CA' AND DCA_ECFE = 1) OR (@EstadoOperacao = 'PDA' AND DCA_ECDE = 1) 
			OR (@EstadoOperacao = 'LED' AND (DCA_ECDE = 1 OR DCA_ECFE = 1 OR DCA_ECAE = 1))		
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_EXP_Declaracoes_ProcessaMensagensSubmissaoAutomatica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_EXP_Declaracoes_ProcessaMensagensSubmissaoAutomatica] @Tipo tinyint, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE	@NumErro int, @TipoMsgXML varchar(8), @IdDeclaracao bigint, @NumeroDeclaracao int, @Erro varchar(MAX)
-- inicia variáveis
	SET @Erros = ''
-- obtem declarações EXP-CAU em situação de submissão ao webservice ou em situação de comunicação de saída (remessas postais)
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT 'PT515C', EXM_IDTY, EXM_NRII
		FROM vw_EXP_Declaracoes_WSPendentesSubmissao	
		WHERE @Tipo = 0 
		UNION 
		SELECT 'PTE85C', dex.EXM_IDTY, dex.EXM_NRII
		FROM PRO_EXML AS dex WITH(NOLOCK) 
			INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dex.NDE_CODI = nat.NDE_CODI		
			INNER JOIN TAB_PDES AS pde WITH(NOLOCK)	ON 1 = 1	
		WHERE @Tipo = 1 AND dex.EXM_CNTX = 1 AND dex.EXM_STAT = 2 AND ISNULL(dex.EXM_ESTO, '') NOT IN ('RE', 'CAP', 'CA', 'LED', 'PDA') AND ISNULL(dex.EXM_TAD5, 0) > 0 
			AND ISNULL(dex.EXM_TVL6, 0) > 0 AND dex.EXM_ASAI = 1 AND dex.EXM_DTCS IS NULL AND dex.EXM_PIUP = 1 AND dex.EXM_DPUP IS NOT NULL AND nat.NDE_FEDI = 1 		
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @TipoMsgXML, @IdDeclaracao, @NumeroDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		SET @Erro = NULL
-- processa a submissão da mensagem XML da declaração EXP-CAU
		EXEC @NumErro = sp_EXP_Declaracoes_MensagensSubmetePedido @TipoMsgXML, @IdDeclaracao, NULL, NULL, NULL, NULL, NULL, NULL, @IdUtilizador, @Erro OUTPUT
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A submissão da mensagem "' + @TipoMsgXML + '" da declaração EXP-CAU N.º ' + CAST(@NumeroDeclaracao AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Declaracoes INTO @TipoMsgXML, @IdDeclaracao, @NumeroDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
-- devolve resultado (0: Sucesso; 1: Erro)
	IF @Erros = ''
		RETURN 0
	ELSE
		RETURN 1
END

ALTER AUTHORIZATION ON [sp_EXP_Declaracoes_ProcessaMensagensSubmissaoAutomatica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_EXP_Declaracoes_ProcessaMensagensSubmissaoAutomatica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_AdicoesGeraDeLinhasOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_AdicoesGeraDeLinhasOGMA] @Ano int, @Codigo int, @CodDeclarante varchar(6), @ParteResto bit, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @DocumentoXML xml(XMLSC_DeclaracoesExpToGIDWin)
	DECLARE @TblTmpLinhas TABLE(
		LIN_IDEN int NOT NULL IDENTITY(1, 1), 
		APA_CODI varchar(22) NOT NULL,
		APA_DESG varchar(150) NOT NULL, 
		PAI_CODI varchar(2) NULL,
		LIN_MBRT decimal(28, 6) NOT NULL,
		LIN_MLIQ decimal(28, 6) NOT NULL,
		LIN_REGI varchar(4) NOT NULL,
		LIN_QUNI decimal(28, 6) NOT NULL,
		LIN_MONT decimal(28, 6) NOT NULL,
		UME_CODI varchar(2) NOT NULL,
		LIN_VOLS decimal(28, 6) NOT NULL)
	DECLARE @TblTmpPrecedentes TABLE(
		PRE_IDEN int NOT NULL IDENTITY(1, 1),	
		LIN_IDEN int NOT NULL, 
		PRE_NDOC varchar(20) NOT NULL,
		PRE_DDOC datetime NOT NULL)
	DECLARE @TblTmpRegimes TABLE(
		REG_IDEN int NOT NULL IDENTITY(1, 1),	
		LIN_IDEN int NOT NULL,
		REG_NPRE varchar(20) NOT NULL,
		REG_ADIC int NOT NULL,  
		REG_PPAU varchar(22) NOT NULL,
		REG_QTDE decimal(28, 6) NOT NULL)
	DECLARE @IdLinha bigint, @TotalPrecedentes int, @NumPrecedentesIguais int, @CodArtigo varchar(22), @DesignacaoArtigo varchar(150), @CodPaisOrigem varchar(2), 
		@MassaBrt decimal(28, 6), @MassaLiq decimal(28, 6), @Regime varchar(4), @QtdUnidades decimal(28, 6), @Montante decimal(28, 6), @CodUnidMedida varchar(2), 
		@Volumes decimal(28, 6), @NumeroDocPrecedente varchar(20), @DataDocPrecedente datetime, @AdicaoPrecedente int, @CodPautalPrecedente varchar(22), 
		@QtdPrecedente decimal(28, 6), @NumAdicao int, @TotalAdicoes int, @IdRegimePrec int
-- inicia processo para geração de adições a partir de linhas OGMA
	BEGIN TRY	
		SET @NumErro = 0
		SET @TotalAdicoes = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem as linhas OGMA da declaração já associadas a artigo pautal para globalização
		DECLARE Linhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT apa.APA_CODI, apa.APA_DESG, pai.PAI_CODI, lin.massaBruta, lin.massaLiquida, lin.observacoes, lin.unidades, lin.montante, ume.UME_CODI, lin.volumes, 
				lin.numeroOrdem, lin.dataOrdem, lin.numeroAdPrec, lin.codigoPautalPrec, lin.quantidade
			FROM PRO_EXML AS exm WITH(NOLOCK)
				INNER JOIN tb_TBL_LinhasOGMA AS lin WITH(NOLOCK) ON exm.EXM_IDTY = lin.id_declaracaoEXP
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON lin.id_artigo = apa.APA_IDTY
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON lin.id_paisOrigem = pai.PAI_IDTY
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON lin.id_unidadeMedida = ume.UME_IDTY
			WHERE exm.EXM_EANO = @Ano AND exm.EXM_CODI = @Codigo AND exm.DEC_CODI = @CodDeclarante AND lin.id_artigo IS NOT NULL
			ORDER BY apa.APA_CODI, pai.PAI_CODI, lin.observacoes, ume.UME_CODI
		OPEN Linhas
		FETCH NEXT FROM Linhas INTO @CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, @Volumes, 
			@NumeroDocPrecedente, @DataDocPrecedente, @AdicaoPrecedente, @CodPautalPrecedente, @QtdPrecedente
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @IdLinha = NULL
			SET @TotalPrecedentes = 0
			SET @NumPrecedentesIguais = 0
			SET @IdRegimePrec = NULL
-- obtem dados referente ao artigo/pais origem/regime/unidade medida para globalização
			SELECT @IdLinha = MAX(lin.LIN_IDEN), @TotalPrecedentes = COUNT(*), @NumPrecedentesIguais = COUNT((CASE WHEN (pre.PRE_NDOC = @NumeroDocPrecedente) AND (pre.PRE_DDOC = @DataDocPrecedente) THEN 1 ELSE NULL END))
			FROM @TblTmpLinhas AS lin
				LEFT OUTER JOIN @TblTmpPrecedentes AS pre ON lin.LIN_IDEN = pre.LIN_IDEN
			WHERE APA_CODI = @CodArtigo AND PAI_CODI = @CodPaisOrigem AND LIN_REGI = @Regime AND UME_CODI = @CodUnidMedida
			GROUP BY lin.LIN_IDEN		
-- se artigo/pais origem/regime/unidade medida ainda não existe ou já existe mas já tem 99 precedentes associados, insere nova linha
			IF (@IdLinha IS NULL) OR ((@TotalPrecedentes = 99) AND (@NumPrecedentesIguais = 0))
			BEGIN		
				INSERT INTO @TblTmpLinhas(APA_CODI, APA_DESG, PAI_CODI, LIN_MBRT, LIN_MLIQ, LIN_REGI, LIN_QUNI, LIN_MONT, UME_CODI, LIN_VOLS)		
				VALUES(@CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, @Volumes)	
				SET @IdLinha = SCOPE_IDENTITY()
			END
			ELSE
			BEGIN
				UPDATE @TblTmpLinhas SET 
					LIN_MBRT = LIN_MBRT + @MassaBrt, 
					LIN_MLIQ = LIN_MLIQ + @MassaLiq, 
					LIN_QUNI = LIN_QUNI + @QtdUnidades, 
					LIN_MONT = LIN_MONT + @Montante, 
					LIN_VOLS = LIN_VOLS + @Volumes
				WHERE LIN_IDEN = @IdLinha
			END	
-- insere precedente se este ainda não existe na linha
			IF NOT EXISTS(SELECT PRE_IDEN FROM @TblTmpPrecedentes WHERE LIN_IDEN = @IdLinha AND PRE_NDOC = @NumeroDocPrecedente AND PRE_DDOC = @DataDocPrecedente)
			BEGIN
				INSERT @TblTmpPrecedentes(LIN_IDEN, PRE_NDOC, PRE_DDOC)
				VALUES(@IdLinha, @NumeroDocPrecedente, @DataDocPrecedente)
			END
-- obtem dados do regime precedente na linha
			SELECT @IdRegimePrec = REG_IDEN 
			FROM @TblTmpRegimes 
			WHERE LIN_IDEN = @IdLinha AND REG_NPRE = @NumeroDocPrecedente AND REG_ADIC = @AdicaoPrecedente AND REG_PPAU = @CodPautalPrecedente
-- insere regime se este ainda não existe na linha
			IF @IdRegimePrec IS NULL
			BEGIN
				INSERT @TblTmpRegimes(LIN_IDEN, REG_NPRE, REG_ADIC, REG_PPAU, REG_QTDE)
				VALUES(@IdLinha, @NumeroDocPrecedente, @AdicaoPrecedente, @CodPautalPrecedente, @QtdPrecedente)
			END
			ELSE
			BEGIN
				UPDATE @TblTmpRegimes SET 
					REG_QTDE = REG_QTDE + @QtdPrecedente
				WHERE REG_IDEN = @IdRegimePrec
			END
			FETCH NEXT FROM Linhas INTO @CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, @Volumes, 
				@NumeroDocPrecedente, @DataDocPrecedente, @AdicaoPrecedente, @CodPautalPrecedente, @QtdPrecedente
		END
		CLOSE Linhas
		DEALLOCATE Linhas
-- obtem o total de adições apuradas
		SELECT @TotalAdicoes = COUNT(*)
		FROM @TblTmpLinhas
-- constroi XML para edição da declaração Exportação/XML com adições sendo as linhas OGMA
		SELECT @DocumentoXML = 
			(SELECT
				(SELECT 'U' AS "@Acao", 
					exm.EXM_TPRO AS "TipoProcedimento",
					exm.NDE_CODI AS "CodNatureza", 
					exm.DEC_CODI AS "CodOperador", 
					(CONVERT(varchar(10), exm.EXM_DATA, 127) + 'Z') AS "Data",					
					exm.EAD_CODA AS "CodEstanciaA", 
					exm.TDE_COD1 AS "CodTipoDeclaracao", 									
					(SELECT 					
						NULLIF(exm.CLI_NOM2, '') AS "Nome",
						NULLIF(exm.CLI_MOR2, '') AS "Morada"
					FOR XML PATH('Expedidor'), TYPE),					
					(SELECT 						
						NULLIF(exm.FOR_NOM8, '') AS "Nome",
						NULLIF(exm.FOR_MOR8, '') AS "Morada"
					FOR XML PATH('Destinatario'), TYPE), 						
					exm.EAD_CO29 AS "CodEstanciaTAC", 					
					exm.PAI_CO22 AS "CodPais", 
					CAST(exm.EXM_TFRT as numeric(28, 6)) AS "TotalFrete", 
					CAST(exm.EXM_TSEG as numeric(28, 6)) AS "TotalSeguro", 		
					(SELECT 
						(SELECT 
							'EXM_CODI' AS "CodigoCampoExtra", 
							exm.EXM_CODI AS "ValorCampoExtra"
						FOR XML PATH('CampoExtra'), TYPE)
					FOR XML PATH('CamposExtra'), TYPE), 											
					(SELECT 
						adi.LIN_NUME AS "NumeroAdicao", 
						adi.APA_CODI AS "CodArtigo", 
						adi.APA_DESG AS "DesignacaoArtigo", 
						adi.PAI_CODI AS "CodPaisOrigem", 
						CAST(adi.LIN_MBRT AS numeric(28, 6)) AS "MassaBruta", 
						CAST(adi.LIN_MLIQ AS numeric(28, 6)) AS "MassaLiquida",						
						adi.LIN_REGI AS "Regime", 							
						CAST(adi.LIN_QUNI AS numeric(28, 6)) AS "QtdUnidades", 
						CAST(adi.LIN_MONT AS numeric(28, 6)) AS "ValorAdicao", 
						CAST(0 AS numeric(28, 6)) AS "ValorFrete", 
						CAST(0 AS numeric(28, 6)) AS "ValorSeguro", 							
						(SELECT 									
							'Z' AS "Tipo", 
							doc.DOC_CODI AS "CodDocumento", 						
							pre.PRE_NDOC AS "RefDocumento", 						
							'PT' AS "CodPais", 
							(CONVERT(varchar(10), pre.PRE_DDOC, 127) + 'Z') AS "DataDocumento"
						FROM @TblTmpPrecedentes AS pre
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'IM' AND doc.DOC_EXPT = 1
						WHERE pre.LIN_IDEN = adi.LIN_IDEN
						FOR XML PATH('DocPrecedente'), ROOT('DocsPrecedentes'), TYPE), 														
						(SELECT 
							rpr.REG_NPRE AS "NumeroDocPrecedente", 
							rpr.REG_ADIC AS "AdicaoDocPrecedente", 
							rpr.REG_PPAU AS "CodArtigoPautal", 
							CAST(rpr.REG_QTDE AS numeric(28, 6)) AS "Quantidade", 
							ume.UME_CODI AS "CodUnidMedida"
						FROM @TblTmpRegimes AS rpr 
							INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON ume.UME_CODI = 'NAR' AND ume.UME_EXPT = 1
						WHERE rpr.LIN_IDEN = adi.LIN_IDEN
						FOR XML PATH('RegimeEconomico'), ROOT('RegimesEconomicos'), TYPE), 														
						(SELECT 
							doc.DOC_CODI AS "CodDocumento",
							NULLIF(t.CLD_NDOC, '') AS "NumeroReferencia", 
							(CONVERT(varchar(10), t.CLD_DDOC, 127) + 'Z') AS "DataEmissao"
						FROM TAB_DOCU AS doc WITH(NOLOCK) 
							INNER JOIN (SELECT DOC_CODI, CLD_NDOC, CLD_DDOC
										FROM TAB_CLDO WITH(NOLOCK) 
										WHERE CLD_UEXP = 1 AND CLI_CODI = exm.CLI_COD2 AND adi.LIN_NUME = 1
										UNION ALL
										SELECT DOC_CODI, NULLIF(exm.EXM_REF1, ''), NULL
										FROM TAB_DOCU WITH(NOLOCK) 
										WHERE DOC_EXPT = 1 AND DOC_CODI = 'N325' AND adi.LIN_NUME = 1
										UNION ALL
										SELECT DOC_CODI, NULLIF(exm.EXM_CPRT, ''), NULL
										FROM TAB_DOCU WITH(NOLOCK) 
										WHERE DOC_EXPT = 1 AND DOC_CODI = 'N740' AND adi.LIN_NUME = 1
										UNION ALL
										SELECT doc.DOC_CODI, (CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END), (CASE doc.DOC_TDDT WHEN 1 THEN exm.EXM_DATA ELSE NULL END)
										FROM TAB_APAU AS apa WITH(NOLOCK) 
											INNER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON apa.APA_CHVE = ado.APA_CHVE
											INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.DOC_CODI = doc.DOC_CODI
										WHERE ado.ADC_UEXP = 1 AND apa.APA_CODI = adi.APA_CODI
										UNION ALL
										SELECT DOC_CODI, 'Conforme lista anexa', @DataAtual
										FROM TAB_DOCU WITH(NOLOCK) 
										WHERE DOC_EXPT = 1 AND DOC_CODI = 'N960'
										UNION ALL
										SELECT doc.DOC_CODI, (CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END), (CASE doc.DOC_TDDT WHEN 1 THEN exm.EXM_DATA ELSE NULL END)
										FROM TAB_APAU AS apa WITH(NOLOCK) 													
											INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'Y901'
										WHERE apa.APA_DPUT = 1 AND apa.APA_CODI = adi.APA_CODI
									) AS t ON doc.DOC_CODI = t.DOC_CODI
						WHERE doc.DOC_EXPT = 1
						FOR XML PATH('Documento'), ROOT('Documentos'), TYPE), 							
						(SELECT 
							men.INF_CODI AS "CodMencao"
						FROM TAB_INFC AS men WITH(NOLOCK)
							INNER JOIN (SELECT INF_CODI
										FROM TAB_INFC WITH(NOLOCK)
										WHERE INF_EXPT = 1 AND INF_CODI = 'CCE' AND adi.LIN_NUME = 1 AND ISNULL(exm.EXM_Q30C, 0) > 0
										UNION ALL
										SELECT INF_CODI
										FROM TAB_INFC WITH(NOLOCK)
										WHERE INF_EXPT = 1 AND INF_CODI = 'CC' AND adi.LIN_NUME = 1 AND ISNULL(exm.EXM_Q30C, 0) = 0 AND ISNULL(exm.EXM_MR30, '') <> ''
										UNION ALL
										SELECT INF_CODI
										FROM TAB_INFC WITH(NOLOCK)
										WHERE INF_EXPT = 1 AND INF_CODI = '30400' AND adi.LIN_NUME = 1 AND ISNULL(exm.EAD_CO29, '') <> 'PT' AND exm.EAD_CODA <> ISNULL(exm.EAD_CO29, '') AND ISNULL(exm.EAD_C29A, '') = ''
										UNION ALL
										SELECT INF_CODI
										FROM TAB_INFC WITH(NOLOCK)
										WHERE INF_EXPT = 1 AND INF_CODI = 'PROC' AND adi.LIN_NUME = 1 AND ISNULL(exm.EXM_TP14, 0) = 2
										UNION ALL
										SELECT INF_CODI
										FROM TAB_INFC WITH(NOLOCK)
										WHERE INF_EXPT = 1 AND INF_CODI = 'EORI' AND adi.LIN_NUME = 1
										UNION ALL
										SELECT men.INF_CODI
										FROM TAB_APAU AS apa WITH(NOLOCK) 
											INNER JOIN TAB_AMEN AS ame WITH(NOLOCK) ON apa.APA_CHVE = ame.APA_CHVE
											INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON ame.INF_CODI = men.INF_CODI
										WHERE ame.AME_UEXP = 1 AND apa.APA_CODI = adi.APA_CODI
							) AS t ON men.INF_CODI = t.INF_CODI
						WHERE men.INF_EXPT = 1
						FOR XML PATH('MencaoEspecial'), ROOT('MencoesEspeciais'), TYPE), 																																																											
						(SELECT 									
							tem.TEM_CODI AS "CodNaturezaVols", 
							CAST(adi.LIN_VOLS AS numeric(28, 6)) AS "NumeroVols", 						
							(CASE WHEN (@ParteResto = 1) AND (adi.LIN_NUME <> @TotalAdicoes) THEN 1 ELSE 0 END) AS "P", 						
							(CASE WHEN (@ParteResto = 1) AND (adi.LIN_NUME = @TotalAdicoes) THEN 1 ELSE 0 END) AS "R"									
						FROM TAB_TEMB AS tem WITH(NOLOCK)
						WHERE tem.TEM_CODI = adi.UME_CODI AND tem.TEM_EXPT = 1	
						FOR XML PATH('MarcaEVolume'), ROOT('MarcasEVolumes'), TYPE)							
					FROM (SELECT ROW_NUMBER() OVER(ORDER BY LIN_IDEN) AS LIN_NUME, LIN_IDEN, APA_CODI, APA_DESG, PAI_CODI, LIN_MBRT, LIN_MLIQ, LIN_REGI, LIN_QUNI, LIN_MONT, LIN_VOLS, UME_CODI
						FROM @TblTmpLinhas) AS adi
					FOR XML PATH('Adicao'), ROOT('Adicoes'), TYPE)					
				FROM PRO_EXML AS exm WITH(NOLOCK) 
				WHERE EXM_EANO = @Ano AND EXM_CODI = @Codigo AND DEC_CODI = @CodDeclarante									
				FOR XML PATH('Declaracao'), TYPE)
			FOR XML PATH('DeclaracoesExpToGIDWin'), ELEMENTS)
-- processa a atualização da declaração para inserir as adições apuradas
		EXEC @NumErro = SP_ExportacaoXML_GeraDeclaracoesDeXML @DocumentoXML, @CodUtilizador, @Erro OUTPUT
		IF @NumErro > 0
			RAISERROR ('Erro na inserção de adições na declaração: %s', 16, 1, @Erro)		
-- inicia o número da adição em todas as linhas OGMA
		UPDATE tb_TBL_LinhasOGMA SET numeroAdicao = NULL
		FROM tb_TBL_LinhasOGMA AS lin WITH(NOLOCK)
			INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON lin.id_declaracaoEXP = exm.EXM_IDTY
		WHERE exm.EXM_EANO = @Ano AND exm.EXM_CODI = @Codigo AND exm.DEC_CODI = @CodDeclarante AND lin.numeroAdicao IS NOT NULL
-- atribui a todas as linhas OGMA o respetivo número de adição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT exa.EXA_LINH, lin.id
			FROM PRO_EXML AS exm WITH(NOLOCK)
				INNER JOIN PRO_EXAD AS exa WITH(NOLOCK) ON exm.EXM_EANO = exa.EXM_EANO AND exm.EXM_CODI = exa.EXM_CODI AND exm.DEC_CODI = exa.EXM_COPE
				INNER JOIN PRO_EXDS AS adp WITH(NOLOCK) ON exa.EXA_CHVE = adp.EXA_CHVE
				INNER JOIN PRO_EXMV AS amv WITH(NOLOCK) ON exa.EXA_CHVE = amv.EXA_CHVE
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON exa.APA_CO33 = apa.APA_CODI
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON exa.PAI_CODI = pai.PAI_CODI
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON amv.TEM_CODI = ume.UME_CODI
				INNER JOIN tb_TBL_LinhasOGMA AS lin WITH(NOLOCK) ON exm.EXM_IDTY = lin.id_declaracaoEXP AND apa.APA_IDTY = lin.id_artigo AND pai.PAI_IDTY = lin.id_paisOrigem AND exa.TDE_REGI = lin.observacoes AND ume.UME_IDTY = lin.id_unidadeMedida AND adp.EXD_DESC = lin.numeroOrdem				
			WHERE exm.EXM_EANO = @Ano AND exm.EXM_CODI = @Codigo AND exm.DEC_CODI = @CodDeclarante			
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdLinha
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			UPDATE tb_TBL_LinhasOGMA SET numeroAdicao = @NumAdicao
			WHERE id = @IdLinha
			FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdLinha
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes					
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_AdicoesGeraDeLinhasOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_AdicoesGeraDeLinhasOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_AnexaDocumentoTipoINVouAWB]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_AnexaDocumentoTipoINVouAWB] @PathFicheiroAnexar varchar(500), @NomeFicheiroAnexar varchar(100), @TipoFicheiroAnexar varchar(8), 
	@DirDestinoDocsExportacao varchar(250), @AnoDecXML int, @CodDecXML int, @CodOperadorDecXML varchar(6), @NumRefLocalDecXML varchar(22), @CodFollowUpDecXML int, 
	@CtxDecXML tinyint, @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @CamposAdicionais int, @TipoFicheiro varchar(8), @DescricaoFicheiro varchar(150), @ExtFicheiro varchar(10), @PathDestinoDocExportacao varchar(500), 
		@IDDocAnexo int, @PathDocAnexo varchar(500), @Erros varchar(MAX), @FicheiroImprSerie bit, @FicheiroBinario varbinary(MAX), @SQLAExecutar nvarchar(4000), 
		@SQLVariaveis nvarchar(1000), @CIAStationID varchar(3), @DataAtual datetime
-- obtem dados dos Parametros Despachos
	SELECT TOP 1 @CamposAdicionais = PDE_CADI
	FROM TAB_PDES WITH(NOLOCK)
-- obtem o tipo de ficheiro e respetiva descrição
	IF @TipoFicheiroAnexar = 'INV' 
	BEGIN
		SET @TipoFicheiro = 'FATURA' 
		SET @DescricaoFicheiro = 'Fatura'
	END
	ELSE
		IF @TipoFicheiroAnexar = 'AWB'
		BEGIN 
			SET @TipoFicheiro = 'DOCTRANS' 
			SET @DescricaoFicheiro = 'Carta de Porte'
		END
		ELSE 
		BEGIN
			SET @TipoFicheiro = NULL 
			SET @DescricaoFicheiro = '.'
		END
-- processa calculos específicos relacionados com contexto EXP-CAU ou EXP/XML
	IF @CtxDecXML = 1
	BEGIN
		SET @PathDestinoDocExportacao = NULL
		IF ISNULL(@TipoFicheiro, '') = ''
		BEGIN
			SET @TipoFicheiro = 'OUTRO'
			SET @FicheiroImprSerie = 0
		END
		ELSE
			SET @FicheiroImprSerie = 1	
-- obtem o ficheiro em binario
		SET @FicheiroBinario = NULL
		SET @SQLVariaveis = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'	
		SET @SQLAExecutar = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiroAnexar + ''', SINGLE_BLOB) AS t)'				
		EXECUTE sp_executesql @SQLAExecutar, @SQLVariaveis, @OUTFicheiroBinario = @FicheiroBinario OUTPUT		
	END
	ELSE
	BEGIN
		SET @FicheiroImprSerie = 0
		SET @FicheiroBinario = NULL
-- obtem extensão do ficheiro a anexar
		SET @ExtFicheiro = REVERSE(SUBSTRING(REVERSE(@NomeFicheiroAnexar), 1, CHARINDEX('.', REVERSE(@NomeFicheiroAnexar))))
-- constroi path completa diretoria dos anexos da declaração de Exportação/XML
		SET @PathDestinoDocExportacao = @DirDestinoDocsExportacao + CAST(@AnoDecXML as varchar(4)) + '\' + @CodOperadorDecXML + '\DEC' + @NumRefLocalDecXML + '\'
-- processa a criação diretoria dos anexos da declaração de Exportação/XML
		EXEC GIDWIN.dbo.SP_Externo_CriaDiretoria @PathDestinoDocExportacao, @Erros OUTPUT
		IF ISNULL(@Erros, '') <> ''
		BEGIN
			RAISERROR ('Não foi possível criar a diretoria "%s"! ERRO: "%s".', 16, 1, @PathDestinoDocExportacao, @Erros)
			RETURN
		END
-- constroi path completa c/ novo nome p/ ficheiro a anexar
		SET @PathDestinoDocExportacao = @PathDestinoDocExportacao + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(50), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121), '-', ''), ':', ''), '.', ''), ' ', '') + (REPLICATE('0', 8 - LEN(CAST(@CodDecXML as varchar(8)))) + CAST(@CodDecXML as varchar(8))) + @ExtFicheiro
-- processa o mover do ficheiro a anexar
		EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiroAnexar, @PathDestinoDocExportacao, @Erros OUTPUT
		IF ISNULL(@Erros, '') <> ''
		BEGIN
			RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 2, @PathFicheiroAnexar, @Erros)	
			RETURN
		END
	END
-- obter CIA Station para determinar se documento é ou não PLT
	SET @CIAStationID = LEFT(RIGHT(@PathFicheiroAnexar, 23), 3) -- As CIA Sations têm códigos numéricos. Os documentos PLT têm como código de station um valor alfanumérico.		
-- verifica se ficheiro .TIF já está anexado na declaração de Exportação/XML
	SELECT TOP 1 @IDDocAnexo = EXF_IDEN, @PathDocAnexo = EXF_LINK 
	FROM PRO_EXFI WITH(NOLOCK)
	WHERE EXM_EANO = @AnoDecXML AND EXM_CODI = @CodDecXML AND DEC_CODI = @CodOperadorDecXML AND EXF_TMSG = @TipoFicheiro
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- se não existe ficheiro anexado ou o CIA Station é alfanumerico ou tem o valor "777", insere
	IF (@IDDocAnexo IS NULL) OR (ISNUMERIC(@CIAStationID) = 0) OR (@CIAStationID = '777')
	BEGIN							
-- procede à inserção do ficheiro .TIF no detalhe de Documentos da declaração de Exportação/XML
		INSERT INTO PRO_EXFI(EXM_EANO, EXM_CODI, DEC_CODI, EXF_DESC, EXF_LINK, EXF_DATA, EXF_UTIL, EXF_NOMF, EXF_ISER, EXF_TMSG, EXF_FICH)
		VALUES(@AnoDecXML, @CodDecXML, @CodOperadorDecXML, @DescricaoFicheiro, @PathDestinoDocExportacao, @DataAtual, @Utilizador, @NomeFicheiroAnexar, @FicheiroImprSerie, @TipoFicheiro, @FicheiroBinario)		
-- se campos adicionais dos Par. Despachos for "DHL", atualiza campo "HV/LV" e "Follow-Up" caso o follow-up não for "Em Processamento (Adm)" ou "Em Processamento (Tec)"
		IF @CamposAdicionais = 3 --DHL		
		BEGIN
			UPDATE PRO_EXML SET EXM_HVLV = (CASE WHEN (ISNUMERIC(@CIAStationID) = 0) OR (@CIAStationID = '777') THEN 'PLT' ELSE 'HV' END), 
				FUP_CODI = (CASE WHEN @CodFollowUpDecXML NOT IN (12, 13) /*"Em Processamento (Adm)", "Em Processamento (Tec)"*/ THEN 
					(CASE WHEN (ISNULL(EXM_TMBR, 0) > 100) OR (ISNULL(EXM_TVL6, 0) > 2) THEN 16 /*"Por Despachar URGENTE"*/ ELSE 10 /*"Despachar"*/ END) 
				ELSE FUP_CODI END),
				EXM_PLET = (CASE WHEN (ISNUMERIC(@CIAStationID) = 0) OR (@CIAStationID = '777') THEN 1 ELSE EXM_PLET END)
			WHERE EXM_EANO = @AnoDecXML AND EXM_CODI = @CodDecXML AND DEC_CODI = @CodOperadorDecXML
		END	
	END
	ELSE
		IF @CodFollowUpDecXML NOT IN (12, 13) /*"Em Processamento (Adm)", "Em Processamento (Tec)"*/
		BEGIN
-- constroi comando DOS para remover o ficheiro anexado, unicamente para Declarações EXP/XML
			IF @CtxDecXML = 0
			BEGIN
				EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathDocAnexo, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
				BEGIN
					RAISERROR ('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 3, @PathDocAnexo, @Erros)						
					RETURN
				END
			END
-- procede à edição do ficheiro .TIF no detalhe de Arquivos da declaração de Exportação/XML
			UPDATE PRO_EXFI SET EXF_LINK = @PathDestinoDocExportacao, 
				EXF_DATA = @DataAtual, 
				EXF_UTIL = @Utilizador, 
				EXF_NOMF = @NomeFicheiroAnexar, 
				EXF_FICH = @FicheiroBinario
			WHERE EXM_EANO = @AnoDecXML AND EXM_CODI = @CodDecXML AND DEC_CODI = @CodOperadorDecXML AND EXF_IDEN = @IDDocAnexo
-- se campos adicionais dos Par. Despachos for "DHL", atualiza campo "Follow-Up"
			IF @CamposAdicionais = 3 --DHL		
			BEGIN
				UPDATE PRO_EXML SET FUP_CODI = 10 /*"Despachar"*/
				WHERE EXM_EANO = @AnoDecXML AND EXM_CODI = @CodDecXML AND DEC_CODI = @CodOperadorDecXML
			END				
		END	
-- remove o ficheiro anexado quando em contexto EXP-CAU								
	IF @CtxDecXML = 1
	BEGIN
		EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroAnexar, @Erros OUTPUT												
		IF ISNULL(@Erros, '') <> ''
		BEGIN
			RAISERROR ('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 4, @PathFicheiroAnexar, @Erros)	
			RETURN
		END
	END
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_AnexaDocumentoTipoINVouAWB] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_AnexaDocumentoTipoINVouAWB] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ExportaFicheiroEX008A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ExportacaoXML_ExportaFicheiroEX008A] @AnoDeclaracao int, @IDDeclaracao int, @CodOperador varchar(6), @Utilizador varchar(30), @FicheiroXML xml OUTPUT, 
	@LinhaXMLEncoding varchar(200) OUTPUT, @NomeFicheiroXML varchar(200) OUTPUT AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @Pacote varchar(3)	
-- atribui linha de encoding para depois ser incluída no ficheiro XML a gerar
	SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="ISO-8859-1" ?>'
-- constroi XML para ficheiro EX008A
	SET @FicheiroXML = 				
		(SELECT '1.0' as "@versao", 0 as "@teste", 
			(SELECT ISNULL(dcl.DEC_XIEM, '') as "identificacao-emissor", 
				'AT' as "identificacao-receptor",
				CONVERT(varchar(19), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) as "data-preparacao",
				'STADAEXP XML' as "referencia-aplicacao"				
			FOR XML PATH('cabecalho'), TYPE),
			(SELECT 
				(SELECT
					(SELECT NULLIF(exm.EXM_NPRO, '') as "numero-referencia-movimento", 
						CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) as "data-apresentacao", 
						ISNULL(dcl.DEC_XIEM, '') as "receptor",
						'1' as "tipo-receptor"
					FOR XML PATH('cabecalho'), TYPE), 
					(SELECT exm.EXM_TP14 as "@tipo", 
						NULLIF(dcl.DEC_CEDU, '') as "numero-identificacao-entidade-hab-despachar", 
						(CASE ISNULL(dcl.DEC_CEDU, '') WHEN '' THEN ('PT' + dcl.DEC_NIF) ELSE NULL END) as "nif-declarante-representante"						
					FOR XML PATH('declarante'), TYPE),
					(SELECT (CASE ISNULL(exm.CLI_PAI2, '') WHEN 'PT' THEN NULL ELSE ISNULL(exm.EXM_TP2A, '') END) as "@tipo", 
						(CASE ISNULL(exm.EXM_TP2A, '') WHEN 'P' THEN ISNULL(exm.EXM_TI2B, '') ELSE NULL END) as "@tipo-identificacao", 
						((CASE ISNULL(exm.EXM_TP2A, '') WHEN 'P' THEN '' ELSE ISNULL(exm.CLI_PAI2, '') END) + exm.CLI_NIF2) as "numero", 
						(CASE WHEN ISNULL(exm.EXM_TP2A, '') in ('C', 'S') and (ISNULL(exm.CLI_PAI2, '') = 'PT') THEN NULL ELSE exm.CLI_NOM2 END) as "nome",
						(CASE WHEN ISNULL(exm.EXM_TP2A, '') in ('C', 'S') and (ISNULL(exm.CLI_PAI2, '') = 'PT') THEN NULL ELSE exm.CLI_MOR2 END) as "morada",
						(CASE WHEN ISNULL(exm.EXM_TP2A, '') in ('C', 'S') and (ISNULL(exm.CLI_PAI2, '') = 'PT') THEN NULL ELSE exm.CLI_CPO2 END) as "cod-postal",
						(CASE WHEN ISNULL(exm.EXM_TP2A, '') in ('C', 'S') and (ISNULL(exm.CLI_PAI2, '') = 'PT') THEN NULL ELSE exm.CLI_LOC2 END) as "localidade", 
						(CASE WHEN ISNULL(exm.EXM_TP2A, '') in ('C', 'S') and (ISNULL(exm.CLI_PAI2, '') = 'PT') THEN NULL ELSE (CASE ISNULL(exm.CLI_PAI2, '') WHEN 'EL' THEN 'GR' ELSE exm.CLI_PAI2 END) END) as "pais"
					FOR XML PATH('exportador'), TYPE),
					exm.EAD_CODA as "estancia"	
				FOR XML PATH('ex008a'), TYPE)
			FOR XML PATH('mensagens'), TYPE)			
		FROM PRO_EXML as exm INNER JOIN TAB_DECL as dcl ON exm.DEC_CODI = dcl.DEC_CODI
		WHERE exm.EXM_EANO = @AnoDeclaracao and exm.EXM_CODI = @IDDeclaracao and exm.DEC_CODI = @CodOperador
		FOR XML PATH('ficheiro'), ELEMENTS)
-- obtem dados de declarante
	SELECT @NomeFicheiroXML = ('e' + dcl.DEC_NIF + '.' + REPLICATE('0', 7 - LEN(CAST(exm.EXM_NRII AS varchar(10)))) + CAST(exm.EXM_NRII AS varchar(10)) + ISNULL(dcl.DEC_XPPE, '000') + '.0000'), @Pacote = ISNULL(dcl.DEC_XPPE, '000')
	FROM PRO_EXML as exm INNER JOIN TAB_DECL as dcl ON exm.DEC_CODI = dcl.DEC_CODI
	WHERE exm.EXM_EANO = @AnoDeclaracao and exm.EXM_CODI = @IDDeclaracao and exm.DEC_CODI = @CodOperador	
-- atualiza declaração de exportação p/ atribuição do pacote de envio e status como "M. Apresentada"
	UPDATE PRO_EXML SET EXM_PENV = @Pacote, EXM_STAT = 6, EXM_UALT = @Utilizador, EXM_DTAL = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), EXM_UENV = @Utilizador, 
		EXM_DENV = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
	WHERE EXM_EANO = @AnoDeclaracao and EXM_CODI = @IDDeclaracao and DEC_CODI = @CodOperador
-- atualiza declarante p/ atribuição de novo pacote de envio
	UPDATE TAB_DECL SET DEC_XPPE = dbo.FNT_Geral_IncrementaPacoteEnvio(@Pacote)
	WHERE DEC_CODI = @CodOperador
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ExportaFicheiroEX008A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ExportaFicheiroEX008A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ExportaFicheiroOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ExportacaoXML_ExportaFicheiroOGMA] @NomeFicheiroXML varchar(100), @Utilizador varchar(30), @FicheiroXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdDeclaracao bigint, @NumAdicao int, @Regime varchar(4), @PathFicheiroXML varchar(500), @ComandoSQL varchar(1500), @FicheiroTXT varchar(MAX)	
	DECLARE @TmpFicheiroOGMA TABLE(
		ID int NOT NULL IDENTITY(1, 1), 	
		EXM_IDTY bigint NOT NULL, 
		EXA_LINH int NOT NULL, 
		TDE_REGI varchar(4) NOT NULL, 
		FICHEIRO xml NOT NULL)
-- inicia processo de geração da declaração	EXP
	BEGIN TRY	
		SET @NumErro = 0		
-- cria tabela temporária p/ conteudo de cada ficheiro
		CREATE TABLE #ConteudoFicheiro(CONTEUDO varchar(MAX) COLLATE Latin1_General_CI_AI)
-- obtem as declarações EXP e respetivos ficheiros XML associados ao nome do ficheiro OGMA recebido
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT exm.EXM_IDTY, exa.EXA_LINH, exa.TDE_REGI, dfm.EXF_LINK				
			FROM  PRO_EXML AS exm WITH(NOLOCK) 			
				INNER JOIN PRO_EXAD AS exa WITH(NOLOCK) ON exm.EXM_EANO = exa.EXM_EANO AND exm.EXM_CODI = exa.EXM_CODI AND exm.DEC_CODI = exa.EXM_COPE
				INNER JOIN PRO_EXFI AS dfm WITH(NOLOCK) ON exm.EXM_EANO = dfm.EXM_EANO AND exm.EXM_CODI = dfm.EXM_CODI AND exm.DEC_CODI = dfm.DEC_CODI AND exm.EXM_FUPS = dfm.EXF_NOMF AND dfm.EXF_ORIG = 2 AND dfm.EXF_ENVI = 0				
			WHERE exm.EXM_FUPS = @NomeFicheiroXML
			ORDER BY exm.EXM_IDTY, exa.EXA_LINH
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumAdicao, @Regime, @PathFicheiroXML
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @FicheiroTXT = NULL			
-- processa a importação dos dados do ficheiro XML na tabela temporária
			SET @ComandoSQL = 'BULK INSERT #ConteudoFicheiro FROM ''' + @PathFicheiroXML + ''''
			EXEC (@ComandoSQL)
-- obtem o xml do ficheiro importado (se xml não minified, torna-o minified)
			SELECT @FicheiroTXT = COALESCE(@FicheiroTXT, '') + CONTEUDO
			FROM #ConteudoFicheiro
-- converte para xml com a remoção do encoding
			SET @FicheiroXML = REPLACE(@FicheiroTXT, ' encoding="UTF-8"', '')
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- insere na tabela tmp o ficheiro XML associado à declaração
			INSERT INTO @TmpFicheiroOGMA(EXM_IDTY, EXA_LINH, TDE_REGI, FICHEIRO)
			VALUES(@IdDeclaracao, @NumAdicao, @Regime, @FicheiroXML.query('(FICH_DESPCHANTE/FICH_DESPCHANTE_LINE[NOTAS=sql:variable("@Regime")])[sql:variable("@NumAdicao")]'))
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumAdicao, @Regime, @PathFicheiroXML
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- remove a tabela temporária
		DROP TABLE #ConteudoFicheiro
-- constroi XML para ficheiro XML no formato OGMA a partir da declaração EXP e respetivo ficheiro original
		SET @FicheiroXML = 
			(SELECT
				(SELECT 
					f.x.value('DT_PROCESSO[1]', 'varchar(10)') AS "DT_PROCESSO", 
					f.x.value('PROCESSO[1]', 'varchar(100)') AS "PROCESSO", 
					f.x.value('TIPO[1]', 'varchar(1)') AS "TIPO", 
					f.x.value('BI_LI_ID[1]', 'varchar(45)') AS "BI_LI_ID", 
					f.x.value('AWB[1]', 'varchar(25)') AS "AWB", 
					f.x.value('RO_ID[1]', 'varchar(45)') AS "RO_ID", 
					f.x.value('PO[1]', 'varchar(20)') AS "PO", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('ARTIGO[1]', 'varchar(40)')) AS "ARTIGO", 
					f.x.value('QTD_REC[1]', 'varchar(45)') AS "QTD_REC", 
					f.x.value('UOM_REC[1]', 'varchar(3)') AS "UOM_REC", 
					f.x.value('VALOR_UNIT_REC[1]', 'varchar(45)') AS "VALOR_UNIT_REC", 
					f.x.value('RRM[1]', 'varchar(30)') AS "RRM", 
					f.x.value('LOTE[1]', 'varchar(80)') AS "LOTE", 
					f.x.value('SERIAL_NUM[1]', 'varchar(250)') AS "SERIAL_NUM", 
					f.x.value('PP_OGMA[1]', 'varchar(22)') AS "PP_OGMA", 
					f.x.value('NOTAS[1]', 'varchar(100)') AS "NOTAS", 
					ISNULL(exm.EXM_NDGA, '') AS "DAU", 
					exm.EXM_REVI AS "REVISAO", 
					ISNULL(CONVERT(varchar(10), exm.EXM_DDGA, 105), '') AS "DAU_DATE", 
					ISNULL(exa.TDE_REGI, '') AS "REGIME", 
					exa.EXA_LINH AS "NUM_ADIC", 
					ISNULL(exa.APA_CP33, '') AS "PP_ALF", 
					f.x.value('QTD_ALF[1]', 'varchar(45)') AS "QTD_ALF", 
					f.x.value('UOM_ALF[1]', 'varchar(3)') AS "UOM_ALF", 
					CAST(ISNULL(exa.EXA_MBRT, 0) AS decimal(28, 6)) AS "PESO_GROSS_ALF", 
					CAST(ISNULL(exa.EXA_MLQD, 0) AS decimal(28, 6)) AS "PESO_NET_TOTAL_ALF", 
					CAST(ROUND((ISNULL(exa.EXA_MLQD, 0) / ISNULL(CAST(NULLIF(f.x.value('QTD_ALF[1]', 'varchar(45)'), '') AS decimal(28, 6)), 1)), 6) AS decimal(28, 6)) AS "PESO_NET_UNIT_ALF", 
					CAST(ISNULL(exa.EXA_VEST, 0) AS decimal(28, 6)) AS "VALOR_ALF", 
					(LTRIM(STR(exm.EXM_NRII, 7, 0)) + '/' + RIGHT(STR(exm.EXM_EANO, 4, 0), 2)) AS "N_PROC_DESPACHANTE", 
					FLOOR(ISNULL(exm.EXM_TVL6, 0)) AS "N_VOLUMES", 
					f.x.value('CLASSIFICACAO[1]', 'varchar(50)') AS "CLASSIFICACAO", 
					f.x.value('LICENCA[1]', 'varchar(50)') AS "LICENCA", 
					f.x.value('END_USER[1]', 'varchar(50)') AS "END_USER", 
					f.x.value('GUIA[1]', 'varchar(20)') AS "GUIA", 
					f.x.value('QTD_EXP[1]', 'varchar(45)') AS "QTD_EXP", 
					f.x.value('UOM_EXP[1]', 'varchar(3)') AS "UOM_EXP", 
					f.x.value('VALOR_UNIT_EXP[1]', 'varchar(45)') AS "VALOR_UNIT_EXP", 
					f.x.value('DAU_PREC[1]', 'varchar(20)') AS "DAU_PREC", 
					f.x.value('REVISAO_PREC[1]', 'varchar(45)') AS "REVISAO_PREC", 
					f.x.value('DAU_DATE_PREC[1]', 'varchar(10)') AS "DAU_DATE_PREC", 
					f.x.value('REGIME_PREC[1]', 'varchar(4)') AS "REGIME_PREC", 
					f.x.value('NUM_ADIC_PREC[1]', 'varchar(45)') AS "NUM_ADIC_PREC", 
					f.x.value('PP_PREC[1]', 'varchar(22)') AS "PP_PREC", 
					f.x.value('PESO_GROSS[1]', 'varchar(45)') AS "PESO_GROSS", 
					f.x.value('PESO_NET_TOTAL[1]', 'varchar(45)') AS "PESO_NET_TOTAL", 
					f.x.value('KEY_ADIC_PREC[1]', 'varchar(45)') AS "KEY_ADIC_PREC", 
					f.x.value('N_PROC_DESPACHANTE_PREC[1]', 'varchar(10)') AS "N_PROC_DESPACHANTE_PREC", 
					f.x.value('BEM[1]', 'varchar(1)') AS "BEM", 
					f.x.value('DESIGN_REC[1]', 'varchar(100)') AS "DESIGN_REC", 
					f.x.value('DESIGN_EXP[1]', 'varchar(100)') AS "DESIGN_EXP", 
					f.x.value('WEIGHT_UNIT[1]', 'varchar(45)') AS "WEIGHT_UNIT", 
					f.x.value('UOM_WEIGHT[1]', 'varchar(12)') AS "UOM_WEIGHT", 
					f.x.value('PESO_NET_REMAINING[1]', 'varchar(45)') AS "PESO_NET_REMAINING", 
					f.x.value('COUNTRY_EXP[1]', 'varchar(50)') AS "COUNTRY_EXP", 
					f.x.value('TIPO_EXP[1]', 'varchar(15)') AS "TIPO_EXP", 
					f.x.value('PROCESS_TYPE[1]', 'varchar(2)') AS "PROCESS_TYPE", 
					f.x.value('FACTURA[1]', 'varchar(100)') AS "FACTURA", 
					f.x.value('PROJECTO[1]', 'varchar(25)') AS "PROJECTO", 
					f.x.value('PAIS_EXP_MERCADORIA[1]', 'varchar(3)') AS "PAIS_EXP_MERCADORIA", 
					f.x.value('TIPO_CERTIFICADO[1]', 'varchar(100)') AS "TIPO_CERTIFICADO", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('EXPEDIDOR[1]', 'varchar(200)')) AS "EXPEDIDOR", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('DESTINATARIO[1]', 'varchar(200)')) AS "DESTINATARIO", 
					f.x.value('DATA_FATURA[1]', 'varchar(10)') AS "DATA_FATURA", 
					f.x.value('PACKING_SLIP[1]', 'varchar(25)') AS "PACKING_SLIP", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('DESIGNACAO_MERCADORIA[1]', 'varchar(100)')) AS "DESIGNACAO_MERCADORIA", 
					f.x.value('PAIS_ORIGEM_MERCADORIA[1]', 'varchar(3)') AS "PAIS_ORIGEM_MERCADORIA", 
					f.x.value('AUTORIZ_REGIME_EVOLUCAO[1]', 'varchar(35)') AS "AUTORIZ_REGIME_EVOLUCAO", 
					f.x.value('DT_AUTORIZ_REGIME_EVOLUCAO[1]', 'varchar(10)') AS "DT_AUTORIZ_REGIME_EVOLUCAO", 
					f.x.value('AUTORIZACAO_PREC[1]', 'varchar(35)') AS "AUTORIZACAO_PREC", 
					f.x.value('GARANTIA[1]', 'varchar(10)') AS "GARANTIA", 
					f.x.value('VALOR_FRETE_LOTE[1]', 'varchar(45)') AS "VALOR_FRETE_LOTE", 
					f.x.value('TAXA_CAMBIO[1]', 'varchar(45)') AS "TAXA_CAMBIO", 
					f.x.value('CODIGO_MOEDA_FATURACAO[1]', 'varchar(3)') AS "CODIGO_MOEDA_FATURACAO", 
					f.x.value('TAXA_CAMBIO_PREC[1]', 'varchar(45)') AS "TAXA_CAMBIO_PREC", 
					f.x.value('NUMERO_CERTIFICADO[1]', 'varchar(100)') AS "NUMERO_CERTIFICADO", 
					f.x.value('DATA_CERTIFICADO[1]', 'varchar(10)') AS "DATA_CERTIFICADO", 
					f.x.value('COD_OPERACAO[1]', 'varchar(10)') AS "COD_OPERACAO", 
					f.x.value('TIPO_PROCEDIMENTO[1]', 'varchar(20)') AS "TIPO_PROCEDIMENTO", 
					f.x.value('DOCS_USAR_DESP_EXP[1]', 'varchar(10)') AS "DOCS_USAR_DESP_EXP" 
				FROM @TmpFicheiroOGMA AS fch	
					CROSS APPLY fch.FICHEIRO.nodes('FICH_DESPCHANTE_LINE') AS f(x)
					INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON fch.EXM_IDTY = exm.EXM_IDTY	
					INNER JOIN PRO_EXAD AS exa WITH(NOLOCK) ON exm.EXM_EANO = exa.EXM_EANO AND exm.EXM_CODI = exa.EXM_CODI AND exm.DEC_CODI = exa.EXM_COPE AND fch.EXA_LINH = exa.EXA_LINH
				ORDER BY fch.ID
				FOR XML PATH('FICH_DESPCHANTE_LINE'), TYPE)				
			FOR XML PATH('FICH_DESPCHANTE'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH				
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ExportaFicheiroOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ExportaFicheiroOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ExportaFicheirosXMLEstadosOperacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ExportacaoXML_ExportaFicheirosXMLEstadosOperacao] @DirDestinoFicheirosXML varchar(500), @DataReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodDeclaranteDeclaracao varchar(6), @NumeroDeclaracao int, @EstOperacaoDeclaracao varchar(3), @NovaExportacao varchar(3), @FicheiroXML xml, 
		@PathFicheiroTmpXML nvarchar(4000), @IDTabelaTmp varchar(100), @Comando nvarchar(4000) 
-- verifica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirDestinoFicheirosXML), 1, 1) <> '\'
		SET @DirDestinoFicheirosXML = @DirDestinoFicheirosXML + '\'
-- obtem a lista de declarações de Exportação/XML cujo "Estado da Operação" seja "AP" e ainda não exportadas como "AP" (posição 1), ou cujo "Estado da Operação" seja "CD", "CF", "CFP" ou "CFS" e ainda não exportadas (posição 2), ou cujo "Estado da Operação" seja "AS" e ainda não exportadas (posição 3)
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NRII, EXM_ESTO, ('1' + SUBSTRING(EXM_EXPE, 2, 2))
		FROM PRO_EXML
		WHERE SUBSTRING(EXM_EXPE, 1, 1) = '0' AND EXM_ESTO = 'AP' AND CAST(CONVERT(varchar(10), EXM_DDGA, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, EXM_DDGA), 105) AS datetime)
		UNION ALL
		SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NRII, EXM_ESTO, (SUBSTRING(EXM_EXPE, 1, 1) + '1' + SUBSTRING(EXM_EXPE, 3, 1))
		FROM PRO_EXML
		WHERE SUBSTRING(EXM_EXPE, 2, 1) = '0' AND (EXM_CRTD = 1 OR EXM_CRTF = 1) AND CAST(CONVERT(varchar(10), EXM_DDGA, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, EXM_DDGA), 105) AS datetime)
		UNION ALL
		SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NRII, EXM_ESTO, (SUBSTRING(EXM_EXPE, 1, 2) + '1')
		FROM PRO_EXML
		WHERE SUBSTRING(EXM_EXPE, 3, 1) = '0' AND EXM_ASAI = 1 AND CAST(CONVERT(varchar(10), EXM_DT6A, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, EXM_DT6A), 105) AS datetime)
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumeroDeclaracao, @EstOperacaoDeclaracao, @NovaExportacao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro de dados da declaração no formato do Estado de Operação
		SET @FicheiroXML = 	
			(SELECT exm.EXM_NRII "numeroProcesso", 
				exm.EXM_NRLO "numeroReferenciaLocal", 
				(exm.CLI_PAI2 + exm.CLI_NIF2) "NIFExpedidor", 
				exm.EXM_CPRT "numeroDocumentoTransporte", 
				exm.CLI_NOM2 "nomeExpedidor", 
				exm.FOR_NOM8 "nomeDestinatario", 
				exm.EAD_CODA "CodigoAlfandega", 
				exm.EXM_NPRO "numeroProvisorio", 
				exm.EXM_NDGA "numeroOrdem", 
				CAST(exm.EXM_MT22 AS decimal(18, 2)) "montanteFatura", 
				exm.PAI_MO22 "moeda", 
				CAST(exm.EXM_TX23 AS decimal(18, 6)) "taxaCambio", 
				exm.EXM_ESTO "EstadoOperacao", 
				CONVERT(varchar(19), (CASE exm.EXM_ASAI WHEN 1 THEN exm.EXM_DT6A ELSE GETDATE() END), 120) "dataEstadoOperacao"					
			FROM PRO_EXML AS exm
			WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CODI = @CodDeclaracao AND exm.DEC_CODI = @CodDeclaranteDeclaracao					
			FOR XML PATH('EstadoOperacao'), ELEMENTS)		
-- obtem nome p/ tabela temporaria do XML
		SET @IDTabelaTmp = '##_tmpTABExportXML_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '')
-- cria tabela temporaria p/ XML e insere o XML
		SET @Comando = N'CREATE TABLE ' + @IDTabelaTmp + ' (Bulkcol xml) INSERT INTO ' + @IDTabelaTmp + '(Bulkcol) VALUES(@FicheiroXML)'	
		EXECUTE sp_executesql @Comando, N'@FicheiroXML xml', @FicheiroXML
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirDestinoFicheirosXML + CAST(@NumeroDeclaracao AS varchar(20)) + '_' + @EstOperacaoDeclaracao + '_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML da resposta
		SET @Comando = 'bcp "SELECT Bulkcol FROM ' + @IDTabelaTmp + '" queryout "' + @PathFicheiroTmpXML + '" -w -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
-- remove tabela temporaria criada p/ XML 	
		SET @Comando = N'DROP TABLE ' + @IDTabelaTmp
		EXECUTE sp_executesql @Comando				
-- atualiza declaração p/ sinalizar como já enviada
		UPDATE PRO_EXML SET EXM_EXPE = @NovaExportacao
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodDeclaranteDeclaracao
			
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumeroDeclaracao, @EstOperacaoDeclaracao, @NovaExportacao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ExportaFicheirosXMLEstadosOperacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ExportaFicheirosXMLEstadosOperacao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ExportaFicheirosXMLKHUNENAGEL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ExportacaoXML_ExportaFicheirosXMLKHUNENAGEL] @DirDestinoFicheirosXML varchar(500), @DataReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodDeclaranteDeclaracao varchar(6), @NumOrdemDeclaracao varchar(21), @FicheiroXML xml, @PathFicheiroTmpXML nvarchar(4000), @IDTabelaTmp varchar(100), 
		@Comando nvarchar(4000)
-- verifica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirDestinoFicheirosXML), 1, 1) <> '\'
		SET @DirDestinoFicheirosXML = @DirDestinoFicheirosXML + '\'
-- obtem a lista de declarações de Exportação/XML cujo "País 17A" seja "GB" e tenha "AS" e ainda não exportadas
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NDGA
		FROM PRO_EXML
		WHERE EXM_P17A = 'GB' AND EXM_ASAI = 1 AND EXM_EXPK = 0 AND CAST(CONVERT(varchar(10), EXM_DTAS, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, EXM_DTAS), 105) AS datetime)
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumOrdemDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro de dados da declaração no formato Khune&Nagel
		SET @FicheiroXML = 	
			(SELECT	
				(SELECT	
					(SELECT 'KNPT' "Tennant", 
						'KNUK' "BranchOffice", 
						'FO' "Division", 
						'IMPOR' "DeclarationType", 												
						'GIDWIN' "Application"
					FOR XML PATH('Transaction'), TYPE),						
					(SELECT exm.EXM_NRLO "IdentificationNumber", 
						exm.EXM_NDGA "CustomerReference", 						
						'EX' "DeclarationType", 
						REPLACE(LTRIM(STR(exm.EXM_TMBR, 18, 3)), '.', ',') "GrossWeight", 
						exm.PAI_MO22 "InvoiceCurrency", 
						(SELECT TOP 1 EXD_NREF FROM PRO_EXDA WHERE DOC_CODI = 'N380' AND EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI AND EXA_LINH = 1) "InvoiceNumber",
						NULLIF(exm.EXM_NCMR, '') "AuthorizationNumberExport", 
						exm.CEN_CO20 "IncotermCode", 
						exm.EXM_LG20 "IncotermPlace", 						
						STUFF(exm.EXM_NDGA, 1, 2, '') "AuthorizationNumberExport", 						
						exm.EXM_P15A "CountryOfDispatch", 
						exm.EXM_P17A "CountryOfDestination", 						
						'40' "ProcedureType", 																 
						(SELECT exm.FOR_NOM8 "Name", 
							exm.FOR_MOR8 "Street", 
							exm.FOR_LOC8 "Place", 
							exm.FOR_CPO8 "PostCode", 
							exm.FOR_PAI8 "Country"
						FOR XML PATH('Consignee'), TYPE),
						(SELECT exm.CLI_NOM2 "Name", 
							exm.CLI_MOR2 "Street", 
							exm.CLI_LOC2 "Place", 
							exm.CLI_CPO2 "PostCode", 
							exm.CLI_PAI2 "Country"
						FOR XML PATH('Supplier'), TYPE), 						
						ISNULL(NULLIF(exm.LME_CO30, ''), exm.EXM_MR30) "AdditionalReference1", 
						(SELECT CLI_EMAI FROM TAB_CLIE WHERE CLI_CODI = exm.CLI_COD2) "AdditionalReference3", 
						(SELECT FOR_EMAI FROM TAB_FORN WHERE CLI_CODI = exm.FOR_COD8) "AdditionalReference4"										  
					FOR XML PATH('Header'), TYPE),
					(SELECT exa.EXA_LINH "Line", 																														
						exa.APA_CP33 "CommodityCode", 						 
						(SELECT CPD_DESI FROM TAB_CPDI WHERE CPD_CPAU = exa.APA_CP33) "DescriptionOfGoods", 
						exa.PAI_CODI "CountryOfOrigin", 						
						CAST((SELECT SUM(EXM_NVOL) FROM PRO_EXMV WHERE EXA_CHVE = exa.EXA_CHVE) AS int) "Quantity", 						
						REPLACE(LTRIM(STR(exa.EXA_MLQD, 18, 3)), '.', ',') "SingleUnitNetWeight",
						REPLACE(LTRIM(STR(exa.EXA_MLQD, 18, 3)), '.', ',') "TotalNetWeight", 
						REPLACE(LTRIM(STR(exa.EXA_MBRT, 18, 3)), '.', ',') "TotalGrossWeight", 
						REPLACE(LTRIM(STR(exa.EXA_VALO, 18, 2)), '.', ',') "InvoicePrice", 																								
						(SELECT CAST(EXM_NVOL AS int) "Quantity", 
							TEM_CODI "Type", 
							EXM_MARN "Indication" 							
						FROM PRO_EXMV
						WHERE EXA_CHVE = exa.EXA_CHVE
						FOR XML PATH('Package'), TYPE),
						(SELECT DOC_CODI "Type", 
							CONVERT(varchar(10), EXD_DTEM, 120) "IssueDate",
							EXD_NREF "Reference" 							
						FROM PRO_EXDA
						WHERE EXA_CHVE = exa.EXA_CHVE AND DOC_CODI = 'N380'
						FOR XML PATH('Document'), TYPE),												
						(SELECT FOR_EMAI FROM TAB_FORN WHERE CLI_CODI = exm.FOR_COD8) "AdditionalReference4"						
					FROM PRO_EXAD AS exa
					WHERE exa.EXM_EANO = exm.EXM_EANO AND exa.EXM_CODI = exm.EXM_CODI AND exa.EXM_COPE = exm.DEC_CODI
					FOR XML PATH('Position'), TYPE)
				FROM PRO_EXML AS exm
				WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CODI = @CodDeclaracao AND exm.DEC_CODI = @CodDeclaranteDeclaracao	
				FOR XML PATH('Declaration'), TYPE)		
			FOR XML PATH('Customs_Declaration'), ELEMENTS)		
-- obtem nome p/ tabela temporaria do XML
		SET @IDTabelaTmp = '##_tmpTABExportXML_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '')
-- cria tabela temporaria p/ XML e insere o XML
		SET @Comando = N'CREATE TABLE ' + @IDTabelaTmp + ' (Bulkcol xml) INSERT INTO ' + @IDTabelaTmp + '(Bulkcol) VALUES(@FicheiroXML)'	
		EXECUTE sp_executesql @Comando, N'@FicheiroXML xml', @FicheiroXML
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirDestinoFicheirosXML + 'GIDWIN_' +@NumOrdemDeclaracao + '_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML da resposta
		SET @Comando = 'bcp "SELECT Bulkcol FROM ' + @IDTabelaTmp + '" queryout "' + @PathFicheiroTmpXML + '" -w -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
-- remove tabela temporaria criada p/ XML 	
		SET @Comando = N'DROP TABLE ' + @IDTabelaTmp
		EXECUTE sp_executesql @Comando	
-- abre o ficheiro para o normalizar e adicionar linha de encoding
		EXEC GIDWIN.dbo.SP_Externo_NormalizaFicheiroXML @PathFicheiroTmpXML, '1.0', 'UTF-8'
-- atualiza declaração p/ sinalizar como já enviada
		UPDATE PRO_EXML SET EXM_EXPK = 1
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodDeclaranteDeclaracao
			
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumOrdemDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END
GRANT EXECUTE ON SP_ExportacaoXML_ExportaFicheirosXMLKHUNENAGEL TO public AS dbo

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ExportaFicheirosXMLKHUNENAGEL] TO  SCHEMA OWNER 
/****** Object:  StoredProcedure [SP_ExportacaoXML_ExportaFicheirosXMLRespostaCTT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_ExportaFicheirosXMLRespostaCTT] @DataReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @DirGeracaoFicheiro nvarchar(500), @AnoDeclaracao int, @CodDeclaracao int, @CodDeclaranteDeclaracao varchar(6), @NumDocTransporte varchar(18), @FicheiroXML xml, 
		@PathFicheiroTmpXML nvarchar(4000)
-- obtem a diretoria p/ geração do ficheiro XML
	SELECT @DirGeracaoFicheiro = PFC_PEPA 
	FROM TAB_PFCT WITH(NOLOCK)
-- obtem a lista de declarações de Exportação/XML que tenham "AS" e ainda não exportadas ou que tenham CS e também ainda não exportadas
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_CPRT
		FROM PRO_EXML WITH(NOLOCK)
		WHERE CAST(CONVERT(varchar(10), EXM_DTAS, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, EXM_DTAS), 105) AS datetime)
			AND ((EXM_ASAI = 1 AND EXM_EXPK = 0 AND EXM_DTCS IS NULL AND EXM_EXPO <> 3) OR (EXM_ASAI = 1 AND EXM_EXPK = 1 AND EXM_DTCS IS NOT NULL AND EXM_EXPO <> 3))
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumDocTransporte
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro de dados da resposta da declaração no formato CTT
		SET @FicheiroXML = 				
			(SELECT 
				EXM_NRII AS "numeroProcesso",
				EXM_NRLO AS "numeroReferenciaLocal",
				NULLIF(EXM_CPRT, '') AS "numeroDocumentoTransporte",
				NULLIF(CLI_NOM2, '') AS "nomeExpedidor", 			 			
				NULLIF(CLI_NIF2, '') AS "NIFExpedidor", 			
				NULLIF(FOR_NOM8, '') AS "nomeDestinatario", 			 			
				EAD_CODA as "codigoAlfandega", 			
				NULLIF(EXM_NDGA, '') AS "numeroOrdem",
				NULLIF(EXM_ESTO, '') AS "estadoOperacao", 
				NULLIF(EXM_MT22, 0) AS "montanteFatura",
				NULLIF(PAI_MO22, '') AS "moeda",
				NULLIF(EXM_TX23, 0) AS "taxaCambio",
				NULLIF(EXM_VATT, 0) AS "valorAduaneiro"
			FROM PRO_EXML WITH(NOLOCK)
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodDeclaranteDeclaracao
			FOR XML PATH('INCIDENCIA'), ELEMENTS)		
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirGeracaoFicheiro + '\' + @NumDocTransporte + '_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML de Respostas c/ encoding UTF-8
		EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroTmpXML			
-- atualiza declaração p/ sinalizar como já enviada
		UPDATE PRO_EXML SET 
			EXM_EXPK = 1, 
			EXM_EXPO = (CASE WHEN (EXM_ASAI = 1 AND EXM_EXPK = 1 AND EXM_DTCS IS NOT NULL AND EXM_EXPO <> 3) THEN 3 ELSE EXM_EXPO END)
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodDeclaranteDeclaracao			
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumDocTransporte
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ExportaFicheirosXMLRespostaCTT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ExportaFicheirosXMLRespostaCTT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ExportaFicheirosXMLRoadKHUNENAGEL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ExportacaoXML_ExportaFicheirosXMLRoadKHUNENAGEL] @DirDestinoFicheirosXML varchar(500), @DataReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodDeclaranteDeclaracao varchar(6), @NumOrdemDeclaracao varchar(21), @FicheiroXML xml, @PathFicheiroTmpXML nvarchar(4000), @IDTabelaTmp varchar(100), 
		@Comando nvarchar(4000)
-- verifica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirDestinoFicheirosXML), 1, 1) <> '\'
		SET @DirDestinoFicheirosXML = @DirDestinoFicheirosXML + '\'
-- obtem a lista de declarações de Exportação/XML cujo "País 17A" seja "GB" e tenha "AS" e ainda não exportadas
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NDGA
		FROM PRO_EXML WITH(NOLOCK) 
		WHERE EXM_P17A = 'GB' AND EXM_ASAI = 1 AND EXM_EXPK = 0 AND CAST(CONVERT(varchar(10), EXM_DTAS, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataReferencia, EXM_DTAS), 105) AS datetime)
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumOrdemDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro de dados da declaração no formato road Khune&Nagel
		SET @FicheiroXML = 	
			(SELECT	
				(SELECT											
					(SELECT exm.EXM_CPRT "IdentificationNumber", 
						exm.EXM_CPRT "CustomerReference", 
						'AESEX' "DeclarationType", 
						'L' "ProcedureType", 
						exm.EXM_P15A "CountryOfDispatch", 
						exm.EXM_P17A "CountryOfDestination", 
						CAST(exm.EXM_TMBR AS decimal(18, 3)) "GrossWeight", 
					    CAST(exm.EXM_TVL6 AS int)"Quantity", 
						CAST(exm.EXM_MT22 AS decimal(18, 2)) "InvoicePrice",
						exm.PAI_MO22 "InvoiceCurrency", 
						(SELECT TOP 1 EXD_NREF FROM PRO_EXDA WITH(NOLOCK) WHERE DOC_CODI = 'N380' AND EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI AND EXA_LINH = 1) "InvoiceNumber",	  
						exm.CEN_CO20 "IncotermCode", 
						CAST(exm.EXM_TVL6 AS int) "Package/Quantity",
						(SELECT (exm.FOR_PAI8 + NULLIF(exm.FOR_NIF8, '')) "Code", 
							exm.FOR_NOM8 "Name",  
							exm.FOR_MOR8 "Street", 
							exm.FOR_LOC8 "Place", 
							exm.FOR_CPO8 "PostCode", 
							exm.FOR_PAI8 "Country"
						FOR XML PATH('Consignee'), TYPE),
						(SELECT (exm.CLI_PAI2 + NULLIF(exm.CLI_NIF2, '')) "Code", 
							exm.CLI_NOM2 "Name", 
							exm.CLI_MOR2 "Street", 
							exm.CLI_LOC2 "Place", 
							exm.CLI_CPO2 "PostCode", 
							exm.CLI_PAI2 "Country"
						FOR XML PATH('Supplier'), TYPE), 						
						ISNULL(NULLIF(exm.LME_CO30, ''), exm.EXM_MR30) "AdditionalReference1", 
						exm.EXM_P15A "AdditionalReference2", 
						(SELECT CLI_EMAI FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_CODI = exm.CLI_COD2) "AdditionalReference3", 
						(SELECT FOR_EMAI FROM TAB_FORN WITH(NOLOCK) WHERE FOR_CODI = exm.FOR_COD8) "AdditionalReference4"															  
					FOR XML PATH('Header'), TYPE),
					(SELECT exa.EXA_LINH "Line", 	
						exa.APA_CO33 "DeclaredProcedureCode", 
						exa.APA_CP33 "CommodityCode", 						 
						(SELECT CPD_DESI FROM TAB_CPDI WITH(NOLOCK) WHERE CPD_CPAU = exa.APA_CP33) "DescriptionOfGoods", 
						exa.PAI_CODI "CountryOfOrigin", 						
						CAST((SELECT SUM(EXM_NVOL) FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = exa.EXA_CHVE) AS int) "Quantity", 						
						CAST(exa.EXA_MLQD AS decimal(18, 2)) "TotalNetWeight", 
						CAST(exa.EXA_MBRT AS decimal(18, 2)) "TotalGrossWeight", 
						CAST(exa.EXA_VALO AS decimal(18, 2)) "InvoicePrice", 																								
						(SELECT CAST(EXM_NVOL AS int) "Quantity", 
							TEM_CODI "Type"							
						FROM PRO_EXMV WITH(NOLOCK)
						WHERE EXA_CHVE = exa.EXA_CHVE
						FOR XML PATH('Package'), TYPE),
						(SELECT DOC_CODI "Type", 
							'Z' "Additional",  							
							EXD_NREF "Reference"
						FROM PRO_EXDA WITH(NOLOCK)
						WHERE EXA_CHVE = exa.EXA_CHVE AND DOC_CODI = 'N380'
						FOR XML PATH('Document'), TYPE)												
						FROM PRO_EXAD AS exa WITH(NOLOCK)
					WHERE exa.EXM_EANO = exm.EXM_EANO AND exa.EXM_CODI = exm.EXM_CODI AND exa.EXM_COPE = exm.DEC_CODI
					FOR XML PATH('Position'), TYPE)
				FROM PRO_EXML AS exm WITH(NOLOCK)
				WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CODI = @CodDeclaracao AND exm.DEC_CODI = @CodDeclaranteDeclaracao	
				FOR XML PATH('Declaration'), TYPE)		
			FOR XML PATH('Customs_Declaration'), ELEMENTS)		
-- obtem nome p/ tabela temporaria do XML
		SET @IDTabelaTmp = '##_tmpTABExportXML_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '')
-- cria tabela temporaria p/ XML e insere o XML
		SET @Comando = N'CREATE TABLE ' + @IDTabelaTmp + ' (Bulkcol xml) INSERT INTO ' + @IDTabelaTmp + '(Bulkcol) VALUES(@FicheiroXML)'	
		EXECUTE sp_executesql @Comando, N'@FicheiroXML xml', @FicheiroXML
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirDestinoFicheirosXML + 'GIDWIN_' +@NumOrdemDeclaracao + '_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.XML'
-- gera o ficheiro XML da resposta
		SET @Comando = 'bcp "SELECT Bulkcol FROM ' + @IDTabelaTmp + '" queryout "' + @PathFicheiroTmpXML + '" -w -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
-- remove tabela temporaria criada p/ XML 	
		SET @Comando = N'DROP TABLE ' + @IDTabelaTmp
		EXECUTE sp_executesql @Comando	
-- abre o ficheiro para o normalizar e adicionar linha de encoding
		EXEC GIDWIN.dbo.SP_Externo_NormalizaFicheiroXML @PathFicheiroTmpXML, '1.0', 'UTF-8'
-- atualiza declaração p/ sinalizar como já enviada
		UPDATE PRO_EXML SET EXM_EXPK = 1
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodDeclaranteDeclaracao
			
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumOrdemDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ExportaFicheirosXMLRoadKHUNENAGEL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ExportaFicheirosXMLRoadKHUNENAGEL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ExportaParaFicheiroXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ExportacaoXML_ExportaParaFicheiroXML] @TipoExportacao int, @NomeSPAGerarXML varchar(100), @DataReferencia datetime, @DirGeracaoFicheiro varchar(500) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodDeclaranteDeclaracao varchar(6), @NumeroOrdemDeclaracao varchar(21), @NumeroCPADeclaracao varchar(18), @FicheiroXML xml, @LinhaXMLEncoding varchar(200), 
		@PathFicheiroTmpXML nvarchar(4000), @SQLString nvarchar(500), @SQLParams nvarchar(500)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirGeracaoFicheiro), 1, 1) <> '\'
		SET @DirGeracaoFicheiro = @DirGeracaoFicheiro + '\'	
-- inicia variaveis para executar o SQL dinamicamente
	SET @SQLString = N'EXEC ' + @NomeSPAGerarXML + ' @INAnoDeclaracao, @INCodDeclaracao, @INCodDeclaranteDeclaracao, @OUTFicheiroXML OUTPUT, @OUTLinhaXMLEncoding OUTPUT'
	SET @SQLParams = N'@INAnoDeclaracao int, @INCodDeclaracao int, @INCodDeclaranteDeclaracao varchar(6), @OUTFicheiroXML xml OUTPUT, @OUTLinhaXMLEncoding varchar(200) OUTPUT'
-- obtem a lista de Declarações de Exportação/XML ainda não exportadas, importadas de Entradas AEX e que tenham CD ou CF 
	IF @TipoExportacao = 1
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NDGA, EXM_CPRT
			FROM PRO_EXML WITH(NOLOCK)
			WHERE EXM_EXPO = 0 AND EXM_ASAI = 0 AND (EXM_CRTD = 1 OR EXM_CRTF = 1) AND EXM_CMPX IS NOT NULL AND EXM_CMPX.exist('/CamposExtra/CampoExtra[CodigoCampoExtra="EDG_EANO"]') = 1						
	END
	ELSE
-- obtem a lista de Declarações de Exportação/XML ainda não exportadas, importadas de Entradas AEX e que tenham AS
	IF @TipoExportacao = 2
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NDGA, EXM_CPRT
			FROM PRO_EXML WITH(NOLOCK)
			WHERE EXM_EXPO IN (0, 1) AND EXM_ASAI = 1 AND EXM_CMPX IS NOT NULL AND EXM_CMPX.exist('/CamposExtra/CampoExtra[CodigoCampoExtra="EDG_EANO"]') = 1
	END
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumeroOrdemDeclaracao, @NumeroCPADeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN			
-- constroi XML para gerar o ficheiro
		EXECUTE sp_executesql @SQLString, @SQLParams, @INAnoDeclaracao = @AnoDeclaracao, @INCodDeclaracao = @CodDeclaracao, @INCodDeclaranteDeclaracao = @CodDeclaranteDeclaracao, @OUTFicheiroXML = @FicheiroXML OUTPUT, @OUTLinhaXMLEncoding = @LinhaXMLEncoding OUTPUT		
-- constroi full path para geração do ficheiro XML produzido
		SET @PathFicheiroTmpXML = @DirGeracaoFicheiro + '\' + @NumeroOrdemDeclaracao + '_' + @NumeroCPADeclaracao + '.XML'
-- gera o ficheiro XML produzido c/ encoding UTF-8
		EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroTmpXML
-- atualiza declaração de Exportação/XML p/ sinalizar como exportada
		UPDATE PRO_EXML SET EXM_EXPO = @TipoExportacao
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodDeclaranteDeclaracao			
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodDeclaranteDeclaracao, @NumeroOrdemDeclaracao, @NumeroCPADeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ExportaParaFicheiroXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ExportaParaFicheiroXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_GeraDeclaracoesDeXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_GeraDeclaracoesDeXML] @XMLDeclaracoes xml(XMLSC_DeclaracoesExpToGIDWin), @Utilizador varchar(30), @MensagemErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @Acao varchar(1), @TipoProcedimento varchar(1), @CodNatureza varchar(3), @CodOperador varchar(6), @Data datetime, @VossaReferencia varchar(50), 
		@CodEstanciaA varchar(8), @CodStatusIncidencia varchar(4), @CodTipoDeclaracao varchar(4), @NumeroCPA varchar(18), @TipoCarga varchar(5),  @DataVoo datetime, @Expedidor_Codigo varchar(18), 
		@Expedidor_Nome varchar(70), @Expedidor_Morada varchar(70), @Expedidor_Localidade varchar(35), @Expedidor_CodPostal varchar(12), @Expedidor_LocPostal varchar(35), 
		@Expedidor_NIF varchar(18), @Expedidor_CodPais varchar(2), @CodClienteServico varchar(18), @NumeroComercialRef varchar(70), @Destinatario_Codigo varchar(18), 
		@Destinatario_Nome varchar(70), @Destinatario_Morada varchar(70), @Destinatario_Localidade varchar(35), @Destinatario_CodPostal varchar(12), @Destinatario_LocPostal varchar(35), 
		@Destinatario_NIF varchar(18), @Destinatario_CodPais varchar(2), @CodPais15A varchar(2), @CodPais17A varchar(2), @ICE varchar(1), @MTPartida_CodMT varchar(2), 
		@MTPartida_MatriculaMT varchar(27), @MTPartida_TipoMT varchar(2), @MTPartida_CodMT25 varchar(2), @MTPartida_CodMT26 varchar(2), @MTPartida_CodAeroporto varchar(8), 
		@MTFronteira_CodMT varchar(2), @MTFronteira_MatriculaMT varchar(27), @MTFronteira_TipoMT varchar(2), @MTFronteira_CodPais varchar(2), @CodEstanciaTAC varchar(8), 
		@CodEstanciaTN varchar(8), @LocMercadorias_CodEstancia30 varchar(8), @LocMercadorias_CodLocalEmbarque varchar(25), @LocMercadorias_CodLocalAutorizado varchar(17), 
		@LocMercadorias_OutroLocal_Morada varchar(70), @LocMercadorias_OutroLocal_CodPostal varchar(12), @LocMercadorias_OutroLocal_LocPostal varchar(35), 
		@LocMercadorias_Armazem_CodArmazem varchar(17), @LocMercadorias_Armazem_CodTipoArmazem varchar(1), @LocMercadorias_Armazem_CodEstadoMembro varchar(2), @CodLocalEmbarque varchar(25), 
		@CodCondEntrega varchar(3), @Lugar varchar(50), @CodNaturezaTransacao varchar(2), @CodPais varchar(2), @TotalFrete numeric(38, 6), @TotalSeguro numeric(38, 6), @HVLV varchar(6), 
		@Origem int, @Anotacoes varchar(MAX), @CamposExtra xml, @DadosManifesto_CodExpedidor varchar(10), @DadosManifesto_NomeExpedidor varchar(70), @DadosManifesto_MoradaExpedidor varchar(70), 
		@DadosManifesto_LocalidadeExpedidor varchar(35), @DadosManifesto_CodPostalExpedidor varchar(12), @DadosManifesto_LocPostalExpedidor varchar(35), 
		@DadosManifesto_CodPaisExpedidor varchar(2), @DadosManifesto_NIFExpedidor varchar(18), @DadosManifesto_CodDestinatario varchar(10), @DadosManifesto_NomeDestinatario varchar(70), 
		@DadosManifesto_MoradaDestinatario varchar(70), @DadosManifesto_LocalidadeDestinatario varchar(35), @DadosManifesto_CodPaisDestinatario varchar(2), @DadosManifesto_Montante numeric(38, 6), 
		@DadosManifesto_CodPais varchar(2), @DadosManifesto_MassaLiqTotal numeric(38, 6), @DadosManifesto_MassaBrtTotal numeric(38, 6), @DadosManifesto_MiniCPA varchar(20), 
		@DadosManifesto_DutyType varchar(2), @DadosManifesto_NomeFicheiro varchar(100), @DadosManifesto_PPouFC varchar(3), @DadosManifesto_NumeroVoo varchar(20), 
		@DadosManifesto_Referencia1 varchar(50), @DadosManifesto_Referencia2 varchar(50), @DadosManifesto_Tracking varchar(35), @DadosManifesto_Shipping varchar(11), @DadosManifesto_VolsDirty int, 
		@Contentores xml, @Adicoes xml, @Arquivos xml
	DECLARE @IdDeclaracao bigint, @AnoDeclaracao int, @NumDeclaracao int, @NomeNatureza varchar(35), @NomeDeclarante varchar(70), @NIFDeclarante varchar(18), @Casa54Declarante varchar(1), 
		@NumReferenciaLocal varchar(22), @NomeEstanciaA varchar(35), @NomeTipoDeclaracao varchar(35), @1CasaTipoDeclaracao varchar(5), @RegimeTipoDeclaracao varchar(4), @TipoNIFCliente varchar(1), 
		@TipoIdCliente varchar(2), @CodigoClienteCC varchar(18), @IndicadorRemessaFornecedor int, @TipoDeclarante int, @CodMTEstancia varchar(2), @NomeMTPartida varchar(35), 
		@NomeMTFronteira varchar(35), @CodPaisEstancia varchar(2), @NomePaisMTFronteira varchar(35), @NomeCondEntrega varchar(35), @LocalizacaoCondEntrega varchar(35), 
		@MetodoPagCondEntrega varchar(1), @CodFormula int, @DescricaoFormula varchar(70), @FormulaFOB bit, @NomeNaturezaTransacao varchar(70), @MoedaPais22 varchar(3), @CambioMoeda numeric(38, 6), 
		@NomeEstanciaTAC varchar(35), @NomeEstanciaTN varchar(35), @NomeEstancia30 varchar(35), @DescricaoLocalEmbarque varchar(70), @DescricaoLocalAutorizado varchar(70), 
		@DescricaoLocalEmbarque30A varchar(70), @NomeArmazem varchar(70), @NomeTipoArmazem varchar(35), @InterfaceSDSViaAereaActivo bit, @DescricaoStatusIncidencia varchar(60), 
		@DataStatusIncidencia datetime, @NomeClienteServico varchar(70), @NomeAeroporto varchar(35), @TotalAdicoes int, @TotalVolumes numeric(38, 6), @MontanteTotal numeric(38, 6), 
		@MassaLiquidaTotal numeric(38, 6), @MassaBrutaTotal numeric(38, 6), @CodFollowUp int, @CodPaisCondEntrega varchar(2), @TextoCondEntrega varchar(512), @CodPaisFreteSeguro varchar(2), 
		@CambioFreteSeguro numeric(38, 6), @TipoLocalizacao varchar(1), @Qualificador varchar(1), @CodPaisLocMercadorias varchar(2), @AnexoB varchar(2), @TipoMTFronteira int, 
		@CodEstanciaAperfeicoamento varchar(8), @PrazoApuramento varchar(512), @AtividadesPrevistas varchar(512), @NumMascaras int, @TipoMascara int, @CodMascara int, @1AdicaoParte bit
	DECLARE @NumLinhaContentor int, @NumeroContentor varchar(50)
	DECLARE @NumeroAdicao int, @CodArtigo varchar(22), @DesignacaoArtigo varchar(150), @CodPaisOrigem varchar(2), @MassaBruta numeric(38, 6), @MassaLiquida numeric(38, 6), @Regime varchar(4), 
		@Desdobramento varchar(3), @QtdUnidades numeric(38, 6), @ValorAdicao numeric(38, 6), @ValorFrete numeric(38, 6), @ValorSeguro numeric(38, 6), @Documentos xml, @MencoesEspeciais xml, 
		@MarcasEVolumes xml, @DocsPrecedentes xml, @RegimesEconomicos xml
	DECLARE @CodPautal varchar(22), @NomePaisOrigem varchar(35), @CodUnidSuplementar varchar(10), @NomeUnidSuplementar varchar(10), @ValorEstatistico numeric(38, 6), @IndicadorArtigo varchar(2), 
		@AnexoCArtigo bit, @AnexoDArtigo bit, @CodMercPerigosasArtigo varchar(10), @AdicionalTARIC1Artigo varchar(4), @AdicionalTARIC2Artigo varchar(4), @AdicionalTARIC3Artigo varchar(4), 
		@CodigoIC1Artigo varchar(4), @CodigoIC2Artigo varchar(4), @CodigoIC3Artigo varchar(4), @CodigoIC4Artigo varchar(4), @CodigoIC5Artigo varchar(4), @CodigoCUSArtigo varchar(9), 
		@IDAdicao int, @NumTotalAdicoesXML int, @MassaBrtTotalAdicoesXML numeric(38, 6), @ValorRestanteFrete numeric(38, 6), @IdDesdobramento int, @Ajustamento numeric(38, 6)
	DECLARE @CodDocumento varchar(5), @NumeroReferencia varchar(50), @DataEmissao datetime, @DataFimValidade datetime
	DECLARE @NomeDocumento varchar(70), @QtdDocumento numeric(38, 6), @IdDocumento int, @TipoDocumento tinyint, @NumAdicaoDocumento int
	DECLARE @CodMencao varchar(8)
	DECLARE @DesignacaoMencao varchar(150)
	DECLARE @Marca varchar(44), @CodNaturezaVols varchar(2), @NumeroVols numeric(38, 6), @P bit, @R bit
	DECLARE @NomeTipoEmbalagem varchar(35), @VolsAZeroTipoEmbalagem bit, @IDStrMarcaEVol varchar(20), @AnoDeclaracaoMarcaEVol int, @NumDeclaracaoMarcaEVol int, @CodOperadorMarcaEVol varchar(6)
	DECLARE @TipoDocPrecedente varchar(1), @RefDocPrecedente varchar(20), @DataDocumento datetime, @VolumesPrecedente int, @IdUnidadeMedidaVolumes int, @IdUnidadeMedidaQualificador int
	DECLARE @NumLinhaDocPrecedente int, @NomePais varchar(35)
	DECLARE @DataAtual datetime, @AuxMsgErro varchar(500), @DirArquivos varchar(250), @CamposAdicionais int, @IntegracaoEXPCAU bit, @PeriodoTransitorio bit, @IdUtilizador int
	DECLARE @NomeFicheiro varchar(100), @DescricaoFicheiro varchar(150), @TipoFicheiro varchar(8), @OrigemFicheiro int, @FicheiroBase64 varchar(MAX)
	DECLARE @ExtFicheiro varchar(10), @PathFicheiro varchar(500), @FicheiroImprSerie bit, @FicheiroBinario varbinary(MAX), @Obj int
	DECLARE @NumeroDocPrecedente varchar(20), @AdicaoDocPrecedente int, @CodArtigoPautal varchar(22), @Quantidade numeric(38, 6), @CodUnidMedida varchar(3)
	DECLARE @NomeUnidMedida varchar(35)
-- obtem dados dos Parametros Despachos
	SELECT TOP 1 @DirArquivos = PDE_EPDI, @CamposAdicionais = PDE_CADI, @IntegracaoEXPCAU = PDE_ECAU, @PeriodoTransitorio = PDE_PTEX
	FROM TAB_PDES WITH(NOLOCK)			
-- obtem dados dos Parametros SDS-Via Aerea			
	SELECT TOP 1 @InterfaceSDSViaAereaActivo = PSD_IXML
	FROM TAB_PSDS WITH(NOLOCK)
-- obtem dados do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador
-- carrega declarações XML p/ INSERT
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT XML_DECL.DCL_DATA.value('@Acao[1]', 'varchar(1)'), XML_DECL.DCL_DATA.value('TipoProcedimento[1]', 'varchar(1)'), 
			XML_DECL.DCL_DATA.value('CodNatureza[1]', 'varchar(3)'), XML_DECL.DCL_DATA.value('CodOperador[1]', 'varchar(6)'), XML_DECL.DCL_DATA.value('Data[1]', 'datetime'), 
			NULLIF(XML_DECL.DCL_DATA.value('VossaReferencia[1]', 'varchar(50)'), ''), XML_DECL.DCL_DATA.value('CodEstanciaA[1]', 'varchar(8)'), 			
			NULLIF(XML_DECL.DCL_DATA.value('CodStatusIncidencia[1]', 'varchar(4)'), ''), XML_DECL.DCL_DATA.value('CodTipoDeclaracao[1]', 'varchar(4)'), 
			NULLIF(XML_DECL.DCL_DATA.value('NumeroCPA[1]', 'varchar(18)'), ''), NULLIF(XML_DECL.DCL_DATA.value('TipoCarga[1]', 'varchar(5)'), ''),  
			XML_DECL.DCL_DATA.value('DataVoo[1]', 'datetime'), NULLIF(XML_DECL.DCL_DATA.value('Expedidor/Codigo[1]', 'varchar(18)'), ''), 
			XML_DECL.DCL_DATA.value('Expedidor/Nome[1]', 'varchar(70)'), XML_DECL.DCL_DATA.value('Expedidor/Morada[1]', 'varchar(70)'), 
			NULLIF(XML_DECL.DCL_DATA.value('Expedidor/Localidade[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Expedidor/CodPostal[1]', 'varchar(12)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Expedidor/LocPostal[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Expedidor/NIF[1]', 'varchar(18)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Expedidor/CodPais[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodClienteServico[1]', 'varchar(18)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('NumeroComercialRef[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Destinatario/Codigo[1]', 'varchar(18)'), ''), 
			XML_DECL.DCL_DATA.value('Destinatario/Nome[1]', 'varchar(70)'), XML_DECL.DCL_DATA.value('Destinatario/Morada[1]', 'varchar(70)'), 
			NULLIF(XML_DECL.DCL_DATA.value('Destinatario/Localidade[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Destinatario/CodPostal[1]', 'varchar(12)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Destinatario/LocPostal[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Destinatario/NIF[1]', 'varchar(18)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('Destinatario/CodPais[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodPais15A[1]', 'varchar(2)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodPais17A[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('ICE[1]', 'varchar(1)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('MeioTransportePartida/CodMeioTransporte[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('MeioTransportePartida/MatriculaMT[1]', 'varchar(27)'), ''),  
			NULLIF(XML_DECL.DCL_DATA.value('MeioTransportePartida/TipoMT[1]', 'varchar(2)'),  ''),  NULLIF(XML_DECL.DCL_DATA.value('MeioTransportePartida/CodMeioTransporte25[1]', 'varchar(2)'), ''), 
			XML_DECL.DCL_DATA.value('MeioTransportePartida/CodMeioTransporte26[1]', 'varchar(2)'), NULLIF(XML_DECL.DCL_DATA.value('MeioTransportePartida/CodAeroporto[1]', 'varchar(8)'), ''), 			
			NULLIF(XML_DECL.DCL_DATA.value('MeioTransporteFronteira/CodMeioTransporte[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('MeioTransporteFronteira/MatriculaMT[1]', 'varchar(27)'), ''),  
			NULLIF(XML_DECL.DCL_DATA.value('MeioTransporteFronteira/TipoMT[1]', 'varchar(2)'),  ''),  NULLIF(XML_DECL.DCL_DATA.value('MeioTransporteFronteira/CodPais[1]', 'varchar(2)'), ''), 			
			XML_DECL.DCL_DATA.value('CodEstanciaTAC[1]', 'varchar(8)'), NULLIF(XML_DECL.DCL_DATA.value('CodEstanciaTN[1]', 'varchar(8)'), ''), 			
			NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/CodEstancia30[1]', 'varchar(8)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/CodLocalEmbarque[1]', 'varchar(25)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/CodLocalAutorizado[1]', 'varchar(17)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/OutroLocal/Morada[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/OutroLocal/CodPostal[1]', 'varchar(12)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/OutroLocal/LocPostal[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/Armazem/CodArmazem[1]', 'varchar(17)'), ''), NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/Armazem/CodTipoArmazem[1]', 'varchar(1)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('LocalizacaoMercadorias/Armazem/CodEstadoMembro[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('CodLocalEmbarque[1]', 'varchar(25)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodCondEntrega[1]', 'varchar(3)'), ''), NULLIF(XML_DECL.DCL_DATA.value('Lugar[1]', 'varchar(50)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('CodNaturezaTransacao[1]', 'varchar(2)'), ''), XML_DECL.DCL_DATA.value('CodPais[1]', 'varchar(2)'), 
			ISNULL(XML_DECL.DCL_DATA.value('TotalFrete[1]', 'numeric(38, 6)'), 0), ISNULL(XML_DECL.DCL_DATA.value('TotalSeguro[1]', 'numeric(38, 6)'), 0), 	
			NULLIF(XML_DECL.DCL_DATA.value('HVLV[1]', 'varchar(6)'), ''), ISNULL(XML_DECL.DCL_DATA.value('Origem[1]', 'int'), 0), 
			NULLIF(XML_DECL.DCL_DATA.value('Anotacoes[1]', 'varchar(MAX)'), ''), XML_DECL.DCL_DATA.query('CamposExtra'), 			
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/CodExpedidor[1]', 'varchar(10)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/NomeExpedidor[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/MoradaExpedidor[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/LocalidadeExpedidor[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/CodPostalExpedidor[1]', 'varchar(12)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/LocPostalExpedidor[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/CodPaisExpedidor[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/NIFExpedidor[1]', 'varchar(18)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/CodDestinatario[1]', 'varchar(10)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/NomeDestinatario[1]', 'varchar(70)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/MoradaDestinatario[1]', 'varchar(70)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/LocalidadeDestinatario[1]', 'varchar(35)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/CodPaisDestinatario[1]', 'varchar(2)'), ''), ISNULL(XML_DECL.DCL_DATA.value('DadosManifesto/Montante[1]', 'numeric(38, 6)'), 0), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/CodPais[1]', 'varchar(2)'), ''), ISNULL(XML_DECL.DCL_DATA.value('DadosManifesto/MassaLiqTotal[1]', 'numeric(38, 6)'), 0), 
			ISNULL(XML_DECL.DCL_DATA.value('DadosManifesto/MassaBrtTotal[1]', 'numeric(38, 6)'), 0), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/MiniCPA[1]', 'varchar(20)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/DutyType[1]', 'varchar(2)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/NomeFicheiro[1]', 'varchar(100)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/PPouFC[1]', 'varchar(3)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/NumeroVoo[1]', 'varchar(20)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/Referencia1[1]', 'varchar(50)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/Referencia2[1]', 'varchar(50)'), ''), 
			NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/Tracking[1]', 'varchar(35)'), ''), NULLIF(XML_DECL.DCL_DATA.value('DadosManifesto/Shipping[1]', 'varchar(11)'), ''), 
			XML_DECL.DCL_DATA.value('DadosManifesto/VolsDirty[1]', 'int'), XML_DECL.DCL_DATA.query('Contentores'), XML_DECL.DCL_DATA.query('Adicoes'), XML_DECL.DCL_DATA.query('Arquivos')
		FROM @XMLDeclaracoes.nodes('DeclaracoesExpToGIDWin/Declaracao') as XML_DECL(DCL_DATA)	
		WHERE XML_DECL.DCL_DATA.value('@Acao[1]', 'varchar(1)') in ('I', 'U')	
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @Acao, @TipoProcedimento, @CodNatureza, @CodOperador, @Data, @VossaReferencia, @CodEstanciaA, @CodStatusIncidencia, @CodTipoDeclaracao, @NumeroCPA, @TipoCarga, 
		@DataVoo, @Expedidor_Codigo, @Expedidor_Nome, @Expedidor_Morada, @Expedidor_Localidade, @Expedidor_CodPostal, @Expedidor_LocPostal, @Expedidor_NIF, @Expedidor_CodPais, @CodClienteServico, 
		@NumeroComercialRef, @Destinatario_Codigo, @Destinatario_Nome, @Destinatario_Morada, @Destinatario_Localidade, @Destinatario_CodPostal, @Destinatario_LocPostal, @Destinatario_NIF, 
		@Destinatario_CodPais, @CodPais15A, @CodPais17A, @ICE, @MTPartida_CodMT, @MTPartida_MatriculaMT, @MTPartida_TipoMT, @MTPartida_CodMT25, @MTPartida_CodMT26, @MTPartida_CodAeroporto, 
		@MTFronteira_CodMT, @MTFronteira_MatriculaMT,  @MTFronteira_TipoMT, @MTFronteira_CodPais, @CodEstanciaTAC, @CodEstanciaTN, @LocMercadorias_CodEstancia30, @LocMercadorias_CodLocalEmbarque, 
		@LocMercadorias_CodLocalAutorizado, @LocMercadorias_OutroLocal_Morada, @LocMercadorias_OutroLocal_CodPostal, @LocMercadorias_OutroLocal_LocPostal, @LocMercadorias_Armazem_CodArmazem, 
		@LocMercadorias_Armazem_CodTipoArmazem, @LocMercadorias_Armazem_CodEstadoMembro, @CodLocalEmbarque, @CodCondEntrega, @Lugar, @CodNaturezaTransacao, @CodPais, @TotalFrete, @TotalSeguro, 
		@HVLV, @Origem, @Anotacoes, @CamposExtra, @DadosManifesto_CodExpedidor, @DadosManifesto_NomeExpedidor, @DadosManifesto_MoradaExpedidor, @DadosManifesto_LocalidadeExpedidor, 
		@DadosManifesto_CodPostalExpedidor, @DadosManifesto_LocPostalExpedidor, @DadosManifesto_CodPaisExpedidor, @DadosManifesto_NIFExpedidor, @DadosManifesto_CodDestinatario, 
		@DadosManifesto_NomeDestinatario, @DadosManifesto_MoradaDestinatario, @DadosManifesto_LocalidadeDestinatario, @DadosManifesto_CodPaisDestinatario, @DadosManifesto_Montante, 
		@DadosManifesto_CodPais, @DadosManifesto_MassaLiqTotal, @DadosManifesto_MassaBrtTotal, @DadosManifesto_MiniCPA, @DadosManifesto_DutyType, @DadosManifesto_NomeFicheiro, 
		@DadosManifesto_PPouFC, @DadosManifesto_NumeroVoo, @DadosManifesto_Referencia1, @DadosManifesto_Referencia2, @DadosManifesto_Tracking, @DadosManifesto_Shipping, @DadosManifesto_VolsDirty, 
		@Contentores, @Adicoes, @Arquivos
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- inicia transacção para inserção dados da declaração
		BEGIN TRANSACTION	
		BEGIN TRY		
			DELETE FROM @TblID
			SET @IdDeclaracao = NULL
-- obtem data atual GMT
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()					
-- obtem dados da Natureza
			SELECT @NomeNatureza = NDE_NOME, @CodFollowUp = FUP_CODI
			FROM TAB_NDES WITH(NOLOCK)
			WHERE NDE_CODI = @CodNatureza	
-- obtem dados das Estâncias
			SELECT @NomeEstanciaA = EAD_NOME, @CodPaisEstancia = PAI_CODI, @CodMTEstancia = (CASE @Origem WHEN 0 THEN MTR_CODI ELSE NULL END)
			FROM TAB_EADU WITH(NOLOCK)
			WHERE EAD_CODI = @CodEstanciaA
			SELECT @NomeEstanciaTAC = EAD_NOME
			FROM TAB_EADU WITH(NOLOCK)
			WHERE EAD_CODI = @CodEstanciaTAC
			SELECT @NomeEstanciaTN = EAD_NOME
			FROM TAB_EADU WITH(NOLOCK)
			WHERE EAD_CODI = @CodEstanciaTN
			SELECT @NomeEstancia30 = EAD_NOME
			FROM TAB_EADU WITH(NOLOCK)
			WHERE EAD_CODI = @LocMercadorias_CodEstancia30
-- obtem dados do Tipo de Declaração
			SELECT @NomeTipoDeclaracao = TDE_NOME, @1CasaTipoDeclaracao = TDE_1CAS, @RegimeTipoDeclaracao = TDE_REGI, 
				@TipoCarga = ISNULL(@TipoCarga, (CASE @InterfaceSDSViaAereaActivo WHEN 1 THEN TDE_TPCG ELSE NULL END))
			FROM TAB_TDEC WITH(NOLOCK)
			WHERE TDE_CODI = @CodTipoDeclaracao			  			
-- obtem dados do Expedidor se este estiver preenchido
			IF @Expedidor_Codigo IS NOT NULL
			BEGIN
				SELECT @Expedidor_Nome = CLI_NOME, @Expedidor_Morada = CLI_MORA, @Expedidor_Localidade = ISNULL(CLI_LOCA, @Expedidor_Localidade), 
					@Expedidor_CodPostal = ISNULL(CLI_CPOS, @Expedidor_CodPostal), @Expedidor_LocPostal = ISNULL(CLI_LPOS, @Expedidor_LocPostal), @Expedidor_NIF = ISNULL(CLI_NIF, @Expedidor_NIF), 
					@Expedidor_CodPais = ISNULL(PAI_CODI, @Expedidor_CodPais), @CodClienteServico = ISNULL(@CodClienteServico, CLI_SENT), @CodigoClienteCC = ISNULL(NULLIF(CLI_CCOR, ''), CLI_CODI), 
					@TipoNIFCliente = (CASE CLI_TNIF WHEN 1 THEN 'S' WHEN 2 THEN 'P' ELSE 'C' END), @TipoIdCliente = (CASE CLI_TNIF WHEN 2 THEN 'BI' ELSE NULL END)					
				FROM TAB_CLIE WITH(NOLOCK)
				WHERE CLI_CODI = @Expedidor_Codigo			
			END
			ELSE
				SELECT @Expedidor_Codigo = '', @TipoNIFCliente = 'C'
-- obtem dados do Cliente de Serviço se este estiver preenchido
			SELECT @NomeClienteServico = CLI_NOME
			FROM TAB_CLIE WITH(NOLOCK)
			WHERE CLI_CODI = @CodClienteServico					
-- obtem dados do Destinatário se este estiver preenchido
			IF @Destinatario_Codigo IS NOT NULL
			BEGIN
				SELECT @Destinatario_Nome = ISNULL(FOR_NOME, @Destinatario_Nome), @Destinatario_Morada = ISNULL(FOR_MORA, @Destinatario_Morada), 
					@Destinatario_Localidade = ISNULL(FOR_LOCA, @Destinatario_Localidade), @Destinatario_CodPostal = ISNULL(FOR_CPOS, @Destinatario_CodPostal), 
					@Destinatario_LocPostal = ISNULL(FOR_LPOS, @Destinatario_LocPostal), @Destinatario_NIF = ISNULL(FOR_NIF, @Destinatario_NIF), 
					@Destinatario_CodPais = ISNULL(PAI_CODI, @Destinatario_CodPais), @IndicadorRemessaFornecedor = FOR_IROR
				FROM TAB_FORN WITH(NOLOCK)
				WHERE FOR_CODI = @Destinatario_Codigo				
			END
			ELSE
				SELECT @IndicadorRemessaFornecedor = 0		
-- obtem dados do pais "PT" se Pais 15A não preenchido
			IF @CodPais15A IS NULL	
			BEGIN
				SELECT @CodPais15A = PAI_CODI 
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = 'PT'
			END		
-- obtem dados em falta
			SELECT @AnoDeclaracao = YEAR(@Data), @CodPais17A = ISNULL(@CodPais17A, @Destinatario_CodPais), 
				@MTPartida_CodMT = ISNULL(@MTPartida_CodMT, @CodMTEstancia), @MTFronteira_CodPais = ISNULL(@MTFronteira_CodPais, @CodPaisEstancia), 
				@DataVoo = ISNULL(@DataVoo, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)), @NumeroComercialRef = ISNULL(@NumeroComercialRef, @NumeroCPA)
-- obtem dados dos Meios de Transporte
			SELECT @NomeMTPartida = MTR_NOME
			FROM TAB_MTRA WITH(NOLOCK)
			WHERE MTR_CODI = @MTPartida_CodMT	
			SELECT @NomeMTFronteira = MTR_NOME, @TipoMTFronteira = MTR_TIPO
			FROM TAB_MTRA WITH(NOLOCK)
			WHERE MTR_CODI = @MTFronteira_CodMT
-- inicia Tipos de Meio de Transporte c/ "VA" quando Tipo de Meio de Transporte não preenchido
			IF (@MTPartida_TipoMT IS NULL) and (@MTPartida_CodMT = '90')
				SELECT @MTPartida_TipoMT = 'VA'
			IF (@MTFronteira_TipoMT IS NULL) and (@MTFronteira_CodMT = '90')
				SELECT @MTFronteira_TipoMT = 'VA'													
-- obtem câmbio do País da Moeda
			SELECT @CambioMoeda = dbo.FNT_Geral_ObtemCambio(1, @CodPais, @Data)
-- obtem dados da Condição Entrega
			SELECT @NomeCondEntrega = CEN_NOME, @MetodoPagCondEntrega = CEN_MPAG, 
				@LocalizacaoCondEntrega = (CASE WHEN ISNULL(CEN_LOCT, 0) = 0 THEN NULL WHEN ISNULL(CEN_LOCD, 0) = 0 THEN @Expedidor_Localidade ELSE @Destinatario_Localidade END), 
				@CodFormula = (CASE WHEN CEN_FOR1 = 1 THEN FIN_CODI1 WHEN CEN_FOR2 = 1 THEN FIN_CODI2 WHEN CEN_FOR3 = 1 THEN FIN_CODI3 WHEN CEN_FOR4 = 1 THEN FIN_CODI4 WHEN CEN_FOR5 = 1 THEN FIN_CODI5 ELSE 0 END), 
				@CodPaisCondEntrega = (CASE WHEN ISNULL(CEN_LOCT, 0) = 0 THEN NULL WHEN ISNULL(CEN_LOCD, 0) = 0 THEN @Expedidor_CodPais ELSE @Destinatario_CodPais END)
			FROM TAB_CENT WITH(NOLOCK)
			WHERE CEN_CODI = @CodCondEntrega			
-- obtem dados da Formula
			SELECT @CodFormula = FIN_CODI, @DescricaoFormula = FIN_DESC, @FormulaFOB = FIN_VFOB
			FROM TAB_FINC WITH(NOLOCK)
			WHERE FIN_CODI = ISNULL(@CodFormula, 0)
-- obtem dados da Natureza de Transação
			SELECT @NomeNaturezaTransacao = NTR_NOME
			FROM TAB_NTRA WITH(NOLOCK)
			WHERE NTR_CODI = @CodNaturezaTransacao			
-- obtem dados dos vários Países		
			SELECT @NomePaisMTFronteira = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @MTFronteira_CodPais
			SELECT @MoedaPais22 = PAI_PREF
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPais
-- obtem dados dos Locais de Embarque
			SELECT @DescricaoLocalEmbarque = LEM_DESC
			FROM TAB_LEMB WITH(NOLOCK)
			WHERE LEM_CODI = @LocMercadorias_CodLocalEmbarque
			SELECT @DescricaoLocalEmbarque30A = LEM_DESC
			FROM TAB_LEMB WITH(NOLOCK)
			WHERE LEM_CODI = @CodLocalEmbarque
-- obtem dados do Local Autorizado
			SELECT @DescricaoLocalAutorizado = LME_NOME
			FROM TAB_LMER WITH(NOLOCK)
			WHERE LME_CODI = @LocMercadorias_CodLocalAutorizado
-- obtem dados do Armazém
			SELECT @NomeArmazem = ARM_NOME
			FROM TAB_ARMZ WITH(NOLOCK)
			WHERE ARM_CODI = @LocMercadorias_Armazem_CodArmazem	
-- obtem dados do Tipo de Armazém
			SELECT @NomeTipoArmazem = TAR_DESC
			FROM TAB_TARM WITH(NOLOCK)	
			WHERE TAR_CODI = @LocMercadorias_Armazem_CodTipoArmazem
-- ontem dados do Status de Incidência
			SELECT @DescricaoStatusIncidencia = SIN_DESP, @DataStatusIncidencia = CAST(CONVERT(varchar(10), @DataAtual, 105) as datetime)
			FROM TAB_SINC WITH(NOLOCK)
			WHERE SIN_CODI = @CodStatusIncidencia
-- obtem dados do Aeroporto
			SELECT @NomeAeroporto = PAE_NOME
			FROM TAB_PAER WITH(NOLOCK)
			WHERE PAE_CODI = @MTPartida_CodAeroporto
-- obtem dados de Declarante
			SELECT @NomeDeclarante = DEC_NOME, @NIFDeclarante = DEC_NIF, @TipoDeclarante = DEC_TIPO, 
				@NumDeclaracao = (CASE @Acao WHEN 'I' THEN ISNULL(DEC_NPRO, 1) ELSE (SELECT TOP 1 EXM_CODI FROM PRO_EXML WITH(NOLOCK) WHERE EXM_EANO = YEAR(@Data) and EXM_CPRT = @NumeroCPA ORDER BY EXM_DATA DESC) END), 				
				@Casa54Declarante = (CASE WHEN ISNULL(DEC_CEDU, '') <> '' THEN 'C' WHEN ISNULL(DEC_NIF, '') <> '' THEN 'N' ELSE 'E' END)
			FROM TAB_DECL WITH(NOLOCK)
			WHERE DEC_CODI = @CodOperador									
-- obtem mais dados em falta
			SELECT @MTPartida_CodMT25 = ISNULL(@MTPartida_CodMT25, ISNULL(@MTFronteira_CodMT, @MTPartida_CodMT)), @MTPartida_CodMT26 = ISNULL(@MTPartida_CodMT26, @MTPartida_CodMT), 
				@Lugar = ISNULL(@Lugar, @LocalizacaoCondEntrega), @CambioMoeda = (CASE @CambioMoeda WHEN 0 THEN 1 ELSE @CambioMoeda END), @TotalAdicoes = 0, 
				@TotalVolumes = 0, @MontanteTotal = 0, @MassaLiquidaTotal = 0, @MassaBrutaTotal = 0, @NumLinhaContentor = 0, @ValorRestanteFrete = @TotalFrete
-- processa calculos específicos relacionados com contexto EXP-CAU ou EXP/XML
			IF @IntegracaoEXPCAU = 1
			BEGIN		
				SET @IndicadorRemessaFornecedor = 0
				SET @MTPartida_MatriculaMT = NULL
				SET @MTPartida_TipoMT = NULL
				SET @MTFronteira_TipoMT = NULL
				SET @MTPartida_CodMT25 = NULL
				SET @CodLocalEmbarque = NULL
				SET @DescricaoLocalEmbarque30A = NULL
				SET @LocMercadorias_Armazem_CodEstadoMembro = NULL
				SET @Casa54Declarante = 'C'
				SET @CodStatusIncidencia = NULL 
				SET @DescricaoStatusIncidencia = NULL
				SET @DataStatusIncidencia = NULL
				SET @DadosManifesto_VolsDirty = 0
				SET @ICE = NULL				
				SET @MetodoPagCondEntrega = NULL
				SET @CodEstanciaTN = NULL
				SET @NomeEstanciaTN = NULL
				IF @TipoDeclarante <> 2 
					SET @TipoDeclarante = NULL
				IF @TipoProcedimento IN ('B', 'C', 'E', 'F')
					SET @Contentores = NULL
				SET @NumReferenciaLocal = (RIGHT(STR(@AnoDeclaracao, 4), 2)  + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 9 - LEN(CAST(@NumDeclaracao AS varchar(9)))) + CAST(@NumDeclaracao AS varchar(9)))
-- obtém o Anexo B 
				IF (ISNULL(@CamposAdicionais, 0) = 3) AND (ISNULL(@CodTipoDeclaracao, '') = 'COM1') --DHL
					SET @AnexoB = 'B4'
				ELSE
					IF ISNULL(@CamposAdicionais, 0) = 8 --ENTREPOSTO
					BEGIN
						SET @AnexoB = ISNULL(NULLIF((SELECT t.c.value('ValorCampoExtra[1]', 'varchar(2)')
													FROM @CamposExtra.nodes('CamposExtra/CampoExtra') AS t(c)
													WHERE t.c.value('CodigoCampoExtra[1]', 'varchar(10)') = 'ANEXOB' 
														AND t.c.value('ValorCampoExtra[1]', 'varchar(5)') IN ('B1', 'B2', 'B3', 'B4', 'C1', 'C2', 'A1', 'A2')), ''), 'B1')						
					END
					ELSE
						SET @AnexoB = 'B1'
				IF (@AnexoB IN ('B1', 'B2')) AND (ISNULL(@1CasaTipoDeclaracao, '') <> 'EX')
					RAISERROR('Tipo de Declaração "%s" inválido.', 16, 1, @CodTipoDeclaracao)				
-- se Estância de Exportação for "PT000236", assume como Meio Transporte Partida o valor "50"
				IF ISNULL(@CodEstanciaA, '') = 'PT000236'
				BEGIN
					SELECT @MTPartida_CodMT = MTR_CODI, @NomeMTPartida = MTR_NOME
					FROM TAB_MTRA WITH(NOLOCK)
					WHERE MTR_CODI = '50'
				END
				ELSE
				BEGIN
					SET @MTPartida_CodMT = NULL
					SET @NomeMTPartida = NULL
				END													
-- gere a existência do Meio Transporte Fronteira
				IF (LEFT(ISNULL(@RegimeTipoDeclaracao, ''), 2) IN ('21', '22')) OR ((ISNULL(@1CasaTipoDeclaracao, '') = 'CO') AND (LEFT(ISNULL(@RegimeTipoDeclaracao, ''), 2) <> '76'))
				BEGIN
					SET @MTFronteira_CodMT = NULL
					SET @NomeMTFronteira = NULL
				END
				ELSE
					IF (ISNULL(@MTFronteira_CodMT, '') = '') AND (ISNULL(@CodEstanciaA, '') = ISNULL(@CodEstanciaTAC, ''))
					BEGIN
						SELECT @MTFronteira_CodMT = MTR_CODI, @NomeMTFronteira = MTR_NOME
						FROM TAB_MTRA WITH(NOLOCK)
						WHERE MTR_CODI = @CodMTEstancia						
					END
					ELSE
						IF (ISNULL(@MTFronteira_CodMT, '') = '') AND (@TipoProcedimento NOT IN ('B', 'C', 'E', 'F'))
						BEGIN
							SELECT @MTFronteira_CodMT = MTR_CODI, @NomeMTFronteira = MTR_NOME
							FROM TAB_MTRA WITH(NOLOCK)
							WHERE MTR_CODI = @MTPartida_CodMT						
						END		
-- se Meio Transporte Fronteira	não definido, limpa restantes campos associados
				IF (ISNULL(@MTFronteira_CodMT, '') = '') OR (LEFT(@MTFronteira_CodMT, 1) IN ('5', '7')) 								
				BEGIN
					SET @MTFronteira_MatriculaMT = NULL
					SET @TipoMTFronteira = NULL
					SET @MTFronteira_CodPais = NULL
					SET @NomePaisMTFronteira = NULL					
				END
-- se Estância de Exportação igual a Estância de Saída, limpa Meio Transporte Interior
				IF ISNULL(@CodEstanciaA, '') = ISNULL(@CodEstanciaTAC, '')
					SET @MTPartida_CodMT26 = NULL
-- gere campos da Condição de Entega
				IF ISNULL(@CodCondEntrega, '') = 'XXX'
				BEGIN
					SET @Lugar = NULL
					SET @CodPaisCondEntrega = NULL
					SET @TextoCondEntrega = 'Livre de Encargos'
				END
				ELSE
					SET @TextoCondEntrega = NULL
-- gere a existência da Natureza de Transação
				IF (LEFT(ISNULL(@RegimeTipoDeclaracao, ''), 2) IN ('71', '76')) OR (@TipoProcedimento IN ('B', 'C', 'E', 'F'))
				BEGIN
					SET @CodNaturezaTransacao = NULL
					SET @NomeNaturezaTransacao = NULL
				END
				ELSE	
					IF ISNULL(@CodNaturezaTransacao, '') = ''
					BEGIN
						SELECT @CodNaturezaTransacao = NTR_CODI, @NomeNaturezaTransacao = NTR_NOME
						FROM TAB_NTRA WITH(NOLOCK)
						WHERE NTR_CODI = '11'
					END
-- gere a existência do Follow-Up
				IF (@CodFollowUp IS NOT NULL) AND (EXISTS(SELECT 1 FROM GIDWIN.dbo.FAP_FWUP WITH(NOLOCK) WHERE FUP_CODI = @CodFollowUp AND FUP_VUTI = 1))
					SET @CodFollowUp = NULL										
-- se cliente (exportador) não existir, assume como cliente o "Consumidor Final"							
				IF ISNULL(@Expedidor_Codigo, '') = '' 
				BEGIN
					SELECT TOP 1 @Expedidor_Codigo = CLI_CODI, @CodigoClienteCC = ISNULL(NULLIF(CLI_CCOR, ''), CLI_CODI)
					FROM TAB_CLIE WITH(NOLOCK) 
					WHERE CLI_INAC = 0 AND CLI_DESP = 1 AND CLI_NIF = '999999990'
				END
-- obtem o País e respetivo Câmbio para o Frete e Seguro							
				SELECT @CodPaisFreteSeguro = PAI_CODI 
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = 'EU'		
				SET @CambioFreteSeguro = dbo.FNT_Geral_ObtemCambio(1, @CodPaisFreteSeguro, @Data)
-- preenche o Tipo de Localização e Qualificador
				IF ISNULL(@LocMercadorias_CodLocalAutorizado, '') <> ''
				BEGIN
					SET @TipoLocalizacao = 'B'
					SET @Qualificador = 'Y'
				END
				ELSE
					IF ISNULL(@LocMercadorias_CodEstancia30, '') <> ''
					BEGIN
						SET @TipoLocalizacao = 'A'
						SET @Qualificador = 'V'
					END
					ELSE					
						IF ISNULL(@LocMercadorias_OutroLocal_Morada, '') <> ''
						BEGIN
							SET @TipoLocalizacao = 'D'
							SET @Qualificador = 'Z'
						END
						ELSE
							IF ISNULL(@LocMercadorias_CodLocalEmbarque, '') <> ''
							BEGIN
								SET @TipoLocalizacao = 'A'
								SET @Qualificador = 'U'
							END
							ELSE
							BEGIN
								SET @TipoLocalizacao = 'A'
								SET @Qualificador = 'V'
								SET @LocMercadorias_CodEstancia30 = @CodEstanciaA
							END						
-- se Morada da Localização das Mercadorias definida, preenche o País da Morada
				IF ISNULL(@LocMercadorias_OutroLocal_Morada, '') <> ''
					SET @CodPaisLocMercadorias = @Expedidor_CodPais
				ELSE
					SET @CodPaisLocMercadorias = NULL	
-- obtém dados do Aperfeiçoamento
				IF (@TipoProcedimento IN ('A', 'D')) AND (LEFT(ISNULL(@RegimeTipoDeclaracao, ''), 2) IN ('21', '22')) AND (@TipoDeclarante = 1) --tipo declarante como "Próprio"	
				BEGIN
					SET @CodEstanciaAperfeicoamento = @CodEstanciaA
					SET @PrazoApuramento = '*****N/A*****'
					SET @AtividadesPrevistas = '*****N/A*****'
				END	
				ELSE
				BEGIN
					SET @CodEstanciaAperfeicoamento = NULL
					SET @PrazoApuramento = NULL
					SET @AtividadesPrevistas = NULL
				END		
-- obtém a máscara de faturação do cliente/natureza
				SET @NumMascaras = 1
				SET @TipoMascara = 0
				SET @CodMascara = 0
				EXEC SP_ObtemMascaraFacturacao @CodigoClienteCC, @CodNatureza, @NumMascaras OUTPUT, @TipoMascara OUTPUT, @CodMascara OUTPUT
-- obtém se 1ª adição é "P" (Parte)
				SELECT TOP 1 @1AdicaoParte = a.m.value('P[1]', 'bit')
				FROM @Adicoes.nodes('Adicoes/Adicao[1]/MarcasEVolumes/MarcaEVolume') AS a(m)
			END
			ELSE
			BEGIN				
				SET @CodPaisCondEntrega = NULL
				SET @TextoCondEntrega = NULL
				SET @CodPaisFreteSeguro = NULL
				SET @CambioFreteSeguro = 0
				SET @TipoLocalizacao = 'B'
				SET @Qualificador = 'Y'
				SET @CodPaisLocMercadorias = NULL
				SET @AnexoB = 'B1'
				SET @RegimeTipoDeclaracao = NULL				
				SET @TipoMTFronteira = NULL
				SET @CodEstanciaAperfeicoamento = NULL
				SET @PrazoApuramento = NULL
				SET @AtividadesPrevistas = NULL
				SET @TipoMascara = 0 
				SET @CodMascara = NULL
				SET @1AdicaoParte = 0
				SET @NumReferenciaLocal = (STR(@AnoDeclaracao, 4) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 7 - LEN(CAST(@NumDeclaracao as varchar(10)))) + CAST(@NumDeclaracao as varchar(10)))
-- se Follow-Up não definido obtem Follow-Up do contexto "Exportação" configurado como estado inicial
				IF @CodFollowUp IS NULL 
				BEGIN
					SELECT TOP 1 @CodFollowUp = FUP_CODI 
					FROM GIDWIN.dbo.FAP_FWUP WITH(NOLOCK) 
					WHERE FUP_EINI = 1 and FUP_EXPO = 1
				END
			END
-- se ação for de "Insert"
			IF @Acao = 'I'
			BEGIN										
-- insere Dados Gerais da declaração			
				INSERT INTO PRO_EXML(EXM_EANO, EXM_CODI, DEC_CODI, EXM_TPRO, NDE_CODI, NDE_NOME, DEC_NOME, EXM_DATA, EXM_NRIN, EXM_NRLO, EXM_STAT, EAD_CODA, EAD_NOMA, TDE_COD1, TDE_NOM1, CLI_COD2, 
					CLI_NOM2, CLI_MOR2, CLI_LOC2, CLI_CPO2, CLI_LPO2, CLI_NIF2, CLI_PAI2, EXM_TP2A, EXM_TI2B, FOR_COD8, FOR_NOM8, FOR_MOR8, FOR_LOC8, FOR_CPO8, FOR_LPO8, FOR_NIF8, FOR_PAI8, 
					EXM_IROR, DEC_CO14, DEC_NO14, EXM_TP14, EXM_P15A, EXM_P17A, MTR_CO18, MTR_NO18, EXM_TP18, EXM_MT18, EXM_P18C, MTR_CO21, MTR_NO21, EXM_TP21, EXM_MT21, PAI_CO21, PAI_NO21, 
					MTR_CO25, MTR_CO26, CEN_CO20, CEN_NO20, EXM_FR20, EXM_LG20, NTR_CO24, NTR_NO24, PAI_CO22, PAI_MO22, EXM_UFOB, EXM_VFOB, EXM_TX23, EXM_TFRT, EXM_TSEG, EAD_CO29, EAD_NO29, 
					EAD_C29A, EAD_N29A, EAD_CO30, EAD_NO30, LEM_CO30, LEM_NO30, LME_CO30, LME_NO30, EXM_MR30, EXM_CP30, EXM_LP30, LEM_C30A, LEM_N30A, ARM_CO49, ARM_NO49, TAR_CO49, TAR_DE49, 
					EXM_ESTM, EXM_Q30C, EXM_UCRI, EXM_DTCR, EXM_UALT, EXM_DTAL, EXM_MASC, EXM_VLRC, EXM_CA54, FIN_CODI, EXM_NRII, EXM_NVRF, EXM_EXNO, EXM_EXMO, EXM_EXLC, EXM_EXCP, EXM_EXLP, 
					EXM_EXPS, EXM_EXCT, EXM_DENO, EXM_DEMO, EXM_DELC, EXM_DEPS, EXM_2P22, EXM_2M22, EXM_2MLQ, EXM_2MBR, EXM_CPRT, EXM_MCPA, EXM_TPCG, EXM_DTVO, EXM_DTYP, EXM_FUPS, EXM_CIEX, 
					EXM_CIDE, EXM_PPFC, EXM_NVOO, EXM_REF1, EXM_REF2, EXM_TRAC, EXM_SHIP, EXM_VDIR, SIN_CODI, SIN_DESP, EXM_INCE, EXM_NCMR, EXM_DTMP, EXM_TMSF, CLI_CODI, CLI_NOME, PAE_CODI, 
					PAE_NOME, EXM_ANOT, EXM_DINC, FUP_CODI, EXM_HVLV, EXM_CMPX, EXM_CNTX, PAI_CODI, EXM_TXTC, PAI_CODI2, EXM_CFRE, PAI_CODI3, EXM_CSEG, EXM_TLOC, EXM_QUAL, PAI_CODI5, EAD_CODI1, 
					EXM_PRZA, EXM_ATVP, EXM_ANXB, EXM_REGI, EXM_MTFT)
				OUTPUT inserted.EXM_IDTY INTO @TblID		
				VALUES(@AnoDeclaracao, @NumDeclaracao, @CodOperador, @TipoProcedimento, @CodNatureza, @NomeNatureza, @NomeDeclarante, @Data, CAST(@NumDeclaracao AS varchar(20)), @NumReferenciaLocal, 0, @CodEstanciaA, @NomeEstanciaA, @CodTipoDeclaracao, @NomeTipoDeclaracao, @Expedidor_Codigo, 
					@Expedidor_Nome, @Expedidor_Morada, @Expedidor_Localidade, @Expedidor_CodPostal, @Expedidor_LocPostal, @Expedidor_NIF, @Expedidor_CodPais, @TipoNIFCliente, @TipoIdCliente, @Destinatario_Codigo, @Destinatario_Nome, @Destinatario_Morada, @Destinatario_Localidade, @Destinatario_CodPostal, @Destinatario_LocPostal, @Destinatario_NIF, @Destinatario_CodPais, 
					@IndicadorRemessaFornecedor, @CodOperador, @NomeDeclarante, @TipoDeclarante, @CodPais15A, @CodPais17A, @MTPartida_CodMT, @NomeMTPartida, @MTPartida_TipoMT, @MTPartida_MatriculaMT, 0, @MTFronteira_CodMT, @NomeMTFronteira, @MTFronteira_TipoMT, @MTFronteira_MatriculaMT, @MTFronteira_CodPais, @NomePaisMTFronteira, 										
					@MTPartida_CodMT25, @MTPartida_CodMT26, @CodCondEntrega, @NomeCondEntrega, @DescricaoFormula, @Lugar, @CodNaturezaTransacao, @NomeNaturezaTransacao, @CodPais, @MoedaPais22, @FormulaFOB, 0, @CambioMoeda, @TotalFrete, @TotalSeguro, @CodEstanciaTAC, @NomeEstanciaTAC, 
					@CodEstanciaTN, @NomeEstanciaTN, @LocMercadorias_CodEstancia30, @NomeEstancia30, @LocMercadorias_CodLocalEmbarque, @DescricaoLocalEmbarque, @LocMercadorias_CodLocalAutorizado, @DescricaoLocalAutorizado, @LocMercadorias_OutroLocal_Morada, @LocMercadorias_OutroLocal_CodPostal, @LocMercadorias_OutroLocal_LocPostal, @CodLocalEmbarque, @DescricaoLocalEmbarque30A, @LocMercadorias_Armazem_CodArmazem, @NomeArmazem, @LocMercadorias_Armazem_CodTipoArmazem, @NomeTipoArmazem, 
					@LocMercadorias_Armazem_CodEstadoMembro, 0, @Utilizador, @DataAtual, @Utilizador, @DataAtual, @CodMascara, 0, @Casa54Declarante, @CodFormula, @NumDeclaracao, @VossaReferencia, @DadosManifesto_NomeExpedidor, @DadosManifesto_MoradaExpedidor, @DadosManifesto_LocalidadeExpedidor, @DadosManifesto_CodPostalExpedidor, @DadosManifesto_LocPostalExpedidor, 
					@DadosManifesto_CodPaisExpedidor, @DadosManifesto_NIFExpedidor, @DadosManifesto_NomeDestinatario, @DadosManifesto_MoradaDestinatario, @DadosManifesto_LocalidadeDestinatario, @DadosManifesto_CodPaisDestinatario, @DadosManifesto_CodPais, @DadosManifesto_Montante, @DadosManifesto_MassaLiqTotal, @DadosManifesto_MassaBrtTotal, @NumeroCPA, @DadosManifesto_MiniCPA, @TipoCarga, @DataVoo, @DadosManifesto_DutyType, @DadosManifesto_NomeFicheiro, @DadosManifesto_CodExpedidor, 
					@DadosManifesto_CodDestinatario, @DadosManifesto_PPouFC, @DadosManifesto_NumeroVoo, @DadosManifesto_Referencia1, @DadosManifesto_Referencia2, @DadosManifesto_Tracking, @DadosManifesto_Shipping, @DadosManifesto_VolsDirty, @CodStatusIncidencia, @DescricaoStatusIncidencia, @ICE, @NumeroComercialRef, @MetodoPagCondEntrega, @TipoMascara, @CodClienteServico, @NomeClienteServico, @MTPartida_CodAeroporto, 
					@NomeAeroporto, @Anotacoes, @DataStatusIncidencia, @CodFollowUp, @HVLV, @CamposExtra, @IntegracaoEXPCAU, @CodPaisCondEntrega, @TextoCondEntrega, @CodPaisFreteSeguro, @CambioFreteSeguro, @CodPaisFreteSeguro, @CambioFreteSeguro, @TipoLocalizacao, @Qualificador, @CodPaisLocMercadorias, @CodEstanciaAperfeicoamento, 
					@PrazoApuramento, @AtividadesPrevistas, @AnexoB, @RegimeTipoDeclaracao, @TipoMTFronteira)		
-- obtém ID da Declaração inserida
				SELECT @IdDeclaracao = ID
				FROM @TblID			
-- actualiza Nº. Prox. Declaração no Declarante
				IF @IntegracaoEXPCAU = 0
				BEGIN
					UPDATE TAB_DECL SET DEC_NPRO = ISNULL(DEC_NPRO, 0) + 1
					WHERE DEC_CODI = @CodOperador
				END
			END
			ELSE			
			BEGIN				
-- edita Dados Gerais da declaração	
				IF ISNULL(@CamposAdicionais, 0) = 8 --ENTREPOSTO
				BEGIN					
					SELECT @NumDeclaracao = t.c.value('ValorCampoExtra[1]', 'varchar(20)')
					FROM @CamposExtra.nodes('CamposExtra/CampoExtra') AS t(c)
					WHERE t.c.value('CodigoCampoExtra[1]', 'varchar(100)') = 'EXM_CODI'
				END
				ELSE
				BEGIN		
					UPDATE PRO_EXML SET EXM_TPRO = @TipoProcedimento, NDE_CODI = @CodNatureza, NDE_NOME = @NomeNatureza, DEC_NOME = @NomeDeclarante, EXM_DATA = @Data, 
						EXM_NRLO = @NumReferenciaLocal, EAD_CODA = @CodEstanciaA, EAD_NOMA = @NomeEstanciaA, TDE_COD1 = @CodTipoDeclaracao, TDE_NOM1 = @NomeTipoDeclaracao, 
						CLI_COD2 = @Expedidor_Codigo, CLI_NOM2 = @Expedidor_Nome, CLI_MOR2 = @Expedidor_Morada, CLI_LOC2 = @Expedidor_Localidade, CLI_CPO2 = @Expedidor_CodPostal, 
						CLI_LPO2 = @Expedidor_LocPostal, CLI_NIF2 = @Expedidor_NIF, CLI_PAI2 = @Expedidor_CodPais, EXM_TP2A = @TipoNIFCliente, EXM_TI2B = @TipoIdCliente, 
						FOR_COD8 = @Destinatario_Codigo, FOR_NOM8 = @Destinatario_Nome, FOR_MOR8 = @Destinatario_Morada, FOR_LOC8 = @Destinatario_Localidade, FOR_CPO8 = @Destinatario_CodPostal, 
						FOR_LPO8 = @Destinatario_LocPostal, FOR_NIF8 = @Destinatario_NIF, FOR_PAI8 = @Destinatario_CodPais, EXM_IROR = @IndicadorRemessaFornecedor, DEC_CO14 = @CodOperador, 
						DEC_NO14 = @NomeDeclarante, EXM_TP14 = @TipoDeclarante, EXM_P15A = @CodPais15A, EXM_P17A = @CodPais17A, MTR_CO18 = @MTPartida_CodMT, MTR_NO18 = @NomeMTPartida, 
						EXM_TP18 = @MTPartida_TipoMT, EXM_MT18 = @MTPartida_MatriculaMT, MTR_CO21 = @MTFronteira_CodMT, MTR_NO21 = @NomeMTFronteira, EXM_TP21 = @MTFronteira_TipoMT, 
						EXM_MT21 = @MTFronteira_MatriculaMT, PAI_CO21 = @MTFronteira_CodPais, PAI_NO21 = @NomePaisMTFronteira, MTR_CO25 = @MTPartida_CodMT25, MTR_CO26 = @MTPartida_CodMT26, 
						CEN_CO20 = @CodCondEntrega, CEN_NO20 = @NomeCondEntrega, EXM_FR20 = @DescricaoFormula, EXM_LG20 = @Lugar, NTR_CO24 = @CodNaturezaTransacao, 
						NTR_NO24 = @NomeNaturezaTransacao, PAI_CO22 = @CodPais, PAI_MO22 = @MoedaPais22, EXM_TX23 = @CambioMoeda, EXM_TFRT = @TotalFrete, EXM_TSEG = @TotalSeguro, 
						EAD_CO29 = @CodEstanciaTAC, EAD_NO29 = @NomeEstanciaTAC, EAD_C29A = @CodEstanciaTN, EAD_N29A = @NomeEstanciaTN, EAD_CO30 = @LocMercadorias_CodEstancia30, 
						EAD_NO30 = @NomeEstancia30, LEM_CO30 = @LocMercadorias_CodLocalEmbarque, LEM_NO30 = @DescricaoLocalEmbarque, LME_CO30 = @LocMercadorias_CodLocalAutorizado, 
						LME_NO30 = @DescricaoLocalAutorizado, EXM_MR30 = @LocMercadorias_OutroLocal_Morada, EXM_CP30 = @LocMercadorias_OutroLocal_CodPostal, 
						EXM_LP30 = @LocMercadorias_OutroLocal_LocPostal, LEM_C30A = @CodLocalEmbarque, LEM_N30A = @DescricaoLocalEmbarque30A, ARM_CO49 = @LocMercadorias_Armazem_CodArmazem, 
						ARM_NO49 = @NomeArmazem, TAR_CO49 = @LocMercadorias_Armazem_CodTipoArmazem, TAR_DE49 = @NomeTipoArmazem, EXM_ESTM = @LocMercadorias_Armazem_CodEstadoMembro, 
						EXM_UALT = @Utilizador, EXM_DTAL = @DataAtual, EXM_CA54 = @Casa54Declarante, FIN_CODI = @CodFormula, EXM_NVRF = @VossaReferencia, EXM_EXNO = @DadosManifesto_NomeExpedidor, 
						EXM_EXMO = @DadosManifesto_MoradaExpedidor, EXM_EXLC = @DadosManifesto_LocalidadeExpedidor, EXM_EXCP = @DadosManifesto_CodPostalExpedidor, 
						EXM_EXLP = @DadosManifesto_LocPostalExpedidor, EXM_EXPS = @DadosManifesto_CodPaisExpedidor, EXM_EXCT = @DadosManifesto_NIFExpedidor, 
						EXM_DENO = @DadosManifesto_NomeDestinatario, EXM_DEMO = @DadosManifesto_MoradaDestinatario, EXM_DELC = @DadosManifesto_LocalidadeDestinatario, 
						EXM_DEPS = @DadosManifesto_CodPaisDestinatario, EXM_2P22 = @DadosManifesto_CodPais, EXM_2M22 = @DadosManifesto_Montante, EXM_2MLQ = @DadosManifesto_MassaLiqTotal, 
						EXM_2MBR = @DadosManifesto_MassaBrtTotal, EXM_CPRT = @NumeroCPA, EXM_MCPA = @DadosManifesto_MiniCPA, EXM_TPCG = @TipoCarga, EXM_DTVO = @DataVoo, 
						EXM_DTYP = @DadosManifesto_DutyType, EXM_FUPS = @DadosManifesto_NomeFicheiro, EXM_CIEX = @DadosManifesto_CodExpedidor, EXM_CIDE = @DadosManifesto_CodDestinatario, 
						EXM_PPFC = @DadosManifesto_PPouFC, EXM_NVOO = @DadosManifesto_NumeroVoo, EXM_REF1 = @DadosManifesto_Referencia1, EXM_REF2 = @DadosManifesto_Referencia2, 
						EXM_TRAC = @DadosManifesto_Tracking, EXM_SHIP = @DadosManifesto_Shipping, EXM_VDIR = @DadosManifesto_VolsDirty, SIN_CODI = @CodStatusIncidencia, 
						SIN_DESP = @DescricaoStatusIncidencia, EXM_INCE = @ICE, EXM_NCMR = @NumeroComercialRef, EXM_DTMP = @MetodoPagCondEntrega, CLI_CODI = @CodClienteServico, 
						CLI_NOME = @NomeClienteServico, PAE_CODI = @MTPartida_CodAeroporto, PAE_NOME = @NomeAeroporto, EXM_DINC = @DataStatusIncidencia, FUP_CODI = @CodFollowUp, EXM_HVLV = @HVLV, 
						EXM_CMPX = @CamposExtra
					WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND DEC_CODI = @CodOperador
				END
-- remove todos os Contentores existentes na declaração
				DELETE FROM PRO_EXCT
				WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND EXM_COPE = @CodOperador
-- remove todas as Adições existentes na declaração
				SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de DELETE não ser processado
				DELETE FROM PRO_EXAD				
				WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND EXM_COPE = @CodOperador
				SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
			END
-- carrega Contentores XML da declaração
			DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT XML_CONT.CON_DATA.value('NumeroContentor[1]', 'varchar(50)')
				FROM @Contentores.nodes('Contentores/Contentor') as XML_CONT(CON_DATA)
			OPEN Contentores
			FETCH NEXT from Contentores into @NumeroContentor
			WHILE @@FETCH_STATUS = 0
			BEGIN			
-- obtem dados em falta
				SELECT @NumLinhaContentor = @NumLinhaContentor + 1
-- insere Contentor na declaração
				INSERT INTO PRO_EXCT(EXM_EANO, EXM_CODI, EXM_COPE, EXC_LINH, EXC_CONT)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @CodOperador, @NumLinhaContentor, @NumeroContentor)				
				FETCH NEXT from Contentores into @NumeroContentor
			END
			CLOSE Contentores
			DEALLOCATE Contentores
-- carrega Documentos da 1ª adição na declaração EXP-CAU quando o período transitório inativo
			IF (@Acao = 'I') AND (@IntegracaoEXPCAU = 1) AND (@PeriodoTransitorio = 0)
			BEGIN
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT a.d.value('CodDocumento[1]', 'varchar(5)'), NULLIF(a.d.value('NumeroReferencia[1]', 'varchar(50)'), '')
					FROM @Adicoes.nodes('Adicoes/Adicao[1]/Documentos/Documento') AS a(d)
				OPEN Documentos
				FETCH NEXT FROM Documentos INTO @CodDocumento, @NumeroReferencia
				WHILE @@FETCH_STATUS = 0
				BEGIN	
-- inicia variáveis
					SET @IdDocumento = NULL
					SET @TipoDocumento = NULL
-- obtem dados do documento
					SELECT @IdDocumento = DOC_IDTY, @TipoDocumento = DOC_DTRA, 
						@NumeroReferencia = ISNULL(@NumeroReferencia, (CASE DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END))
					FROM TAB_DOCU WITH(NOLOCK)
					WHERE DOC_CODI = @CodDocumento									
-- insere o documento no detalhe de documentos e certificados na nova declaracao EXP-CAU
					INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, id_utilizadorControlo, dataControlo)
					VALUES (@IdDeclaracao, @TipoDocumento, @IdDocumento, @NumeroReferencia, @IdUtilizador, @DataAtual)	
					FETCH NEXT FROM Documentos INTO @CodDocumento, @NumeroReferencia
				END
				CLOSE Documentos
				DEALLOCATE Documentos
			END
-- obtem o total de massa bruta e número de adições total existentes no xml da declaração
			SELECT @MassaBrtTotalAdicoesXML = SUM(ISNULL(XML_ADIC.ADI_DATA.value('MassaBruta[1]', 'numeric(38, 6)'), 0)), @NumTotalAdicoesXML = COUNT(*)
			FROM @Adicoes.nodes('Adicoes/Adicao') as XML_ADIC(ADI_DATA)			
-- carrega Adições XML da declaração
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT XML_ADIC.ADI_DATA.value('NumeroAdicao[1]', 'int'), XML_ADIC.ADI_DATA.value('CodArtigo[1]', 'varchar(22)'), XML_ADIC.ADI_DATA.value('DesignacaoArtigo[1]', 'varchar(150)'), 
					NULLIF(XML_ADIC.ADI_DATA.value('CodPaisOrigem[1]', 'varchar(2)'), ''), ISNULL(XML_ADIC.ADI_DATA.value('MassaBruta[1]', 'numeric(38, 6)'), 0), 
					ISNULL(XML_ADIC.ADI_DATA.value('MassaLiquida[1]', 'numeric(38, 6)'), 0),  XML_ADIC.ADI_DATA.value('Regime[1]', 'varchar(4)'), 
					NULLIF(XML_ADIC.ADI_DATA.value('Desdobramento[1]', 'varchar(3)'), ''), ISNULL(XML_ADIC.ADI_DATA.value('QtdUnidades[1]', 'numeric(38, 6)'), 0), 
					ISNULL(XML_ADIC.ADI_DATA.value('ValorAdicao[1]', 'numeric(38, 6)'), 0), ISNULL(XML_ADIC.ADI_DATA.value('ValorFrete[1]', 'numeric(38, 6)'), 0), 
					ISNULL(XML_ADIC.ADI_DATA.value('ValorSeguro[1]', 'numeric(38, 6)'), 0), XML_ADIC.ADI_DATA.query('DocsPrecedentes'), XML_ADIC.ADI_DATA.query('RegimesEconomicos'), 
					XML_ADIC.ADI_DATA.query('Documentos'), XML_ADIC.ADI_DATA.query('MencoesEspeciais'), XML_ADIC.ADI_DATA.query('MarcasEVolumes')
				FROM @Adicoes.nodes('Adicoes/Adicao') as XML_ADIC(ADI_DATA)
			OPEN Adicoes
			FETCH NEXT from Adicoes into @NumeroAdicao, @CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @MassaBruta, @MassaLiquida, @Regime, @Desdobramento, @QtdUnidades, @ValorAdicao, @ValorFrete, @ValorSeguro, 
				@DocsPrecedentes, @RegimesEconomicos, @Documentos, @MencoesEspeciais, @MarcasEVolumes
			WHILE @@FETCH_STATUS = 0
			BEGIN	
				DELETE FROM @TblID
				SET @IDAdicao = NULL	
-- obtem dados do Artigo Pautal
				SELECT @CodPautal = APA_CPAU, @CodUnidSuplementar = USU_CODI, @IndicadorArtigo = APA_INDI, @AnexoCArtigo = APA_ANXC, @AnexoDArtigo = APA_ANXD, @CodMercPerigosasArtigo = APA_ATAR, 
					@CodigoIC1Artigo = APA_AIC1, @CodigoIC2Artigo = APA_AIC2, @CodigoIC3Artigo = APA_AIC3, @CodigoIC4Artigo = APA_AIC4, @CodigoIC5Artigo = APA_AIC5, @CodigoCUSArtigo = APA_CCUS, 
					@QtdUnidades = (CASE WHEN (@QtdUnidades > 0) AND (ISNULL(USU_CODI, '') = '') THEN 0 ELSE @QtdUnidades END)
				FROM TAB_APAU WITH (NOLOCK)
				WHERE APA_CODI = @CodArtigo					
-- obtem dados da Unidade Suplementar
				SELECT @NomeUnidSuplementar = USU_SIGL
				FROM TAB_USUP WITH (NOLOCK)
				WHERE USU_CODI = @CodUnidSuplementar
-- se declaração tiver valor de frete e adição não descrimar frete, efetua o calculo do frete p/ a adição c/ base no valor da massa bruta
				IF (@TotalFrete > 0) AND (@ValorFrete = 0)
				BEGIN
					IF @NumeroAdicao < @NumTotalAdicoesXML						
						SET @ValorFrete = ROUND(@TotalFrete * @MassaBruta / @MassaBrtTotalAdicoesXML, 3)
					ELSE
						SET @ValorFrete = @ValorRestanteFrete
					SET @ValorRestanteFrete = @ValorRestanteFrete - @ValorFrete
				END				
-- obtem dados do País Origem
				SELECT @NomePaisOrigem = PAI_NOME
				FROM TAB_PAIS WITH (NOLOCK)
				WHERE PAI_CODI = @CodPaisOrigem	
-- processa calculos específicos relacionados com contexto EXP-CAU ou EXP/XML
				IF @IntegracaoEXPCAU = 1
				BEGIN	
					SET @CodMercPerigosasArtigo = NULL
					IF @AnexoB <> 'B1'
						SET @CodigoCUSArtigo = NULL
					SET @RegimesEconomicos = NULL
					SET @MencoesEspeciais = NULL
					IF (@PeriodoTransitorio = 0) AND (@NumeroAdicao = 1)
						SET @Documentos = NULL
					IF (@1AdicaoParte = 1) AND (@NumeroAdicao > 1)
						SET @MarcasEVolumes = NULL
					IF @Regime <> ISNULL(@RegimeTipoDeclaracao, '')
						RAISERROR('Regime "%s" inválido.', 16, 2, @Regime)
-- calcula adicionais TARIC
					SET @AdicionalTARIC1Artigo = SUBSTRING(@CodPautal, 11, 4)
					SET @AdicionalTARIC2Artigo = SUBSTRING(@CodPautal, 15, 4)
					SET @AdicionalTARIC3Artigo = SUBSTRING(@CodPautal, 19, 4)
-- calcula ajustamento (usa a função IMP porque a formula de cálculo é a mesma para EXP)
					SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@DescricaoFormula, 0, @CambioFreteSeguro, @CambioFreteSeguro, @valorFrete, @valorSeguro, 0, 0, 0)
-- calcula valor estatístico
					SET @ValorEstatistico = (ROUND(@ValorAdicao / @CambioMoeda, 2) + @Ajustamento)
-- obtém o ID do desdobramento do regime
					SELECT TOP 1 @IdDesdobramento = id
					FROM tb_TBL_Desdobramentos WITH(NOLOCK)
					WHERE tipoDeclaracao = ISNULL(@1CasaTipoDeclaracao, '') AND regime = @Regime AND desdobramento1 = ISNULL(@Desdobramento, '')
				END
				ELSE
				BEGIN
					SET @AdicionalTARIC1Artigo = NULL
					SET @AdicionalTARIC2Artigo = NULL
					SET @AdicionalTARIC3Artigo = NULL
					SET @CodigoIC1Artigo = NULL
					SET @CodigoIC2Artigo = NULL
					SET @CodigoIC3Artigo = NULL
					SET @CodigoIC4Artigo = NULL
					SET @CodigoIC5Artigo = NULL
					SET @CodigoCUSArtigo = NULL
					SET @IdDesdobramento = NULL
					SET @Ajustamento = 0
-- calcula valor estatístico
					SET @ValorEstatistico = (ROUND(@ValorAdicao / @CambioMoeda, 3) - @ValorFrete - @ValorSeguro)
-- obtem dados do pais "PT"/"EU" se Pais Origem não preenchido
					IF @CodPaisOrigem IS NULL	
					BEGIN
						IF @IndicadorArtigo = 'RE'
						BEGIN
							SELECT @CodPaisOrigem = PAI_CODI 
							FROM TAB_PAIS WITH (NOLOCK)
							WHERE PAI_CODI = 'EU'
						END
						ELSE
						BEGIN
							SELECT @CodPaisOrigem = PAI_CODI 
							FROM TAB_PAIS WITH (NOLOCK)
							WHERE PAI_CODI = 'PT'
						END
					END	
				END
-- insere Adições na declaração		
				SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de INSERT não ser processado
				INSERT INTO PRO_EXAD(EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CO33, APA_CP33, APA_DESG, PAI_CODI, PAI_NOME, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, USU_CODI, USU_SIGL, EXA_VALO, 
					EXA_VFRE, EXA_VSEG, EXA_VEST, EXA_IRES, EXA_ANXC, EXA_ANXD, TDE_REGI, EXA_ATAR, EXA_ATA1, EXA_ATA2, EXA_ATA3, EXA_AIC1, EXA_AIC2, EXA_AIC3, EXA_AIC4, EXA_AIC5, EXA_CCUS, 
					id_desdobramento, EXA_AJUS)
				OUTPUT inserted.EXA_CHVE INTO @TblID	
				VALUES(@AnoDeclaracao, @NumDeclaracao, @CodOperador, @NumeroAdicao, @CodArtigo, @CodPautal, @DesignacaoArtigo, @CodPaisOrigem, @NomePaisOrigem, @MassaBruta, @Desdobramento, @MassaLiquida, @QtdUnidades, @CodUnidSuplementar, @NomeUnidSuplementar, @ValorAdicao, 
					@ValorFrete, @ValorSeguro, @ValorEstatistico, @IndicadorArtigo, @AnexoCArtigo, @AnexoDArtigo, @Regime, @CodMercPerigosasArtigo, @AdicionalTARIC1Artigo, @AdicionalTARIC2Artigo, @AdicionalTARIC3Artigo, @CodigoIC1Artigo, @CodigoIC2Artigo, @CodigoIC3Artigo, @CodigoIC4Artigo, @CodigoIC5Artigo, @CodigoCUSArtigo, 
					@IdDesdobramento, @Ajustamento)
				SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
-- obtém ID da Adição inserida
				SELECT @IDAdicao = ID
				FROM @TblID
-- incrementa variaveis
				SELECT @TotalAdicoes = @TotalAdicoes + 1, @MontanteTotal = @MontanteTotal + @ValorAdicao, @MassaLiquidaTotal = @MassaLiquidaTotal + @MassaLiquida, 
					@MassaBrutaTotal = @MassaBrutaTotal + @MassaBruta, @NumLinhaDocPrecedente = 0					
-- carrega Documentos XML da adição
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)'), NULLIF(XML_DOCS.DOC_DATA.value('NumeroReferencia[1]', 'varchar(50)'), ''), 
						XML_DOCS.DOC_DATA.value('DataEmissao[1]', 'datetime'), XML_DOCS.DOC_DATA.value('DataFimValidade[1]', 'datetime')				
					FROM @Documentos.nodes('Documentos/Documento') as XML_DOCS(DOC_DATA)
				OPEN Documentos
				FETCH NEXT from Documentos into @CodDocumento, @NumeroReferencia, @DataEmissao, @DataFimValidade
				WHILE @@FETCH_STATUS = 0
				BEGIN	
-- obtem dados do Documento
					SELECT @NomeDocumento = DOC_NOME, @TipoDocumento = DOC_DTRA, 
						@NumeroReferencia = ISNULL(@NumeroReferencia, (CASE DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END)), 
						@DataEmissao = ISNULL(@DataEmissao, (CASE DOC_TDDT WHEN 1 THEN @Data ELSE NULL END))
					FROM TAB_DOCU WITH (NOLOCK)	
					WHERE DOC_CODI = @CodDocumento				
-- processa calculos específicos relacionados com contexto EXP-CAU ou EXP/XML
					IF @IntegracaoEXPCAU = 1
					BEGIN	
						SET @DataEmissao = NULL 
						SET @DataFimValidade = NULL
						IF ISNULL(@NumeroReferencia, '') = ''
							SET @NumeroReferencia = '*****N/A*****'
						IF (@TipoDocumento = 0) AND (LEFT(@CodDocumento, 1) = 'X') 
						BEGIN
							SET @QtdDocumento = @MassaBruta
-- obtem dados da Unidade de Medida "KGM"
							SELECT @CodUnidMedida = UME_CODI, @NomeUnidMedida = UME_NOME
							FROM TAB_UMED WITH (NOLOCK)
							WHERE UME_CODI = 'KGM'
						END
						ELSE
						BEGIN
							SET @QtdDocumento = 0
							SET @CodUnidMedida = NULL
							SET @NomeUnidMedida = NULL
						END
						IF @TipoDocumento = 0
							SET @NumAdicaoDocumento = @NumeroAdicao
						ELSE
							SET @NumAdicaoDocumento = NULL
					END
					ELSE
					BEGIN
						SET @QtdDocumento = (CASE @CodDocumento WHEN 'X001' THEN @MassaLiquida ELSE 0 END)
						SET @CodUnidMedida = NULL
						SET @NomeUnidMedida = NULL
						SET @NumAdicaoDocumento = NULL
					END
-- insere Documento na adição
					INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EXD_DTFV, EXD_MONT, EXD_QNTD, UME_CODI, UME_NOME, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, 
						EXD_NADI)
					VALUES(@IDAdicao, @CodDocumento, @NomeDocumento, @NumeroReferencia, @DataEmissao, @DataFimValidade, 0, @QtdDocumento, @CodUnidMedida, @NomeUnidMedida, @AnoDeclaracao, @NumDeclaracao, @CodOperador, @NumeroAdicao, @TipoDocumento, 
						@NumAdicaoDocumento)			
					FETCH NEXT from Documentos into @CodDocumento, @NumeroReferencia, @DataEmissao, @DataFimValidade
				END
				CLOSE Documentos
				DEALLOCATE Documentos
-- carrega Menções Especiais XML da adição
				DECLARE Mencoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_MENS.MEN_DATA.value('CodMencao[1]', 'varchar(8)')
					FROM @MencoesEspeciais.nodes('MencoesEspeciais/MencaoEspecial') as XML_MENS(MEN_DATA)
				OPEN Mencoes
				FETCH NEXT from Mencoes into @CodMencao
				WHILE @@FETCH_STATUS = 0
				BEGIN	
-- obtem dados da Menção Especial
					SELECT @DesignacaoMencao = INF_DESI
					FROM TAB_INFC WITH (NOLOCK)
					WHERE INF_CODI = @CodMencao				
-- insere Menção Especial na adição
					INSERT INTO PRO_EXME(EXA_CHVE, INF_CODI, INF_DESI)
					VALUES(@IDAdicao, @CodMencao, @DesignacaoMencao)			
					FETCH NEXT from Mencoes into @CodMencao
				END
				CLOSE Mencoes
				DEALLOCATE Mencoes								
-- carrega Marcas e Volumes XML da adição
				DECLARE MarcasEVols CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT NULLIF(XML_VOLS.VOL_DATA.value('Marca[1]', 'varchar(44)'), ''), XML_VOLS.VOL_DATA.value('CodNaturezaVols[1]', 'varchar(2)'),  
						XML_VOLS.VOL_DATA.value('NumeroVols[1]', 'numeric(38, 6)'), XML_VOLS.VOL_DATA.value('P[1]', 'bit'), XML_VOLS.VOL_DATA.value('R[1]', 'bit') 
					FROM @MarcasEVolumes.nodes('MarcasEVolumes/MarcaEVolume') AS XML_VOLS(VOL_DATA)
				OPEN MarcasEVols
				FETCH NEXT FROM MarcasEVols INTO @Marca, @CodNaturezaVols, @NumeroVols, @P, @R
				WHILE @@FETCH_STATUS = 0
				BEGIN	
-- obtem dados do Tipo de Embalagem
					SELECT @NomeTipoEmbalagem = TEM_NOME, @VolsAZeroTipoEmbalagem = TEM_TVOL
					FROM TAB_TEMB WITH (NOLOCK)
					WHERE TEM_CODI = @CodNaturezaVols	
-- processa calculos específicos relacionados com contexto EXP-CAU ou EXP/XML
					IF @IntegracaoEXPCAU = 1
					BEGIN	
						SET @AnoDeclaracaoMarcaEVol = @AnoDeclaracao
						SET @NumDeclaracaoMarcaEVol = @NumDeclaracao
						SET @CodOperadorMarcaEVol = @CodOperador
						SET @R = 0
						IF @VolsAZeroTipoEmbalagem = 1
						BEGIN
							SET @NumeroVols = 0
							SET @Marca = NULL
						END
						ELSE
							IF @NumeroVols = 0
								RAISERROR('Volumes inválido.', 16, 3)
							ELSE
								IF (ISNULL(@Marca, '') = '') AND (@CodNaturezaVols NOT IN ('NE', 'NF', 'NG'))
									RAISERROR('Marcas inválidas.', 16, 4)
					END
					ELSE
					BEGIN
						SET @AnoDeclaracaoMarcaEVol = NULL
						SET @NumDeclaracaoMarcaEVol = NULL
						SET @CodOperadorMarcaEVol = NULL						
					END								
-- obtem dados em falta
					SELECT @IDStrMarcaEVol = REPLACE(CONVERT(numeric(38, 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), '.', ',')
-- insere Marcas e Volumes na adição
					SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de INSERT não ser processado
					INSERT INTO PRO_EXMV(EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_REST, EXM_TVOL, EXM_IDST, EXM_EANO, EXM_CODI, EXM_COPE)
					VALUES(@IDAdicao, @Marca, @CodNaturezaVols, @NomeTipoEmbalagem, @NumeroVols, @P, @R, @VolsAZeroTipoEmbalagem, @IDStrMarcaEVol, @AnoDeclaracaoMarcaEVol, @NumDeclaracaoMarcaEVol, @CodOperadorMarcaEVol)
					SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
-- incrementa variaveis
					IF (@IntegracaoEXPCAU = 1) OR ((@IntegracaoEXPCAU = 0) AND (((@P = 0) AND (@R = 0)) OR (@R = 1)))
						SET @TotalVolumes = @TotalVolumes + @NumeroVols				
					FETCH NEXT FROM MarcasEVols INTO @Marca, @CodNaturezaVols, @NumeroVols, @P, @R
				END
				CLOSE MarcasEVols
				DEALLOCATE MarcasEVols
-- carrega Documentos Precedentes XML da adição
				DECLARE DocsPrecedentes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_DOCS.DOC_DATA.value('Tipo[1]', 'varchar(1)'), XML_DOCS.DOC_DATA.value('CodDocumento[1]', 'varchar(5)'), 
						XML_DOCS.DOC_DATA.value('RefDocumento[1]', 'varchar(20)'), XML_DOCS.DOC_DATA.value('CodPais[1]', 'varchar(2)'), 
						XML_DOCS.DOC_DATA.value('DataDocumento[1]', 'datetime')
					FROM @DocsPrecedentes.nodes('DocsPrecedentes/DocPrecedente') as XML_DOCS(DOC_DATA)
				OPEN DocsPrecedentes
				FETCH NEXT from DocsPrecedentes into @TipoDocPrecedente, @CodDocumento, @RefDocPrecedente, @CodPais, @DataDocumento
				WHILE @@FETCH_STATUS = 0
				BEGIN										
-- processa inserção de Documento Precedente na adição em função se EXP-CAU ou EXP/XML
					IF @IntegracaoEXPCAU = 1
					BEGIN
						SET @IdDocumento = NULL
						SET @IdUnidadeMedidaVolumes = NULL
						SET @VolumesPrecedente = NULL
						SET @IdUnidadeMedidaQualificador = NULL
-- obtem dados do Documento
						SELECT @IdDocumento = DOC_IDTY
						FROM TAB_DOCU WITH (NOLOCK)
						WHERE DOC_CODI = @CodDocumento
-- obtem dados da unidade de medida de volumes no detalhe de Marcas&Volumes da adição
						SELECT TOP 1 @VolumesPrecedente = NULLIF(dam.EXM_NVOL, 0), @IdUnidadeMedidaVolumes = ume.UME_IDTY
						FROM PRO_EXMV AS dam WITH(NOLOCK)
							LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON dam.TEM_CODI = ume.UME_CODI
						WHERE dam.EXA_CHVE = @IDAdicao
						ORDER BY dam.EXM_CHVE
-- obtem dados da unidade de medida do qualificador
						SELECT @IdUnidadeMedidaQualificador = UME_IDTY
						FROM TAB_UMED WITH(NOLOCK)
						WHERE UME_EXPT = 1 AND UME_CODI = 'KGM'
-- insere Documento Precedente na adição
						INSERT INTO tb_EXP_DeclaracoesAdicoesPrecedentes(id_adicao, id_documento, numero, numeroAdicao, id_unidadeMedidaVolumes, volumes, 
							id_unidadeMedidaQualificador, quantidade, id_utilizadorControlo, dataControlo)
						VALUES(@IDAdicao, @IdDocumento, @RefDocPrecedente, @NumeroAdicao, @IdUnidadeMedidaVolumes, @VolumesPrecedente, 
							@IdUnidadeMedidaQualificador, @MassaBruta, @IdUtilizador, @DataAtual)
					END
					ELSE
					BEGIN
						SET @NumLinhaDocPrecedente = @NumLinhaDocPrecedente + 1
-- obtem dados do País
						SELECT @NomePais = PAI_NOME
						FROM TAB_PAIS WITH (NOLOCK)
						WHERE PAI_CODI = @CodPais									
-- insere Documento Precedente na adição
						INSERT INTO PRO_EXDS(EXA_CHVE, EXD_TIMP, DOC_CODI, EXD_DESC, PAI_CODI, PAI_NOME, EXD_DATA, EXD_NUME)
						VALUES(@IDAdicao, @TipoDocPrecedente, @CodDocumento, @RefDocPrecedente, @CodPais, @NomePais, @DataDocumento, @NumLinhaDocPrecedente)
					END
					FETCH NEXT from DocsPrecedentes into @TipoDocPrecedente, @CodDocumento, @RefDocPrecedente, @CodPais, @DataDocumento
				END
				CLOSE DocsPrecedentes
				DEALLOCATE DocsPrecedentes
-- carrega Regimes Económicos XML da adição
				DECLARE RegsEconomicos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT XML_REGE.REG_DATA.value('NumeroDocPrecedente[1]', 'varchar(20)'), XML_REGE.REG_DATA.value('AdicaoDocPrecedente[1]', 'int'), 
						XML_REGE.REG_DATA.value('CodArtigoPautal[1]', 'varchar(22)'), XML_REGE.REG_DATA.value('Quantidade[1]', 'numeric(38, 6)'), 
						XML_REGE.REG_DATA.value('CodUnidMedida[1]', 'varchar(3)')
					FROM @RegimesEconomicos.nodes('RegimesEconomicos/RegimeEconomico') as XML_REGE(REG_DATA)
				OPEN RegsEconomicos
				FETCH NEXT FROM RegsEconomicos INTO @NumeroDocPrecedente, @AdicaoDocPrecedente, @CodArtigoPautal, @Quantidade, @CodUnidMedida
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @CodArtigo = NULL
					SET @DesignacaoArtigo = NULL
					SET @NomeUnidMedida = NULL
					SET @NumLinhaDocPrecedente = NULL				
-- obtem dados do Artigo
					SELECT TOP 1 @CodArtigo = APA_CODI, @DesignacaoArtigo = APA_DESG
					FROM TAB_APAU WITH (NOLOCK)
					WHERE APA_INAC = 0 AND APA_CPAU = @CodArtigoPautal	
-- obtem dados da Unidade de Medida
					SELECT @NomeUnidMedida = UME_NOME
					FROM TAB_UMED WITH (NOLOCK)
					WHERE UME_EXPT = 1 AND UME_CODI = @CodUnidMedida
-- obtem dados do documento precedente na adição
					SELECT TOP 1 @NumLinhaDocPrecedente = EXD_NUME
					FROM PRO_EXDS WITH(NOLOCK)
					WHERE EXA_CHVE = @IDAdicao AND EXD_TIMP = 'Z' AND EXD_DESC = @NumeroDocPrecedente
-- insere Regime Económico na adição
					INSERT INTO PRO_EXCR(EXA_CHVE, APA_CODI, APA_DESG, EXC_QNTD, UME_CODI, UME_NOME, EXC_LINH, EXC_NADI)
					VALUES(@IDAdicao, @CodArtigo, @DesignacaoArtigo, @Quantidade, @CodUnidMedida, @NomeUnidMedida, @NumLinhaDocPrecedente, @AdicaoDocPrecedente)								
					FETCH NEXT FROM RegsEconomicos INTO @NumeroDocPrecedente, @AdicaoDocPrecedente, @CodArtigoPautal, @Quantidade, @CodUnidMedida
				END
				CLOSE RegsEconomicos
				DEALLOCATE RegsEconomicos
				FETCH NEXT from Adicoes into @NumeroAdicao, @CodArtigo, @DesignacaoArtigo, @CodPaisOrigem, @MassaBruta, @MassaLiquida, @Regime, @Desdobramento, @QtdUnidades, @ValorAdicao, @ValorFrete, @ValorSeguro, 
					@DocsPrecedentes, @RegimesEconomicos, @Documentos, @MencoesEspeciais, @MarcasEVolumes
			END
			CLOSE Adicoes
			DEALLOCATE Adicoes
-- processa criação de diretoria no arquivo documental para os arquivos a anexar unicamente para declaração de Exportação/XML
			IF (@IntegracaoEXPCAU = 0) AND (ISNULL(CAST(@Arquivos AS varchar(MAX)), '') <> '')
			BEGIN
-- procede à alteração da diretoria de dicionários para a diretoria de arquivo documental
				SET @DirArquivos = REPLACE(@DirArquivos, '\MSGS\DICS', '\DOCUMENTOS\EXPORTACAO')
-- verifica se diretoria tem backslash no final	
				IF SUBSTRING(REVERSE(@DirArquivos), 1, 1) <> '\'
					SET @DirArquivos = @DirArquivos + '\'					
-- constroi path completa diretoria dos anexos da declaração de Exportação
				SET @DirArquivos = @DirArquivos + CAST(@AnoDeclaracao AS varchar(4)) + '\' + @CodOperador + '\DEC' + @NumReferenciaLocal + '\'
-- processa a criação diretoria dos anexos da declaração de Exportação
				EXEC GIDWIN.dbo.SP_Externo_CriaDiretoria @DirArquivos, @AuxMsgErro OUTPUT
				IF ISNULL(@AuxMsgErro, '') <> ''
					RAISERROR ('Não foi possível criar a diretoria "%s"! ERRO: "%s".', 16, 5, @PathFicheiro, @AuxMsgErro)								
			END
-- carrega arquivos XML da declaração
			DECLARE Arquivos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT t.a.value('NomeArquivo[1]', 'varchar(100)'), 
					t.a.value('DescricaoArquivo[1]', 'varchar(150)'), 
					NULLIF(t.a.value('TipoArquivo[1]', 'varchar(8)'), ''), 
					t.a.value('OrigemArquivo[1]', 'int'),
					t.a.value('FicheiroBase64[1]', 'varchar(MAX)')
				FROM @Arquivos.nodes('Arquivos/Arquivo') AS t(a)
			OPEN Arquivos
			FETCH NEXT FROM Arquivos INTO @NomeFicheiro, @DescricaoFicheiro, @TipoFicheiro, @OrigemFicheiro, @FicheiroBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN							
-- obtem extensão do ficheiro a anexar
				SET @ExtFicheiro = REVERSE(SUBSTRING(REVERSE(@NomeFicheiro), 1, CHARINDEX('.', REVERSE(@NomeFicheiro))))
-- converte o Base64 para varbinary 
				SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@FicheiroBase64"))', 'varbinary(MAX)')
-- processa calculos específicos relacionados com contexto EXP-CAU ou EXP/XML
				IF @IntegracaoEXPCAU = 1
				BEGIN
					SET @PathFicheiro = NULL
					IF ISNULL(@TipoFicheiro, '') = ''
					BEGIN
						SET @TipoFicheiro = 'OUTRO'
						SET @FicheiroImprSerie = 0
					END
					ELSE
						SET @FicheiroImprSerie = 1											
				END
				ELSE
				BEGIN
					SET @FicheiroImprSerie = 0
-- constroi path completa c/ novo nome p/ ficheiro a anexar
					SET @PathFicheiro = @DirArquivos + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(50), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121), '-', ''), ':', ''), '.', ''), ' ', '') + REPLICATE('0', (8 - LEN(CAST(@NumDeclaracao AS varchar(8))))) + CAST(@NumDeclaracao AS varchar(8)) + @ExtFicheiro
-- gera o ficheiro a anexar no arquivo documental
					BEGIN TRY
						EXEC sp_OACreate 'ADODB.Stream', @Obj OUTPUT
						EXEC sp_OASetProperty @Obj, 'Type', 1
						EXEC sp_OAMethod @Obj, 'Open'
						EXEC sp_OAMethod @Obj, 'Write', NULL, @FicheiroBinario
						EXEC sp_OAMethod @Obj, 'SaveToFile', NULL, @PathFicheiro, 2
						EXEC sp_OAMethod @Obj, 'Close'
						EXEC sp_OADestroy @Obj
					END TRY    
					BEGIN CATCH
						EXEC sp_OADestroy @Obj
					END CATCH
					SET @FicheiroBinario = NULL
				END						
-- insere arquivo na declaração
				INSERT INTO PRO_EXFI(EXM_EANO, EXM_CODI, DEC_CODI, EXF_DESC, EXF_LINK, EXF_DATA, EXF_UTIL, EXF_NOMF, EXF_ISER, EXF_TMSG, EXF_ORIG, EXF_FICH)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @CodOperador, @DescricaoFicheiro, @PathFicheiro, @DataAtual, @Utilizador, @NomeFicheiro, @FicheiroImprSerie, @TipoFicheiro, @OrigemFicheiro, @FicheiroBinario)						
				FETCH NEXT FROM Arquivos INTO @NomeFicheiro, @DescricaoFicheiro, @TipoFicheiro, @OrigemFicheiro, @FicheiroBase64
			END
			CLOSE Arquivos
			DEALLOCATE Arquivos
-- actualiza campos totalizadores na declaração
			UPDATE PRO_EXML SET EXM_TAD5 = @TotalAdicoes, EXM_TVL6 = @TotalVolumes, EXM_CT19 = (CASE @NumLinhaContentor WHEN 0 THEN 0 ELSE 1 END), 
				EXM_MT22 = (CASE (SELECT COUNT(*) FROM PRO_EXAD AS adi INNER JOIN PRO_EXDA AS doc ON adi.EXA_CHVE = doc.EXA_CHVE WHERE adi.EXM_EANO = PRO_EXML.EXM_EANO and adi.EXM_CODI = PRO_EXML.EXM_CODI and adi.EXM_COPE = PRO_EXML.DEC_CODI and doc.DOC_CODI = '9E06') WHEN 0 THEN @MontanteTotal ELSE 0 END), 
				EXM_TMLQ = @MassaLiquidaTotal, EXM_TMBR = @MassaBrutaTotal, EXM_TREM = @MassaBrutaTotal, EXM_VEUR = ROUND(@MontanteTotal / @CambioMoeda, 2), EXM_VATT = @MontanteTotal
			WHERE EXM_EANO = @AnoDeclaracao and EXM_CODI = @NumDeclaracao and DEC_CODI = @CodOperador
		END TRY
		BEGIN CATCH							
-- constroi mensagem de erro detalhada
			SELECT @MensagemErro = ISNULL(@MensagemErro, '') + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '** ERRO DE DECLARACAO NAO INSERIDA ***********************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Carta de Porte N.º:' + ISNULL(@NumeroCPA, (@CodOperador + '/' + CONVERT(varchar(10), @Data, 105))) + CHAR(12) +
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23),@DataAtual, 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
-- em caso de erro faz rollback da transacção iniciada						           
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION	
		END CATCH	
-- se sucesso faz commit da transacção iniciada
		IF @@TRANCOUNT > 0
			COMMIT TRANSACTION			
		FETCH NEXT FROM Declaracoes INTO @Acao, @TipoProcedimento, @CodNatureza, @CodOperador, @Data, @VossaReferencia, @CodEstanciaA, @CodStatusIncidencia, @CodTipoDeclaracao, @NumeroCPA, @TipoCarga, 
			@DataVoo, @Expedidor_Codigo, @Expedidor_Nome, @Expedidor_Morada, @Expedidor_Localidade, @Expedidor_CodPostal, @Expedidor_LocPostal, @Expedidor_NIF, @Expedidor_CodPais, @CodClienteServico, 
			@NumeroComercialRef, @Destinatario_Codigo, @Destinatario_Nome, @Destinatario_Morada, @Destinatario_Localidade, @Destinatario_CodPostal, @Destinatario_LocPostal, @Destinatario_NIF, 
			@Destinatario_CodPais, @CodPais15A, @CodPais17A, @ICE, @MTPartida_CodMT, @MTPartida_MatriculaMT, @MTPartida_TipoMT, @MTPartida_CodMT25, @MTPartida_CodMT26, @MTPartida_CodAeroporto, 
			@MTFronteira_CodMT, @MTFronteira_MatriculaMT,  @MTFronteira_TipoMT, @MTFronteira_CodPais, @CodEstanciaTAC, @CodEstanciaTN, @LocMercadorias_CodEstancia30, @LocMercadorias_CodLocalEmbarque, 
			@LocMercadorias_CodLocalAutorizado, @LocMercadorias_OutroLocal_Morada, @LocMercadorias_OutroLocal_CodPostal, @LocMercadorias_OutroLocal_LocPostal, @LocMercadorias_Armazem_CodArmazem, 
			@LocMercadorias_Armazem_CodTipoArmazem, @LocMercadorias_Armazem_CodEstadoMembro, @CodLocalEmbarque, @CodCondEntrega, @Lugar, @CodNaturezaTransacao, @CodPais, @TotalFrete, @TotalSeguro, 
			@HVLV, @Origem, @Anotacoes, @CamposExtra, @DadosManifesto_CodExpedidor, @DadosManifesto_NomeExpedidor, @DadosManifesto_MoradaExpedidor, @DadosManifesto_LocalidadeExpedidor, 
			@DadosManifesto_CodPostalExpedidor, @DadosManifesto_LocPostalExpedidor, @DadosManifesto_CodPaisExpedidor, @DadosManifesto_NIFExpedidor, @DadosManifesto_CodDestinatario, 
			@DadosManifesto_NomeDestinatario, @DadosManifesto_MoradaDestinatario, @DadosManifesto_LocalidadeDestinatario, @DadosManifesto_CodPaisDestinatario, @DadosManifesto_Montante, 
			@DadosManifesto_CodPais, @DadosManifesto_MassaLiqTotal, @DadosManifesto_MassaBrtTotal, @DadosManifesto_MiniCPA, @DadosManifesto_DutyType, @DadosManifesto_NomeFicheiro, 
			@DadosManifesto_PPouFC, @DadosManifesto_NumeroVoo, @DadosManifesto_Referencia1, @DadosManifesto_Referencia2, @DadosManifesto_Tracking, @DadosManifesto_Shipping, @DadosManifesto_VolsDirty, 
			@Contentores, @Adicoes, @Arquivos
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_GeraDeclaracoesDeXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_GeraDeclaracoesDeXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_GeraLinhaSDSViaAerea]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_GeraLinhaSDSViaAerea] @AnoDeclaracao int, @CodDeclaracao int, @CodDeclaranteDeclaracao varchar(6) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @DataAtual datetime, @UtilizaSDS bit, @ChaveAdicao int, @CodSimplesAlfandega varchar(3), @EntidadeEmissora varchar(60), @TipoManifesto varchar(2), @CodAeroportoEscLIS varchar(8), 
		@CodAeroportoEscOPO varchar(8), @IdConsignatario varchar(20), @TipoCarga varchar(3), @CodLocMercadoriasLIS varchar(17), @CodLocMercadoriasOPO varchar(17), @EditaExp int, 
		@AdicaoXMLExisteSDS int, @AnoSDS int, @NumeroSDS int, @CartaPorteXML varchar(18), @AutSaidaXML bit, @CodIncidenciaXML varchar(4), @LocPostalClienteXML varchar(35), 
		@CodAeroportoDestXML varchar(8), @NomeAeroportoDestXML varchar(35), @TipoCargaXML varchar(5), @NIFCompletoClienteXML varchar(50), @NomeClienteXML varchar(70), 
		@NomeFornecedorXML varchar(70), @MassaBruta numeric(38, 6), @TotalVolsXML int, @DescricaoAdicao varchar(150), @DataDocAdicao datetime, @MarcaVolsAdicao varchar(25), 
		@CodNatVolsAdicao varchar(2), @NomeNatVolsAdicao varchar(35), @AdicaoXMLDifereSDS bit, @NumLinhaAWB int, @NomeDocumentoN740 varchar(70), @NomePaisPT varchar(35), 
		@NomeAeroportoEscOrig varchar(35), @NomeAeroportoEmb varchar(35), @NomeLocMercadorias varchar(70), @NumeroDGAXML varchar(21), @DataDGAXML datetime, @IdDepositarioLIS varchar(20), 
		@IdDepositarioOPO varchar(20), @CodAlfandegaXML varchar(8), @NomeAlfandegaXML varchar(35), @CodDocumento varchar(5), @NomeDocumento varchar(70), @NumDocumentoDGAXML varchar(18), 
		@NumLinhasAWBComMesmaCartaPorteXML int, @CodAlfandegaTAC varchar(8), @MoradaClienteXML varchar(70), @MoradaFornecedorXML varchar(70), @CamposAdicionais int, @NumeroDocSDS int, 
		@DataVooSDS datetime, @CodPaisDestino varchar(2), @CodPostalClienteXML varchar(17), @LocalidadeClienteXML varchar(35), @NumDocPrecedenteXML varchar(70), @CodArtigoAdicao varchar(22), 
		@CodPautalArtigoAdicao varchar(22), @CodPedido varchar(5), @NomePedido varchar(150), @TextoPedido varchar(512)
-- obtem a data atual
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem configuração se utiliza Interface Declaração/SDS
	SELECT TOP 1 @UtilizaSDS = PSD_IXML, @EntidadeEmissora = PSD_EEED, @TipoManifesto = PSD_TIPO, @CodAeroportoEscLIS = PAE_CODI, @CodAeroportoEscOPO = PAE_CODI1, @IdConsignatario = PSD_IDCS, 
		@TipoCarga = PSD_TCAR, @CodLocMercadoriasLIS = LME_CODI, @CodLocMercadoriasOPO = LME_CODI1, @EditaExp = PSD_EREX, @IdDepositarioLIS = PSD_IDDL, @IdDepositarioOPO = PSD_IDDP
	FROM TAB_PSDS WITH(NOLOCK)
-- se utiliza Interface Declaração/SDS, cria/actualiza linha respectiva no SDS Via Aerea
	IF @UtilizaSDS = 1
	BEGIN
-- obtem dados dos parâmetros de despachos
		SELECT TOP 1 @CamposAdicionais = ISNULL(PDE_CADI, 0)
		FROM TAB_PDES WITH(NOLOCK)
-- altera "Data Voo" da Declaração/XML em função da existência ou não de SDS-Via Aerea para a "Data AS" da Declaração/XML
		IF (SELECT ISNULL((SELECT sd.DSD_ASAI FROM PRO_EXML as ex WITH(NOLOCK) INNER JOIN PRO_EXAD as ax WITH(NOLOCK) ON ex.EXM_EANO = ax.EXM_EANO and ex.EXM_CODI = ax.EXM_CODI and ex.DEC_CODI = ax.EXM_COPE and ax.EXA_LINH = 1 INNER JOIN PRO_SDSC as sc WITH(NOLOCK) ON sc.DSC_TIPO = 1 and sc.DSC_IXML = 1 and ex.EXM_DTVO = sc.DSC_DTVO and ex.EAD_CODA = sc.EAD_CODI INNER JOIN PRO_SDSD as sd WITH(NOLOCK) ON sc.DSC_EANO = sd.DSC_EANO and sc.DSC_NPRO = sd.DSC_NPRO and sd.EXA_CHVE = ax.EXA_CHVE WHERE ex.EXM_EANO = @AnoDeclaracao and ex.EXM_CODI = @CodDeclaracao and ex.DEC_CODI = @CodDeclaranteDeclaracao), 0)) = 0
		BEGIN 		
			UPDATE PRO_EXML SET EXM_DTVO = ISNULL((SELECT TOP 1 DSC_DTVO FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_TIPO = 1 and DSC_IXML = 1 and DSC_ACTI = 1 and DSC_DTVO >= ISNULL(EXM_DTAS, EXM_DINC) and EAD_CODI = EAD_CODA ORDER BY DSC_DTVO), EXM_DTVO)
			WHERE ((EXM_ASAI = 1 and EXM_DTAS IS NOT NULL) or (SIN_CODI = 'A13' and EXM_DINC IS NOT NULL)) and EXM_BLOQ = 0 and EXM_EANO = @AnoDeclaracao and EXM_CODI = @CodDeclaracao and DEC_CODI = @CodDeclaranteDeclaracao		
		END
-- obtem dados da Declaração/XML + 1ª Adição + SDS-Via Aerea (se existir)	
		SELECT @CodSimplesAlfandega = RIGHT(ex.EAD_CODA, 3), @CodAlfandegaXML = ex.EAD_CODA, @NomeAlfandegaXML = ex.EAD_NOMA, @CodAlfandegaTAC = ex.EAD_CO29, @CartaPorteXML = ex.EXM_CPRT, 
			@LocPostalClienteXML = ex.CLI_LPO2, @CodAeroportoDestXML = ex.PAE_CODI, @NomeAeroportoDestXML = ex.PAE_NOME, @TipoCargaXML = ex.EXM_TPCG, 
			@NIFCompletoClienteXML = (CASE ex.EXM_CNTX WHEN 1 THEN (ex.CLI_PAI2 + ex.CLI_NIF2) ELSE (CASE ex.CLI_PAI2 WHEN 'PT' THEN (ex.CLI_PAI2 + '/NIF/' + ex.CLI_NIF2) ELSE 'QU' END) END), 
			@NomeClienteXML = ex.CLI_NOM2, @MoradaClienteXML = ex.CLI_MOR2, @LocalidadeClienteXML = ex.CLI_LOC2, @CodPostalClienteXML = ex.CLI_CPO2, @NomeFornecedorXML = ex.FOR_NOM8, 
			@MoradaFornecedorXML = ex.FOR_MOR8, @CodPaisDestino = ex.EXM_P17A, @MassaBruta = ex.EXM_TMBR, @TotalVolsXML = ROUND(ex.EXM_TVL6, 0), @NumeroDGAXML = ex.EXM_NDGA, 
			@DataDGAXML = ex.EXM_DDGA, @NumDocumentoDGAXML = SUBSTRING(ex.EXM_NDGA, 3, 18), @AutSaidaXML = ex.EXM_ASAI, @CodIncidenciaXML = ex.SIN_CODI, 
			@ChaveAdicao = ax.EXA_CHVE, @CodArtigoAdicao = ax.APA_CO33, @CodPautalArtigoAdicao = ax.APA_CP33, @DescricaoAdicao = ax.APA_DESG,
			@DataDocAdicao = (select TOP 1 EXD_DTEM from PRO_EXDA WITH(NOLOCK) where EXA_CHVE = ax.EXA_CHVE and DOC_CODI = 'N740'),
			@MarcaVolsAdicao = (select TOP 1 EXM_MARN from PRO_EXMV WITH(NOLOCK) where EXA_CHVE = ax.EXA_CHVE), 
			@CodNatVolsAdicao = (select TOP 1 TEM_CODI from PRO_EXMV WITH(NOLOCK) where EXA_CHVE = ax.EXA_CHVE),
			@NomeNatVolsAdicao = (select TOP 1 TEM_NOME from PRO_EXMV WITH(NOLOCK) where EXA_CHVE = ax.EXA_CHVE),
			@AnoSDS = sc.DSC_EANO, @NumeroSDS = sc.DSC_NPRO, @DataVooSDS = sc.DSC_DTVO, @NumLinhaAWB = sd.DSD_NUME, 
			@NumLinhasAWBComMesmaCartaPorteXML = (SELECT COUNT(*) FROM PRO_SDSD WITH(NOLOCK) WHERE DSC_EANO = sc.DSC_EANO and DSC_NPRO = sc.DSC_NPRO and EXA_CHVE <> ax.EXA_CHVE and DSD_NRMH = ex.EXM_CPRT), 
			@AdicaoXMLExisteSDS = (case when (sd.DSD_NUME is null) then 0 when (sd.DSD_ANUL = 1 or sd.DSD_ESTA = 'FIN' or sd.DSD_ESTA = 'APU') then 1 else 2 end),
			@AdicaoXMLDifereSDS = (case when (sd.PAE_CODI <> isnull(ex.PAE_CODI, '') 
				or sd.PAE_CODI1 <> (case RIGHT(ex.EAD_CODA, 3) when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end) 
				or sd.PAE_CODI2 <> (case RIGHT(ex.EAD_CODA, 3) when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end) or sd.DSD_EADC <> isnull(ex.EXM_TPCG, '')
				or sd.TEM_CODI <> (select TOP 1 TEM_CODI from PRO_EXMV WITH(NOLOCK) where EXA_CHVE = ax.EXA_CHVE) or sd.DSD_VOLS <> ROUND(isnull(ex.EXM_TVL6, 0), 0) 
				or sd.DSD_PESO <> isnull(ex.EXM_TMBR, 0) or isnull(sd.DSD_NDAU, '') <> isnull(ex.EXM_NDGA, '') 
				or isnull(sd.DSD_DTEN, '01-01-1900') <> isnull(ex.EXM_DDGA, '01-01-1900') 
				or isnull(sd.DSD_DEPO, '') <> (case RIGHT(ex.EAD_CODA, 3) when '020' then @IdDepositarioOPO else @IdDepositarioLIS end)) then 1 else 0 end),
			@NomeDocumentoN740 = (select DOC_NOME from TAB_DOCU WITH(NOLOCK) where DOC_CODI = 'N740'), 			
			@NomePaisPT = (select PAI_NOME from TAB_PAIS WITH(NOLOCK) where PAI_CODI = 'PT'),
			@NomeAeroportoEscOrig = (select PAE_NOME from TAB_PAER WITH(NOLOCK) where PAE_CODI = (case RIGHT(ex.EAD_CODA, 3) when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end)),
			@NomeAeroportoEmb = (select PAE_NOME from TAB_PAER WITH(NOLOCK) where PAE_CODI = (case RIGHT(ex.EAD_CODA, 3) when '020' then 'OPO' else 'LIS' end)), 			
			@NomeLocMercadorias = (select LME_NOME from TAB_LMER WITH(NOLOCK) where LME_CODI = (case RIGHT(ex.EAD_CODA, 3) when '020' then @CodLocMercadoriasOPO else @CodLocMercadoriasLIS end)),
			@NumDocPrecedenteXML = (CASE WHEN ex.EXM_TPCG IN ('TD', 'X') THEN (SELECT TOP 1 numero FROM tb_EXP_DeclaracoesPrecedentes WHERE id_declaracaoEXP = ex.EXM_IDTY) ELSE NULL END),
			@CodPedido = (CASE WHEN ex.EXM_TPCG IN ('TD', 'X') THEN pe.TXM_CODI ELSE NULL END),
			@NomePedido = (CASE WHEN ex.EXM_TPCG IN ('TD', 'X') THEN pe.TXM_DESC ELSE NULL END),
			@TextoPedido = (CASE WHEN ex.EXM_TPCG IN ('TD', 'X') THEN LEFT(pe.TXM_TEXT, 512) ELSE NULL END)
		FROM PRO_EXML as ex WITH(NOLOCK) 
			INNER JOIN PRO_EXAD as ax WITH(NOLOCK) ON ex.EXM_EANO = ax.EXM_EANO and ex.EXM_CODI = ax.EXM_CODI and ex.DEC_CODI = ax.EXM_COPE and ax.EXA_LINH = 1
			LEFT OUTER JOIN PRO_SDSC as sc WITH(NOLOCK) ON sc.DSC_TIPO = 1 and sc.DSC_IXML = 1 and ex.EXM_DTVO = sc.DSC_DTVO and ex.EAD_CODA = sc.EAD_CODI
			LEFT OUTER JOIN PRO_SDSD as sd WITH(NOLOCK) ON sc.DSC_EANO = sd.DSC_EANO and sc.DSC_NPRO = sd.DSC_NPRO and sd.EXA_CHVE = ax.EXA_CHVE
			LEFT OUTER JOIN TAB_TXML as pe WITH(NOLOCK) ON pe.TXM_CODI = 'S1TOT'
		WHERE ex.EXM_EANO = @AnoDeclaracao and ex.EXM_CODI = @CodDeclaracao and ex.DEC_CODI = @CodDeclaranteDeclaracao
			and EXISTS(SELECT EXD_CHVE FROM PRO_EXDA WITH(NOLOCK) WHERE EXA_CHVE = ax.EXA_CHVE and DOC_CODI = 'N740')
			and EXISTS(SELECT EXM_CHVE FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = ax.EXA_CHVE)
			and ex.EAD_CO29 <> 'ES000801'
-- verifica se existe adição XML numero 1 e se Campos Adicionais for diferente de TNT ou se for TNT tem de ter as alfândegas iguais
		if (@ChaveAdicao IS NOT NULL) and ((@AutSaidaXML = 1) or (@CodIncidenciaXML = 'A13')) and ((@CamposAdicionais <> 4) or (@CamposAdicionais = 4 and @CodAlfandegaXML = @CodAlfandegaTAC))
		begin
-- verifica se existe SDS-Via Aerea já criada para a Alfandega/Data Voo e que a "Carta de Porte" não existe em nenhuma outra linha
			if (@AnoSDS IS NOT NULL) and (@NumLinhasAWBComMesmaCartaPorteXML = 0)
			begin
-- valida se Aeroporto definido na Exportação/XML existe. Senão existir assume aeroporto "XXX" fixo
				IF NOT EXISTS(SELECT PAE_CODI FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = @CodAeroportoDestXML)
				BEGIN
					SELECT @CodAeroportoDestXML = PAE_CODI, @NomeAeroportoDestXML = PAE_NOME
					FROM TAB_PAER WITH(NOLOCK)
					WHERE PAE_CODI = 'XXX'
				END
-- obtem o documento "9Z13" ou "N830" em função do país de expedição
				SELECT @CodDocumento = DOC_CODI, @NomeDocumento = DOC_NOME 
				FROM TAB_DOCU WITH(NOLOCK) 
				WHERE DOC_CODI = (CASE @CodPaisDestino WHEN 'GI' THEN '9Z13' ELSE 'N830' END)				
-- se adição XML não existe no SDS-Via Aerea da Alfandega/Data Voo, insere
				IF @AdicaoXMLExisteSDS = 0
				BEGIN	
					SET @NumLinhaAWB = (ISNULL((SELECT MAX(DSD_NUME) FROM PRO_SDSD WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS), 0) + 1)
-- insere linha AWB									
					INSERT INTO PRO_SDSD(DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DOC_NOME, DSD_LOED, DSD_DTED, DSD_EEED, PAI_CODI, PAI_NOME, DSD_TIPO, PAE_CODI, PAE_NOME, PAE_CODI1, 
						PAE_NOME1, PAE_CODI2, PAE_NOME2, DSD_EADC, DSD_IDOS, DSD_NOOS, DSD_IDNS, DSD_NONS, DSD_NOMD, DSD_IDEN, DSD_IDEC, DSD_DMER, DSD_MRNR, TEM_CODI, TEM_NOME, DSD_PESO, 
						DSD_VOLS, DSD_TCAR, LME_CODI, LME_NOME, PAE_CODI3, PAE_NOME3, DSD_DNOW, DSD_ORIG, EXA_CHVE, DSD_NDAU, DSD_DTEN, DSD_DEPO, DSD_IDCR, DSD_MOOS, DSD_MORD, DSD_ENVI, 
						DSD_CPOS, DSD_LOOS, DSD_NDPR, APA_CODI, DSD_CPAU, TXM_CODI, TXM_DESC, DSD_PTXT)
					values(@AnoSDS, @NumeroSDS, @NumLinhaAWB, @CartaPorteXML, 'N740', @NomeDocumentoN740, @LocPostalClienteXML, @DataDocAdicao, @EntidadeEmissora, 'PT', @NomePaisPT, @TipoManifesto, @CodAeroportoDestXML, @NomeAeroportoDestXML, (case @CodSimplesAlfandega when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end), 
						@NomeAeroportoEscOrig,(case @CodSimplesAlfandega when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end), @NomeAeroportoEscOrig, @TipoCargaXML, @NIFCompletoClienteXML, @NomeClienteXML, @NIFCompletoClienteXML, @NomeClienteXML, @NomeFornecedorXML, @IdConsignatario, @IdConsignatario, @DescricaoAdicao, @MarcaVolsAdicao, @CodNatVolsAdicao, @NomeNatVolsAdicao, @MassaBruta, 
						@TotalVolsXML, @TipoCarga, (case @CodSimplesAlfandega when '020' then @CodLocMercadoriasOPO else @CodLocMercadoriasLIS end), @NomeLocMercadorias, (case @CodSimplesAlfandega when '020' then 'OPO' else 'LIS' end), @NomeAeroportoEmb, @DataAtual, 2, @ChaveAdicao, @NumeroDGAXML, ISNULL(@DataDGAXML, @DataVooSDS), (case @CodSimplesAlfandega when '020' then @IdDepositarioOPO else @IdDepositarioLIS end), REPLACE(CONVERT(numeric(38, 10), @DataAtual), '.', ','), @MoradaClienteXML, @MoradaFornecedorXML, (CASE @CodAeroportoDestXML WHEN 'XXX' THEN CAST(0 as bit) ELSE CAST(1 as bit) END), 
						@CodPostalClienteXML, @LocalidadeClienteXML, @NumDocPrecedenteXML, @CodArtigoAdicao, @CodPautalArtigoAdicao, @CodPedido, @NomePedido, @TextoPedido)
-- atualiza a declaração de Exportação/XML c/ ID da linha AWB inserida
					UPDATE PRO_EXML SET DSD_IDNN = @@IDENTITY, EXM_DSDS = @DataAtual
					WHERE EXM_EANO = @AnoDeclaracao and EXM_CODI = @CodDeclaracao and DEC_CODI = @CodDeclaranteDeclaracao
-- insere documento p/ linha AWB se existir Nº. DGA
					IF (ISNULL(@NumeroDGAXML, '') <> '') AND (ISNULL(@CodDocumento, '') <> '')
					BEGIN										
						INSERT INTO PRO_SSDD(DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC, SDD_ORIG)
						VALUES(@AnoSDS, @NumeroSDS, @NumLinhaAWB, 1, @CodDocumento, @NomeDocumento, @NumDocumentoDGAXML, ISNULL(@DataDGAXML, @DataVooSDS), @CodAlfandegaXML, @NomeAlfandegaXML, 'T', 1)
					END
				END
				ELSE			
-- se adição XML já existe no SDS-Via Aerea da Alfandega/Data Voo, edita-a conforme configuração
					IF @AdicaoXMLExisteSDS = 2
					BEGIN
						IF (@EditaExp = 2) AND (@AdicaoXMLDifereSDS = 1) -- Só campos criticos e campos criticos foram alterados
						BEGIN
							UPDATE PRO_SDSD SET PAE_CODI = @CodAeroportoDestXML, PAE_NOME = @NomeAeroportoDestXML, 
								PAE_CODI1 = (case @CodSimplesAlfandega when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end), PAE_NOME1 = @NomeAeroportoEscOrig, 
								PAE_CODI2 = (case @CodSimplesAlfandega when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end), PAE_NOME2 = @NomeAeroportoEscOrig, 
								DSD_EADC = @TipoCargaXML, TEM_CODI = @CodNatVolsAdicao, TEM_NOME = @NomeNatVolsAdicao, DSD_VOLS = @TotalVolsXML, DSD_PESO = @MassaBruta, DSD_NDAU = @NumeroDGAXML, 
								DSD_DTEN = ISNULL(@DataDGAXML, @DataVooSDS), DSD_DEPO = (case @CodSimplesAlfandega when '020' then @IdDepositarioOPO else @IdDepositarioLIS end)
							WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB
						END
						ELSE
							IF @EditaExp = 1 -- Sempre
							BEGIN								
								UPDATE PRO_SDSD SET DSD_NRMH = @CartaPorteXML, DOC_CODI = 'N740', DOC_NOME = @NomeDocumentoN740, DSD_LOED = @LocPostalClienteXML, DSD_DTED = @DataDocAdicao, 
									DSD_EEED = @EntidadeEmissora, PAI_CODI = 'PT', PAI_NOME = @NomePaisPT, DSD_TIPO = @TipoManifesto, PAE_CODI = @CodAeroportoDestXML, PAE_NOME = @NomeAeroportoDestXML, 
									PAE_CODI1 = (case @CodSimplesAlfandega when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end), PAE_NOME1 = @NomeAeroportoEscOrig, 
									PAE_CODI2 = (case @CodSimplesAlfandega when '020' then @CodAeroportoEscOPO else @CodAeroportoEscLIS end), PAE_NOME2 = @NomeAeroportoEscOrig, DSD_EADC = @TipoCargaXML, 
									DSD_IDOS = @NIFCompletoClienteXML, DSD_NOOS = @NomeClienteXML, DSD_IDNS = @NIFCompletoClienteXML, DSD_NONS = @NomeClienteXML, DSD_NOMD = @NomeFornecedorXML, 
									DSD_IDEN = @IdConsignatario, DSD_IDEC = @IdConsignatario, DSD_DMER = @DescricaoAdicao, DSD_MRNR = @MarcaVolsAdicao, TEM_CODI = @CodNatVolsAdicao, 
									TEM_NOME = @NomeNatVolsAdicao, DSD_PESO = @MassaBruta, DSD_VOLS = @TotalVolsXML, DSD_TCAR = @TipoCarga, 
									LME_CODI = (case @CodSimplesAlfandega when '020' then @CodLocMercadoriasOPO else @CodLocMercadoriasLIS end), 
									LME_NOME = @NomeLocMercadorias, PAE_CODI3 = (case @CodSimplesAlfandega when '020' then 'OPO' else 'LIS' end), 
									PAE_NOME3 = @NomeAeroportoEmb, DSD_DNOW = @DataAtual, DSD_NDAU = @NumeroDGAXML, DSD_DTEN = ISNULL(@DataDGAXML, @DataVooSDS), 
									DSD_DEPO = (case @CodSimplesAlfandega when '020' then @IdDepositarioOPO else @IdDepositarioLIS end), DSD_MOOS = @MoradaClienteXML, 
									DSD_MORD = @MoradaFornecedorXML, DSD_CPOS = @CodPostalClienteXML, DSD_LOOS = @LocalidadeClienteXML, DSD_NDPR = @NumDocPrecedenteXML, 
									APA_CODI = @CodArtigoAdicao, DSD_CPAU = @CodPautalArtigoAdicao, TXM_CODI = @CodPedido, TXM_DESC = @NomePedido, DSD_PTXT = @TextoPedido
								WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB
							END 
-- insere documento p/ linha AWB se existir Nº. DGA e o documento ainda não existir
						IF (ISNULL(@NumeroDGAXML, '') <> '') AND (ISNULL(@CodDocumento, '') <> '') AND (NOT EXISTS(SELECT SDD_NUME FROM PRO_SSDD WITH(NOLOCK) WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB and DOC_CODI = @CodDocumento))						
						BEGIN				
							SET @NumeroDocSDS = ISNULL((SELECT MAX(SDD_NUME) FROM PRO_SSDD WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB), 0) + 1 
-- insere documento 
							INSERT INTO PRO_SSDD(DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC, SDD_ORIG)
							VALUES(@AnoSDS, @NumeroSDS, @NumLinhaAWB, @NumeroDocSDS, @CodDocumento, @NomeDocumento, @NumDocumentoDGAXML, ISNULL(@DataDGAXML, @DataVooSDS), @CodAlfandegaXML, @NomeAlfandegaXML, 'T', 1)
						END							
					END
			end		
		end
	END
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_GeraLinhaSDSViaAerea] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_GeraLinhaSDSViaAerea] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ImportaFicheiroOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ExportacaoXML_ImportaFicheiroOGMA] @FicheiroXML xml, @NomeFicheiroXML varchar(100), @Utilizador varchar(30), @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdUtilizador int, @DataAtual datetime, @FicheiroBinario varbinary(MAX), @FicheiroBase64 varchar(MAX), @DocumentoXML xml(XMLSC_DeclaracoesExpToGIDWin)
	DECLARE @TmpFicheiroOGMA TABLE(
		ID int NOT NULL IDENTITY(1, 1), 	
		ADICAO int NOT NULL, 
		DT_PROCESSO datetime NULL, 
		PROCESSO varchar(100) NULL, 
		BI_LI_ID int NULL, 
		AWB varchar(25) NULL, 
		ARTIGO varchar(40) NULL, 		
		QTD_EXP numeric(28, 6) NOT NULL, 
		UOM_EXP varchar(3) NULL, 
		VALOR_UNIT_EXP numeric(28, 6) NOT NULL, 
		SERIAL_NUM varchar(100) NULL, 
		NOTAS varchar(100) NULL, 
		DAU_PREC varchar(20) NULL, 	
		DAU_DATE_PREC datetime NULL, 			
		N_VOLUMES int NOT NULL,		
		GUIA varchar(20) NULL, 		
		NUM_ADIC_PREC int NULL,
		PP_PREC varchar(22) NULL, 		
		PESO_GROSS numeric(28, 6) NOT NULL, 		
		PESO_NET_TOTAL numeric(28, 6) NOT NULL, 
		UOM_WEIGHT varchar(12) NULL, 		
		PROCESS_TYPE varchar(2) NULL, 
		PAIS_EXP_MERCADORIA varchar(3) NULL, 
		DESTINATARIO varchar(200) NULL, 		
		DESIGNACAO_MERCADORIA varchar(100) NULL, 		
		TIPO_PROCEDIMENTO varchar(20) NULL)
-- inicia processo de geração da declaração	Exportação/XML
	BEGIN TRY	
		SET @NumErro = 0	
-- obtem o ID do utilizador
		SELECT @IdUtilizador = UTI_IDTY
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_UTIL = @Utilizador			
-- obtem a data atual
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- converte ficheiro XML para binário e depois para base64
		SET @FicheiroBinario = CAST(CAST(@FicheiroXML AS varchar(MAX)) AS varbinary(MAX))
		SET @FicheiroBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinario")))', 'varchar(MAX)')
-- obtem do ficheiro XML os valores de todos os elementos necessários para a importação
		INSERT INTO @TmpFicheiroOGMA(ADICAO, DT_PROCESSO, PROCESSO, BI_LI_ID, AWB, ARTIGO, QTD_EXP, UOM_EXP, VALOR_UNIT_EXP, SERIAL_NUM, NOTAS, DAU_PREC, DAU_DATE_PREC, N_VOLUMES, GUIA, 
			NUM_ADIC_PREC, PP_PREC, PESO_GROSS, PESO_NET_TOTAL, UOM_WEIGHT, PROCESS_TYPE, PAIS_EXP_MERCADORIA, DESTINATARIO, DESIGNACAO_MERCADORIA, TIPO_PROCEDIMENTO)
		SELECT 
			ROW_NUMBER() OVER(PARTITION BY t.c.value('NOTAS[1]', 'varchar(100)') ORDER BY t.c.value('NOTAS[1]', 'varchar(100)')), 
			CONVERT(varchar(10), NULLIF(t.c.value('DT_PROCESSO[1]', 'varchar(10)'), ''), 127), 
			t.c.value('PROCESSO[1]', 'varchar(100)'), 
			t.c.value('BI_LI_ID[1]', 'int'), 
			t.c.value('AWB[1]', 'varchar(25)'), 
			t.c.value('ARTIGO[1]', 'varchar(40)'), 			
			ISNULL(t.c.value('QTD_EXP[1]', 'numeric(28, 6)'), 0), 
			t.c.value('UOM_EXP[1]', 'varchar(3)'), 
			ISNULL(t.c.value('VALOR_UNIT_EXP[1]', 'numeric(28, 6)'), 0), 
			t.c.value('SERIAL_NUM[1]', 'varchar(100)'), 
			t.c.value('NOTAS[1]', 'varchar(100)'), 
			t.c.value('DAU_PREC[1]', 'varchar(20)'), 
			CONVERT(varchar(10), NULLIF(t.c.value('DAU_DATE_PREC[1]', 'varchar(10)'), ''), 127), 			
			ISNULL(t.c.value('N_VOLUMES[1]', 'int'), 0), 
			t.c.value('GUIA[1]', 'varchar(20)'), 
			t.c.value('NUM_ADIC_PREC[1]', 'int'), 
			t.c.value('PP_PREC[1]', 'varchar(22)'),
			ISNULL(t.c.value('PESO_GROSS[1]', 'numeric(28, 6)'), 0), 
			ISNULL(t.c.value('PESO_NET_TOTAL[1]', 'numeric(28, 6)'), 0), 	
			t.c.value('UOM_WEIGHT[1]', 'varchar(12)'),		
			t.c.value('PROCESS_TYPE[1]', 'varchar(2)'), 
			t.c.value('PAIS_EXP_MERCADORIA[1]', 'varchar(3)'), 
			t.c.value('DESTINATARIO[1]', 'varchar(200)'), 			
			t.c.value('DESIGNACAO_MERCADORIA[1]', 'varchar(100)'), 			
			t.c.value('TIPO_PROCEDIMENTO[1]', 'varchar(20)')
		FROM @FicheiroXML.nodes('FICH_DESPCHANTE/FICH_DESPCHANTE_LINE') AS t(c)	
-- constroi XML para declaração Exportação/XML a partir do ficheiro XML no formato OGMA
		SELECT @DocumentoXML = 
			(SELECT
				(SELECT 'I' AS "@Acao", 
					(CASE 
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Incompleta' THEN 'B'
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Simplificada' THEN 'C'
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Complementar' THEN 'X'
						ELSE 'A'
					END) AS "TipoProcedimento",
					NULLIF(LEFT(fch.NOTAS, 3), '') AS "CodNatureza", 
					(SELECT TOP 1 DEC_CODI FROM TAB_DECL WITH(NOLOCK) WHERE DEC_INAC = 0) AS "CodOperador", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "Data",					
					(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
						WHEN '1000'THEN 'PT000015'
						ELSE 'PT000088'
					END) AS "CodEstanciaA", 
					(CASE 						
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Incompleta' THEN 
							((CASE ISNULL(LEFT(fch.NOTAS, 2), '') 
								WHEN '31' THEN STUFF(LEFT(fch.NOTAS, 3), 2, 1, '')
								ELSE NULLIF(LEFT(fch.NOTAS, 2), '') 
							END) + (CASE 
										WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'U' 
										ELSE 'E' 
									END) + 'B')
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Simplificada' THEN 
							((CASE ISNULL(LEFT(fch.NOTAS, 2), '') 
								WHEN '31' THEN STUFF(LEFT(fch.NOTAS, 3), 2, 1, '')
								ELSE NULLIF(LEFT(fch.NOTAS, 2), '') 
							END) + (CASE 
										WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'U' 
										ELSE 'E' 
									END) + 'C')
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Complementar' THEN 
							((CASE ISNULL(LEFT(fch.NOTAS, 2), '') 
								WHEN '31' THEN STUFF(LEFT(fch.NOTAS, 3), 2, 1, '')
								ELSE NULLIF(LEFT(fch.NOTAS, 2), '') 
							END) + (CASE 
										WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'U' 
										ELSE 'E' 
									END) + 'X')
						ELSE (NULLIF(LEFT(fch.NOTAS, 3), '') + (CASE 
																	WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'U' 
																	ELSE 'E' 
																END))
					END) AS "CodTipoDeclaracao", 				
					NULLIF(LEFT(fch.AWB, 18), '') AS "NumeroCPA", 									
					(SELECT 
						cli.CLI_CODI AS "Codigo", 
						NULLIF(cli.CLI_NOME, '') AS "Nome",
						NULLIF(cli.CLI_MORA, '') AS "Morada",
						NULLIF(cli.CLI_LOCA, '') AS "Localidade",
						NULLIF(cli.CLI_CPOS, '') AS "CodPostal",
						NULLIF(cli.CLI_LPOS, '') AS "LocPostal",
						NULLIF(cli.CLI_NIF, '') AS "NIF",
						cli.PAI_CODI AS "CodPais"
					FOR XML PATH('Expedidor'), TYPE),					
					(SELECT 
						frn.FOR_CODI AS "Codigo", 
						NULLIF(frn.FOR_NOME, '') AS "Nome",
						NULLIF(frn.FOR_MORA, '') AS "Morada",
						NULLIF(frn.FOR_LOCA, '') AS "Localidade",
						NULLIF(frn.FOR_CPOS, '') AS "CodPostal",
						NULLIF(frn.FOR_LPOS, '') AS "LocPostal",							
						NULLIF(frn.FOR_NIF, '') AS "NIF", 
						NULLIF(frn.PAI_CODI, '') AS "CodPais"
					FOR XML PATH('Destinatario'), TYPE), 	
					NULLIF(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') AS "CodPais17A", 				
					'E' AS "ICE", 								
					(SELECT 
						'30' AS "CodMeioTransporte"		
					HAVING ISNULL(LEFT(fch.NOTAS, 4), '') <> '1000'				
					FOR XML PATH('MeioTransportePartida'), TYPE), 							
					(SELECT 
						(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
							WHEN '1000' THEN '40'
							ELSE '30' 
						END) AS "CodMeioTransporte", 
						(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
							WHEN '1000' THEN NULL
							ELSE 'CAMIAO' 
						END) AS "MatriculaMT", 
						(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
							WHEN '1000' THEN NULL
							ELSE 'PT' 
						END) AS "CodPais"					
					FOR XML PATH('MeioTransporteFronteira'), TYPE), 
					'PT000015' AS "CodEstanciaTAC", 
					(SELECT 
						(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
							WHEN '1000' THEN 'AEX00000044015PT'
							ELSE NULL 
						END) AS "CodLocalAutorizado", 
						(SELECT 
							NULLIF(frn.FOR_MORA, '') AS "Morada", 
							NULLIF(frn.FOR_CPOS, '') AS "CodPostal", 
							NULLIF(frn.FOR_LPOS, '') AS "LocPostal"
						HAVING ISNULL(LEFT(fch.NOTAS, 4), '') = '3151'
						FOR XML PATH('OutroLocal'), TYPE), 
						(SELECT 
							ARM_CODI AS "CodArmazem", 
							TAR_CODI AS "CodTipoArmazem", 
							'PT' AS "CodEstadoMembro"
						FROM TAB_ARMZ WITH(NOLOCK)
						WHERE ARM_CODI = 'ENT00000174088' AND ISNULL(LEFT(fch.NOTAS, 4), '') = '3171'						
						FOR XML PATH('Armazem'), TYPE)
					HAVING ISNULL(LEFT(fch.NOTAS, 4), '') IN ('1000', '3151')
					FOR XML PATH('LocalizacaoMercadorias'), TYPE), 	
					(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
						WHEN '3171' THEN NULL
						ELSE 'XXX' 
					END) AS "CodCondEntrega", 	
					(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
						WHEN '3171' THEN NULL
						ELSE 'LIVRE DE ENC. LISBOA' 
					END) AS "Lugar", 			
					(CASE ISNULL(LEFT(fch.NOTAS, 4), '') 
						WHEN '3171' THEN NULL
						ELSE '99' 
					END) AS "CodNaturezaTransacao",
					'US' AS "CodPais", 
					CAST(0 as numeric(28, 6)) AS "TotalFrete", 
					CAST(0 as numeric(28, 6)) AS "TotalSeguro",					
					(SELECT 
						NULLIF(LEFT(fch.DESTINATARIO, 70), '') AS "NomeDestinatario", 
						@NomeFicheiroXML AS "NomeFicheiro", 
						NULLIF(fch.GUIA, '') AS "Referencia1"				
					FOR XML PATH('DadosManifesto'), TYPE), 					
					(SELECT
						(SELECT 
							1 AS "NumeroAdicao", 
							'0000000000' AS "CodArtigo", 
							NULLIF(MIN(fch.DESIGNACAO_MERCADORIA), '') AS "DesignacaoArtigo", 
							CAST(SUM(fch.PESO_GROSS) AS numeric(28, 6)) AS "MassaBruta", 
							CAST(SUM(fch.PESO_NET_TOTAL) AS numeric(28, 6)) AS "MassaLiquida",						
							NULLIF(LEFT(fch.NOTAS, 4), '') AS "Regime", 							
							CAST(0 AS numeric(28, 6)) AS "QtdUnidades", 
							CAST(SUM(fch.VALOR_UNIT_EXP) AS numeric(28, 6)) AS "ValorAdicao", 
							CAST(0 AS numeric(28, 6)) AS "ValorFrete", 
							CAST(0 AS numeric(28, 6)) AS "ValorSeguro", 																																																					
							(SELECT TOP 1
								(SELECT 									
									TEM_CODI AS "CodNaturezaVols", 
									CAST(SUM(fch.N_VOLUMES) AS numeric(28, 6)) AS "NumeroVols", 						
									0 AS "P", 						
									0 AS "R"									
								FOR XML PATH('MarcaEVolume'), TYPE)
							FROM TAB_TEMB WITH(NOLOCK)
							WHERE TEM_CODI = 'CT' AND TEM_EXPT = 1	
							FOR XML PATH('MarcasEVolumes'), TYPE)										
						FOR XML PATH('Adicao'), TYPE)
					FOR XML PATH('Adicoes'), TYPE), 
					(SELECT 
						(SELECT
							@NomeFicheiroXML AS "NomeArquivo", 
							'Ficheiro OGMA AWB/CMR' AS "DescricaoArquivo", 							
							2 AS "OrigemArquivo", 
							@FicheiroBase64 AS "FicheiroBase64" 
						FOR XML PATH('Arquivo'), TYPE)
					FOR XML PATH('Arquivos'), TYPE)
				FROM @TmpFicheiroOGMA AS fch				
					INNER JOIN TAB_FORN AS frn WITH(NOLOCK) ON FOR_INAC = 0 AND FOR_DESP = 1 AND frn.FOR_CODI = ISNULL((SELECT TOP 1 FOR_CODI
																														FROM TAB_FORN WITH(NOLOCK) 
																														WHERE FOR_NOME = NULLIF(fch.DESTINATARIO, '')), '999999999')																
					INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON cli.CLI_CODI = '500792828' AND CLI_INAC = 0 AND CLI_DESP = 1					
				GROUP BY fch.NOTAS, fch.AWB, fch.TIPO_PROCEDIMENTO, fch.GUIA, fch.PAIS_EXP_MERCADORIA, fch.DESTINATARIO, frn.FOR_CODI, frn.FOR_NOME, frn.FOR_MORA, frn.FOR_LOCA, frn.FOR_CPOS, 
					frn.FOR_LPOS, frn.FOR_NIF, frn.PAI_CODI, cli.CLI_CODI, cli.CLI_NOME, cli.CLI_MORA, cli.CLI_LOCA, cli.CLI_CPOS, cli.CLI_LPOS, cli.CLI_NIF, cli.PAI_CODI
				FOR XML PATH('Declaracao'), TYPE)
			FOR XML PATH('DeclaracoesExpToGIDWin'), ELEMENTS)
-- processa a geração da declaração Exportação/XML
		SET @Erro = ''
		EXEC @NumErro = SP_ExportacaoXML_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @Erro OUTPUT	
-- senão houver erros na geração, insere as linhas constantes do ficheiro OGMA
		IF @NumErro = 0
		BEGIN
			INSERT INTO tb_TBL_LinhasOGMA(id_declaracaoEXP, numeroLinha, dataProcesso, numeroProcesso, idBILote, artigo, quantidade, unidadeMedidaQtd, valorUnitario, numeroSerie, observacoes, 
				numeroOrdem, dataOrdem, numeroVolumes, guia, numeroAdPrec, codigoPautalPrec, pesoUnitario, unidadeMedidaPeso, tipoProcesso, expedidor, designacaoMercadoria, id_utilizadorControlo, 
				dataControlo)
			SELECT exm.EXM_IDTY, fch.ADICAO, fch.DT_PROCESSO, fch.PROCESSO, fch.BI_LI_ID, fch.ARTIGO, fch.QTD_EXP, fch.UOM_EXP, fch.VALOR_UNIT_EXP, fch.SERIAL_NUM, fch.NOTAS, 
				fch.DAU_PREC, fch.DAU_DATE_PREC, fch.N_VOLUMES, fch.GUIA, fch.NUM_ADIC_PREC, fch.PP_PREC, fch.PESO_GROSS, fch.UOM_WEIGHT, fch.PROCESS_TYPE, fch.DESTINATARIO, fch.DESIGNACAO_MERCADORIA, @IdUtilizador, 
				@DataAtual
			FROM @TmpFicheiroOGMA AS fch	
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON YEAR(@DataAtual) = exm.EXM_EANO AND LEFT(fch.NOTAS, 3) = exm.NDE_CODI AND LEFT(fch.AWB, 18) = exm.EXM_CPRT 
					AND ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') = ISNULL(EXM_P17A, '') AND ISNULL(LEFT(fch.DESTINATARIO, 70), '') = ISNULL(exm.EXM_DENO, '') 
					AND @NomeFicheiroXML = exm.EXM_FUPS
		END					
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ImportaFicheiroOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ImportaFicheiroOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ImportaFicheirosDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_ImportaFicheirosDHL] @FicheiroXML xml, @Gateway varchar(3), @Utilizador varchar(30), @ListaErros varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
-- declaração de variáveis
	DECLARE @DocumentoXML xml(XMLSC_DeclaracoesExpToGIDWin), @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- cria tabela temporária p/ artigos ativos e com fluxo "Ambos" ou "Importação" agrupados por código pautal
	CREATE TABLE #tmpArtigos(
		APA_IDTY int, 
		APA_CPAU varchar(22) COLLATE Latin1_General_CI_AI)
-- cria tabela temporária p/ adições agrupadas das AWB do ficheiro XML
	CREATE TABLE #tmpAdicoes(
		HAWB varchar(18) COLLATE Latin1_General_CI_AI, 
		NatSPV bit, 
		GrossWgt numeric(28, 6), 
		CstmsVal numeric(28, 6), 
		TotalItems int, 
		GoodsItemNo int, 
		TariffQnty numeric(28, 6), 
		TariffCdNo varchar(22) COLLATE Latin1_General_CI_AI, 
		DescOfGoods varchar(150) COLLATE Latin1_General_CI_AI, 
		InvNo varchar(50) COLLATE Latin1_General_CI_AI, 
		InvLineVal numeric(28, 6), 
		InvoiceDate datetime, 
		NetWeight numeric(28, 6))	
-- obtem os artigos ativos e com fluxo "Ambos" ou "Exportação" agrupados por código pautal sempre a 22 caracteres
	INSERT INTO #tmpArtigos(APA_IDTY, APA_CPAU)
	SELECT MIN(APA_IDTY), (ISNULL(APA_CPAU, '') + REPLICATE('0', (22 - LEN(ISNULL(APA_CPAU, '')))))
	FROM TAB_APAU WITH(NOLOCK) 
	WHERE APA_INAC = 0 AND APA_FLUX IN (0, 2)
	GROUP BY (ISNULL(APA_CPAU, '') + REPLICATE('0', (22 - LEN(ISNULL(APA_CPAU, '')))))
-- insere na tabela temporária as adições agrupadas das AWB do ficheiro XML
	INSERT INTO #tmpAdicoes(HAWB, NatSPV, GrossWgt, CstmsVal, TotalItems, GoodsItemNo, TariffQnty, TariffCdNo, DescOfGoods, InvNo, InvLineVal, InvoiceDate, NetWeight)
	SELECT t0.CAB_HAWB, 0, ISNULL(t0.CAB_MBRT, 0), ABS(ISNULL(t0.CAB_VALO, 0)), COUNT(*) OVER(PARTITION BY t0.CAB_HAWB), ROW_NUMBER() OVER(PARTITION BY t0.CAB_HAWB ORDER BY t0.APA_CODI, t0.LIN_DART), 
		SUM(ISNULL(t0.LIN_QTDE, 0)), ISNULL(t0.APA_CODI, '00000000'), ISNULL(t0.LIN_DART, 'Sem Descricao'), MIN(NULLIF(t0.LIN_INVN, '')), SUM(ABS(ISNULL(t0.LIN_VALO, 0))), 
		MIN(t0.LIN_INVD), SUM(ISNULL(t0.LIN_MBRT, 0))							
	FROM (SELECT XML_LINS.LIN_DATA.value('(../../HAWB)[1]', 'varchar(18)') as CAB_HAWB, XML_LINS.LIN_DATA.value('(../../GrossWgt)[1]', 'numeric(28, 6)') as CAB_MBRT, 
			XML_LINS.LIN_DATA.value('(../../TxAndDty/CstmsVal)[1]', 'numeric(28, 6)') as CAB_VALO, XML_LINS.LIN_DATA.value('TariffQnty[1]', 'numeric(28, 6)') as LIN_QTDE, 
			apa.APA_CODI, ISNULL(NULLIF(apa.APA_DESG, ''), XML_LINS.LIN_DATA.value('DescOfGoods[1]', 'varchar(150)')) as LIN_DART,  
			XML_LINS.LIN_DATA.value('InvNo[1]', 'varchar(50)') as LIN_INVN, XML_LINS.LIN_DATA.value('InvLineVal[1]', 'numeric(28, 6)') as LIN_VALO, 
			XML_LINS.LIN_DATA.value('InvoiceDate[1]', 'datetime') as LIN_INVD, XML_LINS.LIN_DATA.value('NetWeight[1]', 'numeric(28, 6)') as LIN_MBRT
		FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp/LineItems/LineItem') as XML_LINS(LIN_DATA)
			LEFT OUTER JOIN #tmpArtigos AS art ON (NULLIF(XML_LINS.LIN_DATA.value('TariffCdNo[1]', 'varchar(22)'), '') + REPLICATE('0', (22 - LEN(NULLIF(XML_LINS.LIN_DATA.value('TariffCdNo[1]', 'varchar(22)'), ''))))) = art.APA_CPAU
			LEFT OUTER JOIN TAB_APAU AS apa WITH(NOLOCK) ON art.APA_IDTY = apa.APA_IDTY) AS t0
	GROUP BY t0.CAB_HAWB, t0.CAB_MBRT, t0.CAB_VALO, t0.APA_CODI, t0.LIN_DART
-- remove a tabela temporária dos artigos
	DROP TABLE #tmpArtigos
-- processa ajustamentos do valor e peso da adições em função do total de linhas de adições da AWB
	UPDATE #tmpAdicoes SET 
		NatSPV = (CASE 
					WHEN (TotalItems > 1) AND (EXISTS(SELECT t.HAWB FROM #tmpAdicoes AS t WHERE (t.InvLineVal = 0 OR t.NetWeight = 0) AND t.HAWB = #tmpAdicoes.HAWB)) THEN 1 
					ELSE NatSPV 
				END), 		
		InvLineVal = (CASE 
						WHEN (TotalItems = 1) THEN CstmsVal
						WHEN (TotalItems > 1) AND (EXISTS(SELECT t.HAWB FROM #tmpAdicoes AS t WHERE (t.InvLineVal = 0 OR t.NetWeight = 0) AND t.HAWB = #tmpAdicoes.HAWB)) THEN ROUND((CstmsVal / TotalItems), 3)
						ELSE InvLineVal
					END), 
		NetWeight = (CASE 
						WHEN (TotalItems = 1) THEN ROUND(GrossWgt, 3)
						WHEN (TotalItems > 1) AND (GoodsItemNo = TotalItems) THEN (
									ROUND(GrossWgt, 3) - 
									(SELECT SUM(ROUND((ROUND(t.GrossWgt, 3) / t.TotalItems), 3))
									FROM #tmpAdicoes AS t
									WHERE t.HAWB = #tmpAdicoes.HAWB AND t.GoodsItemNo < #tmpAdicoes.GoodsItemNo))
						ELSE ROUND((ROUND(GrossWgt, 3) / TotalItems), 3)
					END)
-- obtem lista das declarações de exportação do ficheiro em formato XML 
	SELECT @DocumentoXML = 
		(SELECT
			(SELECT 'I' AS "@Acao", 
				'A' AS "TipoProcedimento",
				(CASE 
					WHEN (XML_DECL.DCL_DATA.value('(ShpCnsgnr/DHLAcctNo)[1]', 'varchar(18)') IN ('307046822', '307850760', '307023685', '307053046', '307053314')) 
						OR (REPLACE(REPLACE(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="VAT"]/TraderRefId)[1]', 'varchar(18)'), ''), XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/TraderID)[1]', 'varchar(18)')), ' ', ''), 'PT', '') IN ('515540668', '503931705', '980636582', '503226696', '502501510')) THEN '98' 
					WHEN EXISTS(SELECT HAWB FROM #tmpAdicoes WHERE HAWB = NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') and NatSPV = 1) THEN 'SPV' 
					WHEN EXISTS(SELECT HAWB FROM #tmpAdicoes WHERE HAWB = NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '') and ISNULL(TariffCdNo, '') = '00000000') THEN 'CCP' 
					ELSE 'DCC' 
				END) AS "CodNatureza", 
				'00000' AS "CodOperador", 
				(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "Data",
				('DCC ' + XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(50)')) AS "VossaReferencia", 
				(CASE @Gateway 
					WHEN 'OPO' THEN 'PT000020' 
					ELSE 'PT000015' 
				END) AS "CodEstanciaA", 				
				(CASE 
					WHEN XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') in ('CH', 'GB', 'GG', 'IS', 'JE', 'LI', 'MK', 'NO', 'RS', 'XS', 'TR', 'UA') THEN 'EU A' 
					WHEN XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') in ('ES', 'FR', 'NL') THEN 'COM1' 
					WHEN XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') = 'AD' THEN 'EX_S' 
					ELSE 'EX A' 
				END) AS "CodTipoDeclaracao", 				
				XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)') AS "NumeroCPA", 				
				(CASE 
					WHEN XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') in ('ES', 'FR', 'NL') THEN 'TF' 
					WHEN XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') = 'AD' THEN 'TD' 
					ELSE 'X' 
				END) AS "TipoCarga",
				(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "DataVoo", 
				(SELECT 
					ISNULL((SELECT TOP 1 CLI_CODI 
							FROM TAB_CLIE WITH (NOLOCK) 
							WHERE CLI_NIF = REPLACE(REPLACE(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="VAT"]/TraderRefId)[1]', 'varchar(18)'), ''), XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/TraderID)[1]', 'varchar(18)')), ' ', ''), 'PT', '')), 
							(SELECT TOP 1 CLI_CODI 
							FROM TAB_CLIE WITH (NOLOCK) 
							WHERE CLI_CEAN = XML_DECL.DCL_DATA.value('(ShpCnsgnr/DHLAcctNo)[1]', 'varchar(13)'))) AS "Codigo", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/CoName)[1]', 'varchar(70)')) AS "Nome",
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)')) AS "Morada",
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)')) AS "Localidade",
					XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)') AS "CodPostal",
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)')) AS "LocPostal",
					REPLACE(REPLACE(ISNULL(NULLIF(XML_DECL.DCL_DATA.value('(ShpCnsgnr/TraderRef[TraderRefIssAgncyCd="VAT"]/TraderRefId)[1]', 'varchar(18)'), ''), XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/TraderID)[1]', 'varchar(18)')), ' ', ''), 'PT', '') AS "NIF",
					XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') AS "CodPais"
				FOR XML PATH('Expedidor'), TYPE),
				XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(70)') AS "NumeroComercialRef", 
				(SELECT 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(70)')) AS "Nome",
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)')) AS "Morada",
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)')) AS "Localidade",
					XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)') AS "CodPostal",
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)')) AS "LocPostal",							
					(CASE XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') 
						WHEN 'RS' THEN 'XS' 
						WHEN 'PR' THEN 'US' 
						WHEN 'XY' THEN 'BL' 
						WHEN 'KV' THEN 'XK' 
						WHEN 'JE' THEN 'GB' 
						WHEN 'GG' THEN 'GB' 
						WHEN 'XM' THEN 'SX' 
						WHEN 'XB' THEN 'BQ' 
						WHEN 'XC' THEN 'CW'
						ELSE XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') 
					END) AS "CodPais"
				FOR XML PATH('Destinatario'), TYPE), 
				XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') AS "CodPais15A", 
				(CASE XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') 
					WHEN 'RS' THEN 'XS' 
					WHEN 'PR' THEN 'US' 
					WHEN 'XY' THEN 'BL' 
					WHEN 'KV' THEN 'XK' 
					WHEN 'JE' THEN 'GB' 
					WHEN 'GG' THEN 'GB' 
					WHEN 'XM' THEN 'SX' 
					WHEN 'XB' THEN 'BQ' 
					WHEN 'XC' THEN 'CW'
					ELSE XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)') 
				END) AS "CodPais17A", 
				'A' AS "ICE", 
				(SELECT 
					'40' AS "CodMeioTransporte25", 
					XML_DECL.DCL_DATA.value('ShpDest[1]', 'varchar(3)') AS "CodAeroporto"
				FOR XML PATH('MeioTransportePartida'), TYPE), 
				(SELECT 
					'40' AS "CodMeioTransporte", 
					((CASE @Gateway WHEN 'OPO' 
						THEN 'QY8213' 
						ELSE 'BCS8166' 
					END) + ' ' + CONVERT(varchar(10), @DataAtual, 105)) AS "MatriculaMT", 
					'BE' AS "CodPais"
				FOR XML PATH('MeioTransporteFronteira'), TYPE), 
				(CASE @Gateway 
					WHEN 'OPO' THEN 'PT000020' 
					ELSE 'PT000015' 
				END) AS "CodEstanciaTAC", 
				(CASE @Gateway 
					WHEN 'OPO' THEN 'AEX00000473020PT' 
					ELSE 'AEX00000802015PT' 
				END) AS "LocalizacaoMercadorias/CodLocalAutorizado", 
				XML_DECL.DCL_DATA.value('Incoterms[1]', 'varchar(3)') "CodCondEntrega", 
				(CASE 
					WHEN XML_DECL.DCL_DATA.value('Incoterms[1]', 'varchar(3)') IN ('CIP', 'CPT', 'DDP', 'DDU', 'DAP') THEN XML_DECL.DCL_DATA.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(50)') 
					WHEN XML_DECL.DCL_DATA.value('Incoterms[1]', 'varchar(3)') = 'XXX' THEN ('Livre Encargos ' + XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(50)')) 
					ELSE XML_DECL.DCL_DATA.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(50)') 
				END) AS "Lugar", 
				(CASE XML_DECL.DCL_DATA.value('Incoterms[1]', 'varchar(3)') 
					WHEN 'XXX' THEN '99' 
					ELSE '11' 
				END) AS "CodNaturezaTransacao",
				XML_DECL.DCL_DATA.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)') AS "CodPais", 
				CAST(0 as numeric(28, 6)) AS "TotalFrete", 
				CAST(0 as numeric(28, 6)) AS "TotalSeguro",
				(CASE 
					WHEN XML_DECL.DCL_DATA.value('Category[1]', 'varchar(10)') IN ('2', '3', '4') THEN 'LV' 
					WHEN XML_DECL.DCL_DATA.value('Category[1]', 'varchar(10)') IN ('5', '6', '7') THEN 'HV' 
					ELSE NULL 
				END) AS "HVLV", 
				1 AS "Origem",
				XML_DECL.DCL_DATA.value('(ShpCnsgnr/DHLAcctNo)[1]', 'varchar(18)') AS "DadosManifesto/MiniCPA",
				NULLIF(XML_DECL.DCL_DATA.value('(CustomAtts/CustomAtt[Name_Eng="Shipment Reference 1"]/Val)[1]', 'varchar(50)'), '') AS "DadosManifesto/Referencia1", 
				(SELECT
					(SELECT 
						GoodsItemNo AS "NumeroAdicao", 
						TariffCdNo AS "CodArtigo", 
						DescOfGoods AS "DesignacaoArtigo", 
						CAST(NetWeight AS numeric(28, 6)) AS "MassaBruta", 
						CAST((CASE 
								WHEN XML_DECL.DCL_DATA.value('(ShpCnsgnr/DHLAcctNo)[1]', 'varchar(18)') IN ('951733859', '308037410') THEN ROUND((NetWeight * 50 / 100), 3) 
								ELSE ROUND((NetWeight * 95 / 100), 3) 
							END) AS numeric(28, 6)) AS "MassaLiquida",						
						'1000' AS "Regime", 
						CAST(TariffQnty AS numeric(28, 6)) AS "QtdUnidades", 
						CAST(InvLineVal AS numeric(28, 6)) AS "ValorAdicao", 
						CAST(0 AS numeric(28, 6)) AS "ValorFrete", 
						CAST(0 AS numeric(28, 6)) AS "ValorSeguro", 
						(SELECT 
							(SELECT 
								DOC_CODI AS "CodDocumento", 
								DOC_NREF AS "NumeroReferencia", 
								DOC_DTEM AS "DataEmissao"									
							FROM (
								SELECT 'N740' as DOC_CODI, XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(50)') as DOC_NREF, (CONVERT(varchar(10), @DataAtual, 127) + 'Z') as DOC_DTEM
								UNION						
								SELECT 'N380' as DOC_CODI, InvNo as DOC_NREF, (CONVERT(varchar(10), ISNULL(InvoiceDate, @DataAtual), 127) + 'Z') as DOC_DTEM													
								UNION
								SELECT 'N830' as DOC_CODI, XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(50)') as DOC_NREF, (CONVERT(varchar(10), @DataAtual, 127) + 'Z') as DOC_DTEM
								) AS UNI_DOCS									
							FOR XML PATH('Documento'), TYPE)
						HAVING GoodsItemNo = 1
						FOR XML PATH('Documentos'), TYPE), 
						(SELECT
							(SELECT 
								'DHAB' AS "CodMencao"					
							FOR XML PATH('MencaoEspecial'), TYPE)
						HAVING GoodsItemNo = 1
						FOR XML PATH('MencoesEspeciais'), TYPE), 					
						(SELECT
							(SELECT 
								'LET' AS "Marca", 																			
								'CT' AS "CodNaturezaVols", 
								XML_DECL.DCL_DATA.value('SDPieces[1]', 'numeric(28, 6)') AS "NumeroVols", 						
								(CASE 
									WHEN (GoodsItemNo < TotalItems) THEN CAST(1 as bit) 
									ELSE CAST(0 as bit) 
								END) AS "P", 						
								(CASE 
									WHEN ((GoodsItemNo > 1) and (GoodsItemNo = TotalItems)) THEN CAST(1 as bit) 
									ELSE CAST(0 as bit) 
								END) AS "R"						
							FOR XML PATH('MarcaEVolume'), TYPE)
						FOR XML PATH('MarcasEVolumes'), TYPE)
					FROM #tmpAdicoes
					WHERE HAWB = NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), '')
					FOR XML PATH('Adicao'), TYPE)
				FOR XML PATH('Adicoes'), TYPE)
			FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp') AS XML_DECL(DCL_DATA)
			WHERE NOT EXISTS(SELECT EXM_CODI FROM PRO_EXML WITH (NOLOCK) WHERE DATEDIFF(DAY, EXM_DATA, @DataAtual) < 90 and EXM_CPRT = NULLIF(XML_DECL.DCL_DATA.value('HAWB[1]', 'varchar(18)'), ''))
			FOR XML PATH('Declaracao'), TYPE)
		FOR XML PATH('DeclaracoesExpToGIDWin'), ELEMENTS)
-- remove a tabela temporária
		DROP TABLE #tmpAdicoes		
-- processa a geração das Declarações de Exportação/XML carregadas no XML
		EXEC SP_ExportacaoXML_GeraDeclaracoesDeXML @DocumentoXML, @Utilizador, @ListaErros OUTPUT			
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ImportaFicheirosDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ImportaFicheirosDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ImportaFicheirosXMLRespostaCTT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_ImportaFicheirosXMLRespostaCTT] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ErroFicheiro varchar(MAX), @DataAtual datetime, @ComandoSQL varchar(1500), @Erros varchar(MAX), @FicheiroXML xml, 
		@XMLShippingDate datetime, @XMLNumDocTransporte varchar(18), @i int, @PathFicheiroErro varchar(500), @Linha varchar(MAX)
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros CTT a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE FicheirosCTT CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]	
	OPEN FicheirosCTT
	FETCH NEXT FROM FicheirosCTT INTO @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN										
		BEGIN TRY	
			SET @ErroFicheiro = NULL
-- obtem data atual GMT
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'			
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			SET @Erros = ''
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)	
-- obtem o xml do ficheiro xml importado					
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- inicia variaveis
			SET @Erros = ''
-- obtem lista de declarações existentes dentro do ficheiro XML
			DECLARE DeclaracoesCTT CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT 
					NULLIF(x.d.value('shippingDate[1]', 'datetime'), ''), 
					NULLIF(x.d.value('NumDocTransporte[1]', 'varchar(18)'), '')
				FROM @FicheiroXML.nodes('DeclaracoesImpToGIDWin/Declaracao') AS x(d)
			OPEN DeclaracoesCTT
			FETCH NEXT FROM DeclaracoesCTT INTO @XMLShippingDate, @XMLNumDocTransporte
			WHILE @@FETCH_STATUS = 0
			BEGIN											
-- atualiza a data pick-up (shipping date) da declaração EXP
				UPDATE PRO_EXML SET 
					EXM_PIUP = 1, 
					EXM_DPUP = @XMLShippingDate,
					EXM_UALT = @Utilizador, 
					EXM_DTAL = @DataAtual
				WHERE EXM_CPRT = @XMLNumDocTransporte				
				FETCH NEXT FROM DeclaracoesCTT INTO @XMLShippingDate, @XMLNumDocTransporte
			END
			CLOSE DeclaracoesCTT
			DEALLOCATE DeclaracoesCTT							
		END TRY
		BEGIN CATCH			
-- constroi mensagem de erro detalhada p/ gerar ficheiro de erro
			SET @ErroFicheiro = '**********************************************************************************************************' + CHAR(12) +
								'** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								'**********************************************************************************************************' + CHAR(12) + 
								'.Nome Ficheiro CTT:  ' + @NomeFicheiro + CHAR(12) +								   
								'.Detalhe Erro:       ' + CHAR(12) +
								'		*Data do Erro:       ' + CONVERT(varchar(23), @DataAtual, 126) + CHAR(12) + 
								'		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								'		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								'		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								'		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								'		*N. Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								'		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH		
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ErroFicheiro, '') <> ''
		BEGIN									
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ErroFicheiro, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ErroFicheiro = STUFF(@ErroFicheiro, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			END								
		END		
		FETCH NEXT FROM FicheirosCTT INTO @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosCTT
	DEALLOCATE FicheirosCTT
-- remove a tabela temporária	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ImportaFicheirosXMLRespostaCTT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ImportaFicheirosXMLRespostaCTT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ExportacaoXML_ObtemDeclaracaoPorNumeroCPA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_ExportacaoXML_ObtemDeclaracaoPorNumeroCPA] @NumeroCPA varchar(18), @Ano int OUTPUT, @Codigo int OUTPUT, @CodOperador varchar(6) OUTPUT, 
	@NumeroRefLocal varchar(22) OUTPUT, @CodNatureza varchar(3) OUTPUT, @CodFollowUp int OUTPUT, @Contexto tinyint OUTPUT AS
BEGIN
	SET NOCOUNT ON
-- obtem dados de declaração de Exportação/XML por Ano e Numero CPA
	SELECT TOP 1 @Ano = EXM_EANO, @Codigo = EXM_CODI, @CodOperador = DEC_CODI, @NumeroRefLocal = EXM_NRLO, @CodNatureza = NDE_CODI, @CodFollowUp = FUP_CODI, 
		@Contexto = EXM_CNTX
	FROM PRO_EXML WITH(NOLOCK)
	WHERE EXM_EANO = @Ano AND EXM_CPRT = @NumeroCPA
END

ALTER AUTHORIZATION ON [SP_ExportacaoXML_ObtemDeclaracaoPorNumeroCPA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ExportacaoXML_ObtemDeclaracaoPorNumeroCPA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_AtualizaDocContasEmCursoSAPERDO]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_AtualizaDocContasEmCursoSAPERDO] @URLEndpointGet varchar(8000), @URLEndpointSet varchar(8000), @Tennant varchar(250), @Channel varchar(250), @CodEmpresaSAP varchar(10), 
	@DataReferencia datetime, @DirLogFile varchar(500), @CodNaturezaIMP1 varchar(3), @CodNaturezaIMP2 varchar(3), @CodNaturezaIMP3 varchar(3), @CodNaturezaEXP1 varchar(3), 
	@CodNaturezaEXP2 varchar(3), @CodNaturezaEXP3 varchar(3) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis	
	DECLARE @DataAtual datetime, @TotalContasPendentes int, @AnoDocumento int, @CodTipoDocumento varchar(4), @IdDocumento int, @NumProcesso int, @AnoProcesso int, @CtxProcesso bit, 
		@IdConta bigint, @ImpExp varchar(1), @NumLinhaDocumentada int, @NumLinhaDetDocumentada int
	DECLARE @JsonRecord varchar(250), @JsonRequest varchar(MAX), @JsonResponse Varchar(8000), @XMLResponse xml
	DECLARE @TblTmpContas TABLE(CDO_IDTY bigint NOT NULL)
	DECLARE @TblTmpContas10 TABLE(CDO_EANO int NOT NULL, CDO_TDOC varchar(4) NOT NULL, CDO_IDEN int NOT NULL, CDO_NPRO int NOT NULL, CDO_PANO int NOT NULL, CDO_IMEX bit NOT NULL)	
	DECLARE @RESTObj int, @Comando nvarchar(4000), @PathLogFile varchar(600)
	DECLARE @Plataforma varchar(20), @NumDocOrigem varchar(60), @DataDocOrigem datetime, @Montante numeric(38, 6), @ItemDocOrigem varchar(10), @CodDespDocumentada int, 
		@NomeDespDocumentada varchar(70), @MontanteTotal numeric(38, 6)
-- verfica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirLogFile), 1, 1) <> '\'
		SET @DirLogFile = @DirLogFile + '\'
-- cria tabela temporária p/ guardar informação da importação
	CREATE TABLE ##LogTableDocContasSAP0(
		ID int NOT NULL IDENTITY(1, 1), 
		ANODOC int NOT NULL, 
		TIPODOC varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
		IDDOC int NOT NULL,		
		NUMPROCESSO int NOT NULL, 
		ANOPROCESSO int NOT NULL,
		CTXPROCESSO varchar(1) COLLATE Latin1_General_CI_AI NOT NULL, 		
		INFO varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- efetua o log do inicio do processo de atualização de documentos de Contas de SAP	
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# INICIO ATUALIZACAO CONTAS-EM_CURSO ###############################################################################################################################')
	END
	BEGIN TRY
-- obtem os documentos de Contas não emitidos, não anulados, com ligação a processo IMP/EXP, com natureza de Flat-File EDI e enviados p/ SAP
		INSERT INTO @TblTmpContas(CDO_IDTY)
		SELECT dco.CDO_IDTY
		FROM FAC_CDOC AS dco WITH(NOLOCK) 
			INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dco.NDE_CODI = nat.NDE_CODI			
		WHERE dco.CDO_PANO IS NOT NULL AND dco.CDO_STAT = 0 AND dco.CDO_CNUM IS NULL AND dco.CDO_ANUL = 0 AND dco.CDO_IMPR = 0 AND dco.CDO_CPRO = 1 
			AND (nat.NDE_FEDI = 1 OR dco.NDE_CODI IN (@CodNaturezaIMP1, @CodNaturezaIMP2, @CodNaturezaIMP3, @CodNaturezaEXP1, @CodNaturezaEXP2, @CodNaturezaEXP3))
			AND CAST(CONVERT(varchar(10), dco.CDO_DTCR, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
		ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN	
-- obtem o total de documentos de Contas pendentes de processamento
		SELECT @TotalContasPendentes = COUNT(*) 
		FROM @TblTmpContas
-- efetua o log do total de documentos de Conta a atualizar do SAP		
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN
			INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## INFO-CONTAS: Existem ' + LTRIM(STR(@TotalContasPendentes, 20)) + ' documentos de Contas "Em Curso" disponiveis para atualizacao do SAP.')
		END
-- processa todos os documentos de Conta obtidos 
		WHILE (@TotalContasPendentes > 0)
		BEGIN
			SET @JsonRequest = NULL
			SET @JsonResponse = NULL
			DELETE FROM @TblTmpContas10
-- obtem os PRIMEIROS 10 documentos de Contas não emitidos, não anulados, com ligação a processo IMP/EXP, com natureza de Flat-File EDI e enviados p/ SAP
			DECLARE DocsConta CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN, dco.CDO_NPRO, dco.CDO_PANO, dco.CDO_IMEX, dco.CDO_IDTY, 
					(CASE dco.CDO_IMEX WHEN 1 THEN 'E' ELSE 'I' END)
				FROM FAC_CDOC AS dco WITH(NOLOCK) 
					INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dco.NDE_CODI = nat.NDE_CODI			
				WHERE dco.CDO_IDTY IN (SELECT TOP 10 CDO_IDTY FROM @TblTmpContas)
				ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN			
			OPEN DocsConta
			FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso, @IdConta, @ImpExp
			WHILE @@FETCH_STATUS = 0
			BEGIN
-- constroi a linha do documento de Conta no formato Json		
				SET @JsonRecord = ''
				SET @JsonRecord = @JsonRecord + '{"empresa":"' + ISNULL(@CodEmpresaSAP, '') + '",'		
				SET @JsonRecord = @JsonRecord + '"processoNumero":"' + ISNULL(LTRIM(STR(@NumProcesso, 20)), '') + '",'
				SET @JsonRecord = @JsonRecord + '"documentoStatus":""},'	
-- adiciona dados Json do documento de Conta ao Json Request 
				SET @JsonRequest = ISNULL(@JsonRequest, '') + @JsonRecord
-- insere documento de Conta na tabela tmp
				INSERT INTO @TblTmpContas10(CDO_EANO, CDO_TDOC, CDO_IDEN, CDO_NPRO, CDO_PANO, CDO_IMEX)
				VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso)
-- remove documento de Conta do repositório
				DELETE FROM @TblTmpContas
				WHERE CDO_IDTY = @IdConta
-- efetua o log do documento de Conta a enviar p/ SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## JSON-CONTA: ' + @JsonRecord)
				END
				FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso, @IdConta, @ImpExp
			END
			CLOSE DocsConta
			DEALLOCATE DocsConta
-- se foram obtidos documentos, processa envio p/ SAP via REST API
			IF ISNULL(@JsonRequest, '') <> ''
			BEGIN
-- remove último caracter ","
				SET @JsonRequest = REVERSE(STUFF(REVERSE(@JsonRequest), 1, 1, ''))
-- adiciona header ao request
				SET @JsonRequest = '{"header":{"tennant": "' + ISNULL(@Tennant, '') + '","channel":"' + ISNULL(@Channel, '') + '"},"documentos": [' + @JsonRequest + ']}'
-- efetua o log do Json request a enviar p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-REQUEST: ' + @JsonRequest)
				END
-- cria objeto p/ REST API
				EXEC sp_OACreate 'MSXML2.ServerXMLHTTP.3.0', @RESTObj OUTPUT	
-- atribui endpoint ao objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'open', NULL, 'POST', @URLEndpointGet, 'False'
-- inicia header do objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'setRequestHeader', NULL, 'Content-Type', 'application/json'
-- processa envio do request p/ REST API
				EXEC sp_OAMethod @RESTObj, 'send', NULL, @JsonRequest
-- efetua o log do envio do Json request p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## API-URL: ' + ISNULL(@URLEndpointGet, '<nulo>'))
				END
-- obtem response da REST API
				EXEC sp_OAMethod @RESTObj, 'responseText', @JsonResponse OUTPUT			
-- destroi objeto 			
				EXEC sp_OADestroy @RESTObj	
-- efetua o log do Json response recebido da API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-RESPONSE: ' + ISNULL(@JsonResponse, '<nulo>'))
				END
			END					
-- inicia Json Request
			SET @JsonRequest = NULL
-- se respostas obtida do REST API
			IF ISNULL(@JsonResponse, '') <> ''
			BEGIN
				SET @XMLResponse = dbo.fn_Geral_ConverteJson2Xml(@JsonResponse)
-- obtem as despesas documentadas obtidas do REST API
				DECLARE DespDocumentadas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
					SELECT 
						t.d.value('plataforma[1]', 'varchar(20)'), 
						t.d.value('documentoNumero[1]', 'varchar(60)'), 	
						t.d.value('dataCriacao[1]', 'datetime'), 
						((CASE t.d.value('codigo[1]', 'varchar(1)') WHEN 'H' THEN -1 ELSE 1 END) * t.d.value('montante[1]', 'numeric(18, 2)')),	
						t.d.value('item[1]', 'varchar(10)'), 	
						dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN, dco.CDO_NPRO, dco.CDO_PANO, ddo.DDO_CODI, ddo.DDO_NOME, 
						(CASE dco.CDO_IMEX WHEN 1 THEN 'E' ELSE 'I' END)
					FROM @XMLResponse.nodes('documentos') AS t(d)
						INNER JOIN @TblTmpContas10 AS dco ON CAST(t.d.value('processo[1]', 'varchar(20)') AS int) = dco.CDO_NPRO AND t.d.value('ano[1]', 'int') = dco.CDO_PANO AND (CASE t.d.value('tipo[1]', 'varchar(1)') WHEN 'E' THEN 1 ELSE 0 END) = dco.CDO_IMEX
						LEFT OUTER JOIN TAB_DDOC AS ddf ON t.d.value('rubrica[1]', 'varchar(10)') = ddf.DDO_SPCD
						INNER JOIN TAB_DDOC AS ddo ON ISNULL(ddf.DDO_CODI, 999) = ddo.DDO_CODI						
					WHERE ddo.DDO_CREC IS NULL 
				OPEN DespDocumentadas
				FETCH NEXT FROM DespDocumentadas INTO @Plataforma, @NumDocOrigem, @DataDocOrigem, @Montante, @ItemDocOrigem, @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, 
					@AnoProcesso, @CodDespDocumentada, @NomeDespDocumentada, @ImpExp
				WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @NumLinhaDocumentada = NULL
					SET @NumLinhaDetDocumentada = NULL					
-- obtem dados da linha da despesa documentada 
					SELECT TOP 1 @NumLinhaDocumentada = DCD_LINH
					FROM FAC_DCDO WITH(NOLOCK) 						
					WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DDO_CODI = @CodDespDocumentada
-- insere despesa documentada na Conta se não existir
					IF @NumLinhaDocumentada IS NULL
					BEGIN										
-- obtem o 1º número de linha vazio para atribuição de despesa documentada
						SET @NumLinhaDocumentada = ISNULL((SELECT MIN(DCD_LINH) 
														FROM FAC_DCDO 
														WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DDO_CODI IS NULL), 1)
-- insere despesa documentada na Conta
						UPDATE FAC_DCDO SET DDO_CODI = @CodDespDocumentada, DCD_DESC = @NomeDespDocumentada, DCD_VTOT = 0
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada	
-- efetua o log da despesa documentada inserida no documento de Conta
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Despesa documentada adicionada ao documento de Conta: ' + CAST(@CodDespDocumentada AS varchar(10)))
						END								
					END
-- obtem o próximo número de linha para atribuição do detalhe
					SET @NumLinhaDetDocumentada = ISNULL((SELECT MAX(DDC_ADIC) 
														FROM FAC_DDCD 
														WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada), 0) + 1
-- insere detalhe na despesa documentada
					INSERT INTO FAC_DDCD(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DDC_ADIC, DDC_DORI, DDC_DATA, DDC_TIVA, DDC_VALO)
					VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumLinhaDocumentada, @NumLinhaDetDocumentada, @NumDocOrigem, @DataDocOrigem, 0, @Montante)
-- efetua o log do detalhe de documento inserido na despesa documentada
					IF ISNULL(@DirLogFile, '') <> ''
					BEGIN
						INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
						VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Detalhe de documento adicionado a despesa documentada: ' + @NumDocOrigem + ' | ' + LTRIM(STR(@Montante, 18, 2)) + ' | ' + CAST(@CodDespDocumentada AS varchar(10)))
					END					
-- obtém a soma do valor do detalhe das despesas documentadas
					SELECT @MontanteTotal = SUM(ISNULL(DDC_VALO, 0))
					FROM FAC_DDCD 
					WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada
-- atualiza valor da despesa documentada com a soma obtida
					UPDATE FAC_DCDO SET DCD_VTOT = @MontanteTotal, DCD_DNOW = @DataAtual, DCD_VFCX = 1
					WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada
-- efetua o log da atualização do montante na despesa documentada
					IF ISNULL(@DirLogFile, '') <> ''
					BEGIN
						INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
						VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Despesa documentada com montante atualizado: ' + CAST(@CodDespDocumentada AS varchar(10)) + ' | ' + LTRIM(STR(@MontanteTotal, 18, 2)))
					END
-- obtém a soma do valor das despesas documentadas da Conta
					SELECT @MontanteTotal = SUM(ISNULL(DCD_VTOT, 0))
					FROM FAC_DCDO 
					WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento
-- atualiza valores totais da Conta
					UPDATE FAC_CDOC SET CDO_TTDC = @MontanteTotal, CDO_TTPR = (@MontanteTotal + ISNULL(CDO_TTIN, 0) + ISNULL(CDO_TTHO, 0) + ISNULL(CDO_IVA, 0))
					WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento					
-- efetua o log da atualização do total de documentadas no documento de Conta
					IF ISNULL(@DirLogFile, '') <> ''
					BEGIN
						INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
						VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Documento de Conta com total documentadas atualizado: ' + LTRIM(STR(@MontanteTotal, 18, 2)))
					END
-- constroi a linha do documento de Conta no formato Json		
					SET @JsonRecord = ''
					SET @JsonRecord = @JsonRecord + '{"empresa":"' + ISNULL(@CodEmpresaSAP, '') + '",'		
					SET @JsonRecord = @JsonRecord + '"documentoNumero":"' + ISNULL(@NumDocOrigem, '') + '",'
					SET @JsonRecord = @JsonRecord + '"ano":"' + ISNULL(LTRIM(STR(@AnoProcesso, 4)), '') + '",'	
					SET @JsonRecord = @JsonRecord + '"documentoItem":"' + ISNULL(@ItemDocOrigem, '') + '",'
					SET @JsonRecord = @JsonRecord + '"processoNumero":"' + ISNULL(LTRIM(STR(@NumProcesso, 20)), '') + '",'
					SET @JsonRecord = @JsonRecord + '"plataforma":"' + ISNULL(UPPER(@Plataforma), '') + '"},'											
-- adiciona dados Json do documento de Conta ao Json Request 
					SET @JsonRequest = ISNULL(@JsonRequest, '') + @JsonRecord
-- efetua o log do documento de Conta a enviar p/ SAP
					IF ISNULL(@DirLogFile, '') <> ''
					BEGIN
						INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
						VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## JSON-CONTA: ' + @JsonRecord)
					END
					FETCH NEXT FROM DespDocumentadas INTO @Plataforma, @NumDocOrigem, @DataDocOrigem, @Montante, @ItemDocOrigem, @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, 
						@AnoProcesso, @CodDespDocumentada, @NomeDespDocumentada, @ImpExp
				END
				CLOSE DespDocumentadas
				DEALLOCATE DespDocumentadas
			END
-- se foram obtidos documentos, processa envio p/ SAP via REST API
			IF ISNULL(@JsonRequest, '') <> ''
			BEGIN	
				SET @JsonResponse = NULL		
-- remove último caracter ","
				SET @JsonRequest = REVERSE(STUFF(REVERSE(@JsonRequest), 1, 1, ''))
-- adiciona header ao request
				SET @JsonRequest = '{"header":{"tennant": "' + ISNULL(@Tennant, '') + '","channel":"' + ISNULL(@Channel, '') + '"},"documentosLinha": [' + @JsonRequest + ']}'
-- efetua o log do Json request a enviar p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-REQUEST: ' + @JsonRequest)
				END
-- cria objeto p/ REST API
				EXEC sp_OACreate 'MSXML2.ServerXMLHTTP.3.0', @RESTObj OUTPUT	
-- atribui endpoint ao objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'open', NULL, 'POST', @URLEndpointSet, 'False'
-- inicia header do objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'setRequestHeader', NULL, 'Content-Type', 'application/json'
-- processa envio do request p/ REST API
				EXEC sp_OAMethod @RESTObj, 'send', NULL, @JsonRequest
-- efetua o log do envio do Json request p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## API-URL: ' + ISNULL(@URLEndpointSet, '<nulo>'))
				END
-- obtem response da REST API
				EXEC sp_OAMethod @RESTObj, 'responseText', @JsonResponse OUTPUT			
-- destroi objeto 			
				EXEC sp_OADestroy @RESTObj	
-- efetua o log do Json response recebido da API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-RESPONSE: ' + ISNULL(@JsonResponse, '<nulo>'))
				END
			END
-- obtem o total de documentos de Contas pendentes de processamento
			SELECT @TotalContasPendentes = COUNT(*) 
			FROM @TblTmpContas
		END
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de atualização de documentos de Contas de SAP	
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocContasSAP0(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# FIM ATUALIZACAO CONTAS-EM_CURSO ##################################################################################################################################')
	END
-- se diretoria p/ log file especificada, grava ficheiro de log
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
-- constroi full path para geração do ficheiro XML
		SET @PathLogFile = @DirLogFile + 'LOG_SAP2GIDWin0_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), '-', ''), ' ', ''), ':', ''), '.', '') + '.TXT'
-- gera o ficheiro TXT p/ ficheiro log
		SET @Comando = 'bcp "SELECT ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO FROM ##LogTableDocContasSAP0 ORDER BY ID" QUERYOUT "' + @PathLogFile + '" -c -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
	END	
-- remove a tabela temporária	
	DROP TABLE ##LogTableDocContasSAP0
END

ALTER AUTHORIZATION ON [SP_Facturacao_AtualizaDocContasEmCursoSAPERDO] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_AtualizaDocContasEmCursoSAPERDO] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_AtualizaDocContasEncerradosSAPERDO]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_AtualizaDocContasEncerradosSAPERDO] @URLEndpointGet varchar(8000), @URLEndpointSet varchar(8000), @Tennant varchar(250), @Channel varchar(250), @CodEmpresaSAP varchar(10), 
	@DataReferencia datetime, @DirLogFile varchar(500), @Utilizador varchar(30), @CodNaturezaIMP1 varchar(3), @CodNaturezaIMP2 varchar(3), @CodNaturezaIMP3 varchar(3), @CodNaturezaEXP1 varchar(3), 
	@CodNaturezaEXP2 varchar(3), @CodNaturezaEXP3 varchar(3) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis	
	DECLARE @DataAtual datetime, @TotalContasPendentes int, @AnoDocumento int, @CodTipoDocumento varchar(4), @IdDocumento int, @NumProcesso int, @AnoProcesso int, @CtxProcesso bit, 
		@IdConta bigint, @ImpExp varchar(1), @NumLinhaDocumentada int, @NumLinhaDetDocumentada int, @CodNaturezaConta varchar(3), @AnoConta int, @AnoDocumentoOrig int, @IdDocumentoOrig int
	DECLARE @JsonRecord varchar(250), @JsonRequest varchar(MAX), @JsonResponse Varchar(8000), @XMLResponse xml
	DECLARE @TblTmpContas TABLE(CDO_IDTY bigint NOT NULL)
	DECLARE @TblTmpContas10 TABLE(CDO_EANO int NOT NULL, CDO_TDOC varchar(4) NOT NULL, CDO_IDEN int NOT NULL, CDO_NPRO int NOT NULL, CDO_PANO int NOT NULL, CDO_IMEX bit NOT NULL, CDO_IDTY bigint NULL)	
	DECLARE @RESTObj int, @Comando nvarchar(4000), @PathLogFile varchar(600)
	DECLARE @Plataforma varchar(20), @NumDocOrigem varchar(60), @DataDocOrigem datetime, @Montante numeric(38, 6), @ItemDocOrigem varchar(10), @CodDespDocumentada int, 
		@NomeDespDocumentada varchar(70), @MontanteTotal numeric(38, 6)
-- verfica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirLogFile), 1, 1) <> '\'
		SET @DirLogFile = @DirLogFile + '\'
-- cria tabela temporária p/ guardar informação da importação
	CREATE TABLE ##LogTableDocContasSAP1(
		ID int NOT NULL IDENTITY(1, 1),
		ANODOC int NOT NULL, 
		TIPODOC varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
		IDDOC int NOT NULL,		
		NUMPROCESSO int NOT NULL, 
		ANOPROCESSO int NOT NULL,
		CTXPROCESSO varchar(1) COLLATE Latin1_General_CI_AI NOT NULL, 		
		INFO varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- efetua o log do inicio do processo de atualização de documentos de Contas de SAP	
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# INICIO ATUALIZACAO CONTAS-ENCERRADO ###############################################################################################################################')
	END
	BEGIN TRY
-- obtem os documentos de Contas emitidos dentro dos últimos 6 meses, não anulados, com ligação a processo IMP/EXP, com natureza de Flat-File EDI, não duplicados e enviados p/ SAP
		INSERT INTO @TblTmpContas(CDO_IDTY)
		SELECT dco.CDO_IDTY
		FROM FAC_CDOC AS dco WITH(NOLOCK) 
			INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dco.NDE_CODI = nat.NDE_CODI			
		WHERE dco.CDO_PANO IS NOT NULL AND dco.CDO_STAT = 1 AND dco.CDO_CNUM IS NOT NULL AND dco.CDO_ANUL = 0 AND dco.CDO_IMPR = 1 AND dco.CDO_CPRO = 1 
			AND (nat.NDE_FEDI = 1 OR dco.NDE_CODI IN (@CodNaturezaIMP1, @CodNaturezaIMP2, @CodNaturezaIMP3, @CodNaturezaEXP1, @CodNaturezaEXP2, @CodNaturezaEXP3))
			AND NOT EXISTS(SELECT 1
						FROM FAC_CDOC WITH(NOLOCK)
						WHERE CDO_EANO = dco.CDO_EANO AND CDO_TDOC = dco.CDO_TDOC AND CDO_NPRO = dco.CDO_NPRO AND CDO_PANO = dco.CDO_PANO AND CDO_IMEX = dco.CDO_IMEX AND CDO_ORID = dco.CDO_IDEN) 
			AND DATEDIFF(MONTH, dco.CDO_DTEM, @DataAtual) <= 6 AND CAST(CONVERT(varchar(10), dco.CDO_DTCR, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
		ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN			
-- obtem o total de documentos de Contas pendentes de processamento
		SELECT @TotalContasPendentes = COUNT(*) 
		FROM @TblTmpContas
-- efetua o log do total de documentos de Conta a atualizar do SAP		
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN
			INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## INFO-CONTAS: Existem ' + LTRIM(STR(@TotalContasPendentes, 20)) + ' documentos de Contas "Encerrado" disponiveis para atualizacao do SAP.')
		END
-- processa todos os documentos de Conta obtidos 
		WHILE (@TotalContasPendentes > 0)
		BEGIN
			SET @JsonRequest = NULL
			SET @JsonResponse = NULL
			DELETE FROM @TblTmpContas10
-- obtem os PRIMEIROS 10 documentos de Contas emitidos dentro dos últimos 6 meses, não anulados, com ligação a processo IMP/EXP, com natureza de Flat-File EDI, não duplicados e enviados p/ SAP
			DECLARE DocsConta CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN, dco.CDO_NPRO, dco.CDO_PANO, dco.CDO_IMEX, dco.CDO_IDTY, 
					(CASE dco.CDO_IMEX WHEN 1 THEN 'E' ELSE 'I' END)
				FROM FAC_CDOC AS dco WITH(NOLOCK) 
					INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dco.NDE_CODI = nat.NDE_CODI			
				WHERE dco.CDO_IDTY IN (SELECT TOP 10 CDO_IDTY FROM @TblTmpContas)
				ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN			
			OPEN DocsConta
			FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso, @IdConta, @ImpExp
			WHILE @@FETCH_STATUS = 0
			BEGIN
-- constroi a linha do documento de Conta no formato Json		
				SET @JsonRecord = ''
				SET @JsonRecord = @JsonRecord + '{"empresa":"' + ISNULL(@CodEmpresaSAP, '') + '",'					
				SET @JsonRecord = @JsonRecord + '"processoNumero":"' + ISNULL(LTRIM(STR(@NumProcesso, 20)), '') + '",'
				SET @JsonRecord = @JsonRecord + '"documentoStatus":""},'
-- adiciona dados Json do documento de Conta ao Json Request 
				SET @JsonRequest = ISNULL(@JsonRequest, '') + @JsonRecord
-- insere documento de Conta na tabela tmp
				INSERT INTO @TblTmpContas10(CDO_EANO, CDO_TDOC, CDO_IDEN, CDO_NPRO, CDO_PANO, CDO_IMEX)
				VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso)
-- remove documento de Conta do repositório
				DELETE FROM @TblTmpContas
				WHERE CDO_IDTY = @IdConta
-- efetua o log do documento de Conta a enviar p/ SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## JSON-CONTA: ' + @JsonRecord)
				END
				FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso, @IdConta, @ImpExp
			END
			CLOSE DocsConta
			DEALLOCATE DocsConta
-- se foram obtidos documentos, processa envio p/ SAP via REST API
			IF ISNULL(@JsonRequest, '') <> ''
			BEGIN
-- remove último caracter ","
				SET @JsonRequest = REVERSE(STUFF(REVERSE(@JsonRequest), 1, 1, ''))
-- adiciona header ao request
				SET @JsonRequest = '{"header":{"tennant": "' + ISNULL(@Tennant, '') + '","channel":"' + ISNULL(@Channel, '') + '"},"documentos": [' + @JsonRequest + ']}'
-- efetua o log do Json request a enviar p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-REQUEST: ' + @JsonRequest)
				END
-- cria objeto p/ REST API
				EXEC sp_OACreate 'MSXML2.ServerXMLHTTP.3.0', @RESTObj OUTPUT	
-- atribui endpoint ao objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'open', NULL, 'POST', @URLEndpointGet, 'False'
-- inicia header do objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'setRequestHeader', NULL, 'Content-Type', 'application/json'
-- processa envio do request p/ REST API
				EXEC sp_OAMethod @RESTObj, 'send', NULL, @JsonRequest
-- efetua o log do envio do Json request p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## API-URL: ' + ISNULL(@URLEndpointGet, '<nulo>'))
				END
-- obtem response da REST API
				EXEC sp_OAMethod @RESTObj, 'responseText', @JsonResponse OUTPUT			
-- destroi objeto 			
				EXEC sp_OADestroy @RESTObj	
-- efetua o log do Json response recebido da API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-RESPONSE: ' + ISNULL(@JsonResponse, '<nulo>'))
				END
			END		
-- inicia Json Request 
			SET @JsonRequest = NULL		
-- se respostas obtida do REST API
			IF ISNULL(@JsonResponse, '') <> ''
			BEGIN
				SET @XMLResponse = dbo.fn_Geral_ConverteJson2Xml(@JsonResponse)
-- obtem as despesas documentadas obtidas do REST API
				DECLARE DespDocumentadas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
					SELECT 
						t.d.value('plataforma[1]', 'varchar(20)'), 
						t.d.value('documentoNumero[1]', 'varchar(60)'), 	
						t.d.value('dataCriacao[1]', 'datetime'), 
						((CASE t.d.value('codigo[1]', 'varchar(1)') WHEN 'H' THEN -1 ELSE 1 END) * t.d.value('montante[1]', 'numeric(18, 2)')),		
						t.d.value('item[1]', 'varchar(10)'), 				
						dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN, dco.CDO_NPRO, dco.CDO_PANO, dco.CDO_IMEX, ddo.DDO_CODI, ddo.DDO_NOME, 
						(CASE dco.CDO_IMEX WHEN 1 THEN 'E' ELSE 'I' END)
					FROM @XMLResponse.nodes('documentos') AS t(d)
						INNER JOIN @TblTmpContas10 AS dco ON CAST(t.d.value('processo[1]', 'varchar(20)') AS int) = dco.CDO_NPRO AND t.d.value('ano[1]', 'int') = dco.CDO_PANO AND (CASE t.d.value('tipo[1]', 'varchar(1)') WHEN 'E' THEN 1 ELSE 0 END) = dco.CDO_IMEX
						LEFT OUTER JOIN TAB_DDOC AS ddf ON t.d.value('rubrica[1]', 'varchar(10)') = ddf.DDO_SPCD
						INNER JOIN TAB_DDOC AS ddo ON ISNULL(ddf.DDO_CODI, 999) = ddo.DDO_CODI						
					WHERE ddo.DDO_CREC IS NULL 
				OPEN DespDocumentadas
				FETCH NEXT FROM DespDocumentadas INTO @Plataforma, @NumDocOrigem, @DataDocOrigem, @Montante, @ItemDocOrigem, @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, 
					@CtxProcesso, @CodDespDocumentada, @NomeDespDocumentada, @ImpExp
				WHILE @@FETCH_STATUS = 0
				BEGIN	
-- verifica se geração de novo documento de Conta ainda não foi efetuado (caso já tenha ocorrido p/ outra despesa documentada, o processo de atualização das despesas documentadas seguintes irá ocorrer no processo de atualização das Contas "Em Curso")
					IF EXISTS(SELECT 1 FROM @TblTmpContas10 WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND CDO_IDTY IS NULL)
					BEGIN
-- calcula a natureza do novo documento de Conta
						IF NOT EXISTS(SELECT CDO_IDEN 
									FROM FAC_CDOC WITH(NOLOCK) 
									WHERE CDO_TDOC = @CodTipoDocumento AND NDE_CODI = (CASE @CtxProcesso WHEN 1 THEN @CodNaturezaEXP1 ELSE @CodNaturezaIMP1 END) AND CDO_NPRO = @NumProcesso 
										AND CDO_PANO = @AnoProcesso AND CDO_IMEX = @CtxProcesso)
							SET @CodNaturezaConta = (CASE @CtxProcesso WHEN 1 THEN @CodNaturezaEXP1 ELSE @CodNaturezaIMP1 END)
						ELSE
						IF NOT EXISTS(SELECT CDO_IDEN 
									FROM FAC_CDOC WITH(NOLOCK) 
									WHERE CDO_TDOC = @CodTipoDocumento AND NDE_CODI = (CASE @CtxProcesso WHEN 1 THEN @CodNaturezaEXP2 ELSE @CodNaturezaIMP2 END) AND CDO_NPRO = @NumProcesso 
										AND CDO_PANO = @AnoProcesso AND CDO_IMEX = @CtxProcesso)
							SET @CodNaturezaConta = (CASE @CtxProcesso WHEN 1 THEN @CodNaturezaEXP2 ELSE @CodNaturezaIMP2 END)
						ELSE
						IF NOT EXISTS(SELECT CDO_IDEN 
									FROM FAC_CDOC WITH(NOLOCK) 
									WHERE CDO_TDOC = @CodTipoDocumento AND NDE_CODI = (CASE @CtxProcesso WHEN 1 THEN @CodNaturezaEXP3 ELSE @CodNaturezaIMP3 END) AND CDO_NPRO = @NumProcesso 
										AND CDO_PANO = @AnoProcesso AND CDO_IMEX = @CtxProcesso)
							SET @CodNaturezaConta = (CASE @CtxProcesso WHEN 1 THEN @CodNaturezaEXP3 ELSE @CodNaturezaIMP3 END)
						ELSE
							SET @CodNaturezaConta = NULL			
-- calcula o ano do novo documento de Conta
						IF (@AnoDocumento < YEAR(@DataAtual)) AND (EXISTS(SELECT EMP_CODI 
																		FROM GIDWIN.dbo.FAP_EANO WITH(NOLOCK) 
																		WHERE EMP_CODI = DB_NAME() and EAN_ANO = YEAR(@DataAtual)))		
							SET @AnoConta = YEAR(@DataAtual)
						ELSE
							SET @AnoConta = @AnoDocumento
-- processa a duplicação da Conta encerrada p/ nova natureza
						EXEC SP_duplicaConta @IdDocumento, @AnoDocumento, @CodTipoDocumento, @CodNaturezaConta, @Utilizador, @AnoConta, @CodTipoDocumento, 1
-- inicia variaveis
						SET @AnoDocumentoOrig = @AnoDocumento
						SET @IdDocumentoOrig = @IdDocumento
-- obtem dados da nova Conta gerada
						SELECT TOP 1 @AnoDocumento = CDO_EANO, @CodTipoDocumento = CDO_TDOC, @IdDocumento = CDO_IDEN, @IdConta = CDO_IDTY
						FROM FAC_CDOC WITH(NOLOCK)
						WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @CodTipoDocumento AND NDE_CODI = @CodNaturezaConta AND CDO_NPRO = @NumProcesso AND CDO_PANO = @AnoProcesso AND CDO_IMEX = @CtxProcesso 
							AND CDO_ORID = @IdDocumentoOrig
						ORDER BY CDO_IDEN DESC
-- atualiza documento na table tmp com o ID do novo documento de Conta inserido
						UPDATE @TblTmpContas10 SET CDO_IDTY = @IdConta
						WHERE CDO_EANO = @AnoDocumentoOrig AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumentoOrig		
-- efetua o log da duplicação da Conta
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumentoOrig, @CodTipoDocumento, @IdDocumentoOrig, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-INSERT: Documento de Conta duplicado: ' + CAST(@AnoDocumento AS varchar(4)) + ' | ' + CAST(@IdDocumento AS varchar(10)) + ' | ' + @CodNaturezaConta + ' | ' + CAST(@IdConta AS varchar(20)))
						END														
-- obtem o 1º número de linha vazio para atribuição de despesa documentada
						SET @NumLinhaDocumentada = ISNULL((SELECT MIN(DCD_LINH) 
														FROM FAC_DCDO 
														WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DDO_CODI IS NULL), 1)
-- insere despesa documentada na Conta
						UPDATE FAC_DCDO SET DDO_CODI = @CodDespDocumentada, DCD_DESC = @NomeDespDocumentada, DCD_VTOT = 0
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada		
-- efetua o log da despesa documentada inserida no documento de Conta
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Despesa documentada adicionada ao documento de Conta: ' + CAST(@CodDespDocumentada AS varchar(10)))
						END											
-- obtem o próximo número de linha para atribuição do detalhe
						SET @NumLinhaDetDocumentada = ISNULL((SELECT MAX(DDC_ADIC) 
															FROM FAC_DDCD 
															WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada), 0) + 1
-- insere detalhe na despesa documentada
						INSERT INTO FAC_DDCD(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DDC_ADIC, DDC_DORI, DDC_DATA, DDC_TIVA, DDC_VALO)
						VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumLinhaDocumentada, @NumLinhaDetDocumentada, @NumDocOrigem, @DataDocOrigem, 0, @Montante)
-- efetua o log do detalhe de documento inserido na despesa documentada
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Detalhe de documento adicionado a despesa documentada: ' + @NumDocOrigem + ' | ' + LTRIM(STR(@Montante, 18, 2)) + ' | ' + CAST(@CodDespDocumentada AS varchar(10)))
						END								
-- obtém a soma do valor do detalhe das despesas documentadas
						SELECT @MontanteTotal = SUM(ISNULL(DDC_VALO, 0))
						FROM FAC_DDCD 
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada
-- atualiza valor da despesa documentada com a soma obtida
						UPDATE FAC_DCDO SET DCD_VTOT = @MontanteTotal, DCD_DNOW = @DataAtual, DCD_VFCX = 1
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinhaDocumentada
-- efetua o log da atualização do montante na despesa documentada
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Despesa documentada com montante atualizado: ' + CAST(@CodDespDocumentada AS varchar(10)) + ' | ' + LTRIM(STR(@MontanteTotal, 18, 2)))
						END
-- obtém a soma do valor das despesas documentadas da Conta
						SELECT @MontanteTotal = SUM(ISNULL(DCD_VTOT, 0))
						FROM FAC_DCDO 
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento
-- atualiza valores totais da Conta
						UPDATE FAC_CDOC SET CDO_TTDC = @MontanteTotal, CDO_TTPR = (@MontanteTotal + ISNULL(CDO_TTIN, 0) + ISNULL(CDO_TTHO, 0) + ISNULL(CDO_IVA, 0)), CDO_CPRO = 1
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento	
-- efetua o log da atualização do total de documentadas no documento de Conta
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Documento de Conta com total documentadas atualizado: ' + LTRIM(STR(@MontanteTotal, 18, 2)))
						END	
-- constroi a linha do documento de Conta no formato Json		
						SET @JsonRecord = ''
						SET @JsonRecord = @JsonRecord + '{"empresa":"' + ISNULL(@CodEmpresaSAP, '') + '",'		
						SET @JsonRecord = @JsonRecord + '"documentoNumero":"' + ISNULL(@NumDocOrigem, '') + '",'
						SET @JsonRecord = @JsonRecord + '"ano":"' + ISNULL(LTRIM(STR(@AnoProcesso, 4, 0)), '') + '",'	
						SET @JsonRecord = @JsonRecord + '"documentoItem":"' + ISNULL(@ItemDocOrigem, '') + '",'					
						SET @JsonRecord = @JsonRecord + '"processoNumero":"' + ISNULL(LTRIM(STR(@NumProcesso, 20)), '') + '",'
						SET @JsonRecord = @JsonRecord + '"plataforma":"' + ISNULL(UPPER(@Plataforma), '') + '"},'											
-- adiciona dados Json do documento de Conta ao Json Request 
						SET @JsonRequest = ISNULL(@JsonRequest, '') + @JsonRecord
-- efetua o log do documento de Conta a enviar p/ SAP
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## JSON-CONTA: ' + @JsonRecord)
						END													
					END
					ELSE
						IF ISNULL(@DirLogFile, '') <> ''
						BEGIN
							INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
							VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## INFO-CONTAS: Documento de Conta e respetiva despesa documentada nao tratados: ' + CAST(@CodDespDocumentada AS varchar(10)) + ' | ' + @NumDocOrigem + ' | ' + LTRIM(STR(@Montante, 18, 2)))
						END	
					FETCH NEXT FROM DespDocumentadas INTO @Plataforma, @NumDocOrigem, @DataDocOrigem, @Montante, @ItemDocOrigem, @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, 
						@CtxProcesso, @CodDespDocumentada, @NomeDespDocumentada, @ImpExp
				END
				CLOSE DespDocumentadas
				DEALLOCATE DespDocumentadas
			END
-- se foram obtidos documentos, processa envio p/ SAP via REST API
			IF ISNULL(@JsonRequest, '') <> ''
			BEGIN
				SET @JsonResponse = NULL
-- remove último caracter ","
				SET @JsonRequest = REVERSE(STUFF(REVERSE(@JsonRequest), 1, 1, ''))
-- adiciona header ao request
				SET @JsonRequest = '{"header":{"tennant": "' + ISNULL(@Tennant, '') + '","channel":"' + ISNULL(@Channel, '') + '"},"documentosLinha": [' + @JsonRequest + ']}'
-- efetua o log do Json request a enviar p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-REQUEST: ' + @JsonRequest)
				END
-- cria objeto p/ REST API
				EXEC sp_OACreate 'MSXML2.ServerXMLHTTP.3.0', @RESTObj OUTPUT	
-- atribui endpoint ao objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'open', NULL, 'POST', @URLEndpointSet, 'False'
-- inicia header do objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'setRequestHeader', NULL, 'Content-Type', 'application/json'
-- processa envio do request p/ REST API
				EXEC sp_OAMethod @RESTObj, 'send', NULL, @JsonRequest
-- efetua o log do envio do Json request p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## API-URL: ' + ISNULL(@URLEndpointSet, '<nulo>'))
				END
-- obtem response da REST API
				EXEC sp_OAMethod @RESTObj, 'responseText', @JsonResponse OUTPUT			
-- destroi objeto 			
				EXEC sp_OADestroy @RESTObj	
-- efetua o log do Json response recebido da API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-RESPONSE: ' + ISNULL(@JsonResponse, '<nulo>'))
				END
			END
-- obtem o total de documentos de Contas pendentes de processamento
			SELECT @TotalContasPendentes = COUNT(*) 
			FROM @TblTmpContas
		END
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de atualização de documentos de Contas de SAP	
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocContasSAP1(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# FIM ATUALIZACAO CONTAS-ENCERRADO ##################################################################################################################################')
	END
-- se diretoria p/ log file especificada, grava ficheiro de log
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
-- constroi full path para geração do ficheiro XML
		SET @PathLogFile = @DirLogFile + 'LOG_SAP2GIDWin1_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), '-', ''), ' ', ''), ':', ''), '.', '') + '.TXT'
-- gera o ficheiro TXT p/ ficheiro log
		SET @Comando = 'bcp "SELECT ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO FROM ##LogTableDocContasSAP1 ORDER BY ID" QUERYOUT "' + @PathLogFile + '" -c -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
	END	
-- remove a tabela temporária	
	DROP TABLE ##LogTableDocContasSAP1
END

ALTER AUTHORIZATION ON [SP_Facturacao_AtualizaDocContasEncerradosSAPERDO] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_AtualizaDocContasEncerradosSAPERDO] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_EnviaDocContasEmCursoSAPERDO]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_EnviaDocContasEmCursoSAPERDO] @URLEndpoint varchar(8000), @Tennant varchar(250), @Channel varchar(250), @CodEmpresaSAP varchar(10), @DataReferencia datetime, 
	@DirLogFile varchar(500) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis	
	DECLARE @DataAtual datetime, @TotalContasPendentes int, @AnoDocumento int, @CodTipoDocumento varchar(4), @IdDocumento int, @NumProcesso int, @AnoProcesso int, @CtxProcesso bit, 
		@MesProcesso int, @CodClienteCC varchar(18), @IdConta bigint, @Grupo varchar(5), @ImpExp varchar(1), @DescMeioTransporte varchar(20)		
	DECLARE @JsonRecord varchar(250), @JsonRequest varchar(MAX), @JsonResponse Varchar(8000), @XMLResponse xml
	DECLARE @TblTmpContas TABLE(CDO_IDTY bigint NOT NULL)
	DECLARE @TblTmpContas10 TABLE(CDO_EANO int NOT NULL, CDO_TDOC varchar(4) NOT NULL, CDO_IDEN int NOT NULL, CDO_NPRO int NOT NULL, CDO_PANO int NOT NULL, CDO_IMEX bit NOT NULL)	
	DECLARE @RESTObj int, @Comando nvarchar(4000), @PathLogFile varchar(600)
-- verfica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirLogFile), 1, 1) <> '\'
		SET @DirLogFile = @DirLogFile + '\'
-- cria tabela temporária p/ guardar informação da importação
	CREATE TABLE ##LogTableDocContasSAP(
		ID int NOT NULL IDENTITY(1, 1),
		ANODOC int NOT NULL, 
		TIPODOC varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
		IDDOC int NOT NULL,		
		NUMPROCESSO int NOT NULL, 
		ANOPROCESSO int NOT NULL,
		CTXPROCESSO varchar(1) COLLATE Latin1_General_CI_AI NOT NULL, 	
		INFO varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- efetua o log do inicio do processo de envio de documentos de Contas p/ SAP	
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# INICIO ENVIO CONTAS-EM_CURSO ###############################################################################################################################')
	END
	BEGIN TRY
-- obtem os documentos de Contas não emitidos, não anulados, com ligação a processo IMP/EXP, com natureza de Flat-File EDI e ainda não enviados 
		INSERT INTO @TblTmpContas(CDO_IDTY)
		SELECT dco.CDO_IDTY
		FROM FAC_CDOC AS dco WITH(NOLOCK) 
			INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dco.NDE_CODI = nat.NDE_CODI			
		WHERE dco.CDO_PANO IS NOT NULL AND dco.CDO_STAT = 0 AND dco.CDO_CNUM IS NULL AND dco.CDO_ANUL = 0 AND dco.CDO_IMPR = 0 AND dco.CDO_CPRO = 0 AND nat.NDE_FEDI = 1
			AND CAST(CONVERT(varchar(10), dco.CDO_DTCR, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
		ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN
-- obtem o total de documentos de Contas pendentes de processamento
		SELECT @TotalContasPendentes = COUNT(*) 
		FROM @TblTmpContas
-- efetua o log do total de documentos de Conta a enviar p/ SAP		
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN
			INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## INFO-CONTAS: Existem ' + LTRIM(STR(@TotalContasPendentes, 20)) + ' documentos de Contas "Em Curso" disponiveis para envio para o SAP.')
		END
-- processa todos os documentos de Conta obtidos 
		WHILE (@TotalContasPendentes > 0)
		BEGIN
			SET @JsonRequest = NULL
			SET @JsonResponse = NULL
			DELETE FROM @TblTmpContas10
-- obtem os PRIMEIROS 10 documentos de Contas não emitidos, não anulados, com ligação a processo IMP/EXP, com natureza de Flat-File EDI e ainda não enviados 
			DECLARE DocsConta CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN, dco.CDO_NPRO, dco.CDO_PANO, dco.CDO_IMEX, MONTH(dco.CDO_DTAB), dco.CLI_CCOR, dco.CDO_IDTY, 
					(SELECT TOP 1 GRU_CODI FROM GIDWIN.dbo.FAP_UGRU WITH(NOLOCK) WHERE UTI_UTIL = dco.CDO_UCRI), 
					(CASE dco.CDO_IMEX WHEN 1 THEN 'E' ELSE 'I' END), 
					(CASE dco.MTR_CODI WHEN '10' THEN 'MARITIMA' WHEN '20' THEN 'FERROVIARIA' WHEN '40' THEN 'AEREA' WHEN '30' THEN 'RODOVIARIA' ELSE 'ENCOMENDAS POSTAIS' END)
				FROM FAC_CDOC AS dco WITH(NOLOCK) 
					INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dco.NDE_CODI = nat.NDE_CODI			
				WHERE dco.CDO_IDTY IN (SELECT TOP 10 CDO_IDTY FROM @TblTmpContas)
				ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN			
			OPEN DocsConta
			FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso, @MesProcesso, @CodClienteCC, @IdConta, @Grupo, @ImpExp, 
				@DescMeioTransporte
			WHILE @@FETCH_STATUS = 0
			BEGIN
-- constroi a linha do documento de Conta no formato Json	
				SET @JsonRecord = ''				
				SET @JsonRecord = @JsonRecord + '{"empresa":"' + ISNULL(@CodEmpresaSAP, '') + '",'
				SET @JsonRecord = @JsonRecord + '"plataforma":"' + ISNULL(@Grupo, '') + '",'
				SET @JsonRecord = @JsonRecord + '"processoNumero":"' + ISNULL(LTRIM(STR(@NumProcesso, 20)), '') + '",'
				SET @JsonRecord = @JsonRecord + '"tipo":"' + ISNULL(@ImpExp, '') + '",'
				SET @JsonRecord = @JsonRecord + '"parceiroOperacional":"' + ISNULL(@CodClienteCC, '') + '",'
				SET @JsonRecord = @JsonRecord + '"via":"' + ISNULL(@DescMeioTransporte, '') + '",'
				SET @JsonRecord = @JsonRecord + '"processoAno":"' + ISNULL(LTRIM(STR(@AnoProcesso, 4, 0)), '') + '",'
				SET @JsonRecord = @JsonRecord + '"processoMes":"' + ISNULL(LTRIM(STR(@MesProcesso, 2, 0)), '') + '"},'
-- adiciona dados Json do documento de Conta ao Json Request 
				SET @JsonRequest = ISNULL(@JsonRequest, '') + @JsonRecord
-- insere documento de Conta na tabela tmp
				INSERT INTO @TblTmpContas10(CDO_EANO, CDO_TDOC, CDO_IDEN, CDO_NPRO, CDO_PANO, CDO_IMEX)
				VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso)
-- remove documento de Conta do repositório
				DELETE FROM @TblTmpContas
				WHERE CDO_IDTY = @IdConta
-- efetua o log do documento de Conta a enviar p/ SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## JSON-CONTA: ' + @JsonRecord)
				END
				FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @CtxProcesso, @MesProcesso, @CodClienteCC, @IdConta, @Grupo, @ImpExp, 
					@DescMeioTransporte
			END
			CLOSE DocsConta
			DEALLOCATE DocsConta
-- se foram obtidos documentos, processa envio p/ SAP via REST API
			IF ISNULL(@JsonRequest, '') <> ''
			BEGIN
-- remove último caracter ","
				SET @JsonRequest = REVERSE(STUFF(REVERSE(@JsonRequest), 1, 1, ''))
-- adiciona header ao request
				SET @JsonRequest = '{"header":{"tennant": "' + ISNULL(@Tennant, '') + '","channel":"' + ISNULL(@Channel, '') + '"},"processos": [' + @JsonRequest + ']}'
-- efetua o log do Json request a enviar p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-REQUEST: ' + @JsonRequest)
				END
-- cria objeto p/ REST API
				EXEC sp_OACreate 'MSXML2.ServerXMLHTTP.3.0', @RESTObj OUTPUT	
-- atribui endpoint ao objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'open', NULL, 'POST', @URLEndpoint, 'False'
-- inicia header do objeto REST API		
				EXEC sp_OAMethod @RESTObj, 'setRequestHeader', NULL, 'Content-Type', 'application/json'
-- processa envio do request p/ REST API
				EXEC sp_OAMethod @RESTObj, 'send', NULL, @JsonRequest
-- efetua o log do envio do Json request p/ API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## API-URL: ' + ISNULL(@URLEndpoint, '<nulo>'))
				END
-- obtem response da REST API
				EXEC sp_OAMethod @RESTObj, 'responseText', @JsonResponse OUTPUT			
-- destroi objeto 			
				EXEC sp_OADestroy @RESTObj	
-- efetua o log do Json response recebido da API REST do SAP
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(0, '', 0, 0, 0, '', '## JSON-RESPONSE: ' + ISNULL(@JsonResponse, '<nulo>'))
				END
			END			
-- se respostas obtida do REST API
			IF ISNULL(@JsonResponse, '') <> ''
			BEGIN
				SET @XMLResponse = dbo.fn_Geral_ConverteJson2Xml(@JsonResponse)
-- marca os documentos de Conta anteriormente obtidos como "Enviados SAP"
				DECLARE DocsConta CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
					SELECT CDO_EANO, CDO_TDOC, CDO_IDEN, CDO_NPRO, CDO_PANO, (CASE CDO_IMEX WHEN 1 THEN 'E' ELSE 'I' END)
					FROM @XMLResponse.nodes('processos') AS t(d)
						INNER JOIN @TblTmpContas10 AS dco ON CAST(t.d.value('processoNumero[1]', 'varchar(20)') AS int) = dco.CDO_NPRO AND t.d.value('processoAno[1]', 'int') = dco.CDO_PANO AND (CASE t.d.value('tipo[1]', 'varchar(1)') WHEN 'E' THEN 1 ELSE 0 END) = dco.CDO_IMEX
				OPEN DocsConta
				FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp
				WHILE @@FETCH_STATUS = 0
				BEGIN
-- atualiza o documento de Conta
					UPDATE FAC_CDOC SET CDO_CPRO = 1
					WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento
-- efetua o log do documento de Conta marcado como enviado p/ SAP
					IF ISNULL(@DirLogFile, '') <> ''
					BEGIN
						INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
						VALUES(@AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp, '## SQL-UPDATE: Conta marcada como enviada para SAP.')
					END
					FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumProcesso, @AnoProcesso, @ImpExp
				END
				CLOSE DocsConta
				DEALLOCATE DocsConta
			END
-- obtem o total de documentos de Contas pendentes de processamento
			SELECT @TotalContasPendentes = COUNT(*) 
			FROM @TblTmpContas
		END
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de envio de documentos de Contas p/ SAP	
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocContasSAP(ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# FIM ENVIO CONTAS-EM_CURSO ##################################################################################################################################')
	END
-- se diretoria p/ log file especificada, grava ficheiro de log
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
-- constroi full path para geração do ficheiro XML
		SET @PathLogFile = @DirLogFile + 'LOG_GIDWin2SAP_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), '-', ''), ' ', ''), ':', ''), '.', '') + '.TXT'
-- gera o ficheiro TXT p/ ficheiro log
		SET @Comando = 'bcp "SELECT ANODOC, TIPODOC, IDDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO FROM ##LogTableDocContasSAP ORDER BY ID" QUERYOUT "' + @PathLogFile + '" -c -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
	END	
-- remove a tabela temporária	
	DROP TABLE ##LogTableDocContasSAP
END

ALTER AUTHORIZATION ON [SP_Facturacao_EnviaDocContasEmCursoSAPERDO] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_EnviaDocContasEmCursoSAPERDO] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_EnviaDocumentosPortalERDO]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_EnviaDocumentosPortalERDO] @Endpoint varchar(500), @SOAPActionFaturaCab varchar(500), @SOAPActionFaturaLin varchar(500), @HeaderToken varchar(8000), 
	@IdIntegrationSystem int, @DataReferencia datetime, @DirLogFile varchar(500) AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variaveis	
	DECLARE @DataAtual datetime, @AnoDocumento int, @CodTipoDocumento varchar(4), @NumDocumento int, @IdDocumento int, @CtxDocumento int, @DataDocumento datetime, @CodCliente varchar(18), 
		@NumProcesso int, @AnoProcesso int, @CtxProcesso bit, @CodDeclaranteProcesso varchar(6), @IVADocumento numeric(38, 6), @TotalDocumento numeric(38, 6), @VossaReferencia varchar(50), 
		@IdDoc bigint, @Serie varchar(20), @RegimePortal varchar(35), @DataVencimento datetime, @Acao varchar(1), @NumLinha int, @TipoLinha int, @DescricaoLinha varchar(500), 
		@ValorLiqLinha numeric(38, 6), @ValorIVALinha numeric(38, 6), @VerbaLinha varchar(15)
	DECLARE @PathFicheiroPDF varchar(500), @NomeFicheiroPDF varchar(100), @FicheiroBinario varbinary(MAX), @FicheiroFATBase64 varchar(MAX), @FicheiroARQBase64 varchar(MAX), @SQLString nvarchar(500), 
		@SQLParams nvarchar(500)
	DECLARE @XMLDocumento xml, @XMLRequest xml, @XMLResponse xml, @Sucesso bit, @ErrorCode  int, @ErrorMessage varchar(MAX)
	DECLARE @Comando nvarchar(4000), @PathLogFile varchar(600)
-- verfica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirLogFile), 1, 1) <> '\'
		SET @DirLogFile = @DirLogFile + '\'
-- cria tabela temporária p/ guardar informação da exportação
	CREATE TABLE ##LogTableDocsPortal(
		ID int NOT NULL IDENTITY(1, 1), 
		ANODOC int NOT NULL, 
		TIPODOC varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
		NUMDOC int NOT NULL,		
		NUMPROCESSO int NOT NULL, 
		ANOPROCESSO int NOT NULL,
		CTXPROCESSO varchar(1) COLLATE Latin1_General_CI_AI NOT NULL, 
		LINHA varchar(20) COLLATE Latin1_General_CI_AI NULL, 
		INFO varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- efetua o log do inicio do processo de envio do CAB de documentos de Vendas/Contas emitidos e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# INICIO ENVIO FATURACAO-CAB ###############################################################################################################################')
	END
	BEGIN TRY
-- obtem os dados gerais dos documentos de Vendas/Contas emitidos e pendentes de envio para o Portal MyRangel
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, NULL AS DVE_IDEN, dve.DVE_CTXT, dve.DVE_DATA, dve.CLI_CODI, dve.DVE_NPRO, dve.DVE_PANO, dve.DEC_CODI, dve.DVE_IMEX, dve.DVE_VIVA, 
				dve.DVE_VTOT, cdo.CDO_VREF, dve.DVE_IDTY, dve.DVE_SERI, nde.NDE_WDES, DATEADD(DAY, ISNULL(cli.CLI_CPAG, 0), dve.DVE_DATA), 
				(CASE 
					WHEN dve.DVE_PMRD IS NULL THEN 'I'					
					ELSE 'U'
				END) AS DVE_ACAO
			FROM FAC_DVEN AS dve WITH(NOLOCK)
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON dve.NDE_CODI = nde.NDE_CODI
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dve.CLI_CODI = cli.CLI_CODI
				LEFT OUTER JOIN FAC_CDOC AS cdo WITH(NOLOCK) ON dve.DVE_TDOC = cdo.DVE_TDOC AND dve.DVE_NDOC = cdo.DVE_NDOC AND dve.DVE_EANO = cdo.DVE_EANO
			WHERE dve.DVE_PMRP = 1 AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			UNION ALL
			SELECT cdo.CDO_EANO, cdo.CDO_TDOC, cdo.CDO_CNUM, cdo.CDO_IDEN, tdo.TDO_TDOC, cdo.CDO_DTEM, cdo.CLI_CCOR, cdo.CDO_NPRO, cdo.CDO_PANO, cdo.EXM_OPER, cdo.CDO_IMEX, ISNULL(cdo.CDO_IVA, 0), 
				ISNULL(cdo.CDO_TTPR, 0), cdo.CDO_VREF, cdo.CDO_IDTY, cdo.CDO_SERI, nde.NDE_WDES, DATEADD(DAY, ISNULL(cdo.CDO_CPAG, 0), cdo.CDO_DTEM), 
				(CASE 
					WHEN cdo.CDO_PMRD IS NULL THEN 'I'					
					ELSE 'U'
				END) AS DVE_ACAO
			FROM FAC_CDOC AS cdo WITH(NOLOCK)
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON cdo.NDE_CODI = nde.NDE_CODI				
			WHERE cdo.CDO_CNUM IS NOT NULL AND cdo.CDO_IMPR = 1 AND cdo.CDO_PMRP = 1 AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), cdo.CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			ORDER BY DVE_EANO, DVE_TDOC, DVE_NDOC		
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @AnoDocumento, @CodTipoDocumento, @NumDocumento, @IdDocumento, @CtxDocumento, @DataDocumento, @CodCliente, @NumProcesso, @AnoProcesso, @CodDeclaranteProcesso, 
			@CtxProcesso, @IVADocumento, @TotalDocumento, @VossaReferencia, @IdDoc, @Serie, @RegimePortal, @DataVencimento, @Acao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @XMLResponse = NULL
			SET @Sucesso = 0
			SET @ErrorCode = NULL
			SET @ErrorMessage = NULL
			SET @PathFicheiroPDF = NULL
			SET @NomeFicheiroPDF = NULL
			SET @FicheiroBinario = NULL
			SET @FicheiroFATBase64 = NULL
			SET @FicheiroARQBase64 = NULL
-- obtem o ficheiro PDF do documento de Venda/Conta na respetiva declaração de Importação/Exportação
			IF @CtxProcesso = 0
			BEGIN
				SELECT TOP 1 @PathFicheiroPDF = DUF_LINK, @NomeFicheiroPDF = DUF_NOMF, @FicheiroBinario = DUF_FICH
				FROM PRO_DUFI WITH(NOLOCK) 
				WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUF_TMSG = 'FTINTERN' AND DUF_ORIG = 2 
					AND DUF_NOMF LIKE '%' + @CodTipoDocumento + '.' + LTRIM(STR(@NumDocumento, 20)) + '.' + LTRIM(STR(@AnoDocumento, 4)) + '%.pdf'
				ORDER BY DUC_IDEN
			END
			ELSE
			BEGIN
				SELECT TOP 1 @PathFicheiroPDF = dfi.EXF_LINK, @NomeFicheiroPDF = dfi.EXF_NOMF, @FicheiroBinario = dfi.EXF_FICH
				FROM PRO_EXML AS exm WITH(NOLOCK)						
					INNER JOIN PRO_EXFI AS dfi WITH(NOLOCK) ON exm.EXM_EANO = dfi.EXM_EANO AND exm.EXM_CODI = dfi.EXM_CODI AND exm.DEC_CODI = dfi.DEC_CODI
				WHERE exm.EXM_EANO = @AnoProcesso AND exm.DEC_CODI = @CodDeclaranteProcesso AND exm.EXM_NRII = @NumProcesso AND dfi.EXF_TMSG = 'FTINTERN' AND dfi.EXF_ORIG = 0 
					AND dfi.EXF_NOMF LIKE '%' + @CodTipoDocumento + '.' + LTRIM(STR(@NumDocumento, 20)) + '.' + LTRIM(STR(@AnoDocumento, 4)) + '%.pdf'
				ORDER BY dfi.EXF_IDEN
			END
-- efetua o log do ficheiro PDF a converter para Base64
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
				VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), '## FICHEIRO PDF-FT/NC: ' + ISNULL(@NomeFicheiroPDF, '<n.d.>'))
			END
-- carrega ficheiro PDF para binário
			IF (@FicheiroBinario IS NULL) AND (ISNULL(@PathFicheiroPDF, '') <> '')
			BEGIN
-- inicia variaveis para executar o SQL dinamicamente
				SET @SQLString = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiroPDF + ''', SINGLE_BLOB) AS t)'
				SET @SQLParams = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'			
-- obtem o ficheiro em binario
				EXECUTE sp_executesql @SQLString, @SQLParams, @OUTFicheiroBinario = @FicheiroBinario OUTPUT
			END			
-- converte ficheiro PDF para base64						
			SET @FicheiroFATBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinario")))', 'varchar(MAX)')	
-- para os documentos de Conta, obtem o 1º ficheiro do arquivo
			IF @CtxDocumento = 0 
			BEGIN
				SET @NomeFicheiroPDF = NULL
				SET @FicheiroBinario = NULL
-- obtem o 1º ficheiro PDF existente no arquivo do documento de Conta
				SELECT TOP 1 @NomeFicheiroPDF = nomeFicheiro, @FicheiroBinario = ficheiro
				FROM tb_FAC_DocContasArquivos WITH(NOLOCK)
				WHERE id_docConta = @IdDoc AND anexarEmail = 1 AND nomeFicheiro LIKE '%.pdf'
-- efetua o log do ficheiro PDF a converter para Base64
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), '## FICHEIRO PDF-ARQ: ' + ISNULL(@NomeFicheiroPDF, '<n.d.>'))
				END
-- converte ficheiro PDF para base64						
				SET @FicheiroARQBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinario")))', 'varchar(MAX)')	
			END
-- constroi o XML com os dados do documento
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1)
			SELECT @XMLDocumento =
				(SELECT 
					@Acao AS "fjs1:in_Accao", 
					@IdIntegrationSystem AS "fjs1:in_IntegrationSystem", 
					@CodCliente AS "fjs1:in_CodCliente_Is", 
					CONVERT(varchar(10), @DataDocumento, 120) AS "fjs1:in_DataDoc", 
					@NumDocumento AS "fjs1:in_NumDoc", 
					(CASE @CtxDocumento
						WHEN 1 THEN (CASE @Acao WHEN 'I' THEN 2 ELSE 7 END) --valor "2":Nota de Crédito / valor "7":Anul. Nota Crédito
						ELSE (CASE @Acao WHEN 'I' THEN 1 ELSE 5 END) -- valor "1":Factura / valor "5":Anulação Factura
					END) AS "fjs1:in_TipoDoc", 
					@Serie AS "fjs1:in_Serie", 
					NULLIF(@RegimePortal, '') AS "fjs1:in_Regime", 
					LTRIM(STR(@NumProcesso, 20)) AS "fjs1:in_Processo", 
					NULLIF(@VossaReferencia, '') AS "fjs1:in_Referencia", 
					CAST(@TotalDocumento AS decimal(18, 2)) AS "fjs1:in_ValorTotal",
					CAST(@IVADocumento AS decimal(18, 2)) AS "fjs1:in_ValorIVA", 
					@FicheiroFATBase64 AS "fjs1:in_File", 
					@FicheiroARQBase64 AS "fjs1:in_FileDetalhes",
					CONVERT(varchar(10), @DataVencimento, 120) AS "fjs1:in_DataVencimento"					
				FOR XML PATH('fjs1:webserv_Portal_FacturaCab_receiveERDO'), ELEMENTS)
-- constroi estrutura XML com os dados do pedido ao metodo webserv_Portal_FacturaCab_receiveERDO a enviar
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")		
			SELECT @XMLRequest = 
				(SELECT 
					(SELECT 
						(SELECT
							NULLIF(@HeaderToken, '') AS "fjs1:Token"
						FOR XML PATH('fjs1:clsValidaCabecalhoSOAP'), TYPE)
					FOR XML PATH('SOAP-ENV:Header'), ELEMENTS, TYPE),
					(SELECT
						@XMLDocumento		
					FOR XML PATH('SOAP-ENV:Body'), ELEMENTS, TYPE)
				FOR XML PATH('SOAP-ENV:Envelope'), ELEMENTS)
-- efetua o log do XML Request a enviar p/ o WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
				VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), '## XML-REQUEST: ' + CAST(@XMLRequest AS varchar(MAX)))
			END
-- processa envio do XML para o WS do Portal MyRangel	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @XMLRequest, @Endpoint, @SOAPActionFaturaCab, '', '', 0, '', 0, '', '', @XMLResponse OUTPUT
-- efetua o log do XML Response obtido do WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
				VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), '## XML-RESPONSE: ' + CAST(@XMLResponse AS varchar(MAX)))				
			END
-- obtem dados de resposta do WS
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS "tns3", 
				'http://www.example.com/namespaces/tns/1608830539372' AS "tns1", 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "soapenv")
			SELECT 
				@Sucesso = x.r.value('tns3:Sucesso[1]', 'bit'), 
				@ErrorCode = x.r.value('tns3:ErrorCode[1]', 'int'), 
				@ErrorMessage = x.r.value('tns3:ErrorMessage[1]', 'varchar(MAX)')
			FROM @XMLResponse.nodes('soapenv:Envelope/soapenv:Body/tns3:webserv_Portal_FacturaCab_receiveERDOResponse/tns3:webserv_Portal_FacturaCab_receiveERDOResult') AS x(r)
-- se resultado for de sucesso, atualiza documento de Venda/Conta como enviado para Portal MyRangel
			IF @Sucesso = 1
			BEGIN
				IF @CtxDocumento = 1 
				BEGIN
					UPDATE FAC_DVEN SET DVE_PMRP = 0, DVE_PMRD = @DataAtual
					WHERE DVE_EANO = @AnoDocumento AND DVE_TDOC = @CodTipoDocumento AND DVE_NDOC = @NumDocumento
				END
				ELSE
				BEGIN
					UPDATE FAC_CDOC SET CDO_PMRP = 0, CDO_PMRD = @DataAtual
					WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento
				END
-- efetua o log do documento de Venda/Conta marcado como enviado para Portal MyRangel
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
					VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), '## SQL-UPDATE: Documento marcado como enviado para o Portal MyRangel.')					
				END
			END
			FETCH NEXT FROM Documentos INTO @AnoDocumento, @CodTipoDocumento, @NumDocumento, @IdDocumento, @CtxDocumento, @DataDocumento, @CodCliente, @NumProcesso, @AnoProcesso, @CodDeclaranteProcesso, 
				@CtxProcesso, @IVADocumento, @TotalDocumento, @VossaReferencia, @IdDoc, @Serie, @RegimePortal, @DataVencimento, @Acao
		END
		CLOSE Documentos
		DEALLOCATE Documentos
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de envio do CAB de documentos de Vendas/Contas emitidos e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# FIM ENVIO FATURACAO-CAB ##################################################################################################################################')
	END
-- efetua o log do inicio do processo de envio do LIN de documentos de Vendas/Contas emitidos e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# INICIO ENVIO FATURACAO-LIN ###############################################################################################################################')
	END
	BEGIN TRY
-- obtem as linhas dos documentos de Vendas/Contas emitidos e pendentes de envio para o Portal MyRangel
		DECLARE Linhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT lin.DVE_EANO, lin.DVE_TDOC, lin.DVE_NDOC, NULL AS DVE_IDEN, lin.DVE_NLIN, lin.DVD_NOME, NULL AS DVD_TLIN, 
				ROUND((ISNULL(lin.DVD_QUAN, 0) * ISNULL(lin.DVD_VALO, 0)), 2), ROUND((ROUND((ISNULL(lin.DVD_QUAN, 0) * ISNULL(lin.DVD_VALO, 0)), 2) * ISNULL(lin.DVD_IVA, 0) / 100), 2), 		
				rft.RFC_CPOC, dve.DVE_CTXT, dve.DVE_DATA, dve.CLI_CODI, dve.DVE_NPRO, dve.DVE_PANO, dve.DVE_IMEX
			FROM FAC_DVDT AS lin WITH(NOLOCK)
				INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON lin.RFC_CODI = rft.RFC_CODI
				INNER JOIN FAC_DVEN AS dve WITH(NOLOCK) ON lin.DVE_TDOC = dve.DVE_TDOC AND lin.DVE_NDOC = dve.DVE_NDOC AND lin.DVE_EANO = dve.DVE_EANO
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON dve.NDE_CODI = nde.NDE_CODI				
			WHERE lin.DVD_LCRB = 1 AND lin.DVD_PMRP = 1 AND dve.DVE_PMRD IS NOT NULL AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			UNION ALL			
			SELECT ldd.CDO_EANO, ldd.CDO_TDOC, cdo.CDO_CNUM, ldd.CDO_IDEN, ldd.DCD_LINH, ldd.DCD_DESC, 0 AS DVD_TLIN, 
				ISNULL(ldd.DCD_VTOT, 0) AS DCD_VTOT, 0.00 AS DCD_VIVA, 
				ddo.DDO_POCC, tdo.TDO_TDOC, cdo.CDO_DTEM, cdo.CLI_CCOR, cdo.CDO_NPRO, cdo.CDO_PANO, cdo.CDO_IMEX
			FROM FAC_DCDO AS ldd WITH(NOLOCK)
				INNER JOIN TAB_DDOC as ddo ON ldd.DDO_CODI = ddo.DDO_CODI
				INNER JOIN FAC_CDOC AS cdo WITH(NOLOCK) ON ldd.CDO_EANO = cdo.CDO_EANO AND ldd.CDO_TDOC = cdo.CDO_TDOC AND ldd.CDO_IDEN = cdo.CDO_IDEN
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON cdo.NDE_CODI = nde.NDE_CODI				
			WHERE ldd.DCD_PMRP = 1 AND cdo.CDO_CNUM IS NOT NULL AND cdo.CDO_IMPR = 1 AND cdo.CDO_PMRD IS NOT NULL AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), cdo.CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			UNION ALL
			SELECT ldi.CDO_EANO, ldi.CDO_TDOC, cdo.CDO_CNUM, ldi.CDO_IDEN, ldi.ICD_LINH, ldi.ICD_DESC, 1 AS DVD_TLIN, 
				ISNULL(ldi.ICD_VTOT, 0) AS DCD_VTOT, (CASE ldi.ICD_ISEN WHEN 1 THEN 0.00 ELSE ROUND((ISNULL(ldi.ICD_VTOT, 0) * ISNULL(cdo.CDO_TXIV, 0) / 100), 2) END) AS DCD_VIVA, 
				din.DIN_POCC, tdo.TDO_TDOC, cdo.CDO_DTEM, cdo.CLI_CCOR, cdo.CDO_NPRO, cdo.CDO_PANO, cdo.CDO_IMEX
			FROM FAC_ICDO AS ldi WITH(NOLOCK)
				INNER JOIN TAB_DINE as din ON ldi.DIN_CODI = din.DIN_CODI
				INNER JOIN FAC_CDOC AS cdo WITH(NOLOCK) ON ldi.CDO_EANO = cdo.CDO_EANO AND ldi.CDO_TDOC = cdo.CDO_TDOC AND ldi.CDO_IDEN = cdo.CDO_IDEN
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON cdo.NDE_CODI = nde.NDE_CODI				
			WHERE ldi.ICD_PMRP = 1 AND cdo.CDO_CNUM IS NOT NULL AND cdo.CDO_IMPR = 1 AND cdo.CDO_PMRD IS NOT NULL AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), cdo.CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)		
			ORDER BY DVE_EANO, DVE_TDOC, DVE_NDOC, DVE_NLIN
		OPEN Linhas
		FETCH NEXT FROM Linhas INTO @AnoDocumento, @CodTipoDocumento, @NumDocumento, @IdDocumento, @NumLinha, @DescricaoLinha, @TipoLinha, @ValorLiqLinha, @ValorIVALinha, @VerbaLinha, 
			@CtxDocumento, @DataDocumento, @CodCliente, @NumProcesso, @AnoProcesso, @CtxProcesso
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @XMLResponse = NULL
			SET @Sucesso = 0
			SET @ErrorCode = NULL
			SET @ErrorMessage = NULL	
-- constroi o XML com os dados da linha
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1)
			SELECT @XMLDocumento =
				(SELECT 				
					@IdIntegrationSystem AS "fjs1:in_IntegrationSystem", 
					@CodCliente AS "fjs1:in_CodCliente_Is", 
					CONVERT(varchar(10), @DataDocumento, 120) AS "fjs1:in_DataDoc", 
					@NumDocumento AS "fjs1:in_NumDoc", 
					(CASE @CtxDocumento
						WHEN 1 THEN 2 --valor "2":Nota de Crédito                                                                                     
						ELSE 1 -- valor "1":Factura                                                                                             
					END) AS "fjs1:in_TipoDoc", 
					CONVERT(varchar(10), @DataDocumento, 120) AS "fjs1:in_DataMovimento", 
					NULLIF(@DescricaoLinha, '') AS "fjs1:in_DescricaoVerba", 
					NULLIF(@VerbaLinha, '') AS "fjs1:in_TipoVerba", 
					CAST((@ValorLiqLinha + @ValorIVALinha) AS decimal(18, 2)) AS "fjs1:in_Valor", 
					CAST(@ValorLiqLinha AS decimal(18, 2))  AS "fjs1:in_ValorSIVA", 
					CAST(@ValorIVALinha AS decimal(18, 2))  AS "fjs1:in_ValorIVA"								
				FOR XML PATH('fjs1:webserv_Portal_FacturaLin_receiveERDO'), ELEMENTS)
-- constroi estrutura XML com os dados do pedido ao metodo webserv_Portal_FacturaLin_receiveERDO a enviar
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")		
			SELECT @XMLRequest = 
				(SELECT 
					(SELECT 
						(SELECT
							NULLIF(@HeaderToken, '') AS "fjs1:Token"
						FOR XML PATH('fjs1:clsValidaCabecalhoSOAP'), TYPE)
					FOR XML PATH('SOAP-ENV:Header'), ELEMENTS, TYPE),
					(SELECT
						@XMLDocumento		
					FOR XML PATH('SOAP-ENV:Body'), ELEMENTS, TYPE)
				FOR XML PATH('SOAP-ENV:Envelope'), ELEMENTS)
-- efetua o log do XML Request a enviar p/ o WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)
				VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), ((CASE ISNULL(@TipoLinha, -1) WHEN 0 THEN 'D' WHEN 1 THEN 'I' ELSE '' END) + CAST(@NumLinha AS varchar(10))), '## XML-REQUEST: ' + CAST(@XMLRequest AS varchar(MAX)))
			END
-- processa envio do XML para o WS do Portal MyRangel	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @XMLRequest, @Endpoint, @SOAPActionFaturaLin, '', '', 0, '', 0, '', '', @XMLResponse OUTPUT
-- efetua o log do XML Response obtido do WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)
				VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), ((CASE ISNULL(@TipoLinha, -1) WHEN 0 THEN 'D' WHEN 1 THEN 'I' ELSE '' END) + CAST(@NumLinha AS varchar(10))), '## XML-RESPONSE: ' + CAST(@XMLResponse AS varchar(MAX)))				
			END
-- obtem dados de resposta do WS		
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS "tns3", 
				'http://www.example.com/namespaces/tns/1608830539372' AS "tns1", 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "soapenv")
			SELECT 
				@Sucesso = x.r.value('tns3:Sucesso[1]', 'bit'), 
				@ErrorCode = x.r.value('tns3:ErrorCode[1]', 'int'), 
				@ErrorMessage = x.r.value('tns3:ErrorMessage[1]', 'varchar(MAX)')
			FROM @XMLResponse.nodes('soapenv:Envelope/soapenv:Body/tns3:webserv_Portal_FacturaLin_receiveERDOResponse/tns3:webserv_Portal_FacturaLin_receiveERDOResult') AS x(r)
-- se resultado for de sucesso, atualiza linha do documento de Venda/Conta como enviado para Portal MyRangel
			IF @Sucesso = 1
			BEGIN
				IF @CtxDocumento = 1 
				BEGIN
					UPDATE FAC_DVDT SET DVD_PMRP = 0, DVD_PMRD = @DataAtual
					WHERE DVE_EANO = @AnoDocumento AND DVE_TDOC = @CodTipoDocumento AND DVE_NDOC = @NumDocumento AND DVE_NLIN = @NumLinha
				END
				ELSE
				BEGIN
					IF @TipoLinha = 0
					BEGIN
						UPDATE FAC_DCDO SET DCD_PMRP = 0, DCD_PMRD = @DataAtual
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND DCD_LINH = @NumLinha
					END
					ELSE
					BEGIN
						UPDATE FAC_ICDO SET ICD_PMRP = 0, ICD_PMRD = @DataAtual
						WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND ICD_LINH = @NumLinha
					END
				END
-- efetua o log da linha do documento de Venda/Conta marcado como enviada para Portal MyRangel
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)
					VALUES(@AnoDocumento, @CodTipoDocumento, @NumDocumento, @NumProcesso, @AnoProcesso, (CASE @CtxProcesso WHEN 0 THEN 'I' ELSE 'E' END), ((CASE ISNULL(@TipoLinha, -1) WHEN 0 THEN 'D' WHEN 1 THEN 'I' ELSE '' END) + CAST(@NumLinha AS varchar(10))), '## SQL-UPDATE: Linha marcada como enviada para o Portal MyRangel.')					
				END
			END
			FETCH NEXT FROM Linhas INTO @AnoDocumento, @CodTipoDocumento, @NumDocumento, @IdDocumento, @NumLinha, @DescricaoLinha, @TipoLinha, @ValorLiqLinha, @ValorIVALinha, @VerbaLinha, 
				@CtxDocumento, @DataDocumento, @CodCliente, @NumProcesso, @AnoProcesso, @CtxProcesso
		END
		CLOSE Linhas
		DEALLOCATE Linhas
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, '', 0, 0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de envio do LIN de documentos de Vendas/Contas emitidos e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDocsPortal(ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, '', 0, 0, 0, '', '############# FIM ENVIO FATURACAO-LIN ##################################################################################################################################')		
	END
-- se diretoria p/ log file especificada, grava ficheiro de log
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
-- constroi full path para geração do ficheiro XML
		SET @PathLogFile = @DirLogFile + 'LOG_FT_GIDWin2MYRANGEL_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), '-', ''), ' ', ''), ':', ''), '.', '') + '.TXT'
-- gera o ficheiro TXT p/ ficheiro log
		SET @Comando = 'bcp "SELECT ANODOC, TIPODOC, NUMDOC, NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO FROM ##LogTableDocsPortal ORDER BY ID" QUERYOUT "' + @PathLogFile + '" -c -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
	END	
-- remove a tabela temporária	
	DROP TABLE ##LogTableDocsPortal
END

ALTER AUTHORIZATION ON [SP_Facturacao_EnviaDocumentosPortalERDO] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_EnviaDocumentosPortalERDO] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_ExportaFicheiroEDIMWin]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_ExportaFicheiroEDIMWin] @Ano int, @Mes int, @NomeFicheiroTXT varchar(100) OUTPUT, @FicheiroTXT varchar(MAX) OUTPUT, @MensagemErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @DataDoc datetime, @ContaSNC varchar(15), @NumeroDoc int, @InvoiceNrDoc varchar(20), @ValorDoc numeric(38, 6), @SinalConta varchar(1), @FlagConta int, 
		@NIFCliente varchar(18), @DescritivoDoc varchar(15), @AbreviaturaDoc varchar(4), @NumeroLinha int, @SequenciaDoc int
-- inicia variaveis
	SET @FicheiroTXT = ''
-- constroi nome do ficheiro EDI MWin
	SET @NomeFicheiroTXT = '18' + RIGHT(STR(@Ano, 4), 2) + 'N' + REPLICATE('0', 2 - LEN(LTRIM(STR(@Mes, 2)))) + LTRIM(STR(@Mes, 2)) + CONVERT(varchar(2), DAY(DATEADD(MM, DATEDIFF(MM, -1, CAST('01-' + LTRIM(STR(@Mes, 2)) + '-' + STR(@Ano, 4) as datetime)), -1)), 2) + '.txt'
-- obtem os documentos de Contas e Vendas não anulados para o ano e mês selecionados
	DECLARE Docs CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT t.CDO_DTEM, t.CONTA, t.CDO_CNUM, t.CDO_INVN, t.CDO_VALO, t.CDO_SINA, t.CDO_FLAG, t.CDO_CNIF, 
			(CASE t.TDO_TDSF WHEN 'NC' THEN 'NOTAS CREDITO' ELSE 'VENDAS' END) AS TDO_DESC, 
			(CASE t.TDO_TDSF WHEN 'NC' THEN 'NCRE' ELSE 'FAT' END) AS TDO_ABRE, 
			ROW_NUMBER() OVER(PARTITION BY t.CDO_EANO, t.CDO_TDOC, t.CDO_CNUM ORDER BY t.CDO_TDOC, t.CDO_CNUM, t.TIPO) AS NUMERO,
			DENSE_RANK() OVER(ORDER BY t.CDO_TDOC, t.CDO_CNUM) AS ID
		FROM (
			SELECT 1 AS TIPO, 
				(unp.CONTA + (CASE unp.COLUNA WHEN 'CPO_CRFT' THEN RIGHT(ISNULL(cli.CLI_CPOC, ''), 3) ELSE '' END)) AS CONTA,
				cdo.CDO_EANO, cdo.CDO_TDOC, cdo.CDO_CNUM, cdo.CDO_DTEM, cdo.CDO_CNIF, tdo.TDO_TDSF, cdo.CDO_INVN, 	
				(CASE unp.COLUNA WHEN 'CPO_CONT' THEN cdo.CDO_IVA WHEN 'CPO_CLFT' THEN (cdo.CDO_TTIN + cdo.CDO_TTHO) WHEN 'CPO_CRFT' THEN cdo.CDO_TTRF WHEN 'CPO_CVFT' THEN cdo.CDO_TTDC ELSE 0 END) AS CDO_VALO, 
				(CASE unp.COLUNA WHEN 'CPO_CONT' THEN 'C' WHEN 'CPO_CLFT' THEN 'C' WHEN 'CPO_CRFT' THEN 'D' WHEN 'CPO_CVFT' THEN 'C' ELSE NULL END) AS CDO_SINA, 
				(CASE unp.COLUNA WHEN 'CPO_CONT' THEN 1 WHEN 'CPO_CLFT' THEN 1 WHEN 'CPO_CRFT' THEN 0 WHEN 'CPO_CVFT' THEN 3 ELSE NULL END) AS CDO_FLAG
			FROM TAB_CPOC AS cpo WITH(NOLOCK)
				UNPIVOT (CONTA
						FOR COLUNA IN (CPO_CONT, CPO_CLFT, CPO_CRFT, CPO_CVFT)
				) AS unp
				INNER JOIN FAC_CDOC AS cdo WITH(NOLOCK) ON unp.CPO_CODI = (CASE ISNULL(cdo.CDO_TXIV, 0) WHEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) THEN 1 ELSE 4 END)
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON cdo.CLI_CCOR = cli.CLI_CODI
			WHERE cdo.CDO_EANO = @Ano AND cdo.CDO_CNUM IS NOT NULL AND MONTH(cdo.CDO_DTEM) = @Mes AND cdo.CDO_ANUL = 0 AND cdo.CDO_IMPR = 1 AND tdo.TDO_TDSF = 'FT'
			UNION ALL
			SELECT 0 AS TIPO, unp.CONTA, cdo.CDO_EANO, cdo.CDO_TDOC, cdo.CDO_CNUM, cdo.CDO_DTEM, cdo.CDO_CNIF, tdo.TDO_TDSF, cdo.CDO_INVN, 
				(CASE unp.COLUNA WHEN 'CLI_CPOC' THEN (cdo.CDO_TTIN + cdo.CDO_TTHO + cdo.CDO_IVA - cdo.CDO_TTRF) WHEN 'CLI_CSNC' THEN cdo.CDO_TTDC ELSE 0 END) AS CDO_VALO,
				(CASE unp.COLUNA WHEN 'CLI_CPOC' THEN 'D' WHEN 'CLI_CSNC' THEN 'D' ELSE NULL END) AS CDO_SINA, 
				(CASE unp.COLUNA WHEN 'CLI_CPOC' THEN 1 WHEN 'CLI_CSNC' THEN 3 ELSE NULL END) AS CDO_FLAG
			FROM TAB_CLIE AS cli WITH(NOLOCK)
				UNPIVOT (CONTA
						FOR COLUNA IN (CLI_CPOC, CLI_CSNC)
				) AS unp
				INNER JOIN FAC_CDOC AS cdo WITH(NOLOCK) ON unp.CLI_CODI = cdo.CLI_CCOR
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU
			WHERE cdo.CDO_EANO = @Ano AND cdo.CDO_CNUM IS NOT NULL AND MONTH(cdo.CDO_DTEM) = @Mes AND cdo.CDO_ANUL = 0 AND cdo.CDO_IMPR = 1 AND tdo.TDO_TDSF = 'FT'
			UNION ALL
			SELECT 1 AS TIPO, unp.CONTA, dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_DATA, dve.DVE_CNIF, tdo.TDO_TDSF, dve.DVE_INVN, 	
				(CASE unp.COLUNA WHEN 'CPO_CONT' THEN ROUND(SUM(ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) * dvd.DVD_IVA / 100), 2) WHEN 'CPO_CLFT' THEN SUM((CASE WHEN rft.RFC_TIPO IN (1, 2) THEN ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) ELSE 0 END)) WHEN 'CPO_CVFT' THEN SUM((CASE WHEN rft.RFC_TIPO = 0 THEN ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) ELSE 0 END)) ELSE 0 END) AS CDO_VALO, 
				(CASE unp.COLUNA WHEN 'CPO_CONT' THEN 'C' WHEN 'CPO_CLFT' THEN 'C' WHEN 'CPO_CVFT' THEN 'C' ELSE NULL END) AS CDO_SINA, 
				(CASE unp.COLUNA WHEN 'CPO_CONT' THEN 1 WHEN 'CPO_CLFT' THEN 1 WHEN 'CPO_CVFT' THEN 3 ELSE NULL END) AS CDO_FLAG
			FROM TAB_CPOC AS cpo WITH(NOLOCK)
				UNPIVOT (CONTA
						FOR COLUNA IN (CPO_CONT, CPO_CLFT, CPO_CVFT)
				) AS unp
				INNER JOIN FAC_DVDT AS dvd WITH(NOLOCK) ON unp.CPO_CODI = (CASE ISNULL(dvd.DVD_IVA, 0) WHEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) THEN 1 ELSE 4 END)
				INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON dvd.RFC_CODI = rft.RFC_CODI
				INNER JOIN FAC_DVEN AS dve WITH(NOLOCK) ON dvd.DVE_EANO = dve.DVE_EANO AND dvd.DVE_TDOC = dve.DVE_TDOC AND dvd.DVE_NDOC = dve.DVE_NDOC
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU
			WHERE dve.DVE_EANO = @Ano AND MONTH(dve.DVE_DATA) = @Mes AND dve.DVE_ANUL = 0 AND tdo.TDO_TDSF IN ('FT', 'ND')
			GROUP BY unp.CONTA, dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_DATA, dve.DVE_CNIF, tdo.TDO_TDSF, dve.DVE_INVN, unp.COLUNA
			UNION ALL
			SELECT 1 AS TIPO, unp.CONTA, dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_DATA, dve.DVE_CNIF, tdo.TDO_TDSF, dve.DVE_INVN, 	
				(CASE unp.COLUNA WHEN 'CPO_CINC' THEN ROUND(SUM(ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) * dvd.DVD_IVA / 100), 2) WHEN 'CPO_CLNC' THEN SUM((CASE WHEN rft.RFC_TIPO IN (1, 2) THEN ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) ELSE 0 END)) WHEN 'CPO_CVNC' THEN SUM((CASE WHEN rft.RFC_TIPO = 0 THEN ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) ELSE 0 END)) ELSE 0 END) AS CDO_VALO, 
				(CASE unp.COLUNA WHEN 'CPO_CINC' THEN 'D' WHEN 'CPO_CLNC' THEN 'D' WHEN 'CPO_CVNC' THEN 'D' ELSE NULL END) AS CDO_SINA, 
				(CASE unp.COLUNA WHEN 'CPO_CINC' THEN 3 WHEN 'CPO_CLNC' THEN 1 WHEN 'CPO_CVNC' THEN 3 ELSE NULL END) AS CDO_FLAG
			FROM TAB_CPOC AS cpo WITH(NOLOCK)
				UNPIVOT (CONTA
						FOR COLUNA IN (CPO_CINC, CPO_CLNC, CPO_CVNC)
				) AS unp
				INNER JOIN FAC_DVDT AS dvd WITH(NOLOCK) ON unp.CPO_CODI = (CASE ISNULL(dvd.DVD_IVA, 0) WHEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) THEN 1 ELSE 4 END)
				INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON dvd.RFC_CODI = rft.RFC_CODI
				INNER JOIN FAC_DVEN AS dve WITH(NOLOCK) ON dvd.DVE_EANO = dve.DVE_EANO AND dvd.DVE_TDOC = dve.DVE_TDOC AND dvd.DVE_NDOC = dve.DVE_NDOC
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU
			WHERE dve.DVE_EANO = @Ano AND MONTH(dve.DVE_DATA) = @Mes AND dve.DVE_ANUL = 0 AND tdo.TDO_TDSF = 'NC'
			GROUP BY unp.CONTA, dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_DATA, dve.DVE_CNIF, tdo.TDO_TDSF, dve.DVE_INVN, unp.COLUNA
			UNION ALL
			SELECT 0 AS TIPO, unp.CONTA, dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_DATA, dve.DVE_CNIF, tdo.TDO_TDSF, dve.DVE_INVN, 	
				(CASE unp.COLUNA WHEN 'CLI_CPOC' THEN (SUM((CASE WHEN rft.RFC_TIPO IN (1, 2) THEN ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) ELSE 0 END)) + dve.DVE_VIVA) WHEN 'CLI_CSNC' THEN SUM((CASE WHEN rft.RFC_TIPO = 0 THEN ROUND((dvd.DVD_QUAN * dvd.DVD_VALO), 2) ELSE 0 END)) ELSE 0 END) AS CDO_VALO,
				(CASE unp.COLUNA WHEN 'CLI_CPOC' THEN (CASE tdo.TDO_TDSF WHEN 'NC' THEN 'C' ELSE 'D' END) WHEN 'CLI_CSNC' THEN (CASE tdo.TDO_TDSF WHEN 'NC' THEN 'C' ELSE 'D' END) ELSE NULL END) AS CDO_SINA, 
				(CASE unp.COLUNA WHEN 'CLI_CPOC' THEN 1 WHEN 'CLI_CSNC' THEN 3 ELSE NULL END) AS CDO_FLAG
			FROM TAB_CLIE AS cli WITH(NOLOCK)
				UNPIVOT (CONTA
						FOR COLUNA IN (CLI_CPOC, CLI_CSNC)
				) AS unp
				INNER JOIN FAC_DVEN AS dve WITH(NOLOCK) ON unp.CLI_CODI = dve.CLI_CODI 
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU
				INNER JOIN FAC_DVDT AS dvd WITH(NOLOCK) ON dve.DVE_EANO = dvd.DVE_EANO AND dve.DVE_TDOC = dvd.DVE_TDOC AND dve.DVE_NDOC = dvd.DVE_NDOC
				INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON dvd.RFC_CODI = rft.RFC_CODI				
			WHERE dve.DVE_EANO = @Ano AND MONTH(dve.DVE_DATA) = @Mes AND dve.DVE_ANUL = 0 
			GROUP BY unp.CONTA, dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_DATA, dve.DVE_CNIF, tdo.TDO_TDSF, dve.DVE_INVN, unp.COLUNA, dve.DVE_VIVA
		) AS t
		WHERE ISNULL(t.CONTA, '') <> '' AND t.CDO_VALO > 0
		ORDER BY t.CDO_TDOC, t.CDO_CNUM, t.TIPO				
	OPEN Docs
	FETCH NEXT FROM Docs INTO @DataDoc, @ContaSNC, @NumeroDoc, @InvoiceNrDoc, @ValorDoc, @SinalConta, @FlagConta, @NIFCliente, @DescritivoDoc, @AbreviaturaDoc, @NumeroLinha, @SequenciaDoc
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @FicheiroTXT = @FicheiroTXT + CONVERT(varchar(10), @DataDoc, 104) + ';'
		SET @FicheiroTXT = @FicheiroTXT + @ContaSNC + ';' 
		SET @FicheiroTXT = @FicheiroTXT + @DescritivoDoc + ';'
		SET @FicheiroTXT = @FicheiroTXT + REPLICATE('0', 6 - LEN(LTRIM(STR(@SequenciaDoc, 6)))) + LTRIM(STR(@SequenciaDoc, 6)) + ';'
		SET @FicheiroTXT = @FicheiroTXT + @AbreviaturaDoc + ';'
		SET @FicheiroTXT = @FicheiroTXT + REPLICATE('0', 7 - LEN(LTRIM(STR(@NumeroDoc, 7)))) + LTRIM(STR(@NumeroDoc, 10)) + ';'
		SET @FicheiroTXT = @FicheiroTXT + @InvoiceNrDoc + ';' 
		SET @FicheiroTXT = @FicheiroTXT + REPLICATE('0', 11 - LEN(LTRIM(STR(@ValorDoc, 11, 2)))) + LTRIM(STR(@ValorDoc, 11, 2)) + ';'
		SET @FicheiroTXT = @FicheiroTXT + @SinalConta + ';'
		SET @FicheiroTXT = @FicheiroTXT + '01;'
		SET @FicheiroTXT = @FicheiroTXT + LTRIM(STR(@FlagConta, 1)) + ';'
		SET @FicheiroTXT = @FicheiroTXT + '00001;'
		SET @FicheiroTXT = @FicheiroTXT + 'Desc ' + @ContaSNC + ';' 
		SET @FicheiroTXT = @FicheiroTXT + REPLICATE('0', 5 - LEN(LTRIM(STR(@NumeroLinha, 5)))) + LTRIM(STR(@NumeroLinha, 5)) + ';'
		SET @FicheiroTXT = @FicheiroTXT + @NIFCliente
		SET @FicheiroTXT = @FicheiroTXT + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Docs INTO @DataDoc, @ContaSNC, @NumeroDoc, @InvoiceNrDoc, @ValorDoc, @SinalConta, @FlagConta, @NIFCliente, @DescritivoDoc, @AbreviaturaDoc, @NumeroLinha, @SequenciaDoc
	END
	CLOSE Docs
	DEALLOCATE Docs
END

ALTER AUTHORIZATION ON [SP_Facturacao_ExportaFicheiroEDIMWin] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_ExportaFicheiroEDIMWin] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_ExportaFicheiroFEDEX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_ExportaFicheiroFEDEX] @DataReferenciaDe datetime, @DataReferenciaA datetime, @FicheiroDiario bit, @SufixoNomeFicheiro nvarchar(50), @DirGeracaoFicheiro nvarchar(500) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @PathFicheiroCSV nvarchar(4000), @Comando nvarchar(4000) 
-- verifica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirGeracaoFicheiro), 1, 1) <> '\'
		SET @DirGeracaoFicheiro = @DirGeracaoFicheiro + '\'
-- constroi o full path e o comando para o ficheiro CSV (conversão das data no bcp p/ "110" >> mm-dd-yyyy)
	IF @FicheiroDiario = 1
	BEGIN
		SET @PathFicheiroCSV = @DirGeracaoFicheiro + '1-ZARACCDOC_' + ISNULL((@SufixoNomeFicheiro + '_'), '') + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.CSV'	
		SET @Comando = 'bcp "EXEC SP_Facturacao_ExportaFicheiroFEDEXDadosDiarios N''' + CONVERT(varchar(10), @DataReferenciaDe, 110) + ''', N''' + CONVERT(varchar(10), @DataReferenciaA, 110) + '''" queryout "' + @PathFicheiroCSV + '" -c -t, -T -S' + @@servername + ' -d' + DB_NAME()
	END
	ELSE
	BEGIN	
		SET @PathFicheiroCSV = @DirGeracaoFicheiro + '2-ZARRA9MMT_' + ISNULL((@SufixoNomeFicheiro + '_'), '') + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121), ' ', ''), '-', ''), ':', ''), '.', '') + '.CSV'			
		SET @Comando = 'bcp "EXEC SP_Facturacao_ExportaFicheiroFEDEXDadosSemanais N''' + CONVERT(varchar(10), @DataReferenciaDe, 110) + ''', N''' + CONVERT(varchar(10), @DataReferenciaA, 110) + '''" queryout "' + @PathFicheiroCSV + '" -c -t, -T -S' + @@servername + ' -d' + DB_NAME()
	END	
-- gera o ficheiro CSV		
	EXEC master..xp_cmdshell @Comando, NO_OUTPUT		
END

ALTER AUTHORIZATION ON [SP_Facturacao_ExportaFicheiroFEDEX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_ExportaFicheiroFEDEX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_ExportaFicheiroFEDEXDadosDiarios]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_ExportaFicheiroFEDEXDadosDiarios] @DataReferenciaDe datetime, @DataReferenciaA datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @IDRegisto int, @Ano int, @TipoDoc varchar(4), @Numero int
	DECLARE @tmpTblExport TABLE(id int IDENTITY(1, 1), 
									colA varchar(50), colB varchar(50), colC varchar(50), colD varchar(50), colE varchar(50), colF varchar(50), colG varchar(50), colH varchar(50), colI varchar(50), 
									colJ varchar(50), colK varchar(50), colL varchar(50), colM varchar(50), colN varchar(50), colO varchar(50), colP varchar(50), colQ varchar(50), colR varchar(50), 
									colS varchar(50), colT varchar(50), colU varchar(50), colV varchar(50), colW varchar(50), colX varchar(50), colY varchar(50), colZ varchar(50), colAA varchar(50), 
									colAB varchar(50), colAC varchar(50), colAD varchar(50), colAE varchar(50), colAF varchar(50), colAG varchar(50), colAH varchar(50), colAI varchar(50), colAJ varchar(50), 
									colAK varchar(50), colAL varchar(50), colAM varchar(50), colAN varchar(50), colAO varchar(50), colAP varchar(50), colAQ varchar(50), colAR varchar(50), colAS varchar(50), 
									colAT varchar(50), colAU varchar(50), colAV varchar(50), colAW varchar(50), colAX varchar(50), colAY varchar(50), colAZ varchar(50), colBA varchar(50), colBB varchar(50),
									colBC varchar(50), colBD varchar(50), colBE varchar(50), colBF varchar(50))
-- inicia variáveis
	SET @IDRegisto = 0
-- insere os títulos das colunas na tabela de dados tmp 
	INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF)
	VALUES('Transaction Counter', 'Company Code (H)', 'Fiscal Year - CCYY (H)', 'SAP Document Type (H)', 'Document date -CCYYMMDD (H)', 'Posting date - CCYYMMDD (H)', 'Fiscal Period (H)', 'Cross Reference document (H)', 'Currency (H)', 'EBO Accrual Reason Code (H)', 'Accrual Reversal Date - CCYYMMDD (H)', 'Header Text (H)', 'Barcode (H)', 'EBO Accounting document number (H)', 'Line Type', 'Debit / Credit', 'EBO G/L Account', 'Amount in Document Currency', 'Functional Area', 'EBO Cost Centre', 'EBO Profit Centre', 'Internal Order', 'Assignment number', 'Tax Code', 'Amount Tax based upon', 'Legacy Customer ID', 'EBO Customer ID', 'EBO Vendor ID', 'Payment Due Date (CCYYMMDD)', 'Payment Terms', 'Value Date (CCYYMMDD)', 'Credit Control Area', 'Reference Invoice', 'Fiscal Year of Reference Invoice', 'Credit Note Reason Code', 'Line Item Text', 'Transaction Type', 'Asset Transaction Type', 'Trading Partner (Internal TPG)', 'Asset Number', 'Asset Sub-Number', 'Asset Value Date (CCYYMMDD)', 'Discount Amount', 'Tax Jurisdiction Code', 'Cash Flag', 'Cross-Company Code', 'Local Currency Amount', 'Local Currency Tax Base Amt', 'Local Currency Disc. Amt', 'Group Currency Amount', 'Group Currency Tax Base Amt', 'Group Currency Disc. Amt', 'Business Place', 'Section Code', 'Branch number', 'Withholding Tax Code', 'Withholding Tax Type', 'Withholding Tax Base Amount')
-- obtem os documentos de Contas emitidos, não anulados e do tipo SAFT "FT" para o período	
	DECLARE DocsConta CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN
		FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dco.CDO_TDOC = tdo.TDO_DOCU 
		WHERE tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'FT' AND dco.CDO_IMPR = 1 AND dco.CDO_ANUL = 0
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferenciaDe, 105) AS datetime)
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataReferenciaA, 105) AS datetime)
	OPEN DocsConta
	FETCH NEXT FROM DocsConta INTO @Ano, @TipoDoc, @Numero
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @IDRegisto = @IDRegisto + 1
-- insere o registo de dados gerais do documento de Conta na tabela de dados tmp 
		INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF)
		SELECT LTRIM(STR(@IDRegisto, 10)), 'PT11', LTRIM(STR(YEAR(DATEADD(month, 7, dco.CDO_DTEM)), 4)), 'DR', CONVERT(varchar(8), dco.CDO_DTEM, 112), 
			CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112),	
			LTRIM(STR(MONTH(DATEADD(month, 7, dco.CDO_DTEM)), 2)), (dco.CDO_TDOC + LTRIM(STR(dco.CDO_CNUM, 10))), 'EUR', NULL, NULL, (dco.CDO_TDOC + LTRIM(STR(dco.CDO_CNUM, 10))), NULL, NULL, 'C', 
			'D', NULL, LTRIM(STR(dco.CDO_TTPR, 18, 2)), NULL, NULL, NULL, NULL, dco.CDO_CPRT, NULL, NULL, NULL, '2201289330', NULL, CONVERT(varchar(8), dco.CDO_DTEM, 112), 
			NULL, NULL, NULL, (dco.CDO_TDOC + LTRIM(STR(dco.CDO_CNUM, 10))), NULL, NULL, NULL, 
			NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
		FROM FAC_CDOC AS dco WITH(NOLOCK)
		WHERE dco.CDO_EANO = @Ano AND dco.CDO_TDOC = @TipoDoc AND dco.CDO_IDEN = @Numero
-- insere as despesas documentadas e despesas inerentes do documento de Conta na tabela de dados tmp 
		INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF)
		SELECT LTRIM(STR(@IDRegisto, 10)), 'PT11', LTRIM(STR(YEAR(DATEADD(month, 7, t.CDO_DTEM)), 4)), 'DR', CONVERT(varchar(8), t.CDO_DTEM, 112), 
			CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112),	
			LTRIM(STR(MONTH(DATEADD(month, 7, t.CDO_DTEM)), 2)), (t.CDO_TDOC + LTRIM(STR(t.CDO_CNUM, 10))), 'EUR', NULL, NULL, (t.CDO_TDOC + LTRIM(STR(t.CDO_CNUM, 10))), NULL, NULL, NULL, 
			'C', t.CDO_CSAP, LTRIM(STR(SUM(t.CDO_VTOT), 18, 2)), NULL, NULL, '2007OPO', NULL, t.CDO_CPRT, 'Z9', NULL, NULL, NULL, NULL, NULL, 
			NULL, NULL, NULL, (t.CDO_TDOC + LTRIM(STR(t.CDO_CNUM, 10))), NULL, NULL, (CASE t.CDO_CSAP WHEN '361810' THEN '*0.0*0**PT*PT*0*' WHEN '347000' THEN LTRIM(STR(t.CDO_NPRO, 10)) ELSE NULL END), 
			NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
		FROM (			
			SELECT dco.CDO_TDOC, dco.CDO_DTEM, dco.CDO_CNUM, dco.CDO_NPRO, dco.CDO_CPRT, ddo.DDO_SPCD AS CDO_CSAP, cod.DCD_VTOT AS CDO_VTOT
			FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN FAC_DCDO AS cod WITH(NOLOCK) ON dco.CDO_EANO = cod.CDO_EANO AND dco.CDO_TDOC = cod.CDO_TDOC AND dco.CDO_IDEN = cod.CDO_IDEN
				INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON cod.DDO_CODI = ddo.DDO_CODI
			WHERE dco.CDO_EANO = @Ano AND dco.CDO_TDOC = @TipoDoc AND dco.CDO_IDEN = @Numero
			UNION ALL
			SELECT dco.CDO_TDOC, dco.CDO_DTEM, dco.CDO_CNUM, dco.CDO_NPRO, dco.CDO_CPRT, din.DIN_SPCD AS CDO_CSAP, coi.ICD_VTOT AS CDO_VTOT
			FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN FAC_ICDO AS coi WITH(NOLOCK) ON dco.CDO_EANO = coi.CDO_EANO AND dco.CDO_TDOC = coi.CDO_TDOC AND dco.CDO_IDEN = coi.CDO_IDEN
				INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON coi.DIN_CODI = din.DIN_CODI
			WHERE dco.CDO_EANO = @Ano AND dco.CDO_TDOC = @TipoDoc AND dco.CDO_IDEN = @Numero
			UNION ALL
			SELECT dco.CDO_TDOC, dco.CDO_DTEM, dco.CDO_CNUM, dco.CDO_NPRO, dco.CDO_CPRT, din.DIN_SPCD AS CDO_CSAP, dco.CDO_TTHO AS CDO_VTOT
			FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON dco.DIN_HONO = din.DIN_CODI
			WHERE dco.CDO_EANO = @Ano AND dco.CDO_TDOC = @TipoDoc AND dco.CDO_IDEN = @Numero		
			) AS t
		GROUP BY t.CDO_TDOC, t.CDO_DTEM, t.CDO_CNUM, t.CDO_NPRO, t.CDO_CPRT, t.CDO_CSAP
		ORDER BY t.CDO_CSAP
-- insere o registo de dados do IVA do documento de Conta na tabela de dados tmp
		INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF)
		SELECT LTRIM(STR(@IDRegisto, 10)), 'PT11', LTRIM(STR(YEAR(DATEADD(month, 7, dco.CDO_DTEM)), 4)), 'DR', CONVERT(varchar(8), dco.CDO_DTEM, 112), 
			CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112),	
			LTRIM(STR(MONTH(DATEADD(month, 7, dco.CDO_DTEM)), 2)), (dco.CDO_TDOC + LTRIM(STR(dco.CDO_CNUM, 10))), 'EUR', NULL, NULL, (dco.CDO_TDOC + LTRIM(STR(dco.CDO_CNUM, 10))), NULL, NULL, NULL, 
			'C', '351200', LTRIM(STR(dco.CDO_IVA, 18, 2)), NULL, NULL, NULL, NULL, dco.CDO_CPRT, 'Z9', NULL, NULL, NULL, NULL, NULL, 
			NULL, NULL, NULL, (dco.CDO_TDOC + LTRIM(STR(dco.CDO_CNUM, 10))), NULL, NULL, NULL, 
			NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL					
		FROM FAC_CDOC AS dco WITH(NOLOCK) 
		WHERE dco.CDO_EANO = @Ano AND dco.CDO_TDOC = @TipoDoc AND dco.CDO_IDEN = @Numero
			
		FETCH NEXT FROM DocsConta INTO @Ano, @TipoDoc, @Numero
	END
	CLOSE DocsConta
	DEALLOCATE DocsConta
-- obtem os documentos de Vendas emitidos, não anulados e do tipo SAFT "NC" para o período	
	DECLARE DocsVenda CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC
		FROM FAC_DVEN AS dve WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU 
		WHERE tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'NC' AND dve.DVE_ANUL = 0 
			AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferenciaDe, 105) AS datetime)
			AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataReferenciaA, 105) AS datetime)
	OPEN DocsVenda
	FETCH NEXT FROM DocsVenda INTO @Ano, @TipoDoc, @Numero
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @IDRegisto = @IDRegisto + 1
-- insere o registo de dados gerais do documento de Venda na tabela de dados tmp 
		INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF)
		SELECT LTRIM(STR(@IDRegisto, 10)), 'PT11', LTRIM(STR(YEAR(DATEADD(month, 7, dve.DVE_DATA)), 4)), 'DR', CONVERT(varchar(8), dve.DVE_DATA, 112), 
			CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112),	
			LTRIM(STR(MONTH(DATEADD(month, 7, dve.DVE_DATA)), 2)), (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), 'EUR', NULL, NULL, (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), NULL, NULL, 'C', 
			'C', NULL, LTRIM(STR(dve.DVE_VTOT, 18, 2)), NULL, NULL, NULL, NULL, dco.CDO_CPRT, NULL, NULL, NULL, '2201289330', NULL, CONVERT(varchar(8), dve.DVE_DATA, 112), 
			NULL, NULL, NULL, (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), NULL, NULL, NULL, 
			NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
		FROM FAC_DVEN AS dve WITH(NOLOCK) LEFT OUTER JOIN FAC_MVCC AS mcc WITH(NOLOCK) ON dve.MVC_IDEN = mcc.MVC_IDEN
			LEFT OUTER JOIN FAC_CDOC AS dco WITH(NOLOCK) ON mcc.MVC_TDOC = dco.CDO_TDOC AND mcc.MVC_NDOC = dco.CDO_CNUM AND mcc.MVC_EANO = dco.CDO_EANO
		WHERE dve.DVE_EANO = @Ano AND dve.DVE_TDOC = @TipoDoc AND dve.DVE_NDOC = @Numero
-- insere as rúbricas de faturação do documento de Venda na tabela de dados tmp 
		INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF)
		SELECT LTRIM(STR(@IDRegisto, 10)), 'PT11', LTRIM(STR(YEAR(DATEADD(month, 7, dve.DVE_DATA)), 4)), 'DR', CONVERT(varchar(8), dve.DVE_DATA, 112), 
			CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112),	
			LTRIM(STR(MONTH(DATEADD(month, 7, dve.DVE_DATA)), 2)), (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), 'EUR', NULL, NULL, (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), NULL, NULL, NULL, 
			'D', rft.RFC_CPOC, LTRIM(STR(SUM(det.DVD_QUAN * det.DVD_VALO), 18, 2)), NULL, NULL, '2007OPO', NULL, dco.CDO_CPRT, 'Z9', NULL, NULL, NULL, NULL, NULL, 
			NULL, NULL, NULL, (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), NULL, NULL, (CASE rft.RFC_CPOC WHEN '361810' THEN '*0.0*0**PT*PT*0*' WHEN '347000' THEN LTRIM(STR(dve.DVE_NPRO, 10)) ELSE NULL END), 
			NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
		FROM FAC_DVEN AS dve WITH(NOLOCK) LEFT OUTER JOIN FAC_MVCC AS mcc WITH(NOLOCK) ON dve.MVC_IDEN = mcc.MVC_IDEN
			LEFT OUTER JOIN FAC_CDOC AS dco WITH(NOLOCK) ON mcc.MVC_TDOC = dco.CDO_TDOC AND mcc.MVC_NDOC = dco.CDO_CNUM AND mcc.MVC_EANO = dco.CDO_EANO
			INNER JOIN FAC_DVDT AS det WITH(NOLOCK) ON dve.DVE_EANO = det.DVE_EANO AND dve.DVE_TDOC = det.DVE_TDOC AND dve.DVE_NDOC = det.DVE_NDOC
			INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON det.RFC_CODI = rft.RFC_CODI
		WHERE dve.DVE_EANO = @Ano AND dve.DVE_TDOC = @TipoDoc AND dve.DVE_NDOC = @Numero 
		GROUP BY dve.DVE_TDOC, dve.DVE_DATA, dve.DVE_NDOC, dve.DVE_NPRO, dco.CDO_CPRT, rft.RFC_CPOC
		ORDER BY rft.RFC_CPOC				
-- insere o registo de dados do IVA do documento de Venda na tabela de dados tmp 
		INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF)
		SELECT LTRIM(STR(@IDRegisto, 10)), 'PT11', LTRIM(STR(YEAR(DATEADD(month, 7, dve.DVE_DATA)), 4)), 'DR', CONVERT(varchar(8), dve.DVE_DATA, 112), 
			CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112),	
			LTRIM(STR(MONTH(DATEADD(month, 7, dve.DVE_DATA)), 2)), (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), 'EUR', NULL, NULL, (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), NULL, NULL, NULL, 
			'D', '351200', LTRIM(STR(dve.DVE_VIVA, 18, 2)), NULL, NULL, NULL, NULL, dco.CDO_CPRT, 'Z9', NULL, NULL, NULL, NULL, NULL, 
			NULL, NULL, NULL, (dve.DVE_TDOC + LTRIM(STR(dve.DVE_NDOC, 10))), NULL, NULL, NULL, 
			NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL					
		FROM FAC_DVEN AS dve WITH(NOLOCK) LEFT OUTER JOIN FAC_MVCC AS mcc WITH(NOLOCK) ON dve.MVC_IDEN = mcc.MVC_IDEN
			LEFT OUTER JOIN FAC_CDOC AS dco WITH(NOLOCK) ON mcc.MVC_TDOC = dco.CDO_TDOC AND mcc.MVC_NDOC = dco.CDO_CNUM AND mcc.MVC_EANO = dco.CDO_EANO
		WHERE dve.DVE_EANO = @Ano AND dve.DVE_TDOC = @TipoDoc AND dve.DVE_NDOC = @Numero

		FETCH NEXT FROM DocsVenda INTO @Ano, @TipoDoc, @Numero
	END
	CLOSE DocsVenda
	DEALLOCATE DocsVenda
-- devolve os dados de faturação no formato diário obtidos para o período da tabela de dados tmp 
	SELECT colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS, colT, colU, colV, colW, colX, colY, colZ, colAA, colAB, colAC, colAD, colAE, colAF, colAG, colAH, colAI, colAJ, colAK, colAL, colAM, colAN, colAO, colAP, colAQ, colAR, colAS, colAT, colAU, colAV, colAW, colAX, colAY, colAZ, colBA, colBB, colBC, colBD, colBE, colBF
	FROM @tmpTblExport
	ORDER BY id
END

ALTER AUTHORIZATION ON [SP_Facturacao_ExportaFicheiroFEDEXDadosDiarios] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_ExportaFicheiroFEDEXDadosDiarios] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_ExportaFicheiroFEDEXDadosSemanais]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Facturacao_ExportaFicheiroFEDEXDadosSemanais] @DataReferenciaDe datetime, @DataReferenciaA datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @tmpTblExport TABLE(id int IDENTITY(1, 1), 
									colA varchar(50), colB varchar(50), colC varchar(50), colD varchar(50), colE varchar(50), colF varchar(50), colG varchar(50), colH varchar(50), colI varchar(50), 
									colJ varchar(50), colK varchar(50), colL varchar(50), colM varchar(50), colN varchar(50), colO varchar(50), colP varchar(50), colQ varchar(50), colR varchar(50), 
									colS varchar(50))
-- insere os títulos das colunas na tabela de dados tmp
	INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS)
	VALUES('Source System', 'Company Code', 'Posting Date (CCYYMMDD)', 'Document Date (CCYYMMDD)', 'Accrual Currency  Code', 'General Ledger Account', 'Accrual GL Account', 'Profit Center', 'Material Number', 'Freight/Parcel Indicator', 'Zero Revenue Indicator', 'Debit/Credit Indicator', 'Amount in Company Code Currency', 'Pay Weight', 'Weight Unit', 'Number of Consignments', 'Country of Origin', 'Country of Destination', 'No of Packages')		
-- insere os documentos de Contas emitidos para o período somente relativos à conta "361810" na tabela de dados tmp
	INSERT INTO @tmpTblExport(colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS)
	SELECT 'CS_GLOB_LK', 'PT11', CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112),	
		CONVERT(varchar(8), (CASE WHEN DATEDIFF(day, DATEADD(month, DATEDIFF(month, -1, GETDATE()), -1), GETDATE()) = 0 THEN DATEADD(day, 1, GETDATE()) ELSE GETDATE() END), 112), 'EUR', '400000', '361810', 
		'2007OPO', 'GD15D', NULL, NULL, (CASE WHEN SUM(t.CDO_VTOT) < 0 THEN 'D' ELSE 'C' END), LTRIM(STR(ISNULL(ABS(SUM(t.CDO_VTOT)), 0), 18, 2)), 0, 'KG', 0, 'PT', 'PT', 0						
	FROM (			
		SELECT SUM(cod.DCD_VTOT) AS CDO_VTOT
		FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dco.CDO_TDOC = tdo.TDO_DOCU 
			INNER JOIN FAC_DCDO AS cod WITH(NOLOCK) ON dco.CDO_EANO = cod.CDO_EANO AND dco.CDO_TDOC = cod.CDO_TDOC AND dco.CDO_IDEN = cod.CDO_IDEN
			INNER JOIN TAB_DDOC AS ddo WITH(NOLOCK) ON cod.DDO_CODI = ddo.DDO_CODI
		WHERE tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'FT' AND dco.CDO_IMPR = 1 AND dco.CDO_ANUL = 0 AND ddo.DDO_SPCD = '361810'
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferenciaDe, 105) AS datetime)
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataReferenciaA, 105) AS datetime)		
		UNION ALL
		SELECT SUM(coi.ICD_VTOT) AS CDO_VTOT			
		FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dco.CDO_TDOC = tdo.TDO_DOCU 
			INNER JOIN FAC_ICDO AS coi WITH(NOLOCK) ON dco.CDO_EANO = coi.CDO_EANO AND dco.CDO_TDOC = coi.CDO_TDOC AND dco.CDO_IDEN = coi.CDO_IDEN
			INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON coi.DIN_CODI = din.DIN_CODI
		WHERE tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'FT' AND dco.CDO_IMPR = 1 AND dco.CDO_ANUL = 0 AND din.DIN_SPCD = '361810'
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferenciaDe, 105) AS datetime)
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataReferenciaA, 105) AS datetime)		
		UNION ALL
		SELECT SUM(dco.CDO_TTHO) AS CDO_VTOT 
		FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dco.CDO_TDOC = tdo.TDO_DOCU 		
			INNER JOIN TAB_DINE AS din WITH(NOLOCK) ON dco.DIN_HONO = din.DIN_CODI
		WHERE tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'FT' AND dco.CDO_IMPR = 1 AND dco.CDO_ANUL = 0 AND din.DIN_SPCD = '361810'		
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferenciaDe, 105) AS datetime)
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataReferenciaA, 105) AS datetime)
		UNION ALL
		SELECT -SUM(det.DVD_QUAN * det.DVD_VALO) AS CDO_VTOT			
		FROM FAC_DVEN AS dve WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU 			
			INNER JOIN FAC_DVDT AS det WITH(NOLOCK) ON dve.DVE_EANO = det.DVE_EANO AND dve.DVE_TDOC = det.DVE_TDOC AND dve.DVE_NDOC = det.DVE_NDOC
			INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON det.RFC_CODI = rft.RFC_CODI
		WHERE tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'NC' AND dve.DVE_ANUL = 0 AND rft.RFC_CPOC = '361810'
			AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferenciaDe, 105) AS datetime)
			AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataReferenciaA, 105) AS datetime)		
		) AS t	
-- devolve os dados de faturação no formato semanal obtidos para o período da tabela de dados tmp
	SELECT colA, colB, colC, colD, colE, colF, colG, colH, colI, colJ, colK, colL, colM, colN, colO, colP, colQ, colR, colS
	FROM @tmpTblExport
	ORDER BY id
END

ALTER AUTHORIZATION ON [SP_Facturacao_ExportaFicheiroFEDEXDadosSemanais] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_ExportaFicheiroFEDEXDadosSemanais] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_ExportaFicheiroSAPALS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_Facturacao_ExportaFicheiroSAPALS] @DataReferencia datetime, @PrefixoNomeFicheiro nvarchar(50), @DirGeracaoFicheiro nvarchar(500) AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @TblTmpLinhas TABLE(
		id int NOT NULL IDENTITY(1, 1), 
		numDocumento int NOT NULL,
		tipoLinha tinyint NOT NULL,
		nomeLinha varchar(50) NOT NULL,
		ordem tinyint NOT NULL, 
		textoLinha varchar(2500) NOT NULL)
	DECLARE @DataAtual datetime, @PathFicheiroSAP nvarchar(4000), @FileSystemObj int, @TextFileObj int, @TotalLinhasGeradas int, @NumDocsExportados int, @NumDocsExportadosSTR varchar(12), 
		@LinhaTXT varchar(2500)		
	DECLARE @AnoDocumento int, @CodTipoDocumento varchar(4), @IdDocumento int, @NumDocumento int, @DataDocumento datetime, @CodNatureza varchar(3), @TotalIVADocumento numeric(38, 6), 
		@CodigoEANCliente varchar(13), @SerieDocumento varchar(20), @DataVencimento datetime, @CtxTipoDoc int, @TipoSAFT varchar(2), @TotalDocumento numeric(38, 6), @NumProcessoGlobal int, 
		@CodAlfandega varchar(8), @NIFCliente varchar(18), @CodPaisCliente varchar(2), @DiasAPagamentoCliente int, @TotalBaseIVADocumento numeric(38, 6), @TotalInerentesIsentas numeric(38, 6), 
		@TotalDocumentadasDocumento numeric(38, 6)
	DECLARE @NumLinhaIVA int, @TipoIVA varchar(2), @BaseIVA numeric(38, 6), @ValorIVA numeric(38, 6)
-- verifica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirGeracaoFicheiro), 1, 1) <> '\'
		SET @DirGeracaoFicheiro = @DirGeracaoFicheiro + '\'
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia variáveis
	SET @TotalLinhasGeradas = 0
	SET @NumDocsExportados = 0
-- obtem os documentos de Contas e Vendas emitidos, não anulados e de exportação SAFT para a data	
	DECLARE Docs CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN, dco.CDO_CNUM, dco.CDO_DTEM, dco.NDE_CODI, dco.ALF_CODI, ISNULL(dco.CDO_TTDC, 0), ISNULL(dco.CDO_BIVA, 0), ISNULL(dco.CDO_IVA, 0), 
			ISNULL(dco.CDO_TTPR, 0), ISNULL(dco.CDO_CNIF, ''), dco.CDO_CPAI, ISNULL(dco.CDO_CEAN, ''), ISNULL(dco.CDO_CPAG, 0), ISNULL(dco.CDO_SERI, ''), tdo.TDO_TDOC, tdo.TDO_TDSF, 
			DATEADD(DAY, ISNULL(dco.CDO_CPAG, 0), dco.CDO_DTEM), 						
			(CASE 
				WHEN EXISTS(SELECT 1 FROM FAC_CDOC WITH(NOLOCK) WHERE CDO_ANOG = dco.CDO_EANO AND CDO_TDOG = dco.CDO_TDOC AND CDO_IDEG = dco.CDO_IDEN) THEN dco.CDO_NPRO
				ELSE NULL
			END), 
			ISNULL((SELECT SUM(ISNULL(ICD_VTOT, 0)) FROM FAC_ICDO WITH(NOLOCK) WHERE CDO_EANO = dco.CDO_EANO AND CDO_TDOC = dco.CDO_TDOC AND CDO_IDEN = dco.CDO_IDEN AND ICD_ISEN = 1), 0)
		FROM FAC_CDOC AS dco WITH(NOLOCK) 
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dco.CDO_TDOC = tdo.TDO_DOCU 			
		WHERE dco.CDO_CNUM IS NOT NULL AND dco.CDO_ANUL = 0 AND dco.CDO_IMPR = 1 AND tdo.TDO_DCON = 1 AND tdo.TDO_EXSF = 1 
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)			
		UNION ALL
		SELECT dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_NDOC, dve.DVE_DATA, dve.NDE_CODI, NULL AS ALF_CODI, 0.00 AS CDO_TTDC, dve.DVE_VLIQ, dve.DVE_VIVA, 
			dve.DVE_VTOT, dve.DVE_CNIF, dve.PAI_CLIV, ISNULL(cli.CLI_CEAN, ''), ISNULL(cli.CLI_CPAG, 0), dve.DVE_SERI, tdo.TDO_TDOC, tdo.TDO_TDSF, 
			DATEADD(DAY, ISNULL(cli.CLI_CPAG, 0), dve.DVE_DATA), 						
			NULL, 			
			ISNULL((SELECT SUM(ROUND(ISNULL(DVD_QUAN, 0) * ISNULL(DVD_VALO, 0), 2)) FROM FAC_DVDT WITH(NOLOCK) WHERE DVE_TDOC = dve.DVE_TDOC AND DVE_NDOC = dve.DVE_NDOC AND DVE_EANO = dve.DVE_EANO AND ISNULL(DVD_IVA, 0) = 0 AND DVD_LCRB = 1), 0)
		FROM FAC_DVEN AS dve WITH(NOLOCK) 
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dve.CLI_CODI = cli.CLI_CODI			
		WHERE dve.DVE_ANUL = 0 AND tdo.TDO_DCON = 1 AND tdo.TDO_EXSF = 1
			AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime) 			
		ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_CNUM
	OPEN Docs
	FETCH NEXT FROM Docs INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumDocumento, @DataDocumento, @CodNatureza, @CodAlfandega, @TotalDocumentadasDocumento, @TotalBaseIVADocumento, 
		@TotalIVADocumento, @TotalDocumento, @NIFCliente, @CodPaisCliente, @CodigoEANCliente, @DiasAPagamentoCliente, @SerieDocumento, @CtxTipoDoc, @TipoSAFT, @DataVencimento, @NumProcessoGlobal, 
		@TotalInerentesIsentas
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @NumLinhaIVA = 4
-- incrementa variáveis
		SET @NumDocsExportados = @NumDocsExportados + 1
		SET @NumDocsExportadosSTR = REPLICATE('0', (12 - LEN(LTRIM(STR(@NumDocsExportados, 12))))) + LTRIM(STR(@NumDocsExportados, 12))
-- para os documentos de venda, ajusta o valor da base do IVA
		IF @CtxTipoDoc = 1
			SET @TotalBaseIVADocumento = @TotalBaseIVADocumento - @TotalInerentesIsentas
-- constroi a linha do tipo "Header record"
		SET @LinhaTXT = '02' --SATZART
		SET @LinhaTXT = @LinhaTXT + @NumDocsExportadosSTR --SATZNUMMER
		SET @LinhaTXT = @LinhaTXT + SPACE(22) --SENDERKENNZEICHEN
		SET @LinhaTXT = @LinhaTXT + SPACE(22) --EMPFAENGERKENNZEICHEN
		SET @LinhaTXT = @LinhaTXT + 'FI-BELEG' + SPACE(22) --SATZTYP
		SET @LinhaTXT = @LinhaTXT + 'FI-BELEG' + SPACE(22) --NACHRICHTENTYP		
-- escreve a linha do tipo "Header record" na tabela tmp
		INSERT INTO @TblTmpLinhas(numDocumento, tipoLinha, nomeLinha, ordem, textoLinha)
		VALUES(@NumDocsExportados, 2, '', 0, @LinhaTXT)
-- constroi a linha do tipo "Header document" (KOPF)
		SET @LinhaTXT = '03' --SATZART
		SET @LinhaTXT = @LinhaTXT + @NumDocsExportadosSTR --SATZNR
		SET @LinhaTXT = @LinhaTXT + '000001' --SEGNR
		SET @LinhaTXT = @LinhaTXT + '000001' --PSEGNR
		SET @LinhaTXT = @LinhaTXT + 'KOPF' + SPACE(26) --SEGTYP
		SET @LinhaTXT = @LinhaTXT + '2049' + SPACE(2) --BUKRS
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --BELNR
		SET @LinhaTXT = @LinhaTXT + STR(@AnoDocumento, 4) --GJAHR
		SET @LinhaTXT = @LinhaTXT + (CASE @TipoSAFT WHEN 'NC' THEN 'FG' ELSE 'FR' END) --BLART
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataDocumento, 112) --BLDAT
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataDocumento, 112) --BUDAT
		SET @LinhaTXT = @LinhaTXT + REPLICATE('0', (2 - LEN(LTRIM(STR(MONTH(@DataDocumento), 2))))) + LTRIM(STR(MONTH(@DataDocumento), 2)) --MONAT 
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataDocumento, 112) --WWERT
		SET @LinhaTXT = @LinhaTXT + SPACE(12) --USNAM 
		SET @LinhaTXT = @LinhaTXT + 'FB01' + SPACE(16) --TCODE
		SET @LinhaTXT = @LinhaTXT + SPACE(16) --BVORG 
		SET @LinhaTXT = @LinhaTXT + (LTRIM(STR(@NumDocumento, 16)) + SPACE(16 - LEN(LTRIM(STR(@NumDocumento, 16))))) --XBLNR
		SET @LinhaTXT = @LinhaTXT + SPACE(25) --BKTXT
		SET @LinhaTXT = @LinhaTXT + 'EUR' + SPACE(2) --WAERS
		SET @LinhaTXT = @LinhaTXT + '00000100000' --KURSF
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --GLVOR
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --AWTYP
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --AWREF
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --AWORG
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --FIKRS
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --HWAER
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --HWAE2
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --HWAE3
		SET @LinhaTXT = @LinhaTXT + SPACE(11) --KURS2
		SET @LinhaTXT = @LinhaTXT + SPACE(11) --KURS3
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --BASW2
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --BASW3
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --UMRD2
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --UMRD3
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --CURT2
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --CURT3
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --AUSBK
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --AWSYS
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --LOTKZ
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --BUKRS_SND
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --FILTER
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --STGRD
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --STODT
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataDocumento, 112) --VATDATE
-- escreve a linha do tipo "Header document" (KOPF) na tabela tmp
		INSERT INTO @TblTmpLinhas(numDocumento, tipoLinha, nomeLinha, ordem, textoLinha)
		VALUES(@NumDocsExportados, 3, 'KOPF', 0, @LinhaTXT)
-- constroi a linha do tipo "Item document" (POSITION)
		SET @LinhaTXT = '03' --SATZART
		SET @LinhaTXT = @LinhaTXT + @NumDocsExportadosSTR --SATZNR
		SET @LinhaTXT = @LinhaTXT + '000002' --SEGNR
		SET @LinhaTXT = @LinhaTXT + '000001' --PSEGNR
		SET @LinhaTXT = @LinhaTXT + 'POSITION' + SPACE(22) --SEGTYP
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --BUZEI
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --BUZID
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --AUGDT
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --AUGCP
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --AUGBL
		SET @LinhaTXT = @LinhaTXT + (CASE @TipoSAFT WHEN 'NC' THEN '11' ELSE '01' END) --BSCHL
		SET @LinhaTXT = @LinhaTXT + 'D' --KOART
		SET @LinhaTXT = @LinhaTXT + (CASE @TipoSAFT WHEN 'NC' THEN 'H' ELSE 'S' END) --SHKZG
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --GSBER
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --PARGB
		SET @LinhaTXT = @LinhaTXT + '**' --MWSKZ		
		SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@TotalDocumento, 15, 2), ' ', '0'), '.', '')) --DMBTR
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --DMBE2
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --DMBE3
		SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@TotalDocumento, 15, 2), ' ', '0'), '.', '')) --WRBTR
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --KZBTR 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --PSWBT
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --PSWSL
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --HWBAS
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --FWBAS
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --MWART
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --KTOSL
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataDocumento, 112) --VALUT
		SET @LinhaTXT = @LinhaTXT + (CASE WHEN @NumProcessoGlobal IS NULL THEN LTRIM(STR(@NumDocumento, 18)) + SPACE(18 - LEN(LTRIM(STR(@NumDocumento, 18)))) ELSE LTRIM(STR(@NumProcessoGlobal, 18)) + SPACE(18 - LEN(LTRIM(STR(@NumProcessoGlobal, 18)))) END) --ZUONR		
		SET @LinhaTXT = @LinhaTXT + LEFT((ISNULL(@CodNatureza + '_', '') + ISNULL(@CodAlfandega + '_' , '') + @SerieDocumento + '/' + LTRIM(STR(@NumDocumento, 10))), 50) + SPACE(50 - LEN(LEFT((ISNULL(@CodNatureza + '_', '') + ISNULL(@CodAlfandega + '_' , '') + @SerieDocumento + '/' + LTRIM(STR(@NumDocumento, 10))), 50))) --SGTXT
		SET @LinhaTXT = @LinhaTXT + SPACE(6) --VBUND
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --BEWAR
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --VORGN
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --FDLEV
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --FDGRP
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --FDTAG
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --KOKRS
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --TXGRP
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --KOSTL
		SET @LinhaTXT = @LinhaTXT + '120490106101' --AUFNR
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --VBELN
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --VBEL2
		SET @LinhaTXT = @LinhaTXT + SPACE(6) --POSN2
		SET @LinhaTXT = @LinhaTXT + SPACE(12) --ANLN1
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --ANLN2 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --ANBWA 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --BZDAT 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --PERNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --XUMSW 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --XSKRL 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --XAUTO 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --SAKNR
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --HKONT 
		SET @LinhaTXT = @LinhaTXT + SPACE(6) --ABPER 
		SET @LinhaTXT = @LinhaTXT + SPACE(18) --MATNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --WERKS 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --MENGE 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --MEINS 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --ERFMG 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --ERFME 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --BPMNG 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --BPRME 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --EBELN 
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --EBELP 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --ZEKKN 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --BWKEY 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --BWTAR 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --BUSTW 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --BUALT 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --TBTKZ 
		SET @LinhaTXT = @LinhaTXT + @CodPaisCliente + @NIFCliente + SPACE(20 - LEN(@CodPaisCliente + @NIFCliente)) --STCEG		
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --RSTGR 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --PRCTR 
		SET @LinhaTXT = @LinhaTXT + SPACE(6) --VNAME 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --RECID 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --EGRUP 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --VPTNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --VERTT 
		SET @LinhaTXT = @LinhaTXT + SPACE(13) --VERTN 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --VBEWA 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --TAXJURCODE 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --IMKEY 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --DABRZ 
		SET @LinhaTXT = @LinhaTXT + SPACE(14) --FIPOS 
		SET @LinhaTXT = @LinhaTXT + SPACE(12) --KSTRG 
		SET @LinhaTXT = @LinhaTXT + SPACE(12) --NPLNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --AUFPL 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --APLZL 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --PROJK 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --PAOBJNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --BTYPE 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --ETYPE 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --XEGDR 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --HRKFT 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --LOKKT 
		SET @LinhaTXT = @LinhaTXT + SPACE(16) --FISTL 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --GEBER 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --STBUK 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --ALTKT 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --PPRCT 
		SET @LinhaTXT = @LinhaTXT + SPACE(12) --XREF1 
		SET @LinhaTXT = @LinhaTXT + SPACE(12) --XREF2 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --KBLNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --KBLPOS 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --FKBER 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --OBZEI 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --XNEGP 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --CACCT 
		SET @LinhaTXT = @LinhaTXT + SPACE(20) --XREF3 
		SET @LinhaTXT = @LinhaTXT + SPACE(6) --DOKTP 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --DWART 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --HERLD 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --VERART 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --EUTXGOAL 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --EUTXSEAC 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --EUTXCONF 
-- escreve a linha do tipo "Item document" (POSITION) na tabela tmp
		INSERT INTO @TblTmpLinhas(numDocumento, tipoLinha, nomeLinha, ordem, textoLinha)
		VALUES(@NumDocsExportados, 3, 'POSITION', 1, @LinhaTXT)
-- constroi a linha do tipo "Item Supplement" (POSITIONZUSATZ)
		SET @LinhaTXT = '03' --SATZART
		SET @LinhaTXT = @LinhaTXT + @NumDocsExportadosSTR --SATZNR
		SET @LinhaTXT = @LinhaTXT + '000003' --SEGNR
		SET @LinhaTXT = @LinhaTXT + '000002' --PSEGNR
		SET @LinhaTXT = @LinhaTXT + 'POSITIONZUSATZ' + SPACE(16) --SEGTYP
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --UMSKZ
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --MWSTS
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --WMWST
		SET @LinhaTXT = @LinhaTXT + LEFT(@CodigoEANCliente, 10) + SPACE(10 - LEN(LEFT(@CodigoEANCliente, 10))) --KUNNR
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --FILKD
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataVencimento, 112) --ZFBDT
		SET @LinhaTXT = @LinhaTXT + 'ZB' + REPLACE(STR(@DiasAPagamentoCliente, 2), ' ', '0') + SPACE(4 - LEN('ZB' + REPLACE(STR(@DiasAPagamentoCliente, 2), ' ', '0'))) --ZTERM		
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --ZBD1T 
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --ZBD2T 
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --ZBD3T 
		SET @LinhaTXT = @LinhaTXT + SPACE(7) --ZBD1P 
		SET @LinhaTXT = @LinhaTXT + SPACE(7) --ZBD2P 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --SKFBT 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --SKNTO 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --WSKTO 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --ZLSCH 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --ZLSPR 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --UZAWE 
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --HBKID 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --BVTYP 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --REBZG 
		SET @LinhaTXT = @LinhaTXT + SPACE(4) --REBZJ 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --REBZZ 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --REBZT 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --LZBKZ 
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --LANDL 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --DIEKZ 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --VRSKZ 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --VRSDT 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --MSCHL 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --MANSP 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --MABER 
		SET @LinhaTXT = @LinhaTXT + SPACE(8) --MADAT 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --MANST 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --QSSKZ 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --QSSHB 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --QSFBT 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --LIFNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(11) --ESRNR 
		SET @LinhaTXT = @LinhaTXT + SPACE(27) --ESRRE 
		SET @LinhaTXT = @LinhaTXT + SPACE(2) --ESRPZ 
		SET @LinhaTXT = @LinhaTXT + SPACE(1) --ZBFIX 
		SET @LinhaTXT = @LinhaTXT + SPACE(30) --KIDNO 
		SET @LinhaTXT = @LinhaTXT + SPACE(10) --EMPFB 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --SKNT2 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --SKNT3 
		SET @LinhaTXT = @LinhaTXT + SPACE(5) --PYCUR 
		SET @LinhaTXT = @LinhaTXT + SPACE(15) --PYAMT 
		SET @LinhaTXT = @LinhaTXT + SPACE(35) --MNDID 
		SET @LinhaTXT = @LinhaTXT + SPACE(462) --QRIBAN 
-- escreve a linha do tipo "Item Supplement" (POSITIONZUSATZ) na tabela tmp
		INSERT INTO @TblTmpLinhas(numDocumento, tipoLinha, nomeLinha, ordem, textoLinha)
		VALUES(@NumDocsExportados, 3, 'POSITIONZUSATZ', 2, @LinhaTXT)
-- obtem as linhas do tipo "Tax data" (STEUERDATEN)
		DECLARE ResumoIVA CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT t.IVA_TIPO, t.IVA_BASE, t.IVA_VALO
			FROM (SELECT 1 AS IVA_ORDE, 'RM' AS IVA_TIPO, @TotalInerentesIsentas AS IVA_BASE, 0.00 AS IVA_VALO
				UNION ALL
				SELECT 2 AS IVA_ORDE, (CASE @CodPaisCliente WHEN 'PT' THEN 'RO' ELSE 'RD' END) AS IVA_TIPO, @TotalDocumentadasDocumento AS IVA_BASE, 0.00 AS IVA_VALO
				UNION ALL				
				SELECT 3 AS IVA_ORDE, 'RQ' AS IVA_TIPO, @TotalBaseIVADocumento AS IVA_BASE, @TotalIVADocumento AS IVA_VALO
			) AS t
			WHERE t.IVA_BASE > 0			
			ORDER BY t.IVA_ORDE
		OPEN ResumoIVA
		FETCH NEXT FROM ResumoIVA INTO @TipoIVA, @BaseIVA, @ValorIVA
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- incrementa variável
			SET @NumLinhaIVA = @NumLinhaIVA + 1			
-- constroi a linha do tipo "Tax data" (STEUERDATEN)
			SET @LinhaTXT = '03' --SATZART
			SET @LinhaTXT = @LinhaTXT + @NumDocsExportadosSTR --SATZNR
			SET @LinhaTXT = @LinhaTXT + REPLACE(STR(@NumLinhaIVA, 6), ' ', '0') --SEGNR
			SET @LinhaTXT = @LinhaTXT + REPLACE(STR((@NumLinhaIVA - 1), 6), ' ', '0') --PSEGNR
			SET @LinhaTXT = @LinhaTXT + 'STEUERDATEN' + SPACE(19) --SEGTYP
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --BUZEI
			SET @LinhaTXT = @LinhaTXT + @TipoIVA --MWSKZ 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --HKONT
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --TXGRP
			SET @LinhaTXT = @LinhaTXT + (CASE @TipoSAFT WHEN 'NC' THEN 'S' ELSE 'H' END) --SHKZG 
			SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@BaseIVA, 17, 2), ' ', '0'), '.', '')) --HWBAS
			SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@BaseIVA, 17, 2), ' ', '0'), '.', '')) --FWBAS
			SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@ValorIVA, 15, 2), ' ', '0'), '.', '')) --HWSTE
			SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@ValorIVA, 15, 2), ' ', '0'), '.', '')) --FWSTE		
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --KTOSL
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --KNUMH 
			SET @LinhaTXT = @LinhaTXT + SPACE(20) --STCEG 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --EGBLD 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --EGLLD 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --TAXJURCODE 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --H2STE 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --H3STE 
			SET @LinhaTXT = @LinhaTXT + SPACE(17) --H2BAS 
			SET @LinhaTXT = @LinhaTXT + SPACE(17) --H3BAS 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --KSCHL 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --STMDT 
			SET @LinhaTXT = @LinhaTXT + SPACE(6) --STMTI 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --MLDDT 
			SET @LinhaTXT = @LinhaTXT + SPACE(13) --KBETR 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --STBKZ 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --LSTML 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --LWSTE 
			SET @LinhaTXT = @LinhaTXT + SPACE(17) --LWBAS 
-- escreve a linha do tipo "Tax data" (STEUERDATEN) na tabela tmp
			INSERT INTO @TblTmpLinhas(numDocumento, tipoLinha, nomeLinha, ordem, textoLinha)
			VALUES(@NumDocsExportados, 3, 'STEUERDATEN', 4, @LinhaTXT)
			FETCH NEXT FROM ResumoIVA INTO @TipoIVA, @BaseIVA, @ValorIVA
		END
		CLOSE ResumoIVA
		DEALLOCATE ResumoIVA
-- obtem as linhas do tipo "Item document" (POSITION)
		DECLARE ResumoIVA CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT t.IVA_TIPO, t.IVA_BASE, t.IVA_VALO
			FROM (SELECT 1 AS IVA_ORDE, 'RM' AS IVA_TIPO, @TotalInerentesIsentas AS IVA_BASE, 0.00 AS IVA_VALO
				UNION ALL
				SELECT 2 AS IVA_ORDE, (CASE @CodPaisCliente WHEN 'PT' THEN 'RO' ELSE 'RD' END) AS IVA_TIPO, @TotalDocumentadasDocumento AS IVA_BASE, 0.00 AS IVA_VALO
				UNION ALL				
				SELECT 3 AS IVA_ORDE, 'RQ' AS IVA_TIPO, @TotalBaseIVADocumento AS IVA_BASE, @TotalIVADocumento AS IVA_VALO
			) AS t
			WHERE t.IVA_BASE > 0			
			ORDER BY t.IVA_ORDE
		OPEN ResumoIVA
		FETCH NEXT FROM ResumoIVA INTO @TipoIVA, @BaseIVA, @ValorIVA
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- incrementa variável 
			SET @NumLinhaIVA = @NumLinhaIVA + 1							
-- constroi a linha do tipo "Item document" (POSITION)
			SET @LinhaTXT = '03' --SATZART
			SET @LinhaTXT = @LinhaTXT + @NumDocsExportadosSTR --SATZNR
			SET @LinhaTXT = @LinhaTXT + REPLACE(STR(@NumLinhaIVA, 6), ' ', '0') --SEGNR
			SET @LinhaTXT = @LinhaTXT + REPLACE(STR((@NumLinhaIVA - 1), 6), ' ', '0') --PSEGNR			
			SET @LinhaTXT = @LinhaTXT + 'POSITION' + SPACE(22) --SEGTYP
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --BUZEI
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --BUZID
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --AUGDT
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --AUGCP
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --AUGBL
			SET @LinhaTXT = @LinhaTXT + (CASE @TipoSAFT WHEN 'NC' THEN '40' ELSE '50' END) --BSCHL
			SET @LinhaTXT = @LinhaTXT + 'S' --KOART
			SET @LinhaTXT = @LinhaTXT + (CASE @TipoSAFT WHEN 'NC' THEN 'D' ELSE 'H' END) --SHKZG
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --GSBER
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --PARGB
			SET @LinhaTXT = @LinhaTXT + @TipoIVA --MWSKZ		
			SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@BaseIVA, 15, 2), ' ', '0'), '.', '')) --DMBTR
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --DMBE2
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --DMBE3
			SET @LinhaTXT = @LinhaTXT + ('0' + REPLACE(REPLACE(STR(@BaseIVA, 15, 2), ' ', '0'), '.', '')) --WRBTR
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --KZBTR 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --PSWBT
			SET @LinhaTXT = @LinhaTXT + SPACE(5) --PSWSL
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --HWBAS
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --FWBAS
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --MWART
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --KTOSL
			SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataDocumento, 112) --VALUT
			SET @LinhaTXT = @LinhaTXT + (CASE WHEN @NumProcessoGlobal IS NULL THEN LTRIM(STR(@NumDocumento, 18)) + SPACE(18 - LEN(LTRIM(STR(@NumDocumento, 18)))) ELSE LTRIM(STR(@NumProcessoGlobal, 18)) + SPACE(18 - LEN(LTRIM(STR(@NumProcessoGlobal, 18)))) END) --ZUONR		
			SET @LinhaTXT = @LinhaTXT + LEFT((ISNULL(@CodNatureza + '_', '') + ISNULL(@CodAlfandega + '_' , '') + @SerieDocumento + '/' + LTRIM(STR(@NumDocumento, 10))), 50) + SPACE(50 - LEN(LEFT((ISNULL(@CodNatureza + '_', '') + ISNULL(@CodAlfandega + '_' , '') + @SerieDocumento + '/' + LTRIM(STR(@NumDocumento, 10))), 50))) --SGTXT
			SET @LinhaTXT = @LinhaTXT + SPACE(6) --VBUND
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --BEWAR
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --VORGN
			SET @LinhaTXT = @LinhaTXT + SPACE(2) --FDLEV
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --FDGRP
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --FDTAG
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --KOKRS
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --TXGRP
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --KOSTL
			SET @LinhaTXT = @LinhaTXT + '120490106101' --AUFNR
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --VBELN
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --VBEL2
			SET @LinhaTXT = @LinhaTXT + SPACE(6) --POSN2
			SET @LinhaTXT = @LinhaTXT + SPACE(12) --ANLN1
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --ANLN2 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --ANBWA 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --BZDAT 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --PERNR 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --XUMSW 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --XSKRL 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --XAUTO 
			SET @LinhaTXT = @LinhaTXT + (CASE WHEN @TipoIVA IN ('RO', 'RD') THEN '129965' ELSE '801000' END) + SPACE(4) --SAKNR
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --HKONT 
			SET @LinhaTXT = @LinhaTXT + SPACE(6) --ABPER 
			SET @LinhaTXT = @LinhaTXT + SPACE(18) --MATNR 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --WERKS 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --MENGE 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --MEINS 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --ERFMG 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --ERFME 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --BPMNG 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --BPRME 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --EBELN 
			SET @LinhaTXT = @LinhaTXT + SPACE(5) --EBELP 
			SET @LinhaTXT = @LinhaTXT + SPACE(2) --ZEKKN 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --BWKEY 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --BWTAR 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --BUSTW 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --BUALT 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --TBTKZ 
			SET @LinhaTXT = @LinhaTXT + @CodPaisCliente + @NIFCliente + SPACE(20 - LEN(@CodPaisCliente + @NIFCliente)) --STCEG		
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --RSTGR 			
			SET @LinhaTXT = @LinhaTXT + (CASE WHEN @TipoIVA IN ('RO', 'RD') THEN '2049019900' ELSE SPACE(10) END) --PRCTR
			SET @LinhaTXT = @LinhaTXT + SPACE(6) --VNAME 
			SET @LinhaTXT = @LinhaTXT + SPACE(2) --RECID 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --EGRUP 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --VPTNR 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --VERTT 
			SET @LinhaTXT = @LinhaTXT + SPACE(13) --VERTN 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --VBEWA 
			SET @LinhaTXT = @LinhaTXT + SPACE(15) --TAXJURCODE 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --IMKEY 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --DABRZ 
			SET @LinhaTXT = @LinhaTXT + SPACE(14) --FIPOS 
			SET @LinhaTXT = @LinhaTXT + SPACE(12) --KSTRG 
			SET @LinhaTXT = @LinhaTXT + SPACE(12) --NPLNR 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --AUFPL 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --APLZL 
			SET @LinhaTXT = @LinhaTXT + SPACE(8) --PROJK 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --PAOBJNR 
			SET @LinhaTXT = @LinhaTXT + SPACE(2) --BTYPE 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --ETYPE 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --XEGDR 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --HRKFT 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --LOKKT 
			SET @LinhaTXT = @LinhaTXT + SPACE(16) --FISTL 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --GEBER 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --STBUK 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --ALTKT 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --PPRCT 
			SET @LinhaTXT = @LinhaTXT + SPACE(12) --XREF1 
			SET @LinhaTXT = @LinhaTXT + SPACE(12) --XREF2 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --KBLNR 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --KBLPOS 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --FKBER 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --OBZEI 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --XNEGP 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --CACCT 
			SET @LinhaTXT = @LinhaTXT + SPACE(20) --XREF3 
			SET @LinhaTXT = @LinhaTXT + SPACE(6) --DOKTP 
			SET @LinhaTXT = @LinhaTXT + SPACE(2) --DWART 
			SET @LinhaTXT = @LinhaTXT + SPACE(3) --HERLD 
			SET @LinhaTXT = @LinhaTXT + SPACE(10) --VERART 
			SET @LinhaTXT = @LinhaTXT + SPACE(2) --EUTXGOAL 
			SET @LinhaTXT = @LinhaTXT + SPACE(4) --EUTXSEAC 
			SET @LinhaTXT = @LinhaTXT + SPACE(1) --EUTXCONF 
-- escreve a linha do tipo "Item document" (POSITION) na tabela tmp
			INSERT INTO @TblTmpLinhas(numDocumento, tipoLinha, nomeLinha, ordem, textoLinha)
			VALUES(@NumDocsExportados, 3, 'POSITION', 3, @LinhaTXT)
-- incrementa variável novamente 			
			SET @NumLinhaIVA = @NumLinhaIVA + 1													
			FETCH NEXT FROM ResumoIVA INTO @TipoIVA, @BaseIVA, @ValorIVA
		END
		CLOSE ResumoIVA
		DEALLOCATE ResumoIVA
		FETCH NEXT FROM Docs INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumDocumento, @DataDocumento, @CodNatureza, @CodAlfandega, @TotalDocumentadasDocumento, @TotalBaseIVADocumento, 
			@TotalIVADocumento, @TotalDocumento, @NIFCliente, @CodPaisCliente, @CodigoEANCliente, @DiasAPagamentoCliente, @SerieDocumento, @CtxTipoDoc, @TipoSAFT, @DataVencimento, @NumProcessoGlobal, 
			@TotalInerentesIsentas
	END
	CLOSE Docs
	DEALLOCATE Docs
-- obtem o total de linhas geradas
	SELECT @TotalLinhasGeradas = COUNT(*)
	FROM @TblTmpLinhas 
-- gera ficheiro apenas se existirem linhas apuradas
	IF @TotalLinhasGeradas > 0
	BEGIN
-- constroi a linha do tipo "Info record"
		SET @LinhaTXT = '01' --SATZART
		SET @LinhaTXT = @LinhaTXT + 'GIDWIN' + SPACE(2) --ERSTELLSYSTEM
		SET @LinhaTXT = @LinhaTXT + SPACE(32) --ERSTELLHOST
		SET @LinhaTXT = @LinhaTXT + SPACE(3) --ERSTELLMANDANT
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(8), @DataAtual, 112) --ERSTELLDATUM
		SET @LinhaTXT = @LinhaTXT + REPLACE(CONVERT(varchar(8), @DataAtual, 108), ':', '') --ERSTELLUHRZEIT
		SET @LinhaTXT = @LinhaTXT + SPACE(12) --ERSTELLER ?PL? O ficheiro tem este elemento preenchido
		SET @LinhaTXT = @LinhaTXT + REPLACE(STR(CAST(ROUND(CAST(@DataAtual AS decimal(18, 8)) + 2415020.5, 0) AS int), 12, 0), ' ', '0') --SEQUENZ_NR
		SET @LinhaTXT = @LinhaTXT + REPLACE(STR(@TotalLinhasGeradas + 1, 12, 0), ' ', '0') --ANZ_ZEILEN
-- escreve a linha do tipo "Info record" na tabela tmp
		INSERT INTO @TblTmpLinhas(numDocumento, tipoLinha, nomeLinha, ordem, textoLinha)
		VALUES(0, 1, '', 0, @LinhaTXT)
-- constroi o full path para o ficheiro SAP
		SET @PathFicheiroSAP = @DirGeracaoFicheiro + ISNULL(@PrefixoNomeFicheiro, '') + CONVERT(varchar(8), @DataAtual, 112) + REPLACE(CONVERT(varchar(8), @DataAtual, 108), ':', '') + '_GIDWIN.dat'	
-- cria ficheiro no path definido
		EXEC sp_OACreate 'Scripting.FileSystemObject', @FileSystemObj OUTPUT		
		EXEC sp_OAMethod @FileSystemObj, 'CreateTextFile', @TextFileObj OUT, @PathFicheiroSAP, 2, True
-- obtem todas as linhas inseridas na tabela tmp
		DECLARE Linhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT textoLinha
			FROM @TblTmpLinhas
			ORDER BY numDocumento, tipoLinha, ordem, id
		OPEN Linhas
		FETCH NEXT FROM Linhas INTO @LinhaTXT
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- escreve a linha no ficheiro		
			EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXT
			FETCH NEXT FROM Linhas INTO @LinhaTXT
		END
		CLOSE Linhas
		DEALLOCATE Linhas
-- fecha o ficheiro criado
		EXEC sp_OAMethod @FileSystemObj, 'Close', Null, Null
-- destroi os objetos 			
		EXEC sp_OADestroy @TextFileObj	
		EXEC sp_OADestroy @FileSystemObj
	END
END

ALTER AUTHORIZATION ON [SP_Facturacao_ExportaFicheiroSAPALS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_ExportaFicheiroSAPALS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Facturacao_ExportaFicheiroSAPDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_Facturacao_ExportaFicheiroSAPDHL] @DataReferencia datetime, @PrefixoNomeFicheiro nvarchar(50), @DirGeracaoFicheiro nvarchar(500) AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @DataAtual datetime, @PathFicheiroSAP nvarchar(4000), @FileSystemObj int, @TextFileObj int, @LinhaTXT varchar(1000)
	DECLARE @AnoDocumento int, @CodTipoDocumento varchar(4), @IdDocumento int, @NumDocumento int, @DataDocumento datetime, @TxIVADocumento numeric(38, 6), 
		@TotalIVA numeric(38, 6), @TotalLiquido numeric(38, 6), @AWBDocumento varchar(18), @NomeClienteCCDocumento varchar(70), @MoradaClienteCCDocumento varchar(70), 
		@CodPostalClienteCCDocumento varchar(12), @LocPostalClienteCCDocumento varchar(35), @CodigoEAN varchar(13), @CodMotivoIsencaoIVADocumento varchar(3), 
		@SerieDocumento varchar(20), @DataVencimento datetime, @TipoInvoice varchar(10), @OrigemProcesso varchar(100), @DestinoProcesso varchar(3), @NumDocumentoCreditado int, 
		@SerieDocumentoCreditado varchar(20)
	DECLARE @TipoLinha varchar(4), @ValorLinha numeric(38, 6), @CodChargeCodeLinha varchar(4), @CodMotivoIsencaoIVALinha varchar(3), @IVALinha numeric(38, 6), 
		@LocalProductCodeLinha varchar(1)
	DECLARE @LinhaTXTChargeCode varchar(1000), @CodChargeCode1 varchar(4), @CodChargeCode2 varchar(4), @CodChargeCode3 varchar(4), @ValorChargeCode numeric(38, 6), 
		@IVAChargeCode numeric(38, 6), @ValorRestanteChargeCode numeric(38, 6), @IVARestanteChargeCode numeric(38, 6)
-- verifica se existem documentos de Contas ou de Vendas que cumprem os requisitos na data especificada, pois senão existirem não gera ficheiro
	IF NOT EXISTS(SELECT 1 FROM FAC_CDOC AS dco WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dco.CDO_TDOC = tdo.TDO_DOCU WHERE dco.CDO_CNUM IS NOT NULL AND dco.CDO_ANUL = 0 AND dco.CDO_IMPR = 1 AND tdo.TDO_DCON = 1 AND tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'FT' AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime))
	AND NOT EXISTS(SELECT 1 FROM FAC_DVEN AS dve WITH(NOLOCK) INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dve.CLI_CODI = cli.CLI_CODI WHERE dve.DVE_ANUL = 0 AND tdo.TDO_DCON = 1 AND tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF IN ('FT', 'NC') AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime))
		RETURN
-- verifica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirGeracaoFicheiro), 1, 1) <> '\'
		SET @DirGeracaoFicheiro = @DirGeracaoFicheiro + '\'
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi o full path para o ficheiro SAP
	SET @PathFicheiroSAP = @DirGeracaoFicheiro + ISNULL((@PrefixoNomeFicheiro + '_'), '') + CONVERT(varchar(8), @DataAtual, 112) + '_' + REPLACE(CONVERT(varchar(8), @DataAtual, 108), ':', '') + '.txt'	
-- cria ficheiro no path definido
	EXEC sp_OACreate 'Scripting.FileSystemObject', @FileSystemObj OUTPUT		
	EXEC sp_OAMethod @FileSystemObj, 'CreateTextFile', @TextFileObj OUT, @PathFicheiroSAP, 2, True
-- obtem os documentos de Contas emitidos, não anulados e do tipo SAFT "FT" para a data	
	DECLARE DocsConta CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_IDEN, dco.CDO_CNUM, dco.CDO_DTEM, ISNULL(LTRIM(RTRIM(dco.CDO_CPRT)), '9999999999'), 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(ISNULL(dco.CDO_CNOM, ''), CHAR(9), ' '), '|', ' ')))), 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(ISNULL(dco.CDO_CMOR, ''), CHAR(9), ' '), '|', ' ')))), 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(ISNULL(dco.CDO_CCPO, ''), CHAR(9), ' '), '|', ' ')))), 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(ISNULL(dco.CDO_CLPO, ''), CHAR(9), ' '), '|', ' ')))), 
			ISNULL(dco.CDO_CEAN, ''), NULLIF(dco.IIV_CODI, ''), ISNULL(dco.CDO_SERI, ''), DATEADD(DAY, ISNULL(dco.CDO_CPAG, 0), dco.CDO_DTEM), 
			ISNULL(dco.CDO_IVA, 0), ISNULL(CDO_TXIV, 0), (ISNULL(dco.CDO_TTDC, 0) + ISNULL(dco.CDO_TTIN, 0) + ISNULL(dco.CDO_TTHO, 0)), 'INV-STD', 
			(CASE RIGHT(dco.ALF_CODI, 3)
				WHEN '020' THEN 'OPO'
				ELSE 'LIS'
			END), 
			(CASE dco.CDO_IMEX 
				WHEN 0 THEN (CASE 
								WHEN dco.id_declaracaoDAR IS NULL THEN ISNULL(NULLIF(duc.DUC_FUPS, ''), ISNULL(duc.DUC_AERO, '')) 
								ELSE ISNULL(NULLIF(dar.nomeFicheiroUPS, ''), ISNULL(dar.aeroportoOrigem, ''))
							END) 
				ELSE ISNULL(exm.PAE_CODI, '')
			END)
		FROM FAC_CDOC AS dco WITH(NOLOCK) 
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dco.CDO_TDOC = tdo.TDO_DOCU 
			LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dco.CDO_NPRO = duc.DUC_PNUM AND dco.CDO_PANO = duc.DUC_EANO AND dco.CDO_IMEX = 0 AND dco.id_declaracaoDAR IS NULL
			LEFT OUTER JOIN PRO_EXML AS exm WITH(NOLOCK) ON dco.CDO_NPRO = exm.EXM_NRII AND dco.CDO_PANO = exm.EXM_EANO AND dco.EXM_OPER = exm.DEC_CODI AND dco.CDO_IMEX = 1 AND dco.id_declaracaoDAR IS NULL
			LEFT OUTER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON dco.id_declaracaoDAR = dar.id
		WHERE dco.CDO_TDOC NOT IN ('CDAS', 'CEXB', 'TDAS', 'TEXB') AND dco.CDO_CNUM IS NOT NULL AND dco.CDO_ANUL = 0 AND dco.CDO_IMPR = 1 AND tdo.TDO_DCON = 1 
			AND tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF = 'FT' 
			AND CAST(CONVERT(varchar(10), dco.CDO_DTEM, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
		ORDER BY dco.CDO_EANO, dco.CDO_TDOC, dco.CDO_CNUM			
	OPEN DocsConta
	FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumDocumento, @DataDocumento, @AWBDocumento, @NomeClienteCCDocumento, 
		@MoradaClienteCCDocumento, @CodPostalClienteCCDocumento, @LocPostalClienteCCDocumento, @CodigoEAN, @CodMotivoIsencaoIVADocumento, @SerieDocumento, @DataVencimento, 
		@TotalIVA, @TxIVADocumento, @TotalLiquido, @TipoInvoice, @DestinoProcesso, @OrigemProcesso
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- constroi a linha do tipo "invoice header"
		SET @LinhaTXT = 'HPT|'
		SET @LinhaTXT = @LinhaTXT + @SerieDocumento + CAST(@NumDocumento AS varchar(10)) + '|'
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataDocumento, 105) + '|'
		SET @LinhaTXT = @LinhaTXT + @TipoInvoice + '|'
		SET @LinhaTXT = @LinhaTXT + @CodigoEAN + '|'
		SET @LinhaTXT = @LinhaTXT + '||||EUR|1|||||'
		SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@TotalLiquido, 18, 2)) + '|'
		SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@TotalIVA, 18, 2)) + '|'
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataVencimento, 105) + '|'
		SET @LinhaTXT = @LinhaTXT + '||||||||||'	
		SET @LinhaTXT = @LinhaTXT + @SerieDocumento + CAST(@NumDocumento AS varchar(10)) + '|'		
-- escreve a linha do tipo "invoice header" no ficheiro		
		EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXT
-- obtem as despesas documentadas e despesas inerentes do documento de Conta 
		DECLARE Despesas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT t.DCD_TIPO, SUM(t.DCD_VTOT), t.CCO_CODI, t.IIV_CODI, SUM(t.DCD_VIVA), (CASE LEFT(t.CCO_CODI, 1) WHEN 'W' THEN 'P' ELSE 'Z' END)
			FROM (SELECT 'DUTY' AS DCD_TIPO, DCD_LINH, ISNULL(DCD_VTOT, 0) AS DCD_VTOT, LEFT(ISNULL(CCO_CODI, ''), 2) AS CCO_CODI, 'M01' AS IIV_CODI, 
					0.00 AS DCD_VIVA					 
				FROM FAC_DCDO WITH(NOLOCK) 				
				WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND ISNULL(DCD_VTOT, 0) <> 0
				UNION ALL
				SELECT 'SCS', ICD_LINH, ISNULL(ICD_VTOT, 0), LEFT(ISNULL(CCO_CODI, ''), 2), ISNULL(NULLIF(IIV_CODI, ''), ISNULL(@CodMotivoIsencaoIVADocumento, 'NOR')), 
					(CASE ICD_ISEN WHEN 1 THEN 0.00 ELSE ROUND(ISNULL(ICD_VTOT, 0) * @TxIVADocumento / 100, 2) END)					
				FROM FAC_ICDO WITH(NOLOCK) 
				WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND ISNULL(ICD_VTOT, 0) <> 0
				UNION ALL
				SELECT 'SCS' AS DCD_TIPO, 999999999, ISNULL(CDO_TTHO, 0), LEFT(ISNULL(CCO_CODI, ''), 2), ISNULL(@CodMotivoIsencaoIVADocumento, 'NOR'), 
					ROUND(ISNULL(CDO_TTHO, 0) * @TxIVADocumento / 100, 2)
				FROM FAC_CDOC WITH(NOLOCK) 				
				WHERE CDO_EANO = @AnoDocumento AND CDO_TDOC = @CodTipoDocumento AND CDO_IDEN = @IdDocumento AND ISNULL(CDO_TTHO, 0) <> 0
			) AS t
			GROUP BY t.DCD_TIPO, t.CCO_CODI, t.IIV_CODI
			ORDER BY t.DCD_TIPO, t.CCO_CODI
		OPEN Despesas
		FETCH NEXT FROM Despesas INTO @TipoLinha, @ValorLinha, @CodChargeCodeLinha, @CodMotivoIsencaoIVALinha, @IVALinha, @LocalProductCodeLinha
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- constroi a linha do tipo "invoice line"
			SET @LinhaTXT = 'IPT|'
			SET @LinhaTXT = @LinhaTXT + @SerieDocumento + CAST(@NumDocumento AS varchar(10)) + '|'
			SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataDocumento, 105) + '|'
			SET @LinhaTXT = @LinhaTXT + @TipoInvoice + '|'
			SET @LinhaTXT = @LinhaTXT + @CodigoEAN + '|'
			SET @LinhaTXT = @LinhaTXT + @AWBDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + @OrigemProcesso + '|'
			SET @LinhaTXT = @LinhaTXT + @DestinoProcesso + '|'
			SET @LinhaTXT = @LinhaTXT + '|EUR|1|'
			SET @LinhaTXT = @LinhaTXT + @CodMotivoIsencaoIVALinha + '|'
			SET @LinhaTXT = @LinhaTXT + '|'
			SET @LinhaTXT = @LinhaTXT + @TipoLinha + '|'
			SET @LinhaTXT = @LinhaTXT + @LocalProductCodeLinha + '|'
-- para o charge code "WB" não coloca respetivos valores de despesa nem IVA
			IF @CodChargeCodeLinha = 'WB'
			BEGIN				
				SET @LinhaTXT = @LinhaTXT + '[@ValorLinha]|'
				SET @LinhaTXT = @LinhaTXT + '[@IVALinha]|'
			END
			ELSE
			BEGIN				
				SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@ValorLinha, 18, 2)) + '|'
				SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@IVALinha, 18, 2)) + '|'
			END
			SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataVencimento, 105) + '|'
			SET @LinhaTXT = @LinhaTXT + @NomeClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + @MoradaClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + '|||'
			SET @LinhaTXT = @LinhaTXT + @CodPostalClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + @LocPostalClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + '||'
-- para o charge code "WB" não coloca o código
			IF @CodChargeCodeLinha = 'WB'
				SET @LinhaTXT = @LinhaTXT + '[@CodChargeCodeLinha]|'	
			ELSE
				SET @LinhaTXT = @LinhaTXT + @CodChargeCodeLinha + '|'
			SET @LinhaTXT = @LinhaTXT + '|'
-- escreve a linha do tipo "invoice line" no ficheiro quando o charge code não é "WB" 
			IF @CodChargeCodeLinha <> 'WB'							
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXT
			ELSE
			BEGIN				
-- obtem os charge codes extra conforme o EAN
				SET @CodChargeCode1 = @CodChargeCodeLinha
				SET @CodChargeCode2 = 'WD'
				IF @CodigoEAN = 'DUTYPTCSH'						
					SET @CodChargeCode3 = 'WW'											
				ELSE								
					SET @CodChargeCode3 = 'WC'																	
-- inicia valores restantes
				SET @ValorRestanteChargeCode = @ValorLinha
				SET @IVARestanteChargeCode = @IVALinha
-- processa calculos para o charge code n.º 1 "WB" conforme valor superior a 30
				IF @ValorLinha > 30				
					SET @ValorChargeCode = 10									
				ELSE				
					SET @ValorChargeCode = ROUND(@ValorLinha * 49 / 100, 2)
				SET @IVAChargeCode = ROUND(@ValorChargeCode * @TxIVADocumento / 100, 2)
-- atualiza valores restantes
				SET @ValorRestanteChargeCode = @ValorRestanteChargeCode - @ValorChargeCode
				SET @IVARestanteChargeCode = @IVARestanteChargeCode - @IVAChargeCode
-- constroi a linha do tipo "invoice line" para o charge code n.º 1 "WB"
				SET @LinhaTXTChargeCode = @LinhaTXT
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@ValorLinha]', LTRIM(STR(@ValorChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@IVALinha]', LTRIM(STR(@IVAChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@CodChargeCodeLinha]', @CodChargeCode1)
-- escreve a linha do tipo "invoice line" do charge code n.º 1 "WB" no ficheiro
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXTChargeCode
-- processa calculos para o charge code n.º 2 "WD" conforme valor superior a 30
				IF @ValorLinha > 30
					SET @ValorChargeCode = 10									
				ELSE
					SET @ValorChargeCode = ROUND(@ValorLinha * 49 / 100, 2)
				SET @IVAChargeCode = ROUND(@ValorChargeCode * @TxIVADocumento / 100, 2)
-- atualiza valores restantes
				SET @ValorRestanteChargeCode = @ValorRestanteChargeCode - @ValorChargeCode
				SET @IVARestanteChargeCode = @IVARestanteChargeCode - @IVAChargeCode
-- constroi a linha do tipo "invoice line" para o charge code n.º 2 "WD"
				SET @LinhaTXTChargeCode = @LinhaTXT
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@ValorLinha]', LTRIM(STR(@ValorChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@IVALinha]', LTRIM(STR(@IVAChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@CodChargeCodeLinha]', @CodChargeCode2)
-- escreve a linha do tipo "invoice line" do charge code n.º 2 "WD" no ficheiro	
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXTChargeCode
-- processa calculos para o charge code n.º 3 "WW" ou "WC" conforme valor superior a 30
				IF @ValorLinha > 30
				BEGIN
					SET @ValorChargeCode = @ValorLinha - 20									
					SET @IVAChargeCode = ROUND(@ValorChargeCode * @TxIVADocumento / 100, 2)
				END
				ELSE
				BEGIN
					SET @ValorChargeCode = @ValorRestanteChargeCode			
					SET @IVAChargeCode = @IVARestanteChargeCode
				END
-- constroi a linha do tipo "invoice line" para o charge code n.º 3 "WW" ou "WC"
				SET @LinhaTXTChargeCode = @LinhaTXT
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@ValorLinha]', LTRIM(STR(@ValorChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@IVALinha]', LTRIM(STR(@IVAChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@CodChargeCodeLinha]', @CodChargeCode3)
-- escreve a linha do tipo "invoice line" do charge code n.º 3 "WW" ou "WC" no ficheiro
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXTChargeCode							
			END							
			FETCH NEXT FROM Despesas INTO @TipoLinha, @ValorLinha, @CodChargeCodeLinha, @CodMotivoIsencaoIVALinha, @IVALinha, @LocalProductCodeLinha
		END
		CLOSE Despesas
		DEALLOCATE Despesas
		FETCH NEXT FROM DocsConta INTO @AnoDocumento, @CodTipoDocumento, @IdDocumento, @NumDocumento, @DataDocumento, @AWBDocumento, @NomeClienteCCDocumento, 
			@MoradaClienteCCDocumento, @CodPostalClienteCCDocumento, @LocPostalClienteCCDocumento, @CodigoEAN, @CodMotivoIsencaoIVADocumento, @SerieDocumento, @DataVencimento, 
			@TotalIVA, @TxIVADocumento, @TotalLiquido, @TipoInvoice, @DestinoProcesso, @OrigemProcesso
	END
	CLOSE DocsConta
	DEALLOCATE DocsConta
-- obtem os documentos de Vendas emitidos, não anulados e do tipo SAFT "FT"/"NC" para a data	
	DECLARE DocsVenda CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_DATA, 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(dve.DVE_CNOM, CHAR(9), ' '), '|', ' ')))), 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(dve.DVE_CMOR, CHAR(9), ' '), '|', ' ')))), 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(ISNULL(dve.DVE_CCPO, ''), CHAR(9), ' '), '|', ' ')))), 
			dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(RTRIM(LTRIM(REPLACE(REPLACE(ISNULL(dve.DVE_CLPO, ''), CHAR(9), ' '), '|', ' ')))), 
			ISNULL(LTRIM(RTRIM(dve.DVE_CPRT)), '9999999999'), ISNULL(NULLIF(tdo.TDO_CPAR, ''), ISNULL(cli.CLI_CEAN, '')), dve.DVE_SERI, 
			DATEADD(DAY, ISNULL(cli.CLI_CPAG, 0), dve.DVE_DATA), (CASE tdo.TDO_TDSF WHEN 'NC' THEN -dve.DVE_VIVA ELSE dve.DVE_VIVA END), 
			(CASE tdo.TDO_TDSF WHEN 'NC' THEN -dve.DVE_VLIQ ELSE dve.DVE_VLIQ END), (CASE tdo.TDO_TDSF WHEN 'NC' THEN 'CR' ELSE 'INV-STD' END), 
			(CASE (CASE dve.DVE_IMEX
					WHEN 0 THEN (CASE 
									WHEN dve.DVE_IDAR IS NULL THEN RIGHT(duc.ALF_CODI, 3)																		
									ELSE RIGHT(alf.ALF_CODI, 3)										
								END) 
					ELSE RIGHT(exm.EAD_CODA, 3)
				END) WHEN '020' THEN 'OPO'
				ELSE 'LIS'
			END), 
			(CASE dve.DVE_IMEX 
				WHEN 0 THEN (CASE 
								WHEN dve.DVE_IDAR IS NULL THEN ISNULL(NULLIF(duc.DUC_FUPS, ''), ISNULL(duc.DUC_AERO, '')) 
								ELSE ISNULL(NULLIF(dar.nomeFicheiroUPS, ''), ISNULL(dar.aeroportoOrigem, ''))
							END) 
				ELSE ISNULL(exm.PAE_CODI, '')
			END), 
			mcc.MVC_NDOC, ISNULL(mcc.MVC_SERI, '')
		FROM FAC_DVEN AS dve WITH(NOLOCK) 
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dve.CLI_CODI = cli.CLI_CODI
			LEFT OUTER JOIN FAC_MVCC AS mcc WITH(NOLOCK) ON dve.MVC_IDEN = mcc.MVC_IDEN
			LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dve.DVE_NPRO = duc.DUC_PNUM AND dve.DVE_PANO = duc.DUC_EANO AND dve.DVE_IMEX = 0 AND dve.DVE_IDAR IS NULL
			LEFT OUTER JOIN PRO_EXML AS exm WITH(NOLOCK) ON dve.DVE_NPRO = exm.EXM_NRII AND dve.DVE_PANO = exm.EXM_EANO AND dve.DEC_CODI = exm.DEC_CODI AND dve.DVE_IMEX = 1 AND dve.DVE_IDAR IS NULL
			LEFT OUTER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON dve.DVE_IDAR = dar.id
			LEFT OUTER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY
		WHERE dve.DVE_TDOC NOT IN ('NEXB', 'TEXC') AND dve.DVE_ANUL = 0 AND tdo.TDO_DCON = 1 AND tdo.TDO_EXSF = 1 AND tdo.TDO_TDSF IN ('FT', 'NC') 
			AND CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime) 
		ORDER BY dve.DVE_EANO, dve.DVE_TDOC, dve.DVE_NDOC
	OPEN DocsVenda
	FETCH NEXT FROM DocsVenda INTO @AnoDocumento, @CodTipoDocumento, @NumDocumento, @DataDocumento, @NomeClienteCCDocumento, @MoradaClienteCCDocumento, 
		@CodPostalClienteCCDocumento, @LocPostalClienteCCDocumento, @AWBDocumento, @CodigoEAN, @SerieDocumento, @DataVencimento, @TotalIVA, @TotalLiquido, @TipoInvoice, 
		@DestinoProcesso, @OrigemProcesso, @NumDocumentoCreditado, @SerieDocumentoCreditado
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- constroi a linha do tipo "invoice header"
		SET @LinhaTXT = 'HPT|'
		SET @LinhaTXT = @LinhaTXT + @SerieDocumento + CAST(@NumDocumento AS varchar(10)) + '|'
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataDocumento, 105) + '|'
		SET @LinhaTXT = @LinhaTXT + @TipoInvoice + '|'
		SET @LinhaTXT = @LinhaTXT + @CodigoEAN + '|'
		SET @LinhaTXT = @LinhaTXT + '||||EUR|1|||||'
		SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@TotalLiquido, 18, 2)) + '|'
		SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@TotalIVA, 18, 2)) + '|'
		SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataVencimento, 105) + '|'
		SET @LinhaTXT = @LinhaTXT + '||||||||||'	
		SET @LinhaTXT = @LinhaTXT + @SerieDocumento + CAST(@NumDocumento AS varchar(10)) + '|'		
-- escreve a linha do tipo "invoice header" no ficheiro
		EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXT
-- obtém as rúbricas de faturação do documento de Venda 
		DECLARE Despesas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT t.RFC_TIPO, t.CCO_CODI, t.IIV_CODI, MAX(t.DVD_IVA), SUM(t.DVD_VLIQ), SUM(t.DVD_VIVA), (CASE LEFT(t.CCO_CODI, 1) WHEN 'W' THEN 'P' ELSE 'Z' END)
			FROM (SELECT ISNULL(det.DVD_IVA, 0) AS DVD_IVA, (CASE ISNULL(rft.RFC_TIPO, 0) WHEN 0 THEN 'DUTY' ELSE 'SCS' END) AS RFC_TIPO, LEFT(ISNULL(det.CCO_CODI, ''), 2) AS CCO_CODI, 
					ISNULL(NULLIF(det.IIV_CODI, ''), 'NOR') AS IIV_CODI, 
					((CASE @TipoInvoice WHEN 'CR' THEN -1 ELSE 1 END) * ROUND(ISNULL(det.DVD_QUAN, 0) * ISNULL(det.DVD_VALO, 0), 2)) AS DVD_VLIQ, 
					((CASE @TipoInvoice WHEN 'CR' THEN -1 ELSE 1 END) * ROUND(ROUND(ISNULL(det.DVD_QUAN, 0) * ISNULL(det.DVD_VALO, 0), 2) * ISNULL(det.DVD_IVA, 0) / 100, 2)) AS DVD_VIVA					
				FROM FAC_DVDT AS det WITH(NOLOCK)
					INNER JOIN TAB_RFCT AS rft WITH(NOLOCK) ON det.RFC_CODI = rft.RFC_CODI
				WHERE det.DVE_EANO = @AnoDocumento AND det.DVE_TDOC = @CodTipoDocumento AND det.DVE_NDOC = @NumDocumento AND det.DVD_LCRB = 1 
					AND ROUND(ISNULL(det.DVD_QUAN, 0) * ISNULL(det.DVD_VALO, 0), 2) <> 0
			) AS t
			GROUP BY t.RFC_TIPO, t.CCO_CODI, t.IIV_CODI
			ORDER BY t.RFC_TIPO, t.CCO_CODI	
		OPEN Despesas
		FETCH NEXT FROM Despesas INTO @TipoLinha, @CodChargeCodeLinha, @CodMotivoIsencaoIVALinha, @TxIVADocumento, @ValorLinha, @IVALinha, @LocalProductCodeLinha
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- constroi a linha do tipo "invoice line"
			SET @LinhaTXT = 'IPT|'
			SET @LinhaTXT = @LinhaTXT + @SerieDocumento + CAST(@NumDocumento AS varchar(10)) + '|'
			SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataDocumento, 105) + '|'
			SET @LinhaTXT = @LinhaTXT + @TipoInvoice + '|'
			SET @LinhaTXT = @LinhaTXT + @CodigoEAN + '|'
			SET @LinhaTXT = @LinhaTXT + @AWBDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + @OrigemProcesso + '|'
			SET @LinhaTXT = @LinhaTXT + @DestinoProcesso + '|'
			SET @LinhaTXT = @LinhaTXT + '|EUR|1|'
			SET @LinhaTXT = @LinhaTXT + @CodMotivoIsencaoIVALinha + '|'
			SET @LinhaTXT = @LinhaTXT + '|'
			SET @LinhaTXT = @LinhaTXT + @TipoLinha + '|'
			SET @LinhaTXT = @LinhaTXT + @LocalProductCodeLinha + '|'
-- para o charge code "WB" não coloca respetivos valores de despesa nem IVA
			IF @CodChargeCodeLinha = 'WB'
			BEGIN				
				SET @LinhaTXT = @LinhaTXT + '[@ValorLinha]|'
				SET @LinhaTXT = @LinhaTXT + '[@IVALinha]|'
			END
			ELSE
			BEGIN				
				SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@ValorLinha, 18, 2)) + '|'
				SET @LinhaTXT = @LinhaTXT + LTRIM(STR(@IVALinha, 18, 2)) + '|'
			END			
			SET @LinhaTXT = @LinhaTXT + CONVERT(varchar(10), @DataVencimento, 105) + '|'
			SET @LinhaTXT = @LinhaTXT + @NomeClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + @MoradaClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + '|||'
			SET @LinhaTXT = @LinhaTXT + @CodPostalClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + @LocPostalClienteCCDocumento + '|'
			SET @LinhaTXT = @LinhaTXT + @SerieDocumentoCreditado + ISNULL(CAST(@NumDocumentoCreditado AS varchar(10)), '') + '||'
-- para o charge code "WB" não coloca o código
			IF @CodChargeCodeLinha = 'WB'
				SET @LinhaTXT = @LinhaTXT + '[@CodChargeCodeLinha]|'	
			ELSE
				SET @LinhaTXT = @LinhaTXT + @CodChargeCodeLinha + '|'
			SET @LinhaTXT = @LinhaTXT + '|'
-- escreve a linha do tipo "invoice line" no ficheiro quando o charge code não é "WB" 
			IF @CodChargeCodeLinha <> 'WB'
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXT
			ELSE
			BEGIN				
-- obtem os charge codes extra conforme o EAN
				SET @CodChargeCode1 = @CodChargeCodeLinha
				SET @CodChargeCode2 = 'WD'
				IF @CodigoEAN = 'DUTYPTCSH'				
					SET @CodChargeCode3 = 'WW'				
				ELSE				
					SET @CodChargeCode3 = 'WC'	
-- inicia valores restantes
				SET @ValorRestanteChargeCode = @ValorLinha												
				SET @IVARestanteChargeCode = @IVALinha
-- processa calculos para o charge code n.º 1 "WB" conforme valor superior a 30
				IF @ValorLinha > 30				
					SET @ValorChargeCode = 10									
				ELSE				
					SET @ValorChargeCode = ROUND(@ValorLinha * 49 / 100, 2)
				SET @IVAChargeCode = ROUND(@ValorChargeCode * @TxIVADocumento / 100, 2)
-- atualiza valores restantes
				SET @ValorRestanteChargeCode = @ValorRestanteChargeCode - @ValorChargeCode
				SET @IVARestanteChargeCode = @IVARestanteChargeCode - @IVAChargeCode
-- constroi a linha do tipo "invoice line" para o charge code n.º 1 "WB"
				SET @LinhaTXTChargeCode = @LinhaTXT
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@ValorLinha]', LTRIM(STR(@ValorChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@IVALinha]', LTRIM(STR(@IVAChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@CodChargeCodeLinha]', @CodChargeCode1)
-- escreve a linha do tipo "invoice line" do charge code n.º 1 "WB" no ficheiro
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXTChargeCode
-- processa calculos para o charge code n.º 2 "WD" conforme valor superior a 30
				IF @ValorLinha > 30
					SET @ValorChargeCode = 10									
				ELSE
					SET @ValorChargeCode = ROUND(@ValorLinha * 49 / 100, 2)
				SET @IVAChargeCode = ROUND(@ValorChargeCode * @TxIVADocumento / 100, 2)
-- atualiza valores restantes
				SET @ValorRestanteChargeCode = @ValorRestanteChargeCode - @ValorChargeCode
				SET @IVARestanteChargeCode = @IVARestanteChargeCode - @IVAChargeCode
-- constroi a linha do tipo "invoice line" para o charge code n.º 2 "WD"
				SET @LinhaTXTChargeCode = @LinhaTXT
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@ValorLinha]', LTRIM(STR(@ValorChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@IVALinha]', LTRIM(STR(@IVAChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@CodChargeCodeLinha]', @CodChargeCode2)
-- escreve a linha do tipo "invoice line" do charge code n.º 2 "WD" no ficheiro
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXTChargeCode							
-- processa calculos para o charge code n.º 3 "WW" ou "WC" conforme valor superior a 30
				IF @ValorLinha > 30
				BEGIN
					SET @ValorChargeCode = @ValorLinha - 20									
					SET @IVAChargeCode = ROUND(@ValorChargeCode * @TxIVADocumento / 100, 2)
				END
				ELSE
				BEGIN
					SET @ValorChargeCode = @ValorRestanteChargeCode		
					SET @IVAChargeCode = @IVARestanteChargeCode
				END				
-- constroi a linha do tipo "invoice line" para o charge code n.º 3 "WW" ou "WC"
				SET @LinhaTXTChargeCode = @LinhaTXT
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@ValorLinha]', LTRIM(STR(@ValorChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@IVALinha]', LTRIM(STR(@IVAChargeCode, 18, 2)))
				SET @LinhaTXTChargeCode = REPLACE(@LinhaTXTChargeCode, '[@CodChargeCodeLinha]', @CodChargeCode3)
-- escreve a linha do tipo "invoice line" do charge code n.º 3 "WW" ou "WC" no ficheiro
				EXEC sp_OAMethod @TextFileObj, 'WriteLine', NULL, @LinhaTXTChargeCode
			END					
			FETCH NEXT FROM Despesas INTO @TipoLinha, @CodChargeCodeLinha, @CodMotivoIsencaoIVALinha, @TxIVADocumento, @ValorLinha, @IVALinha, @LocalProductCodeLinha
		END
		CLOSE Despesas
		DEALLOCATE Despesas
		FETCH NEXT FROM DocsVenda INTO @AnoDocumento, @CodTipoDocumento, @NumDocumento, @DataDocumento, @NomeClienteCCDocumento, @MoradaClienteCCDocumento, 
			@CodPostalClienteCCDocumento, @LocPostalClienteCCDocumento, @AWBDocumento, @CodigoEAN, @SerieDocumento, @DataVencimento, @TotalIVA, @TotalLiquido, @TipoInvoice, 
			@DestinoProcesso, @OrigemProcesso, @NumDocumentoCreditado, @SerieDocumentoCreditado
	END
	CLOSE DocsVenda
	DEALLOCATE DocsVenda
-- destroi os objetos 			
	EXEC sp_OADestroy @TextFileObj	
	EXEC sp_OADestroy @FileSystemObj		
END

ALTER AUTHORIZATION ON [SP_Facturacao_ExportaFicheiroSAPDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Facturacao_ExportaFicheiroSAPDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraATR]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraATR] @cod int, @ano int AS
--declaracoes de variaveis --
declare @contador int, @codAlf varchar(8), @docTrans varchar(15), @docDe varchar(15), @status int,
	@codExp varchar(18), @nomeExp varchar(70), @morExp varchar(70), @locExp varchar(35), @codPosExp varchar(12),
	@locPosExp varchar(35), @nifExp varchar(18), @paisExp varchar(2), @codDest varchar(18), @nomeDest varchar(70),
	@morDest varchar(70), @locDest varchar(35), @codPosDest varchar(12), @locPosDest varchar(35),
	@nifDest varchar(18), @paisDest varchar(2), @marca varchar(20), @quant numeric(38,6), @natur varchar(3),
	@pBruto numeric(38,6), @codLinha int, @codArtigo varchar(22), @desArtigo varchar(150), @masBruta numeric(38,6),
	@assumATR bit, @desComercial varchar(150)

--busca registo da tabela PRO_DUCG
	SELECT @codAlf = duc.ALF_CODI, @pBruto = duc.DUC_MBRT, @status = duc.DUC_STAT,
	@codExp = duc.DUC_EXP2, @paisExp = duc.PAI_PA15, @nomeExp = duc.DUC_ENOM, @morExp = duc.DUC_EMOR,
	@locExp = duc.DUC_ELOC, @codPosExp = duc.DUC_ECPO, @locPosExp = duc.DUC_ELPO, @nifExp = duc.DUC_ENIF,
	@codDest = duc.DUC_DST8, @paisDest = duc.PAI_PA17, @nomeDest = duc.DUC_DNOM, @morDest = duc.DUC_DMOR,
	@locDest = duc.DUC_DLOC, @codPosDest = duc.DUC_DCPO, @locPosDest = duc.DUC_DLPO, @nifDest = duc.DUC_DNIF
	FROM PRO_DUCG duc
	WHERE duc.DUC_PNUM = @cod and duc.DUC_EANO = @ano
	
	SELECT @marca = d31.D31_MARC, @quant = d31.D31_QNTD, @natur = d31.UME_CODI
	FROM PRO_DU31 d31
	WHERE d31.DUC_PNUM = @cod AND d31.DUC_EANO = @ano AND d31.DUA_CODI = 1 AND d31.D31_CODI = 1
	
--verifica se O MODELO ATR ja foi gerado	
	SELECT @contador = count(*)
	FROM PRO_ATRC
	WHERE DUC_PNUM = @cod and DUC_EANO = @ano

--se nao foi gerado insere campos na PRO_ATRC
	IF @contador = 0
	BEGIN
		SET DATEFORMAT dmy
		INSERT INTO PRO_ATRC(DUC_EANO, DUC_PNUM, ATR_DATA, ATR_STAT, ALF_CODI,
			ATR_EXP1, PAI_COD5, ATR_ENOM, ATR_EMOR, ATR_ELOC, ATR_ECPO, ATR_ELPO, ATR_ENIF,
			ATR_DST3, PAI_COD6, ATR_DNOM, ATR_DMOR, ATR_DLOC, ATR_DCPO, ATR_DLPO, ATR_DNIF,
			ATR_MC10, ATR_QT10, UME_CO10, ATR_PBTT)
		VALUES (@ano, @cod, getdate(), @status, @codAlf, @codExp, @paisExp, @nomeExp,
			@morExp, @locExp, @codPosExp, @locPosExp, @nifExp, @codDest, @paisDest, @nomeDest,
			@morDest, @locDest, @codPosDest, @locPosDest, @nifDest, @marca, @quant, @natur, @pBruto)

	END
	ELSE
--se ja foi gerado altera campos do modelo PRO_GCIR
	BEGIN
		UPDATE PRO_ATRC SET DUC_EANO = @ano, DUC_PNUM = @cod, ATR_DATA = getdate(), ATR_STAT = @status,
			ALF_CODI = @codAlf, ATR_EXP1 = @codExp, PAI_COD5 = @paisExp, ATR_ENOM = @nomeExp,
			ATR_EMOR = @morExp, ATR_ELOC = @locExp, ATR_ECPO = @codPosExp, ATR_ELPO = @locPosExp,
			ATR_ENIF = @nifExp, ATR_DST3 = @codDest, PAI_COD6 = @paisDest, ATR_DNOM = @nomeDest,
			ATR_DMOR = @morDest, ATR_DLOC = @locDest, ATR_DCPO = @codPosDest, ATR_DLPO = @locPosDest,
			ATR_DNIF = @nifDest, ATR_MC10 = @marca, ATR_QT10 = @quant, UME_CO10 = @natur,
			ATR_PBTT = @pBruto
		WHERE DUC_PNUM = @cod and DUC_EANO = @ano
	END

--obtem as adições do documento único
	DELETE FROM PRO_AATR WHERE DUC_PNUM = @cod and DUC_EANO = @ano	

	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT DUA_CODI, APA_CO33, DUA_DESG, DUA_MB35
	FROM PRO_DUAD
	WHERE DUC_PNUM = @cod and DUC_EANO = @ano

	OPEN Detalhe
	FETCH NEXT from Detalhe into @codLinha, @codArtigo, @desArtigo, @masBruta

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT @assumATR = APA_EUR1, @desComercial = APA_DCOM
		FROM TAB_APAU
		WHERE APA_CODI = @codArtigo	
		
		IF ((@desComercial is not NULL) OR (@desComercial = '')) AND (@assumATR = '1')
		BEGIN
			INSERT INTO PRO_AATR(DUC_EANO, DUC_PNUM, AAT_CODI, APA_CODI, AAT_DPAU, AAT_PBRT)
			VALUES(@ano, @cod, @codLinha, @codArtigo, @desComercial, @masBruta)
		END
		ELSE
		BEGIN
			INSERT INTO PRO_AATR(DUC_EANO, DUC_PNUM, AAT_CODI, APA_CODI, AAT_DPAU, AAT_PBRT)
			VALUES(@ano, @cod, @codLinha, @codArtigo, @desArtigo, @masBruta)
		END
		FETCH NEXT from Detalhe into @codLinha, @codArtigo, @desArtigo, @masBruta
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe

ALTER AUTHORIZATION ON [SP_geraATR] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraATR] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraContas]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraContas] @proc int, @ano int, @tdoc varchar(4), @nde_codi varchar(3), @util varchar(30), @TipoMascara int, @mascara int, @valhonor numeric(38,6), @cdo_obsr varchar(500), 
	@valorCauc numeric(38,6), @cartaPorte varchar(18), @GeraContaDVU bit, @TipoCliente varchar(3), @Origem int AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracoes de variaveis
	declare @AnoConta int, @IDConta int, @StatusConta int, @contador int, @alf_codi varchar(8), @cdo_nord varchar(20), @cdo_dtab datetime, @cli_desp varchar(18), 
		@cli_ccor varchar(18), @cli_endc varchar(18), @cdo_qunt numeric(38,6), @cdo_pbrt numeric(38,6), @cdo_pliq numeric(38,6), @cdo_vadu numeric(38,6), @mtr_codi varchar(2), 
		@cdo_mtra varchar(30), @pai_mtra varchar(2), @cdo_isiv varchar(100), @cdo_agra numeric(38,6), @cdo_desa numeric(38,6), @cdo_forh varchar(4000), @cdo_desc varchar(40), 
		@cdo_marc varchar(20), @cdo_rtfo numeric(38,6), @valor numeric(38,6), @din_hono int, @linha int, @despesa int, @descri varchar(70), @valo numeric(38,6), @cont int, 
		@valorDocu numeric(38,6), @TotalInerentes numeric(38,6), @retfonte numeric(38,6), @valIVA numeric(38,6), @cdo_txiv numeric(38,6), @TotalInerentesIsentoIVA numeric(38,6), 
		@cdo_qual varchar(35), @cdo_ctmr varchar(20), @TotalRecapitulativo numeric(38,6), @dec_codi varchar(6), @despesaCauc int, @descriCauc varchar(70), @taxaCauc numeric(38,6), 
		@contCauc int, @valorAnt numeric(38,6), @vRef varchar(50), @regLiq varchar(20), @dataReg datetime, @mpag int, @trafego bit, @limMax numeric(38,6), @valorKg numeric(38,6), 
		@utiliza bit, @valorTrafego numeric(38,6), @Nome varchar(70), @Morada varchar(70), @Localidade varchar(35), @CodPostal varchar(12), @LocPostal varchar(35), 
		@NumContribuinte varchar(18), @Pais varchar(2), @NaturezaDUContasAutSaida bit, @FormulaCalcValor varchar(4000), @OUTValorNumerico numeric(38, 6), 
		@UltNumLinhaDespDocInserida int, @ProcessamentoParteResto bit, @ProcessoDVU bit, @TipoDocContaDVU varchar(4), @CodNaturezaDVU varchar(3), @TipoMascaraDVU int, 
		@MascaraDVU int, @ObservacoesDVU varchar(5000), @CodigoEAN varchar(13), @DataOrdem datetime, @NumTotalAdics int, @CodIsencaoIVA varchar(3), @CodFornecedor varchar(18), 
		@NomeFornecedor varchar(70), @ValorIVAAlfandega numeric(38, 6), @ValorDireitos numeric(38, 6), @IDTarifa int, @CodRubHonorariosSAD int, @CodRubCaucao int, 
		@CodRubMultiClass int, @NumAdicoesMultiClass int, @ValorPorAdicaoMultiClass numeric(38, 6), @CodRubContactoObr int, @ValorContactoObr numeric(38, 6), 
		@ValorReferenciaTarifa numeric(38, 6), @CampoRecapitulativo int, @ContactoObrigatorio bit, @CodChargeCode varchar(4), @ValorIVAAdicoes numeric(38, 6), 
		@TipoDestinatarioPC bit, @CodDespInerenteClienteCC int, @CondPagamentoCliente int, @IsentaIVADespInerente bit, @CodIsencaoIVADespInerente varchar(3), 
		@MencaoIsencaoIVADespInerente varchar(100), @PartShipment bit, @NumLinhaDespDoc int, @TipoEntidadeCaucao int
-- busca registo da tabela PRO_DUCG 
	SELECT @alf_codi = d.ALF_CODI, @cdo_nord = d.DUC_NORD, @DataOrdem = d.DUC_NDAT, @cdo_dtab = CAST(CONVERT(varchar(10), d.DUC_DATA, 105) as datetime), @TipoEntidadeCaucao = ISNULL(d.DUC_CENT, 0), 
		@cdo_qunt = (CASE d.DUC_TSHI WHEN 1 THEN d.DUC_VDIR ELSE d.DUC_TVL6 END), 
		@cdo_pbrt = (CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TMBO ELSE d.DUC_MBRT END), 
		@cdo_pliq = (CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TMLO ELSE d.DUC_MLQT END), 
		@NumTotalAdics = d.DUC_ADI5, @mtr_codi = d.MTR_PT18, @cdo_mtra = d.DUC_MT18, @pai_mtra = d.PAI_PA18, @ContactoObrigatorio = d.DUC_COBR, @dec_codi = d.DEC_CO14, 
		@vRef = d.DUC_NVRF, @regLiq = d.DUC_REGL, @dataReg = d.DUC_DTRL, 
		@PartShipment = (CASE d.DUC_TSHI WHEN 1 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END), 
		@CodIsencaoIVA = n.IIV_CODI, 
		@cdo_isiv = (select IIV_MENC from GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) where IIV_CODI = n.IIV_CODI), 
		@cdo_agra = n.NDE_AHON, @CodChargeCode = n.CCO_CODI, @cdo_desa = n.NDE_DHON, @cdo_forh = n.NDE_FORM, @cdo_txiv = n.NDE_TIVA, @cdo_desc = ISNULL(NULLIF(d.DUC_DGEN, ''), a.DUA_DESG), 
		@trafego = n.NDE_CTEN, @limMax = n.NDE_LMAX, @valorKg = n.NDE_VLKG, @cdo_ctmr = a.DUA_DNUM, 
		@TipoDestinatarioPC = (CASE d.DUC_TPDS WHEN 0 THEN CAST(1 as bit) ELSE CAST(0 as bit) END), 
		@ProcessoDVU = (case @GeraContaDVU when 0 then d.DUC_PDVU else cast(0 as bit) end), 
		@TipoDocContaDVU = (case @GeraContaDVU when 0 then d.TDO_DOCU1 else NULL end), 
		@CodNaturezaDVU = (case @GeraContaDVU when 0 then d.NDE_CODI1 else NULL end),
		@cli_desp = (case d.DUC_TIPO when 1 then d.DUC_DST8 else d.DUC_EXP2 end),
		@cli_ccor = (case d.DUC_TIPO when 1 then ISNULL(c.CLI_CCOR, d.DUC_DST8) else ISNULL(c.CLI_CCOR, d.DUC_EXP2) end),
		@cli_endc = (case d.DUC_TIPO when 1 then ISNULL(c.CLI_ECON, d.DUC_DST8) else ISNULL(c.CLI_ECON, d.DUC_EXP2) end), 
		@cdo_vadu = (case d.DUC_TIPO when 1 then (CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TVAO ELSE ISNULL(d.DUC_VATT, 0) END) else (SELECT ISNULL(SUM(DUA_VEST), 0) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = d.DUC_PNUM AND DUC_EANO = d.DUC_EANO) end), 
		@cdo_marc = (SELECT D31_MARC FROM PRO_DU31 WITH(NOLOCK) WHERE DUC_PNUM = a.DUC_PNUM AND DUC_EANO = @ano AND DUA_CODI = a.DUA_CODI AND D31_CODI = 1), 
		@cdo_qual = (SELECT UME_NOME FROM PRO_DU31 WITH(NOLOCK) WHERE DUC_PNUM = a.DUC_PNUM AND DUC_EANO = @ano AND DUA_CODI = a.DUA_CODI AND D31_CODI = 1), 
		@cdo_rtfo = (SELECT PFC_RFNT FROM TAB_PFCT WITH(NOLOCK)), @NaturezaDUContasAutSaida = (case when (isnull(n.NDE_TLCV, -1) = 0) then cast(1 as bit) else cast(0 as bit) end),
		@CodFornecedor = NULLIF((case d.DUC_TIPO when 1 then d.DUC_EXP2 else d.DUC_DST8 end), ''), @NomeFornecedor = (case d.DUC_TIPO when 1 then d.DUC_ENOM else d.DUC_DNOM end),				
		@TotalRecapitulativo = ISNULL((CASE d.DUC_TSHI WHEN 1 THEN (SELECT SUM(lo.DUL_MONT) FROM PRO_DULO AS lo WITH(NOLOCK) INNER JOIN TAB_RREC AS rr WITH(NOLOCK) ON lo.RRE_CODI = rr.RRE_CODI WHERE rr.RRE_DOIN = 1 AND lo.DUC_EANO = d.DUC_EANO AND lo.DUC_PNUM = d.DUC_PNUM) ELSE (SELECT SUM(lr.DUL_MONT) FROM PRO_DULR as lr WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON lr.RRE_CODI = rr.RRE_CODI WHERE rr.RRE_DOIN = 1 AND lr.DUC_EANO = d.DUC_EANO AND lr.DUC_PNUM = d.DUC_PNUM) END), 0), 
		@ValorIVAAlfandega = ISNULL((CASE d.DUC_TSHI WHEN 1 THEN (SELECT SUM(lo.DUL_MONT) FROM PRO_DULO AS lo WITH(NOLOCK) INNER JOIN TAB_RREC AS rr WITH(NOLOCK) ON lo.RRE_CODI = rr.RRE_CODI WHERE rr.RRE_DOIN = 1 AND lo.DUC_EANO = d.DUC_EANO AND lo.DUC_PNUM = d.DUC_PNUM AND lo.RRE_CODI IN (SELECT RRE_CDIS FROM TAB_PAPL WITH(NOLOCK) UNION SELECT RRE_CDRD FROM TAB_PAPL WITH(NOLOCK) UNION SELECT RRE_CDIN FROM TAB_PAPL WITH(NOLOCK) UNION SELECT RRE_CDNR FROM TAB_PAPL WITH(NOLOCK))) ELSE (SELECT SUM(lr.DUL_MONT) FROM PRO_DULR as lr WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON lr.RRE_CODI = rr.RRE_CODI WHERE rr.RRE_DOIN = 1 AND lr.DUC_EANO = d.DUC_EANO AND lr.DUC_PNUM = d.DUC_PNUM and lr.RRE_CODI in (select RRE_CDIS from TAB_PAPL WITH(NOLOCK) UNION select RRE_CDRD from TAB_PAPL WITH(NOLOCK) UNION select RRE_CDIN from TAB_PAPL WITH(NOLOCK) UNION select RRE_CDNR from TAB_PAPL WITH(NOLOCK))) END), 0),		
		@ValorDireitos = ISNULL((CASE d.DUC_TSHI WHEN 1 THEN (SELECT SUM(lo.DUL_MONT) FROM PRO_DULO AS lo WITH(NOLOCK) INNER JOIN TAB_RREC AS rr WITH(NOLOCK) ON lo.RRE_CODI = rr.RRE_CODI WHERE rr.RRE_DOIN = 1 AND lo.DUC_EANO = d.DUC_EANO AND lo.DUC_PNUM = d.DUC_PNUM AND lo.RRE_CODI BETWEEN 800 AND 899) ELSE (SELECT SUM(lr.DUL_MONT) FROM PRO_DULR as lr WITH(NOLOCK) INNER JOIN TAB_RREC as rr WITH(NOLOCK) ON lr.RRE_CODI = rr.RRE_CODI WHERE rr.RRE_DOIN = 1 AND lr.DUC_EANO = d.DUC_EANO AND lr.DUC_PNUM = d.DUC_PNUM and lr.RRE_CODI BETWEEN 800 and 899) END), 0), 		
		@IDTarifa = n.CBT_IDEN, @ValorReferenciaTarifa = (CASE d.DUC_TPDS WHEN 0 THEN (CASE t.CBT_VREF WHEN 0 THEN (CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TVAO ELSE ISNULL(d.DUC_VATT, 0) END) WHEN 1 THEN ((CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TVEO ELSE ISNULL(d.DUC_VEUR, 0) END) - ROUND((d.DUC_VDES / d.DUC_TX23), 2)) WHEN 2 THEN ((CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TLRO ELSE ISNULL(d.DUC_VLRC, 0) END) - (CASE d.DUC_BIVA WHEN 1 THEN ISNULL((CASE d.DUC_TSHI WHEN 1 THEN (SELECT SUM(DUA_TIVO) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = d.DUC_PNUM and DUC_EANO = d.DUC_EANO) ELSE (SELECT SUM(ISNULL(DUA_VIVA, 0)) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = d.DUC_PNUM and DUC_EANO = d.DUC_EANO) END), 0) ELSE 0 END)) ELSE 0 END) ELSE (CASE t.CBT_VRFP WHEN 0 THEN (CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TVAO ELSE ISNULL(d.DUC_VATT, 0) END) WHEN 1 THEN ((CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TVEO ELSE ISNULL(d.DUC_VEUR, 0) END) - ROUND((d.DUC_VDES / d.DUC_TX23), 2)) WHEN 2 THEN ((CASE d.DUC_TSHI WHEN 1 THEN d.DUC_TLRO ELSE ISNULL(d.DUC_VLRC, 0) END) - (CASE d.DUC_BIVA WHEN 1 THEN ISNULL((CASE d.DUC_TSHI WHEN 1 THEN (SELECT SUM(DUA_TIVO) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = d.DUC_PNUM and DUC_EANO = d.DUC_EANO) ELSE (SELECT SUM(ISNULL(DUA_VIVA, 0)) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = d.DUC_PNUM and DUC_EANO = d.DUC_EANO) END), 0) ELSE 0 END)) ELSE 0 END) END), 		
		@CodRubHonorariosSAD = b.DIN_CODI1, @CodRubCaucao = b.DIN_CODI3, @CodRubMultiClass = b.DIN_CODI2, @NumAdicoesMultiClass = b.CBI_NADF, 
		@ValorPorAdicaoMultiClass = b.CBI_VLAD, @CodRubContactoObr = b.DIN_CODI, @ValorContactoObr = b.CBI_VLCO,		
		@ValorIVAAdicoes = (CASE d.DUC_BIVA WHEN 1 THEN ISNULL((CASE d.DUC_TSHI WHEN 1 THEN (SELECT SUM(DUA_TIVO) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = d.DUC_PNUM and DUC_EANO = d.DUC_EANO) ELSE (SELECT SUM(ISNULL(DUA_VIVA, 0)) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = d.DUC_PNUM and DUC_EANO = d.DUC_EANO) END), 0) ELSE 0 END)
	FROM PRO_DUCG as d INNER JOIN TAB_NDES as n WITH(NOLOCK) ON (case @GeraContaDVU when 0 then d.NDE_CODI else d.NDE_CODI1 end) = n.NDE_CODI
		LEFT OUTER JOIN TAB_CLIE as c WITH(NOLOCK) ON (d.DUC_TIPO = 1 and d.DUC_DST8 = c.CLI_CODI) or (d.DUC_TIPO = 2 and d.DUC_EXP2 = c.CLI_CODI)
		LEFT OUTER JOIN PRO_DUAD as a WITH(NOLOCK) ON a.DUA_CODI = 1 and d.DUC_PNUM = a.DUC_PNUM and d.DUC_EANO = a.DUC_EANO 
		LEFT OUTER JOIN TAB_PCBT as t WITH(NOLOCK) ON n.CBT_IDEN = t.CBT_IDEN
		LEFT OUTER JOIN TAB_PCBI as b WITH(NOLOCK) ON t.CBI_IDEN = b.CBI_IDEN
	WHERE d.DUC_PNUM = @proc AND d.DUC_EANO = @ano

	IF @cli_desp <> '' 
	BEGIN
-- obtem dados do cliente de conta corrente
		SELECT @Nome = CLI_NOME, @Morada = CLI_MORA, @Localidade = CLI_LOCA, @CodPostal = CLI_CPOS, @LocPostal = CLI_LPOS, @NumContribuinte = CLI_NIF, @Pais = PAI_CODI, 
			@mpag = CLI_MPAG, @CodigoEAN = CLI_CEAN, @CodDespInerenteClienteCC = DIN_CODI, @taxaCauc = ISNULL(CLI_SUCA, 0), @CondPagamentoCliente = CLI_CPAG
		FROM TAB_CLIE WITH(NOLOCK) 
		WHERE CLI_CODI = @cli_ccor			
-- verifica se é geracao da Conta através de Processamento Parte e Resto (apenas quando se utiliza Interface Du/Contas (Aut. Saida) e se trata de "Expressos")
		IF (@PartShipment = 0) AND (@GeraContaDVU = 0) AND (@NaturezaDUContasAutSaida = 1) AND (@cartaPorte <> '') AND (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI IN (1, 2, 3, 4)))
		BEGIN 
			SELECT @ProcessamentoParteResto = (case count(*) when 0 then cast(0 as bit) else cast(1 as bit) end)
			FROM FAC_CDOC WITH(NOLOCK) 
			WHERE CDO_IMEX = 0 and CDO_PANO = @ano and CDO_NPRO <> @proc and CDO_CPRT = @cartaPorte
		END
		ELSE
			SET @ProcessamentoParteResto = 0
-- se natureza não tiver Tarifa definida, processa calculos "normais"
		IF @IDTarifa is null
		BEGIN			
-- nos processamento normais calcula despesa inerente de honorarios e respectivos valores
			if (@GeraContaDVU = 0) and (@ProcessamentoParteResto = 0)
			begin
-- obtem despesa inerente de Honorarios
				select @din_hono = DIN_CODI, @FormulaCalcValor = isnull(DIN_FCLC, '')
				from TAB_DINE WITH(NOLOCK) 
				where DIN_CODI = 13
-- se despesa inerente de Honorarios existe, obtem valor de honorários
				if @din_hono is not null
				begin			
-- obtem valores de Honorarios nas Mascaras
					if @mascara > 0  
					begin
						if @TipoMascara = 1 
						begin
							select @cdo_agra = MCF_VAGR, @cdo_desa = MCF_VDES, @valhonor = (case isnull(MCF_VALO, 0) when 0 then @valhonor else isnull(MCF_VALO, 0) end)
							from TAB_MCFT WITH(NOLOCK) 
							where CLI_CODI = @cli_ccor and NDE_CODI = @nde_codi and MCF_CODI = @mascara	
						end
						else
						begin
							select @cdo_agra = MNF_VAGR, @cdo_desa = MNF_VDES, @valhonor = (case isnull(MNF_VALO, 0) when 0 then @valhonor else isnull(MNF_VALO, 0) end)
							from TAB_MNFT WITH(NOLOCK) 
							where NDE_CODI = @nde_codi and MNF_CODI = @mascara	
						end
					end
					else
						select @cdo_agra = 0, @cdo_desa = 0
-- se utiliza Interface Du/Contas (Aut. Saida) e desp. inerente de Honorarios tem formula de calculo associada, obtem valor da formula
					if (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
					begin
						select @OUTValorNumerico = 0
						exec SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @proc, @ano
						if @OUTValorNumerico <> 0
							select @valhonor = @OUTValorNumerico
					end
-- agrava o valor dos honorários -----------------------------------------------------------
					IF @cdo_agra > 0 
						SELECT @valhonor = round(ISNULL(@valhonor, 0) + (ISNULL(@valhonor, 0)* (@cdo_agra/100)), 2)
-- desagrava o valor dos honorários --------------------------------------------------------
					IF @cdo_desa > 0 
						SELECT @valhonor = round(ISNULL(@valhonor, 0) - (ISNULL(@valhonor, 0)* (@cdo_desa/100)), 2)
				end
				else
					select @din_hono = NULL, @cdo_agra = 0, @cdo_desa = 0, @valhonor = 0
			end
			else
				select @din_hono = NULL, @cdo_agra = 0, @cdo_desa = 0, @valhonor = 0
		END
		ELSE
		BEGIN
			SET @din_hono = @CodRubHonorariosSAD
			SET @cdo_agra = 0
			SET @cdo_desa = 0
-- verifica se a exceção p/ calculo de honorarios se verifica		
			IF ((@GeraContaDVU = 0) and (@tdoc = 'CEXB') and (@ProcessoDVU = 0)) or (@GeraContaDVU = 1)
				SET @valhonor = 0
			ELSE
				SET @valhonor = dbo.FNT_CustomsBilling_CalculaValorTarifa(@IDTarifa, @ValorReferenciaTarifa, @ValorReferenciaTarifa, (@TotalRecapitulativo - @ValorIVAAdicoes), 1, @cli_desp, @TipoDestinatarioPC)
		END
-- verifica se Processo já possui Conta associada		
		SELECT @AnoConta = CDO_EANO, @IDConta = CDO_IDEN, @StatusConta = CDO_STAT, @TotalInerentes = ISNULL(CDO_TTIN, 0), 
			@TotalInerentesIsentoIVA = ISNULL((SELECT SUM(ISNULL(ICD_VTOT, 0)) FROM FAC_ICDO WHERE CDO_EANO = FAC_CDOC.CDO_EANO AND CDO_TDOC = FAC_CDOC.CDO_TDOC AND CDO_IDEN = FAC_CDOC.CDO_IDEN AND ICD_ISEN = 1), 0)
		FROM FAC_CDOC
		WHERE CDO_TDOC = @tdoc and CDO_IMEX = 0 and CDO_PANO = @ano AND CDO_NPRO = @proc --ligação c/ CDO_TDOC pq em processos DVU, 1 processo gera 2 contas
-- se Processo não possui Conta associada, cria Conta
		IF @AnoConta IS NULL
		BEGIN
			IF @ano = YEAR(GETDATE())
				SELECT @AnoConta = @ano
			ELSE
				SELECT @AnoConta = YEAR(GETDATE())
-- obtem próximo ID para Conta			
			SELECT @IDConta = ISNULL((MAX(CDO_IDEN) + 1), 1)
  			FROM FAC_CDOC
			WHERE CDO_TDOC = @tdoc AND CDO_EANO = @AnoConta			
-- insere nova Conta			
			INSERT INTO FAC_CDOC(CDO_EANO, CDO_TDOC, CDO_IDEN, NDE_CODI, CDO_NPRO, ALF_CODI, CDO_NORD, CDO_DTAC, CDO_DTAB, CLI_DESP, CLI_CCOR, CLI_ENDC, CDO_QUNT, CDO_PBRT, 
				CDO_PLIQ, CDO_VADU, MTR_CODI, CDO_MTRA, PAI_MTRA, CDO_ISIV, CDO_AGRA, CDO_DESA, CDO_FORH, CDO_DESC, CDO_MARC, CDO_RTFO, CDO_UCRI, CDO_DTCR, CDO_DTIN, CDO_STAT, 
				DIN_HONO, CDO_TTHO, CDO_TXIV, CDO_QUAL, CDO_CTMR, CDO_OBSR, CDO_UALT, CDO_DTAL, DEC_CODI, CDO_PANO, CDO_VREF, CDO_REGL, CDO_DTRL, CDO_MPAG, CDO_CPRT, CDO_CNOM, 
				CDO_CMOR, CDO_CLOC, CDO_CCPO, CDO_CLPO, CDO_CNIF, CDO_CPAI, CDO_CEAN, CDO_CTIP, IIV_CODI, FOR_CODI, FOR_NOME, CDO_IVAA, CCO_CODI, CDO_ORIG, CDO_CPAG)
			VALUES (@AnoConta, @tdoc, @IDConta, @nde_codi, @proc, @alf_codi, @cdo_nord, @DataOrdem, @cdo_dtab, @cli_desp, @cli_ccor, @cli_endc, @cdo_qunt, @cdo_pbrt, 
				@cdo_pliq, @cdo_vadu, @mtr_codi, @cdo_mtra, @pai_mtra, @cdo_isiv, @cdo_agra, @cdo_desa, @cdo_forh, @cdo_desc, @cdo_marc, @cdo_rtfo, @util, getdate(), @cdo_dtab, 0, 
				@din_hono, ISNULL(@valhonor,0), @cdo_txiv, @cdo_qual, @cdo_ctmr, @cdo_obsr, @util, getdate(), @dec_codi, @ano, @vRef, @regLiq, @dataReg, @mpag, @cartaPorte, @Nome, 
				@Morada, @Localidade, @CodPostal, @LocPostal, @NumContribuinte, @Pais, @CodigoEAN, @TipoCliente, @CodIsencaoIVA, @CodFornecedor, @NomeFornecedor, @ValorIVAAlfandega, 
				@CodChargeCode, @Origem, @CondPagamentoCliente)	
		END
		ELSE
-- actualiza dados da Conta apenas se "Status" estiver como "Em Curso"		
			IF @StatusConta = 0
			BEGIN													
				UPDATE FAC_CDOC SET NDE_CODI = @nde_codi, CDO_NPRO = @proc, ALF_CODI = @alf_codi, CDO_NORD = @cdo_nord, CDO_DTAC = @DataOrdem, CDO_DTAB = @cdo_dtab, 
					CLI_DESP = @cli_desp, CLI_CCOR = @cli_ccor, CLI_ENDC = @cli_endc, CDO_QUNT = @cdo_qunt, CDO_PBRT = @cdo_pbrt, CDO_PLIQ = @cdo_pliq, CDO_VADU = @cdo_vadu, 
					MTR_CODI = @mtr_codi, CDO_MTRA = @cdo_mtra, PAI_MTRA = @pai_mtra, CDO_ISIV = @cdo_isiv, CDO_AGRA = @cdo_agra, CDO_DESA = @cdo_desa, CDO_FORH = @cdo_forh, 
					CDO_DESC = @cdo_desc, CDO_MARC = @cdo_marc, CDO_RTFO = @cdo_rtfo, CDO_UALT = @util, CDO_DTAL = getdate(), DIN_HONO = @din_hono, CDO_TTHO = ISNULL(@valhonor,0), 
					CDO_TXIV = @cdo_txiv, CDO_QUAL = @cdo_qual, CDO_CTMR = @cdo_ctmr, CDO_OBSR = @cdo_obsr, DEC_CODI = @dec_codi, CDO_TTIN = ISNULL(@TotalInerentes,0), 
					CDO_PANO = @ano, CDO_IVA = ROUND((ISNULL(@valhonor,0) + ISNULL(@TotalInerentes,0) - ISNULL(@TotalInerentesIsentoIVA,0)) * (ISNULL(@cdo_txiv, 0) / 100), 2), 
					CDO_VREF = @vRef, CDO_REGL = @regLiq, CDO_DTRL = @dataReg, CDO_MPAG = @mpag, CDO_CPRT=@cartaPorte, CDO_CNOM = @Nome, CDO_CMOR = @Morada, 
					CDO_CLOC = @Localidade, CDO_CCPO = @CodPostal, CDO_CLPO = @LocPostal, CDO_CNIF = @NumContribuinte, CDO_CPAI = @Pais, CDO_CEAN = @CodigoEAN, 
					CDO_CTIP = @TipoCliente, IIV_CODI = @CodIsencaoIVA, FOR_CODI = @CodFornecedor, FOR_NOME = @NomeFornecedor, CDO_IVAA = @ValorIVAAlfandega, 
					CCO_CODI = @CodChargeCode, CDO_ORIG = @Origem, CDO_CPAG = @CondPagamentoCliente
				WHERE CDO_EANO = @AnoConta and CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
			END
			ELSE
				RETURN
-- remove detalhes da Conta		
		DELETE FROM FAC_DDCD 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta 
			AND EXISTS(SELECT DCD_LINH 
						FROM FAC_DCDO WITH(NOLOCK) 
						WHERE CDO_EANO = FAC_DDCD.CDO_EANO AND CDO_TDOC = FAC_DDCD.CDO_TDOC AND CDO_IDEN = FAC_DDCD.CDO_IDEN AND DCD_LINH = FAC_DDCD.DCD_LINH AND DCD_VFCX = 0)
		DELETE FROM FAC_DCDO 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_VFCX = 0		
		DELETE FROM FAC_DICD 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
		DELETE FROM FAC_ICDO 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta		
-- atualiza detalhe de despesas documentadas e respetivo sub-detalhe nos registos não removidos por serem de origem de "Folhas de Caixa"
		UPDATE FAC_DDCD SET DCD_LINH = (-1 * ddd.DCD_LINH)
		FROM FAC_DDCD AS ddd WITH(NOLOCK) INNER JOIN FAC_DCDO AS ddo WITH(NOLOCK) ON ddd.CDO_EANO = ddo.CDO_EANO AND ddd.CDO_TDOC = ddo.CDO_TDOC AND ddd.CDO_IDEN = ddo.CDO_IDEN AND ddd.DCD_LINH = ddo.DCD_LINH
		WHERE ddd.CDO_EANO = @AnoConta AND ddd.CDO_TDOC = @tdoc AND ddd.CDO_IDEN = @IDConta AND ddo.DCD_VFCX = 1
		UPDATE FAC_DCDO SET DCD_LINH = (-1 * DCD_LINH)
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_VFCX = 1		
-- insere as despesas documentadas 
		SELECT @cont = 1
		WHILE (@cont < 10)
		BEGIN
			IF NOT EXISTS(SELECT DCD_LINH FROM FAC_DCDO WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @cont)
			BEGIN
				INSERT INTO FAC_DCDO(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DCD_VTOT) 
				VALUES(@AnoConta, @tdoc, @IDConta, @cont, 0)
			END
			SELECT @cont = @cont + 1
		END
-- insere as despesas inerentes
		SELECT @cont = 1
		WHILE (@cont < 13)
		BEGIN
			INSERT INTO FAC_ICDO(CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, ICD_VTOT) 
			VALUES(@AnoConta, @tdoc, @IDConta, @cont, 0)
			SELECT @cont = @cont + 1
		END
-- inicia variaveis		
		SET @valorDocu = ISNULL((SELECT SUM(DCD_VTOT) FROM FAC_DCDO WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_VFCX = 1), 0)
		SELECT @TotalInerentes = 0
		SELECT @TotalInerentesIsentoIVA = 0
		SELECT @retfonte = 0
		SELECT @valIVA = 0
		SELECT @NumLinhaDespDoc = 0
-- se máscara a aplicar for a por defeito 
		IF @mascara = 0	
		BEGIN	
			-- despesas documentadas --------------------------------------------------
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT DDO_CODI, DDO_NOME, DDO_UCTE, isnull(DDO_FCLC, ''), DDO_CREC, CCO_CODI
				FROM TAB_DDOC WITH(NOLOCK) 
				WHERE DDO_CCDO = 1
			OPEN Detalhe
			FETCH NEXT from Detalhe into @despesa, @descri, @utiliza, @FormulaCalcValor, @CampoRecapitulativo, @CodChargeCode
			WHILE @@FETCH_STATUS = 0
			BEGIN						
				SET @valo = 0
				SET @NumLinhaDespDoc = @NumLinhaDespDoc + 1				
				IF @CampoRecapitulativo IS NOT NULL
				BEGIN
					IF @TipoEntidadeCaucao = 1 
						SET @valo = 0
					ELSE
						SET @valo = (CASE @CampoRecapitulativo 
										WHEN 1 THEN (CASE 
														WHEN (@GeraContaDVU = 0) and (@ProcessoDVU = 1) THEN (@TotalRecapitulativo - @ValorIVAAlfandega) 
														WHEN (@GeraContaDVU = 1) THEN @ValorIVAAlfandega 
														ELSE (@TotalRecapitulativo - @ValorIVAAdicoes) 
													END) 
										WHEN 2 THEN (CASE 
														WHEN (@GeraContaDVU = 1) THEN 0 
														ELSE @ValorDireitos 
													END) 
										WHEN 3 THEN (CASE 
														WHEN (@GeraContaDVU = 0) and (@ProcessoDVU = 1) THEN 0 
														ELSE (@ValorIVAAlfandega - @ValorIVAAdicoes) 
													END) 
										WHEN 4 THEN (CASE 
														WHEN (@GeraContaDVU = 1) THEN 0 
														ELSE (@TotalRecapitulativo - @ValorDireitos - @ValorIVAAlfandega) 
													END) 
										ELSE 0 
									END)
				END
				ELSE
				BEGIN
					if (@GeraContaDVU = 0) and (@utiliza = 1) AND (@trafego = 1) and (@cdo_pbrt > @limMax)
						SET @valo = @valorKg * CEILING(@cdo_pbrt) 
					else
						if @GeraContaDVU = 1
							SET @valo = 0
					if (@GeraContaDVU = 0) and (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
					begin
						SET @OUTValorNumerico = 0
						exec SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @proc, @ano
						if @OUTValorNumerico <> 0
							SET @valo = @OUTValorNumerico
					end				
				END			
				SET @valorDocu = @valorDocu + @valo	
				UPDATE FAC_DCDO SET DDO_CODI = @despesa, DCD_DESC = @descri, DCD_VTOT = @valo, CCO_CODI = @CodChargeCode
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @NumLinhaDespDoc
				FETCH NEXT from Detalhe into @despesa, @descri, @utiliza, @FormulaCalcValor, @CampoRecapitulativo, @CodChargeCode
			END
			CLOSE Detalhe
			DEALLOCATE Detalhe
			SET @UltNumLinhaDespDocInserida = @NumLinhaDespDoc
			-- despesas inerentes ------------------------------------------------------
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT DIN_PCDO, DIN_CODI, DIN_NOME, DIN_UCTE, isnull(DIN_FCLC, ''), CCO_CODI, DIN_ISEN, IIV_CODI, IIV_MENC
				FROM TAB_DINE WITH(NOLOCK) 
				WHERE DIN_CCDO = 1 and @ProcessamentoParteResto = 0
			OPEN Detalhe
			FETCH NEXT from Detalhe into @linha, @despesa, @descri, @utiliza, @FormulaCalcValor, @CodChargeCode, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, 
				@MencaoIsencaoIVADespInerente
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @valorTrafego = 0
				IF @despesa = @CodRubCaucao
					SET @valorTrafego = dbo.FNT_CustomsBilling_CalculaValorTarifa(@IDTarifa, @ValorReferenciaTarifa, (@TotalRecapitulativo - @ValorIVAAdicoes), (@TotalRecapitulativo - @ValorIVAAdicoes), 2, @cli_desp, @TipoDestinatarioPC)
				ELSE
					IF @despesa = @CodRubMultiClass
					BEGIN
						SET @valorTrafego = (CASE 
												WHEN (@NumTotalAdics - @NumAdicoesMultiClass) < 0 THEN 0 
												ELSE (@NumTotalAdics - @NumAdicoesMultiClass) 
											END) * @ValorPorAdicaoMultiClass
					END
					ELSE
						IF @despesa = @CodRubContactoObr
						BEGIN
							SET @valorTrafego = (CASE @ContactoObrigatorio 
													WHEN 1 THEN @ValorContactoObr 
													ELSE 0 
												END)
						END
						ELSE
						BEGIN
							if (@GeraContaDVU = 0) and (@utiliza = 1) AND (@trafego = 1) and (@cdo_pbrt > @limMax)
								SET @valorTrafego = @valorKg * CEILING(@cdo_pbrt) 
							if (@GeraContaDVU = 0) and (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
							begin
								SET @OUTValorNumerico = 0
								exec SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @proc, @ano
								if @OUTValorNumerico <> 0
									SET @valorTrafego = @OUTValorNumerico
							end
						END
				if @IsentaIVADespInerente = 1
					SET @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + @valorTrafego
				SELECT @TotalInerentes = @TotalInerentes + @valorTrafego
				UPDATE FAC_ICDO SET DIN_CODI = @despesa, ICD_DESC = @descri, ICD_VTOT = @valorTrafego, CCO_CODI = @CodChargeCode, ICD_ISEN = @IsentaIVADespInerente, 
					IIV_CODI = @CodIsencaoIVADespInerente, IIV_MENC = @MencaoIsencaoIVADespInerente
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @linha
				FETCH NEXT from Detalhe into @linha, @despesa, @descri, @utiliza, @FormulaCalcValor, @CodChargeCode, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, 
					@MencaoIsencaoIVADespInerente
			END
			CLOSE Detalhe
			DEALLOCATE Detalhe
		END
		ELSE
-- se máscara a aplicar for do cliente 
			IF @TipoMascara = 1 
			BEGIN
			-- despesas documentadas ---------------------------------------------------
				DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
					SELECT mas.DDO_CODI, ddo.DDO_UCTE, ISNULL(mas.MCD_VALO, 0), ddo.DDO_NOME, isnull(ddo.DDO_FCLC, ''), ddo.DDO_CREC, ddo.CCO_CODI
					FROM TAB_MCDO as mas WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON mas.DDO_CODI = ddo.DDO_CODI						
					WHERE mas.CLI_CODI = @cli_ccor AND mas.MCF_CODI = @mascara
				OPEN Detalhe
				FETCH NEXT from Detalhe into @despesa, @utiliza, @valo, @descri, @FormulaCalcValor, @CampoRecapitulativo, @CodChargeCode
				WHILE @@FETCH_STATUS = 0
				BEGIN	
					SET @NumLinhaDespDoc = @NumLinhaDespDoc + 1					
					IF @CampoRecapitulativo IS NOT NULL					
					BEGIN
						IF @TipoEntidadeCaucao = 1 
							SET @valo = 0
						ELSE
							SET @valo = (CASE @CampoRecapitulativo 
											WHEN 1 THEN (CASE 
															WHEN (@GeraContaDVU = 0) and (@ProcessoDVU = 1) THEN (@TotalRecapitulativo - @ValorIVAAlfandega) 
															WHEN (@GeraContaDVU = 1) THEN @ValorIVAAlfandega 
															ELSE (@TotalRecapitulativo - @ValorIVAAdicoes) 
														END) 
											WHEN 2 THEN (CASE 
															WHEN (@GeraContaDVU = 1) THEN 0 
															ELSE @ValorDireitos 
														END) 
											WHEN 3 THEN (CASE 
															WHEN (@GeraContaDVU = 0) and (@ProcessoDVU = 1) THEN 0 
															ELSE (@ValorIVAAlfandega - @ValorIVAAdicoes) 
														END) 
											WHEN 4 THEN (CASE 
															WHEN (@GeraContaDVU = 1) THEN 0 
															ELSE (@TotalRecapitulativo - @ValorDireitos - @ValorIVAAlfandega) 
														END) 
											ELSE 0 
										END)
					END
					ELSE
					BEGIN							
						if (@GeraContaDVU = 0) and (@utiliza = 1) AND (@trafego = 1) and (@cdo_pbrt > @limMax)
							SET @valo = @valorKg * CEILING(@cdo_pbrt) 						
						else
							if @GeraContaDVU = 1
								SET @valo = 0							
						if (@GeraContaDVU = 0) and (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
						begin							
							SET @OUTValorNumerico = 0
							exec SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @proc, @ano
							if @OUTValorNumerico <> 0
								SET @valo = @OUTValorNumerico
						end
					END					
					SET @valorDocu = @valorDocu + @valo				
					UPDATE FAC_DCDO SET DDO_CODI = @despesa, DCD_DESC = @descri, DCD_VTOT = @valo, CCO_CODI = @CodChargeCode
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @NumLinhaDespDoc
					FETCH NEXT from Detalhe into @despesa, @utiliza, @valo, @descri, @FormulaCalcValor, @CampoRecapitulativo, @CodChargeCode
				END
				CLOSE Detalhe
				DEALLOCATE Detalhe
				SET @UltNumLinhaDespDocInserida = @NumLinhaDespDoc
			-- despesas inerentes ------------------------------------------------------	
				DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
					SELECT m.MCI_POSI, m.DIN_CODI, m.MCI_VALO, d.DIN_UCTE, d.DIN_NOME, isnull(d.DIN_FCLC, ''), d.CCO_CODI, d.DIN_ISEN, d.IIV_CODI, d.IIV_MENC
					FROM TAB_MCIN as m WITH(NOLOCK) INNER JOIN TAB_DINE as d WITH(NOLOCK) ON m.DIN_CODI = d.DIN_CODI
					WHERE m.CLI_CODI = @cli_ccor AND m.MCF_CODI = @mascara and @ProcessamentoParteResto = 0
				OPEN Detalhe
				FETCH NEXT from Detalhe into @linha, @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @CodChargeCode, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, 
					@MencaoIsencaoIVADespInerente
				WHILE @@FETCH_STATUS = 0
				BEGIN			
					IF @despesa = @CodRubCaucao
						SET @valo = dbo.FNT_CustomsBilling_CalculaValorTarifa(@IDTarifa, @ValorReferenciaTarifa, (@TotalRecapitulativo - @ValorIVAAdicoes), (@TotalRecapitulativo - @ValorIVAAdicoes), 2, @cli_desp, @TipoDestinatarioPC)
					ELSE
						IF @despesa = @CodRubMultiClass
						BEGIN
							SET @valo = (CASE 
											WHEN (@NumTotalAdics - @NumAdicoesMultiClass) < 0 THEN 0 
											ELSE (@NumTotalAdics - @NumAdicoesMultiClass) 
										END) * @ValorPorAdicaoMultiClass
						END
						ELSE
							IF @despesa = @CodRubContactoObr
							BEGIN
								SET @valo = (CASE @ContactoObrigatorio 
												WHEN 1 THEN @ValorContactoObr 
												ELSE 0 
											END)
							END
							ELSE
							BEGIN
								if (@GeraContaDVU = 0) and (@utiliza = 1) AND (@trafego = 1) and (@cdo_pbrt > @limMax)
									SET @valo = @valorKg * CEILING(@cdo_pbrt) 
								else
									if @GeraContaDVU = 1
										SET @valo = 0
								if (@GeraContaDVU = 0) and (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
								begin
									SET @OUTValorNumerico = 0
									exec SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @proc, @ano
									if @OUTValorNumerico <> 0
										SET @valo = @OUTValorNumerico
								end
							END
					if @IsentaIVADespInerente = 1
						SET @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + @valo
					SET @TotalInerentes = @TotalInerentes + @valo
					UPDATE FAC_ICDO SET DIN_CODI = @despesa, ICD_DESC = @descri, ICD_VTOT = @valo, CCO_CODI = @CodChargeCode, ICD_ISEN = @IsentaIVADespInerente, 
						IIV_CODI = @CodIsencaoIVADespInerente, IIV_MENC = @MencaoIsencaoIVADespInerente
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @linha
					FETCH NEXT from Detalhe into @linha, @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @CodChargeCode, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, 
						@MencaoIsencaoIVADespInerente
				END
				CLOSE Detalhe
				DEALLOCATE Detalhe
			END
-- se máscara a aplicar for da natureza
			ELSE
			BEGIN
			-- despesas documentadas ---------------------------------------------------
				DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
					select mas.DDO_CODI, ddo.DDO_UCTE, ISNULL(mas.MND_VALO, 0), ddo.DDO_NOME, isnull(ddo.DDO_FCLC, ''), ddo.DDO_CREC, ddo.CCO_CODI
					from TAB_MNDO as mas WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON mas.DDO_CODI = ddo.DDO_CODI						
					where mas.NDE_CODI = @nde_codi and mas.MNF_CODI = @mascara 
				OPEN Detalhe
				FETCH NEXT from Detalhe into @despesa, @utiliza, @valo, @descri, @FormulaCalcValor, @CampoRecapitulativo, @CodChargeCode
				WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @NumLinhaDespDoc = @NumLinhaDespDoc + 1					
					IF @CampoRecapitulativo IS NOT NULL			
					BEGIN		
						IF @TipoEntidadeCaucao = 1 
							SET @valo = 0
						ELSE
							SET @valo = (CASE @CampoRecapitulativo 
											WHEN 1 THEN (CASE 
															WHEN (@GeraContaDVU = 0) and (@ProcessoDVU = 1) THEN (@TotalRecapitulativo - @ValorIVAAlfandega) 
															WHEN (@GeraContaDVU = 1) THEN @ValorIVAAlfandega 
															ELSE (@TotalRecapitulativo - @ValorIVAAdicoes) 
														END) 
											WHEN 2 THEN (CASE 
															WHEN (@GeraContaDVU = 1) THEN 0 
															ELSE @ValorDireitos 
														END) 
											WHEN 3 THEN (CASE 
															WHEN (@GeraContaDVU = 0) and (@ProcessoDVU = 1) THEN 0 
															ELSE (@ValorIVAAlfandega - @ValorIVAAdicoes) 
														END) 
											WHEN 4 THEN (CASE 
															WHEN (@GeraContaDVU = 1) THEN 0 
															ELSE (@TotalRecapitulativo - @ValorDireitos - @ValorIVAAlfandega) 
														END) 
											ELSE 0 
										END)					
					END
					ELSE
					BEGIN
						if (@GeraContaDVU = 0) and (@utiliza = 1) AND (@trafego = 1) and (@cdo_pbrt > @limMax)
							SET @valo = @valorKg * CEILING(@cdo_pbrt)
						else
							if @GeraContaDVU = 1
								SET @valo = 0 
						if (@GeraContaDVU = 0) and (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
						begin
							SET @OUTValorNumerico = 0
							exec SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @proc, @ano
							if @OUTValorNumerico <> 0
								SET @valo = @OUTValorNumerico
						end
					END
					SET @valorDocu = @valorDocu + @valo				
					UPDATE FAC_DCDO SET DDO_CODI = @despesa, DCD_DESC = @descri, DCD_VTOT = @valo, CCO_CODI = @CodChargeCode
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @NumLinhaDespDoc
					FETCH NEXT from Detalhe into @despesa, @utiliza, @valo, @descri, @FormulaCalcValor, @CampoRecapitulativo, @CodChargeCode
				END
				CLOSE Detalhe
				DEALLOCATE Detalhe
				SET @UltNumLinhaDespDocInserida = @NumLinhaDespDoc
			-- despesas inerentes ------------------------------------------------------	
				select @linha = 0
				DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
					select m.DIN_CODI, m.MNI_VALO, d.DIN_UCTE, d.DIN_NOME, isnull(d.DIN_FCLC, ''), d.CCO_CODI, d.DIN_ISEN, d.IIV_CODI, d.IIV_MENC
					from TAB_MNIN as m WITH(NOLOCK) INNER JOIN TAB_DINE as d WITH(NOLOCK) ON m.DIN_CODI = d.DIN_CODI
					where m.NDE_CODI = @nde_codi and m.MNF_CODI = @mascara and @ProcessamentoParteResto = 0
				OPEN Detalhe
				FETCH NEXT from Detalhe into @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @CodChargeCode, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, 
					@MencaoIsencaoIVADespInerente
				WHILE @@FETCH_STATUS = 0
				BEGIN			
					select @linha = @linha + 1
					IF @despesa = @CodRubCaucao
						SET @valo = dbo.FNT_CustomsBilling_CalculaValorTarifa(@IDTarifa, @ValorReferenciaTarifa, (@TotalRecapitulativo - @ValorIVAAdicoes), (@TotalRecapitulativo - @ValorIVAAdicoes), 2, @cli_desp, @TipoDestinatarioPC)
					ELSE
						IF @despesa = @CodRubMultiClass
						BEGIN
							SET @valo = (CASE 
											WHEN (@NumTotalAdics - @NumAdicoesMultiClass) < 0 THEN 0 
											ELSE (@NumTotalAdics - @NumAdicoesMultiClass) 
										END) * @ValorPorAdicaoMultiClass
						END
						ELSE
							IF @despesa = @CodRubContactoObr
							BEGIN
								SET @valo = (CASE @ContactoObrigatorio 
												WHEN 1 THEN @ValorContactoObr 
												ELSE 0 
											END)
							END
							ELSE
							BEGIN
								if (@GeraContaDVU = 0) and (@utiliza = 1) AND (@trafego = 1) and (@cdo_pbrt > @limMax) 
									SET @valo = @valorKg * CEILING(@cdo_pbrt) 
								else
									if @GeraContaDVU = 1
										SET @valo = 0
								if (@GeraContaDVU = 0) and (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
								begin
									SET @OUTValorNumerico = 0
									exec SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @proc, @ano
									if @OUTValorNumerico <> 0
										SET @valo = @OUTValorNumerico
								end
							END
					if @IsentaIVADespInerente = 1
						SET @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + @valo
					SET @TotalInerentes = @TotalInerentes + @valo
					UPDATE FAC_ICDO SET DIN_CODI = @despesa, ICD_DESC = @descri, ICD_VTOT = @valo, CCO_CODI = @CodChargeCode, ICD_ISEN = @IsentaIVADespInerente, 
						IIV_CODI = @CodIsencaoIVADespInerente, IIV_MENC = @MencaoIsencaoIVADespInerente
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @linha
					FETCH NEXT from Detalhe into @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @CodChargeCode, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, 
						@MencaoIsencaoIVADespInerente
				END
				CLOSE Detalhe
				DEALLOCATE Detalhe
			END
-- exclui do valor da caução a soma do montante IVA das adições da declaração cujo cliente é "Beneficiário IVA"
		SET @valorCauc = @valorCauc - @ValorIVAAdicoes
-- trata despesa inerente relativa à caução		
		IF (@GeraContaDVU = 0) and (@valorCauc <> 0)
		BEGIN
			-- busca código da despesa inerente ----------------------------------------
			SELECT  @despesaCauc = DIN_CODI, @descriCauc = DIN_NOME, @CodChargeCode = CCO_CODI, @IsentaIVADespInerente = DIN_ISEN, @CodIsencaoIVADespInerente = IIV_CODI, 
				@MencaoIsencaoIVADespInerente = IIV_MENC
			FROM TAB_DINE WITH(NOLOCK) 
			WHERE DIN_CODI = @CodDespInerenteClienteCC			
			IF (@despesaCauc <> '') AND (@taxaCauc <> 0)
			BEGIN
				SELECT @contCauc = COUNT(*) 
				FROM FAC_ICDO
				WHERE DIN_CODI = @despesaCauc AND CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
				-- verifica se já existe linha com despesa --------------------------
				IF @contCauc > 0 
				BEGIN
					SELECT @valorAnt = ISNULL(ICD_VTOT, 0)
					FROM FAC_ICDO
					WHERE DIN_CODI = @despesaCauc AND CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta

					if @IsentaIVADespInerente = 1
						SET @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA - @valorAnt + ROUND(@valorCauc * (@taxaCauc / 100), 2)
					SET @TotalInerentes = @TotalInerentes - @valorAnt + ROUND(@valorCauc * (@taxaCauc / 100), 2)

					UPDATE FAC_ICDO SET ICD_VTOT = ROUND(@valorCauc * (@taxaCauc / 100), 2), CCO_CODI = @CodChargeCode, ICD_ISEN = @IsentaIVADespInerente, 
						IIV_CODI = @CodIsencaoIVADespInerente, IIV_MENC = @MencaoIsencaoIVADespInerente
					WHERE DIN_CODI = @despesaCauc AND CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
				END
				ELSE
				BEGIN
					-- busca posição da linha ----------------------------------
					SELECT @contCauc = COUNT(*) 
					FROM FAC_ICDO
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DIN_CODI <> ''					
					IF (@contCauc + 1) <= 12 
					BEGIN
						if @IsentaIVADespInerente = 1
							SET @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + ROUND(@valorCauc * (@taxaCauc / 100), 2)
						SET @TotalInerentes = @TotalInerentes + ROUND(@valorCauc * (@taxaCauc / 100), 2)

						UPDATE FAC_ICDO SET DIN_CODI = @despesaCauc, ICD_DESC = @descriCauc, ICD_VTOT = ROUND(@valorCauc * (@taxaCauc / 100), 2), CCO_CODI = @CodChargeCode, 
							ICD_ISEN = @IsentaIVADespInerente, IIV_CODI = @CodIsencaoIVADespInerente, IIV_MENC = @MencaoIsencaoIVADespInerente
						WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @contCauc + 1
					END
				END
			END	
		END
-- atualiza detalhe de despesas documentadas de origem de "Folhas de Caixa" e respetivo sub-detalhe para atualizar o número da linha
		DECLARE DespDocumentadas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT DCD_LINH
			FROM FAC_DCDO WITH(NOLOCK) 
			WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_VFCX = 1
			ORDER BY DCD_LINH DESC
		OPEN DespDocumentadas
		FETCH NEXT FROM DespDocumentadas INTO @linha
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @UltNumLinhaDespDocInserida = @UltNumLinhaDespDocInserida + 1
-- remove a linha já existente para o novo número de linha
			DELETE FROM FAC_DCDO 
			WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @UltNumLinhaDespDocInserida			
-- atribui novo número de linha à despesa documentada
			UPDATE FAC_DCDO SET DCD_LINH = @UltNumLinhaDespDocInserida
			WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @linha			
-- atribui novo número de linha ao sub-detalhe da despesa documentada
			UPDATE FAC_DDCD SET DCD_LINH = @UltNumLinhaDespDocInserida
			WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @linha
			FETCH NEXT FROM DespDocumentadas INTO @linha
		END
		CLOSE DespDocumentadas
		DEALLOCATE DespDocumentadas
-- trata despesas documentadas extra associadas ao DU Importação (só no caso de utilizar "Interface DU/Contas (Aut. Saida)")
		IF (@GeraContaDVU = 0) and (@NaturezaDUContasAutSaida = 1)
		BEGIN
			SET @linha = @UltNumLinhaDespDocInserida
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				select u.DDO_CODI, u.DDD_VALO, d.DDO_NOME, d.CCO_CODI
				from PRO_DUDD as u WITH(NOLOCK) INNER JOIN TAB_DDOC as d WITH(NOLOCK) ON u.DDO_CODI = d.DDO_CODI
				where u.DUC_PNUM = @proc and u.DUC_EANO = @ano
			OPEN Detalhe
			FETCH NEXT from Detalhe into @despesa, @valo, @descri, @CodChargeCode
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @linha = @linha + 1
				SET @valorDocu = @valorDocu + @valo				
				UPDATE FAC_DCDO SET DDO_CODI = @despesa, DCD_DESC = @descri, DCD_VTOT = @valo, CCO_CODI = @CodChargeCode
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @linha
				FETCH NEXT from Detalhe into @despesa, @valo, @descri, @CodChargeCode
			END
			CLOSE Detalhe
			DEALLOCATE Detalhe
		END
-- calcula valor total da retenção na fonte
		SET @retfonte = ROUND((@TotalInerentes + ISNULL(@valhonor, 0)) * (@cdo_rtfo / 100), 2)
-- calculo valor total do IVA
		SET @valIVA = ROUND((ISNULL(@valhonor, 0) + @TotalInerentes - @TotalInerentesIsentoIVA) * (@cdo_txiv / 100), 2)
-- actualiza valores totais da Conta
		UPDATE FAC_CDOC SET CDO_TTDC = @valorDocu, CDO_TTIN = @TotalInerentes, CDO_TTRF = @retfonte, CDO_IVA = @valIVA, 
			CDO_TTPR = (@valorDocu + @TotalInerentes + ISNULL(@valhonor, 0) + @valIVA), 
			CDO_IN01 = (@valorDocu + (CASE WHEN (CDO_TXIV = 0) THEN (@TotalInerentes + ISNULL(@valhonor, 0)) ELSE @TotalInerentesIsentoIVA END)), 
			CDO_IN02 = 0, CDO_IN03 = 0, CDO_IN04 = (CASE WHEN (CDO_TXIV > 0) THEN (@TotalInerentes - @TotalInerentesIsentoIVA + ISNULL(@valhonor, 0)) ELSE 0 END), 
			CDO_VI01 = 0, CDO_VI02 = 0, CDO_VI03 = 0, CDO_VI04 = @valIVA
		WHERE CDO_EANO = @AnoConta and CDO_TDOC = @tdoc and CDO_IDEN = @IDConta
-- se for processo de gerar Doc. Conta Normal e Processo DU for DVU, gera novo Doc. Conta DVU
		IF (@GeraContaDVU = 0) and (@ProcessoDVU = 1)
		BEGIN
			exec SP_ObtemMascaraFacturacao @cli_desp, @CodNaturezaDVU, @contador OUTPUT, @TipoMascaraDVU OUTPUT, @MascaraDVU OUTPUT
			exec SP_ObtemObservacoesParaConta @MascaraDVU, @ano, @proc, @cli_desp, @CodNaturezaDVU, '', @ObservacoesDVU OUTPUT
			exec SP_geraContas @proc, @ano, @TipoDocContaDVU, @CodNaturezaDVU, @util, @TipoMascaraDVU, @MascaraDVU, 0, @ObservacoesDVU, 0, @cartaPorte, 1, @TipoCliente, @Origem
		END
	END
END

ALTER AUTHORIZATION ON [SP_geraContas] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraContas] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraContasExportXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraContasExportXML] @proc int, @ano int, @operador varchar(6), @tdoc varchar(4), @util varchar(30), @TipoMascara int, @mascara int, @valhonor numeric(38,6), @valadua numeric(38,6), 
	@cdo_obsr varchar(500), @valorCauc numeric(38,6), @TipoCliente varchar(3) AS
BEGIN
SET DATEFORMAT DMY
-- declaracoes de variaveis 
declare @AnoConta int, @IDConta int, @StatusConta int, @contador int, @alf_codi varchar(8), @cdo_nord varchar(25), @cdo_dtab datetime, @cli_desp varchar(18), @cli_ccor varchar(18), 
	@cli_endc varchar(18), @cdo_qunt numeric(38,6), @cdo_pbrt numeric(38,6), @cdo_pliq numeric(38,6), @cdo_vadu numeric(38,6), @mtr_codi varchar(2), @cdo_mtra varchar(30), @pai_mtra varchar(2), 
	@cdo_isiv varchar(100), @cdo_agra numeric(38,6), @cdo_desa numeric(38,6), @cdo_forh varchar(4000), @cdo_desc varchar(40), @cdo_marc varchar(44), @cdo_rtfo numeric(38,6), @valor numeric(38,6), 
	@din_hono int, @linha int, @despesa int, @descri varchar(70), @valo numeric(38,6), @cont int, @valorDocu numeric(38,6), @TotalInerentes numeric(38,6), @retfonte numeric(38,6), 
	@valIVA numeric(38,6), @cdo_txiv numeric(38,6), @TotalInerentesIsentoIVA numeric(38,6), @cdo_qual varchar(35), @cdo_ctmr varchar(20), @liqRecap numeric(38,6), @dec_codi varchar(6), 
	@nde_codi varchar(3), @despesaCauc int, @descriCauc varchar(70), @taxaCauc numeric(38,6), @contCauc int, @valorAnt numeric(38,6), @mpag int, @trafego bit, @limMax numeric(38,6), 
	@valorKg numeric(38,6), @utiliza bit, @valorTrafego numeric(38,6), @NumRefInt int, @NumVossaRef varchar(50), @Nome varchar(70), @Morada varchar(70), @Localidade varchar(35), 
	@CodPostal varchar(12), @LocPostal varchar(35), @NumContribuinte varchar(18), @Pais varchar(2), @NumCPA varchar(18), @CodigoEAN varchar(13), @DataOrdem datetime, @CodIsencaoIVA varchar(3), 
	@CodFornecedor varchar(18), @NomeFornecedor varchar(70), @CodDespInerenteClienteCC int, @CondPagamentoCliente int, @NaturezaDUContasAutSaida bit, @FormulaCalcValor varchar(4000), 
	@OUTValorNumerico numeric(38, 6), @IsentaIVADespInerente bit, @CodIsencaoIVADespInerente varchar(3), @MencaoIsencaoIVADespInerente varchar(100)
-- busca registo da tabela XML
select @NumRefInt = d.EXM_NRII, @nde_codi = d.NDE_CODI, @alf_codi = d.EAD_CODA, @cdo_nord = d.EXM_NDGA, @DataOrdem = d.EXM_DDGA, @cdo_dtab = CAST(CONVERT(varchar(10), d.EXM_DATA, 105) as datetime), 
	@cdo_qunt = d.EXM_TVL6, @cdo_pbrt = d.EXM_TMBR, @cdo_pliq = d.EXM_TMLQ, @mtr_codi = d.MTR_CO25,	@cdo_mtra = d.EXM_MT21, @pai_mtra = d.PAI_CO21, @dec_codi = d.DEC_CO14, 
	@NumVossaRef = d.EXM_NVRF, @cli_endc = ISNULL(c.CLI_ECON, d.CLI_COD2), @NumCPA = d.EXM_CPRT, @CodFornecedor = NULLIF(d.FOR_COD8, ''), @NomeFornecedor = d.FOR_NOM8, @trafego = n.NDE_CTEN, 
	@limMax = n.NDE_LMAX, @valorKg = n.NDE_VLKG, @CodIsencaoIVA = n.IIV_CODI, @cdo_isiv = (select IIV_MENC from GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) where IIV_CODI = n.IIV_CODI), 
	@cdo_agra = n.NDE_AHON, @cdo_desa = n.NDE_DHON, @cdo_forh = n.NDE_FORM, @cdo_txiv = n.NDE_TIVA, 
	@NaturezaDUContasAutSaida = (case when (isnull(n.NDE_TLCV, -1) = 0) then cast(1 as bit) else cast(0 as bit) end), @cdo_desc = a.APA_DESG, 	
	@cdo_marc = (SELECT TOP 1 EXM_MARN FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = a.EXA_CHVE), @cdo_qual = (SELECT TOP 1 TEM_NOME FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = a.EXA_CHVE), 
	@cdo_rtfo = (SELECT PFC_RFNT FROM TAB_PFCT WITH(NOLOCK)), @cdo_ctmr = (SELECT TOP 1 EXD_DESC FROM PRO_EXDS WITH(NOLOCK) WHERE EXA_CHVE = a.EXA_CHVE), @cli_desp = d.CLI_COD2, 
	@cli_ccor = ISNULL(c.CLI_CCOR, d.CLI_COD2)
FROM PRO_EXML as d WITH(NOLOCK) INNER JOIN TAB_CLIE as c WITH(NOLOCK) ON d.CLI_COD2 = c.CLI_CODI
	INNER JOIN TAB_NDES as n WITH(NOLOCK) ON d.NDE_CODI = n.NDE_CODI
	LEFT OUTER JOIN PRO_EXAD as a WITH(NOLOCK) ON d.EXM_CODI = a.EXM_CODI AND d.EXM_EANO = a.EXM_EANO AND d.DEC_CODI = a.EXM_COPE AND a.EXA_LINH = 1
WHERE d.EXM_CODI = @proc AND d.EXM_EANO = @ano AND d.DEC_CODI = @operador
	
IF @cli_desp <> '' 
BEGIN
-- busca a soma do valor estatistico das adicoes
	select @cdo_vadu = isnull(sum(isnull(EXA_VEST, 0)), 0)
	from PRO_EXAD WITH(NOLOCK)
	where EXM_CODI = @proc and EXM_EANO = @ano and EXM_COPE = @operador
-- obtem dados do cliente de conta corrente
	SELECT @Nome = CLI_NOME, @Morada = CLI_MORA, @Localidade = CLI_LOCA, @CodPostal = CLI_CPOS, @LocPostal = CLI_LPOS, @NumContribuinte = CLI_NIF, @Pais = PAI_CODI, @mpag = CLI_MPAG, 
		@CodigoEAN = CLI_CEAN, @CodDespInerenteClienteCC = DIN_CODI, @taxaCauc = ISNULL(CLI_SUCA, 0), @CondPagamentoCliente = CLI_CPAG
	FROM TAB_CLIE WITH(NOLOCK)
	WHERE CLI_CODI = @cli_ccor	
-- obtem despesa inerente de Honorarios
	SELECT @din_hono = DIN_CODI, @FormulaCalcValor = isnull(DIN_FCLE, '')
	FROM TAB_DINE WITH(NOLOCK)
	WHERE DIN_CODI = 13
-- se despesa inerente de Honorarios existe, obtem valor de honorários
	if @din_hono is not null
	begin			
-- obtem valores de Honorarios nas Mascaras
		if @mascara > 0  
		begin
			if @TipoMascara = 1 
			begin
				SELECT @cdo_agra = MCF_VAGR, @cdo_desa = MCF_VDES, @valor = MCF_VALO
				FROM TAB_MCFT WITH(NOLOCK)
				WHERE CLI_CODI = @cli_ccor AND MCF_CODI = @mascara	
			end
			else
			begin
				select @cdo_agra = MNF_VAGR, @cdo_desa = MNF_VDES, @valor = MNF_VALO
				FROM TAB_MNFT WITH(NOLOCK)
				WHERE NDE_CODI = @nde_codi and MNF_CODI = @mascara	
			end
		end	
		else
			select @cdo_agra = 0, @cdo_desa = 0
-- se tem valor atribuido ------------------------------------------------------------------
		IF @valor > 0 
			SELECT @valhonor = @valor
-- se utiliza Interface Du/Contas (Aut. Saida) e desp. inerente de Honorarios tem formula de calculo associada, obtem valor da formula
		IF (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
		BEGIN
			SELECT @OUTValorNumerico = 0
			EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @ano, @proc, @operador
			IF @OUTValorNumerico <> 0
				SELECT @valhonor = @OUTValorNumerico
		END	
	-- agrava o valor dos honorários -----------------------------------------------------------
		IF @cdo_agra > 0 
			SELECT @valhonor = round(@valhonor + (@valhonor* (@cdo_agra/100)), 2)
	-- desagrava o valor dos honorários --------------------------------------------------------
		IF @cdo_desa > 0 
			SELECT @valhonor = round(@valhonor - (@valhonor* (@cdo_desa/100)), 2)
	end
	else
		select @din_hono = NULL, @cdo_agra = 0, @cdo_desa = 0, @valhonor = 0
-- verifica se Declaração já possui Conta associada		
	SELECT @AnoConta = CDO_EANO, @IDConta = CDO_IDEN, @StatusConta = CDO_STAT, @TotalInerentes = ISNULL(CDO_TTIN, 0), 
		@TotalInerentesIsentoIVA = ISNULL((SELECT SUM(ISNULL(ICD_VTOT, 0)) FROM FAC_ICDO WHERE CDO_EANO = FAC_CDOC.CDO_EANO AND CDO_TDOC = FAC_CDOC.CDO_TDOC AND CDO_IDEN = FAC_CDOC.CDO_IDEN AND ICD_ISEN = 1), 0)
	FROM FAC_CDOC 
	WHERE CDO_IMEX = 1 and CDO_PANO = @ano AND CDO_NPRO = @NumRefInt AND EXM_OPER = @operador
-- se Declaração não possui Conta associada, cria Conta
	IF @AnoConta IS NULL
	BEGIN
		SELECT @AnoConta = @ano
-- obtem próximo ID para Conta			
		SELECT @IDConta = ISNULL((MAX(CDO_IDEN) + 1), 1)
  		FROM FAC_CDOC
		WHERE CDO_TDOC = @tdoc AND CDO_EANO = @AnoConta			
-- insere nova Conta			
		INSERT INTO FAC_CDOC(CDO_EANO, CDO_TDOC, CDO_IDEN, NDE_CODI, CDO_NPRO, ALF_CODI, CDO_NORD, CDO_DTAC, CDO_DTAB, CLI_DESP, CLI_CCOR, CLI_ENDC, CDO_QUNT, CDO_PBRT, CDO_PLIQ, CDO_VADU, 
			MTR_CODI, CDO_MTRA, PAI_MTRA, CDO_ISIV, CDO_AGRA, CDO_DESA, CDO_FORH, CDO_DESC, CDO_MARC, CDO_RTFO, CDO_UCRI, CDO_DTCR, CDO_DTIN, CDO_STAT, DIN_HONO, CDO_TTHO, CDO_TXIV, CDO_QUAL, 
			CDO_CTMR, CDO_OBSR, CDO_UALT, CDO_DTAL, DEC_CODI, CDO_PANO, CDO_VREF, CDO_MPAG, EXM_OPER, CDO_IMEX, CDO_CNOM, CDO_CMOR, CDO_CLOC, CDO_CCPO, CDO_CLPO, CDO_CNIF, CDO_CPAI, CDO_CPRT, 
			CDO_CEAN, CDO_CTIP, IIV_CODI, FOR_CODI, FOR_NOME, CDO_CPAG)
		VALUES (@AnoConta, @tdoc, @IDConta, @nde_codi, @NumRefInt, @alf_codi, @cdo_nord, @DataOrdem, @cdo_dtab, @cli_desp, @cli_ccor, @cli_endc, @cdo_qunt, @cdo_pbrt, @cdo_pliq, @cdo_vadu, 
			@mtr_codi, @cdo_mtra, @pai_mtra, @cdo_isiv, @cdo_agra, @cdo_desa, @cdo_forh, @cdo_desc, @cdo_marc, @cdo_rtfo, @util, getdate(), @cdo_dtab, 0, @din_hono, @valhonor, @cdo_txiv, @cdo_qual, 
			@cdo_ctmr, @cdo_obsr, @util, getdate(), @dec_codi, @ano, @NumVossaRef, @mpag, @operador, 1, @Nome, @Morada, @Localidade, @CodPostal, @LocPostal, @NumContribuinte, @Pais, @NumCPA, 
			@CodigoEAN, @TipoCliente, @CodIsencaoIVA, @CodFornecedor, @NomeFornecedor, @CondPagamentoCliente)	
	END
	ELSE
-- actualiza dados da Conta apenas se "Status" estiver como "Em Curso"		
		IF @StatusConta = 0
		BEGIN						
			UPDATE FAC_CDOC SET NDE_CODI = @nde_codi, ALF_CODI = @alf_codi, CDO_NORD = @cdo_nord, CDO_DTAC = @DataOrdem, CDO_DTAB = @cdo_dtab, CLI_DESP = @cli_desp, CLI_CCOR = @cli_ccor, 
				CLI_ENDC = @cli_endc, CDO_QUNT = @cdo_qunt, CDO_PBRT = @cdo_pbrt, CDO_PLIQ = @cdo_pliq, CDO_VADU = @cdo_vadu, MTR_CODI = @mtr_codi, CDO_MTRA = @cdo_mtra, PAI_MTRA = @pai_mtra, 
				CDO_ISIV = @cdo_isiv, CDO_AGRA = @cdo_agra, CDO_DESA = @cdo_desa, CDO_FORH = @cdo_forh, CDO_DESC = @cdo_desc, CDO_MARC = @cdo_marc, CDO_RTFO = @cdo_rtfo, CDO_UALT = @util, 
				CDO_DTAL = getdate(), DIN_HONO = @din_hono, CDO_TTHO = @valhonor, CDO_TXIV = @cdo_txiv, CDO_QUAL = @cdo_qual, CDO_CTMR = @cdo_ctmr, CDO_OBSR = @cdo_obsr, DEC_CODI = @dec_codi, 
				CDO_TTIN = ISNULL(@TotalInerentes,0), CDO_IVA = ROUND((ISNULL(@valhonor,0) + ISNULL(@TotalInerentes,0) - ISNULL(@TotalInerentesIsentoIVA,0)) * (ISNULL(@cdo_txiv, 0) / 100), 2), 
				CDO_VREF = @NumVossaRef, CDO_MPAG = @mpag, CDO_CNOM = @Nome, CDO_CMOR = @Morada, CDO_CLOC = @Localidade, CDO_CCPO = @CodPostal, CDO_CLPO = @LocPostal, CDO_CNIF = @NumContribuinte, 
				CDO_CPAI = @Pais, CDO_CPRT = @NumCPA, CDO_CEAN = @CodigoEAN, CDO_CTIP = @TipoCliente,IIV_CODI = @CodIsencaoIVA, FOR_CODI = @CodFornecedor, FOR_NOME = @NomeFornecedor, 
				CDO_CPAG = @CondPagamentoCliente	
			WHERE CDO_EANO = @AnoConta and CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
		END
		ELSE
			RETURN
-- remove detalhes da Conta	
	DELETE FROM FAC_DCDO 
	WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
	DELETE FROM FAC_DDCD 
	WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
	DELETE FROM FAC_ICDO 
	WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
	DELETE FROM FAC_DICD 
	WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
-- insere as despesas documentadas 
	SELECT @cont = 1
	WHILE (@cont < 10)
	BEGIN
		INSERT INTO FAC_DCDO(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DCD_VTOT) 
		VALUES(@AnoConta, @tdoc, @IDConta, @cont, 0)
		SELECT @cont = @cont + 1
	END
-- insere as despesas inerentes
	SELECT @cont = 1
	WHILE (@cont < 13)
	BEGIN
		INSERT INTO FAC_ICDO(CDO_EANO, CDO_TDOC, CDO_IDEN, ICD_LINH, ICD_VTOT) 
		VALUES(@AnoConta, @tdoc, @IDConta, @cont, 0)
		SELECT @cont = @cont + 1
	END
-- inicia variaveis				
	SELECT @valorDocu = 0
	SELECT @TotalInerentes = 0
	SELECT @TotalInerentesIsentoIVA = 0
	SELECT @retfonte = 0
	SELECT @valIVA = 0
	SELECT @liqRecap = 0
-- se máscara a aplicar for a por defeito 
	IF @mascara = 0	
	BEGIN	
		-- despesas documentadas --------------------------------------------------
		DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT DDO_PCDO, DDO_CODI, DDO_NOME, DDO_UCTE, ISNULL(DDO_FLCE, '')
			FROM TAB_DDOC WITH(NOLOCK)
			WHERE DDO_CCDO = '1'
		OPEN Detalhe
		FETCH NEXT from Detalhe into @linha, @despesa, @descri, @utiliza, @FormulaCalcValor
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @valo = 0
			IF @despesa = 1
				SELECT @valo = @liqRecap
			ELSE
			BEGIN
				IF (@utiliza = 1) AND (@trafego = 1) AND (@cdo_pbrt > @limMax)
					SELECT @valo = @valorKg * CEILING(@cdo_pbrt) 				
				IF (@NaturezaDUContasAutSaida = 1) AND (@FormulaCalcValor <> '')
				BEGIN
					SELECT @OUTValorNumerico = 0
					EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @ano, @proc, @operador
					IF @OUTValorNumerico <> 0
						SELECT @valo = @OUTValorNumerico
				END		
			END
			SELECT @valorDocu = @valorDocu + @valo
			UPDATE FAC_DCDO SET DDO_CODI = @despesa, DCD_DESC = @descri, DCD_VTOT = @valo
			WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @linha
			FETCH NEXT from Detalhe into @linha, @despesa, @descri, @utiliza, @FormulaCalcValor
		END
		CLOSE Detalhe
		DEALLOCATE Detalhe
		-- despesas inerentes ------------------------------------------------------
		DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT DIN_PCDO, DIN_CODI, DIN_NOME, DIN_UCTE, ISNULL(DIN_FCLE, ''), DIN_ISEN, IIV_CODI, IIV_MENC
			FROM TAB_DINE WITH(NOLOCK)
			WHERE DIN_CCDO = '1'
		OPEN Detalhe
		FETCH NEXT from Detalhe into @linha, @despesa, @descri, @utiliza, @FormulaCalcValor, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, @MencaoIsencaoIVADespInerente
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @valorTrafego = 0
			IF (@utiliza = 1) AND (@trafego = 1) AND (@cdo_pbrt > @limMax)
				SELECT @valorTrafego = @valorKg * CEILING(@cdo_pbrt) 			
			IF (@NaturezaDUContasAutSaida = 1) AND (@FormulaCalcValor <> '')
			BEGIN
				SELECT @OUTValorNumerico = 0
				EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @ano, @proc, @operador
				IF @OUTValorNumerico <> 0
					SELECT @valorTrafego = @OUTValorNumerico
			END
			if @IsentaIVADespInerente = 1
				SELECT @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + @valorTrafego
			SELECT @TotalInerentes = @TotalInerentes + @valorTrafego
			UPDATE FAC_ICDO SET DIN_CODI = @despesa, ICD_DESC = @descri, ICD_VTOT = @valorTrafego, ICD_ISEN = @IsentaIVADespInerente, IIV_CODI = @CodIsencaoIVADespInerente, 
				IIV_MENC = @MencaoIsencaoIVADespInerente
			WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @linha
			FETCH NEXT from Detalhe into @linha, @despesa, @descri, @utiliza, @FormulaCalcValor, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, @MencaoIsencaoIVADespInerente
		END
		CLOSE Detalhe
		DEALLOCATE Detalhe
	END
	ELSE
-- se máscara a aplicar for do cliente 
		IF @TipoMascara = 1 
		BEGIN		
		-- despesas documentadas ---------------------------------------------------
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT mas.MCD_POSI, mas.DDO_CODI, ddo.DDO_UCTE, ISNULL(mas.MCD_VALO, 0), ddo.DDO_NOME, ISNULL(ddo.DDO_FLCE, '')
				FROM TAB_MCDO as mas WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON mas.DDO_CODI = ddo.DDO_CODI					
				WHERE mas.CLI_CODI = @cli_ccor AND mas.MCF_CODI = @mascara
			OPEN Detalhe
			FETCH NEXT from Detalhe into @linha, @despesa, @utiliza, @valo, @descri, @FormulaCalcValor
			WHILE @@FETCH_STATUS = 0
			BEGIN
				IF (@despesa = 1) AND (@valo = 0)
					SELECT @valo = @liqRecap
				ELSE
				BEGIN
					IF (@utiliza = 1) AND (@trafego = 1) AND (@cdo_pbrt > @limMax)
						SELECT @valo = @valorKg * CEILING(@cdo_pbrt) 
					IF (@NaturezaDUContasAutSaida = 1) AND (@FormulaCalcValor <> '')
					BEGIN
						SELECT @OUTValorNumerico = 0
						EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @ano, @proc, @operador
						IF @OUTValorNumerico <> 0
							SELECT @valo = @OUTValorNumerico
					END
				END		
				SELECT @valorDocu = @valorDocu + @valo			
				UPDATE FAC_DCDO SET DDO_CODI = @despesa, DCD_DESC = @descri, DCD_VTOT = @valo
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @linha
				FETCH NEXT from Detalhe into @linha, @despesa, @utiliza, @valo, @descri, @FormulaCalcValor
			END
			CLOSE Detalhe
			DEALLOCATE Detalhe
		-- despesas inerentes ------------------------------------------------------	
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				SELECT m.MCI_POSI, m.DIN_CODI, m.MCI_VALO, d.DIN_UCTE, d.DIN_NOME, ISNULL(d.DIN_FCLE, ''), d.DIN_ISEN, d.IIV_CODI, d.IIV_MENC
				FROM TAB_MCIN as m WITH(NOLOCK) INNER JOIN TAB_DINE as d WITH(NOLOCK) ON m.DIN_CODI = d.DIN_CODI
				WHERE m.CLI_CODI = @cli_ccor AND m.MCF_CODI = @mascara	
			OPEN Detalhe
			FETCH NEXT from Detalhe into @linha, @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, @MencaoIsencaoIVADespInerente
			WHILE @@FETCH_STATUS = 0
			BEGIN							
				IF (@utiliza = 1) AND (@trafego = 1) AND  (@cdo_pbrt > @limMax)
					SELECT @valo = @valorKg * CEILING(@cdo_pbrt) 
				IF (@NaturezaDUContasAutSaida = 1) AND (@FormulaCalcValor <> '')
				BEGIN
					SELECT @OUTValorNumerico = 0
					EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @ano, @proc, @operador
					if @OUTValorNumerico <> 0
						select @valo = @OUTValorNumerico
				END
				if @IsentaIVADespInerente = 1
					SELECT @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + @valo
				SELECT @TotalInerentes = @TotalInerentes + @valo
				UPDATE FAC_ICDO SET DIN_CODI = @despesa, ICD_DESC = @descri, ICD_VTOT = @valo, ICD_ISEN = @IsentaIVADespInerente, IIV_CODI = @CodIsencaoIVADespInerente, 
					IIV_MENC = @MencaoIsencaoIVADespInerente
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @linha
				FETCH NEXT from Detalhe into @linha, @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, @MencaoIsencaoIVADespInerente
			END
			CLOSE Detalhe
			DEALLOCATE Detalhe
		END
-- se máscara a aplicar for da natureza
		ELSE
		BEGIN
		-- despesas documentadas ---------------------------------------------------
			select @linha = 0
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				select mas.DDO_CODI, ddo.DDO_UCTE, ISNULL(mas.MND_VALO, 0), ddo.DDO_NOME, ISNULL(ddo.DDO_FLCE, '')
				from TAB_MNDO as mas WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON mas.DDO_CODI = ddo.DDO_CODI					
				where mas.NDE_CODI = @nde_codi and mas.MNF_CODI = @mascara
			OPEN Detalhe
			FETCH NEXT from Detalhe into @despesa, @utiliza, @valo, @descri, @FormulaCalcValor
			WHILE @@FETCH_STATUS = 0
			BEGIN
				select @linha = @linha + 1
				IF (@despesa = 1) AND (@valo = 0)
					SELECT @valo = @liqRecap
				ELSE
				BEGIN
					IF (@utiliza = 1) AND (@trafego = 1) AND (@cdo_pbrt > @limMax)
						SELECT @valo = @valorKg * CEILING(@cdo_pbrt) 
					IF (@NaturezaDUContasAutSaida = 1) AND (@FormulaCalcValor <> '')
					BEGIN
						SELECT @OUTValorNumerico = 0
						EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @ano, @proc, @operador
						IF @OUTValorNumerico <> 0
							SELECT @valo = @OUTValorNumerico
					END
				END		
				SELECT @valorDocu = @valorDocu + @valo				
				UPDATE FAC_DCDO SET DDO_CODI = @despesa, DCD_DESC = @descri, DCD_VTOT = @valo
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DCD_LINH = @linha
				FETCH NEXT from Detalhe into @despesa, @utiliza, @valo, @descri, @FormulaCalcValor, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, @MencaoIsencaoIVADespInerente
			END
			CLOSE Detalhe
			DEALLOCATE Detalhe
		-- despesas inerentes ------------------------------------------------------	
			select @linha = 0
			DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
				select m.DIN_CODI, m.MNI_VALO, d.DIN_UCTE, d.DIN_NOME, ISNULL(d.DIN_FCLE, ''), d.DIN_ISEN, d.IIV_CODI, d.IIV_MENC
				from TAB_MNIN as m WITH(NOLOCK) INNER JOIN TAB_DINE as d WITH(NOLOCK) ON m.DIN_CODI = d.DIN_CODI
				where m.NDE_CODI = @nde_codi and m.MNF_CODI = @mascara
			OPEN Detalhe
			FETCH NEXT from Detalhe into @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, @MencaoIsencaoIVADespInerente
			WHILE @@FETCH_STATUS = 0
			BEGIN			
				select @linha = @linha + 1
				IF (@utiliza = 1) AND (@trafego = 1) AND (@cdo_pbrt > @limMax)
					SELECT @valo = @valorKg * CEILING(@cdo_pbrt) 
				IF (@NaturezaDUContasAutSaida = 1) and (@FormulaCalcValor <> '')
				BEGIN
					SELECT @OUTValorNumerico = 0
					EXEC SP_ObtemValorNumericoComSQLDinamico @FormulaCalcValor, @OUTValorNumerico OUTPUT, @ano, @proc, @operador
					IF @OUTValorNumerico <> 0
						SELECT @valo = @OUTValorNumerico
				END
				if @IsentaIVADespInerente = 1
					SELECT @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + @valo
				SELECT @TotalInerentes = @TotalInerentes + @valo
				UPDATE FAC_ICDO SET DIN_CODI = @despesa, ICD_DESC = @descri, ICD_VTOT = @valo, ICD_ISEN = @IsentaIVADespInerente, IIV_CODI = @CodIsencaoIVADespInerente, 
					IIV_MENC = @MencaoIsencaoIVADespInerente
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @linha
				FETCH NEXT from Detalhe into @despesa, @valo, @utiliza, @descri, @FormulaCalcValor, @IsentaIVADespInerente, @CodIsencaoIVADespInerente, @MencaoIsencaoIVADespInerente
			END
			CLOSE Detalhe
			DEALLOCATE Detalhe
		END
-- trata despesa inerente relativa à caução
	IF @valorCauc <> 0 
	BEGIN
		-- busca código da despesa inerente ----------------------------------------
		SELECT  @despesaCauc = DIN_CODI, @descriCauc = DIN_NOME, @IsentaIVADespInerente = DIN_ISEN, @CodIsencaoIVADespInerente = IIV_CODI, @MencaoIsencaoIVADespInerente = IIV_MENC
		FROM TAB_DINE WITH(NOLOCK)
		WHERE DIN_CODI = @CodDespInerenteClienteCC		

		IF (@despesaCauc <> '') AND (@taxaCauc <> 0)
		BEGIN
			SELECT @contCauc = COUNT(*) 
			FROM FAC_ICDO
			WHERE DIN_CODI = @despesaCauc AND CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
			-- verifica se já existe linha com despesa --------------------------
			IF @contCauc > 0 
			BEGIN
				SELECT @valorAnt = ISNULL(ICD_VTOT, 0)
				FROM FAC_ICDO
				WHERE DIN_CODI = @despesaCauc AND CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
				
				if @IsentaIVADespInerente = 1
					SELECT @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA - @valorAnt + ROUND(@valorCauc * (@taxaCauc / 100), 2)
				SELECT @TotalInerentes = @TotalInerentes - @valorAnt + ROUND(@valorCauc * (@taxaCauc / 100), 2)
				UPDATE FAC_ICDO SET ICD_VTOT = ROUND(@valorCauc * (@taxaCauc / 100), 2), ICD_ISEN = @IsentaIVADespInerente, IIV_CODI = @CodIsencaoIVADespInerente, 
					IIV_MENC = @MencaoIsencaoIVADespInerente
				WHERE DIN_CODI = @despesaCauc AND CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta
			END
			ELSE
			BEGIN
				-- busca posição da linha ----------------------------------
				SELECT @contCauc = COUNT(*) 
				FROM FAC_ICDO
				WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND DIN_CODI <> ''
				
				IF (@contCauc + 1) <= 12 
				BEGIN
					if @IsentaIVADespInerente = 1
						SELECT @TotalInerentesIsentoIVA = @TotalInerentesIsentoIVA + ROUND(@valorCauc * (@taxaCauc / 100), 2)
					SELECT @TotalInerentes = @TotalInerentes + ROUND(@valorCauc * (@taxaCauc / 100), 2)

					UPDATE FAC_ICDO SET DIN_CODI = @despesaCauc, ICD_DESC = @descriCauc, ICD_VTOT = ROUND(@valorCauc * (@taxaCauc / 100), 2), ICD_ISEN = @IsentaIVADespInerente, 
						IIV_CODI = @CodIsencaoIVADespInerente, IIV_MENC = @MencaoIsencaoIVADespInerente
					WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @tdoc AND CDO_IDEN = @IDConta AND ICD_LINH = @contCauc + 1
				END
			END
		END	
	END
-- calcula valor total da retenção na fonte
	SELECT @retfonte = ROUND((@TotalInerentes + @valhonor) * (@cdo_rtfo / 100), 2)
-- calculo valor total do IVA
	SELECT @valIVA = ROUND((@valhonor + @TotalInerentes - @TotalInerentesIsentoIVA) * (@cdo_txiv / 100), 2)	
-- actualiza valores totais da Conta
	UPDATE FAC_CDOC SET CDO_TTDC = @valorDocu , CDO_TTIN = @TotalInerentes, CDO_TTRF = @retfonte, CDO_TTPR = (@valorDocu + @TotalInerentes + @valhonor + @valIVA), CDO_IVA = @valIVA, 
		CDO_IN01 = (@valorDocu + (CASE WHEN (CDO_TXIV = 0) THEN (@TotalInerentes + @valhonor) ELSE @TotalInerentesIsentoIVA END)), CDO_IN02 = 0, CDO_IN03 = 0, 
		CDO_IN04 = (CASE WHEN (CDO_TXIV > 0) THEN (@TotalInerentes - @TotalInerentesIsentoIVA + @valhonor) ELSE 0 END), CDO_VI01 = 0, CDO_VI02 = 0, CDO_VI03 = 0, CDO_VI04 = @valIVA
	WHERE CDO_EANO = @AnoConta and CDO_TDOC = @tdoc and CDO_IDEN = @IDConta
END
END

ALTER AUTHORIZATION ON [SP_geraContasExportXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraContasExportXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraDocVendaDUImportacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraDocVendaDUImportacao] @AnoDocVendaAGerar int, @AnoProcesso int, @NumeroProcesso int, @CodClienteVendaAGerar varchar(18), @Utilizador varchar(30) AS
BEGIN
-- declaracao de variaveis
	declare @TipoDocVnd varchar(4), @NumDocVnd int, @CtxDocVnd int, @DataDocVnd datetime, @NomeClienteDocVnd varchar(70), @MoradaClienteDocVnd varchar(70), 
		@LocalidadeClienteDocVnd varchar(35), @CodPostalClienteDocVnd varchar(12), @LocPostalClienteDocVnd varchar(35), @NIFClienteDocVnd varchar(18), 
		@PaisClienteDocVnd varchar(2), @CodNaturezaDocVnd varchar(3), @NumCPAProcesso varchar(18), @ValidaDatasDocVnd bit, @AuxData datetime, 
		@CodRubFactLinha int, @NomeRubFactLinha varchar(70), @ValorRubFactLinha numeric(38, 6), @TxIVARubFactLinha numeric(38, 6), @LancHonRubFactLinha bit, 
		@ValorLiqDocVnd numeric(38, 6), @ValorIVADocVnd numeric(38, 6), @ValorTotalDocVnd numeric(38, 6), @TxIVAIsenta numeric(38, 6), 
		@TxIVAReduzida numeric(38, 6), @TxIVAIntermedia numeric(38, 6), @TxIVANormal numeric(38, 6), @IncidenciaIVA1DocVnd numeric(38, 6), 
		@IncidenciaIVA2DocVnd numeric(38, 6), @IncidenciaIVA3DocVnd numeric(38, 6), @IncidenciaIVA4DocVnd numeric(38, 6), @ValorIVA1DocVnd numeric(38, 6), 
		@ValorIVA2DocVnd numeric(38, 6), @ValorIVA3DocVnd numeric(38, 6), @ValorIVA4DocVnd numeric(38, 6), @ValorEspecialVDIN numeric(38, 6), @NumDGAItem varchar(70),
		@TipoDocSAFT varchar(2), @CodIsencaoIVA varchar(3), @MencaoIsencaoIVA varchar(100), @CodChargeCode varchar(4), @Serie varchar(20)
	set dateformat DMY
-- inicia variaveis
	select @IncidenciaIVA1DocVnd = 0, @IncidenciaIVA2DocVnd = 0, @IncidenciaIVA3DocVnd = 0, @IncidenciaIVA4DocVnd = 0, @ValorIVA1DocVnd = 0, @ValorIVA2DocVnd = 0, @ValorIVA3DocVnd = 0, 
		@ValorIVA4DocVnd = 0
-- obtem dados do cliente
	select @NomeClienteDocVnd = CLI_NOME, @MoradaClienteDocVnd = CLI_MORA, @LocalidadeClienteDocVnd = CLI_LOCA, @CodPostalClienteDocVnd = CLI_CPOS, @LocPostalClienteDocVnd = CLI_LPOS, 
		@NIFClienteDocVnd = CLI_NIF, @PaisClienteDocVnd = PAI_CODI, @ValorEspecialVDIN = CLI_VEVD
	from TAB_CLIE WITH(NOLOCK)
	where CLI_CODI = @CodClienteVendaAGerar
-- obtem dados do DU Importação
	select @CodNaturezaDocVnd = d.NDE_CODI, @NumCPAProcesso = d.DUC_CPRT, @NumDGAItem = isnull(d.DUC_LC27, ''), @TipoDocVnd = n.TDO_DOCU, @CodRubFactLinha = n.RFC_CODI, @CtxDocVnd = t.TDO_TDOC, 
		@ValidaDatasDocVnd = t.TDO_VALI, @TipoDocSAFT = t.TDO_TDSF, @NomeRubFactLinha = r.RFC_NOME, @TxIVARubFactLinha = r.RFC_IVA, @CodChargeCode = r.CCO_CODI, 
		@CodIsencaoIVA = (case r.RFC_IVA when 0 then 'M04' else NULL end), 
		@MencaoIsencaoIVA = (case r.RFC_IVA when 0 then (select IIV_MENC from GIDWIN..FAP_MIIV where IIV_CODI = 'M04') else NULL end),
		@ValorRubFactLinha = (case substring(@NIFClienteDocVnd, 1, 1) when '5' then r.RFC_VLNC when '6' then r.RFC_VLNC when '9' then r.RFC_VLNC else r.RFC_VLNS end),
		@LancHonRubFactLinha = cast((case r.RFC_TIPO when 2 then 1 else 0 end) as bit)
	from PRO_DUCG as d WITH(NOLOCK) INNER JOIN TAB_NDES as n WITH(NOLOCK) ON d.NDE_CODI = n.NDE_CODI
		INNER JOIN TAB_TDOC as t WITH(NOLOCK) ON n.TDO_DOCU = t.TDO_DOCU
		INNER JOIN TAB_RFCT as r WITH(NOLOCK) ON n.RFC_CODI = r.RFC_CODI
	where d.DUC_EANO = @AnoProcesso and d.DUC_PNUM = @NumeroProcesso
-- verifica se existe valor especial VDIN para o cliente
	if @ValorEspecialVDIN > 0
		select @ValorRubFactLinha = @ValorEspecialVDIN
-- calcula valores totais p/ doc. venda
	select @ValorLiqDocVnd = @ValorRubFactLinha
	select @ValorIVADocVnd = round((@ValorRubFactLinha * @TxIVARubFactLinha / 100), 2)
	select @ValorTotalDocVnd = @ValorLiqDocVnd + @ValorIVADocVnd
-- obtem taxas de IVA configuradas na aplicação
	select @TxIVAIsenta = PAP_TXIS, @TxIVAReduzida = PAP_TXRD, @TxIVAIntermedia = PAP_TXIN, @TxIVANormal = PAP_TXNR
	from TAB_PAPL WITH(NOLOCK)
-- calcula valores incidencia de IVA p/ doc. venda
	if @TxIVARubFactLinha = @TxIVAIsenta
	begin
		select @IncidenciaIVA1DocVnd = @ValorLiqDocVnd
		select @ValorIVA1DocVnd = @ValorIVADocVnd
	end
	else
		if @TxIVARubFactLinha = @TxIVAReduzida
		begin
			select @IncidenciaIVA2DocVnd = @ValorLiqDocVnd
			select @ValorIVA2DocVnd = @ValorIVADocVnd
		end
		else
			if @TxIVARubFactLinha = @TxIVAIntermedia
			begin
				select @IncidenciaIVA3DocVnd = @ValorLiqDocVnd
				select @ValorIVA3DocVnd = @ValorIVADocVnd
			end
			else
				if @TxIVARubFactLinha = @TxIVANormal
				begin
					select @IncidenciaIVA4DocVnd = @ValorLiqDocVnd
					select @ValorIVA4DocVnd = @ValorIVADocVnd
				end
-- obtem a data p/ doc. venda em função do ano activo na aplicação e ano actual
	if year(getdate()) = @AnoDocVendaAGerar
		select @DataDocVnd = cast(convert(varchar(10), getdate(), 105) as datetime)
	else
	begin
		select @DataDocVnd = cast(convert(varchar(10), max(DVE_DATA), 105) as datetime)
		from FAC_DVEN WITH(NOLOCK)
		where DVE_EANO = @AnoDocVendaAGerar
	end
-- valida a data obtida p/ doc. venda se tipo documento configurado para tal
	if @ValidaDatasDocVnd = 1
	begin
		select @AuxData = cast(convert(varchar(10), NUM_DATA, 105) as datetime)
		from TAB_NUMD
		where TDO_DOCU = @TipoDocVnd and NUM_EANO = @AnoDocVendaAGerar
		if @AuxData > @DataDocVnd
			select @DataDocVnd = @AuxData
	end
-- obtem o numero do doc. venda da tabela de numeradores
	select @NumDocVnd = isnull(NUM_NUME, 0) + 1, @Serie = ISNULL(NULLIF(NUM_SERI, ''), '1')
	from TAB_NUMD 
	where TDO_DOCU = @TipoDocVnd and NUM_EANO = @AnoDocVendaAGerar
-- insere registo de cabeçalho do doc. venda
	insert into FAC_DVEN (DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_CTXT, DVE_DATA, CLI_CODI, DVE_CNOM, DVE_CMOR, DVE_CLOC, DVE_CCPO, DVE_CLPO, DVE_CNIF, PAI_CLIV, NDE_CODI, DVE_NPRO, DVE_OBSV, 
		DVE_UTIC, DVE_DTCR, DVE_UTIA, DVE_DTAL, DVE_IN01, DVE_IN02, DVE_IN03, DVE_IN04, DVE_VI01, DVE_VI02, DVE_VI03, DVE_VI04, DVE_VLIQ, DVE_VIVA, DVE_VTOT, DVE_STAT, DVE_DIPS, DVE_DFPS, 
		DVE_PANO, DVE_IMEX, TDO_TDSF, DVE_CPRT, DVE_SERI)
	values(@TipoDocVnd, @NumDocVnd, @AnoDocVendaAGerar, @CtxDocVnd, @DataDocVnd, @CodClienteVendaAGerar, @NomeClienteDocVnd, @MoradaClienteDocVnd, @LocalidadeClienteDocVnd, 
		@CodPostalClienteDocVnd, @LocPostalClienteDocVnd, @NIFClienteDocVnd, @PaisClienteDocVnd, @CodNaturezaDocVnd, @NumeroProcesso,
		('CPA Nº.: ' + @NumCPAProcesso + char(13) + char(10) + 'NRM SDS:' + @NumDGAItem), @Utilizador, getdate(), @Utilizador, getdate(), @IncidenciaIVA1DocVnd, @IncidenciaIVA2DocVnd, 
		@IncidenciaIVA3DocVnd, @IncidenciaIVA4DocVnd, @ValorIVA1DocVnd, @ValorIVA2DocVnd, @ValorIVA3DocVnd, @ValorIVA4DocVnd, @ValorLiqDocVnd, @ValorIVADocVnd, @ValorTotalDocVnd, 1, 
		@DataDocVnd, @DataDocVnd, @AnoProcesso, 0, @TipoDocSAFT, @NumCPAProcesso, @Serie)
-- actualiza dados da tabela de numeradores
	update TAB_NUMD set NUM_NUME = @NumDocVnd, NUM_DATA = @DataDocVnd
	where TDO_DOCU = @TipoDocVnd and NUM_EANO = @AnoDocVendaAGerar
-- insere registo de detalhe do doc. venda
	insert into FAC_DVDT (DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_CTXT, DVD_LHON, IIV_CODI, IIV_MENC, CCO_CODI)
	values (@TipoDocVnd, @NumDocVnd, @AnoDocVendaAGerar, 1, @CodRubFactLinha, @NomeRubFactLinha, 1, @ValorRubFactLinha, @TxIVARubFactLinha, 1, @CtxDocVnd, 
		@LancHonRubFactLinha, @CodIsencaoIVA, @MencaoIsencaoIVA, @CodChargeCode)
END

ALTER AUTHORIZATION ON [SP_geraDocVendaDUImportacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraDocVendaDUImportacao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraDV1]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraDV1] @cod int, @ano int, @sinalFret int, @sinalSegu int, @sinalDire int AS
BEGIN
	SET DATEFORMAT DMY
-- declaracoes de variaveis 
	DECLARE @NumErro int, @DataAtual datetime, @codAlf varchar(8), @codVend varchar(18), @nomeVend varchar(70), @morVend varchar(70), @locVend varchar(35), @codPosVend varchar(12), 
		@locPosVend varchar(35), @nifVend varchar(18), @paisVend varchar(2), @codComp varchar(18), @nomeComp varchar(70), @morComp varchar(70), @locComp varchar(35), @codPosComp varchar(12), 
		@locPosComp varchar(35), @nifComp varchar(18), @paisComp varchar(2), @codDecla varchar(6), @nomeDecla varchar(70), @codCondEnt varchar(3), @subCasa varchar(30), @numFact varchar(35), 
		@dataFact datetime, @moeda varchar(3), @taxaC numeric(38,6), @status int, @codLinha numeric(38,6), @vAdic numeric(38,6), @vAdEuro numeric(38,6), @vFrete numeric(38,6), 
		@vSegu numeric(38,6), @direit numeric(38,6), @txFrete numeric(38,6), @txSegu numeric(38,6), @ajust numeric(38,6), @txFda numeric(38,6), @DUA_MTPR numeric(38,6), @Royalties numeric(38,6), 
		@CtxDeclaracao int, @IdDeclaracao bigint
-- inicia transacção para a inserção das adições
	BEGIN TRANSACTION TspGeraDV1
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia variaveis
		SET @numFact = NULL
		SET @dataFact = NULL
-- obtem dados da declaração DUI2/IMP-CAU
		SELECT @codAlf = ALF_CODI, @status = DUC_STAT, @codVend = DUC_EXP2, @paisVend = PAI_PA15, @nomeVend = DUC_ENOM, @morVend = DUC_EMOR, @locVend = DUC_ELOC, @codPosVend = DUC_ECPO, 
			@locPosVend = DUC_ELPO, @nifVend = DUC_ENIF, @codComp = DUC_DST8, @paisComp = PAI_PA17, @nomeComp = DUC_DNOM, @morComp = DUC_DMOR, @locComp = DUC_DLOC, @codPosComp = DUC_DCPO, 
			@locPosComp = DUC_DLPO, @nifComp = DUC_DNIF, @codCondEnt = CEN_CO20, @subCasa = DUC_DE20, @codDecla = DEC_CO14, @taxaC = DUC_TX23, @txFrete = DUC_TXFR, @txSegu = DUC_TXSE, 
			@txFda = DUC_TFDA, @moeda = PAI_MO22, @nomeDecla = DEC_NOME, @CtxDeclaracao = DUC_DUNO, @IdDeclaracao = DUC_IDTY
		FROM PRO_DUCG WITH(NOLOCK)
		WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
--obtem dados do documento de faturacao em função se declaração IMP-CAU ou DUI2
		IF @CtxDeclaracao = 2
		BEGIN
-- obtem dados do documento de faturacao nos documentos da declaração IMP-CAU
			SELECT TOP 1 @numFact = SUBSTRING(ddo.numero, 1, 35), @dataFact = ddo.dataValidade
			FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK)
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
			WHERE ddo.id_declaracaoIMP = @IdDeclaracao AND doc.DOC_CODI = 'N380'
		END
		ELSE
		BEGIN
-- obtem dados do documento de faturacao nos documentos da 1ª adicao da declaração DUI2
			SELECT TOP 1 @numFact = SUBSTRING(DDO_NUME, 1, 35), @dataFact = DDO_DINI
			FROM PRO_DDOC WITH(NOLOCK)
			WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DUA_CODI = 1 AND DOC_CODI = 'N380'
		END
-- verifica se DV1 ja foi gerado	
		IF NOT EXISTS(SELECT 1 FROM PRO_DV1C WITH(NOLOCK) WHERE DUC_PNUM = @cod AND DUC_EANO = @ano)
		BEGIN
			INSERT INTO PRO_DV1C(DUC_EANO, DUC_PNUM, DV1_DATA, DV1_STAT, ALF_CODI, DV1_VEN1, DV1_VNOM, DV1_VMOR, DV1_VLOC, DV1_VCPO, DV1_VLPO, DV1_VNIF, PAI_CODV, DV1_COM2, DV1_CNOM, DV1_CMOR, 
				DV1_CLOC, DV1_CCPO, DV1_CLPO, DV1_CNIF, PAI_CODC, DV1_DE2B, DV1_DNOM, CEN_COD3, DV1_SUB3, DV1_NFC4, DV1_DAT4, DV1_C7AS, DV1_C7AN, DV1_C7BS, DV1_C7BN, DV1_C7CS, DV1_C7CN, DV1_C8AS, 
				DV1_C8AN, DV1_C8BS, DV1_C8BN, DV1_C9AS, DV1_C9AN, DV1_C9BS, DV1_C9BN)
			VALUES (@ano, @cod, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), @status, @codAlf, @codVend, @nomeVend, @morVend, @locVend, @codPosVend, @locPosVend, @nifVend, @paisVend, @codComp, @nomeComp, @morComp, 
				@locComp, @codPosComp, @locPosComp, @nifComp, @paisComp, @codDecla, @nomeDecla, @codCondEnt, @subCasa, @numFact, @dataFact, 0, 1, 0, 0, 0, 0, 0, 
				1, 0, 1, 0, 1, 0, 1)	
		END
		ELSE
		BEGIN
			UPDATE PRO_DV1C SET 
				DV1_DATA = CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), 
				ALF_CODI = @codAlf, 
				DV1_STAT = @status, 
				DV1_VEN1 = @codVend, 
				DV1_VNOM = @nomeVend, 
				DV1_VMOR = @morVend, 
				DV1_VLOC = @locVend, 
				DV1_VCPO = @codPosVend, 
				DV1_VLPO = @locPosVend, 
				DV1_VNIF = @nifVend, 
				PAI_CODV = @paisVend, 
				DV1_COM2 = @codComp, 
				DV1_CNOM = @nomeComp, 
				DV1_CMOR = @morComp, 
				DV1_CLOC = @locComp, 
				DV1_CCPO = @codPosComp, 
				DV1_CLPO = @locPosComp, 
				DV1_CNIF = @nifComp, 
				PAI_CODC = @paisComp, 
				DV1_DE2B = @codDecla, 
				DV1_DNOM = @nomeDecla, 
				CEN_COD3 = @codCondEnt, 
				DV1_SUB3 = @subCasa, 
				DV1_NFC4 = @numFact, 
				DV1_DAT4 = @dataFact
			WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
		END
-- remove adicoes existentes no DV1
		DELETE FROM PRO_ADV1 
		WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
-- busca as adicoes do Doc. Unico
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUA_CODI, DUA_VA42, DUA_VAEU, DUA_VFRE, DUA_VSEG, DUA_VDIR, DUA_AJUS, ABS(ISNULL(DUA_MTPR, 0)), ISNULL(DUA_ROYA, 0)
			FROM PRO_DUAD WITH(NOLOCK)
			WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @codLinha, @vAdic, @vAdEuro, @vFrete, @vSegu, @direit, @ajust, @DUA_MTPR, @Royalties
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula valor do frete em funcao da tx FDA
			IF @txFda <> 0	
				SET @vFrete = @vFrete * (@txFda / 100)
-- conforme valor dos direitos, insere adicao no DV1 
			IF @direit = 0
			BEGIN 
				INSERT INTO PRO_ADV1(DUC_EANO, DUC_PNUM, ADV_LINH, ADV_C11A, ADV_CS12, ADV_C17A, ADV_C17C, ADV_C11M, ADV_C11B, ADV_C17T, ADV_C13A, ADV_C13B, ADV_C13C, ADV_C14A, ADV_C14B, 
					ADV_C14C, ADV_C14D, ADV_CS15, ADV_CS16, ADV_C17B, ADV_CS19, ADV_CS20, ADV_CS21, ADV_CS22, ADV_CS23, ADV_CS18, ADV_CS24) 
				VALUES(@ano, @cod, @codLinha, @vAdic, @vAdEuro, (@sinalFret * (@vFrete / @txFrete)), (@sinalSegu * (@vSegu / @txSegu)), @moeda, @taxaC, @subCasa, 0, 0, 0, @DUA_MTPR, 0, 
					0, 0, @Royalties, 0, 0, 0, 0, 0, 0, 0, (@sinalFret * (@vFrete / @txFrete)) + (@sinalSegu * (@vSegu / @txSegu) + @DUA_MTPR), (@vAdEuro + (@sinalFret * (@vFrete / @txFrete)) + (@sinalSegu * (@vSegu / @txSegu)) + @DUA_MTPR))
			END
			ELSE
			BEGIN 
				INSERT INTO PRO_ADV1(DUC_EANO, DUC_PNUM, ADV_LINH, ADV_C11A, ADV_CS12, ADV_C17A, ADV_C17C, ADV_C11M, ADV_C11B, ADV_C17T, ADV_C13A, ADV_C13B, ADV_C13C, ADV_C14A, ADV_C14B, 
					ADV_C14C, ADV_C14D, ADV_CS15, ADV_CS16, ADV_C17B, ADV_CS19, ADV_CS20, ADV_CS21, ADV_CS22, ADV_CS23, ADV_CS18, ADV_CS24) 
				VALUES(@ano, @cod, @codLinha, @vAdic, @vAdEuro, 0, 0, @moeda, @taxaC, @subCasa, 0, 0, 0, @DUA_MTPR, 0, 
					0, 0, @Royalties, 0, 0, 0, 0, 0, @direit, (@direit * (-1)), @DUA_MTPR, (@vAdEuro + (@direit * (-1)) + @DUA_MTPR))
			END
			FETCH NEXT FROM Adicoes INTO @codLinha, @vAdic, @vAdEuro, @vFrete, @vSegu, @direit, @ajust, @DUA_MTPR, @Royalties
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspGeraDV1
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspGeraDV1
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro
END

ALTER AUTHORIZATION ON [SP_geraDV1] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraDV1] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraEUR1]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraEUR1] @cod int, @ano int AS
BEGIN
	set nocount on
	set DATEFORMAT dmy
-- declaracoes de variaveis
	declare @contador int, @codAlf varchar(8), @docTrans varchar(15), @docDe varchar(15), @nomePaisDest varchar(35), @codExp varchar(18), 
		@nomeExp varchar(70), @morExp varchar(70), @locExp varchar(35), @codPosExp varchar(12), @locPosExp varchar(35), @nifExp varchar(18), 
		@paisExp varchar(2), @codDest varchar(18), @nomeDest varchar(70), @morDest varchar(70), @locDest varchar(35), @codPosDest varchar(12), 
		@locPosDest varchar(35), @nifDest varchar(18), @paisDest varchar(2), @marca varchar(20), @quant numeric(38,6), @natur varchar(3),
		@pBruto numeric(38,6), @codLinha int, @codArtigo varchar(22), @desArtigo varchar(150), @masBruta numeric(38,6), @casa2 varchar(6),
		@casa4 varchar(6), @desComercial varchar(150), @assumEur1 bit, @status int, @volumes numeric(38,6), @NumsDocFact varchar(500), 
		@AuxCodDocumento varchar(70), @ParteResto int, @NumDGA varchar(40), @DataDGA datetime, @TipoDecl1Casa varchar(5)
-- inicia variaveis
	select @NumsDocFact = ''
-- busca dados do DU Importacao
	select @codAlf = ALF_CODI, @pBruto = DUC_MBRT, @status = DUC_STAT, @volumes = DUC_TVL6, @codExp = DUC_EXP2, @paisExp = PAI_PA15, 
		@nomeExp = DUC_ENOM, @morExp = DUC_EMOR, @locExp = DUC_ELOC, @codPosExp = DUC_ECPO, @locPosExp = DUC_ELPO, @nifExp = DUC_ENIF,
		@codDest = DUC_DST8, @paisDest = PAI_PA17, @nomeDest = DUC_DNOM, @morDest = DUC_DMOR, @locDest = DUC_DLOC, @codPosDest = DUC_DCPO, 
		@locPosDest = DUC_DLPO, @nifDest = DUC_DNIF, @NumDGA = DUC_NORD, @DataDGA = DUC_NDAT, @TipoDecl1Casa = TDE_1CAS
	from PRO_DUCG
	where DUC_PNUM = @cod and DUC_EANO = @ano
-- busca dados do Pais de Destino	
	select @nomePaisDest = PAI_NOME, @casa2 = PAI_C2E1, @casa4 = PAI_C4E1
	from TAB_PAIS
	where PAI_CODI = @paisDest
-- busca dados da Casa 31 da 1ª linha da 1ª adicao
	select @marca = D31_MARC, @natur = UME_CODI
	from PRO_DU31
	where DUC_PNUM = @cod and DUC_EANO = @ano and DUA_CODI = 1 and D31_CODI = 1
-- busca documentos de facturacao apenas da 1ª adicao
	DECLARE DocsFacturacao CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
		select DDO_NUME
		from PRO_DDOC
		where DUC_EANO = @ano and DUC_PNUM = @cod and DUA_CODI = 1 and DDO_NUME <> '' and DDO_NUME is not null 
			and (DOC_CODI = 'FACT' or DOC_CODI = 'N380')
	OPEN DocsFacturacao
	FETCH NEXT from DocsFacturacao into @AuxCodDocumento
	WHILE @@FETCH_STATUS = 0
	BEGIN
		select @NumsDocFact = @NumsDocFact + '; ' + @AuxCodDocumento
		FETCH NEXT from DocsFacturacao into @AuxCodDocumento
	END
	CLOSE DocsFacturacao
	DEALLOCATE DocsFacturacao
-- trata lista de documentos de facturacao
	if @NumsDocFact <> '' 
		select @NumsDocFact = stuff(@NumsDocFact, 1, 2, '')
-- verifica se EUR1 ja existe
	SELECT @contador = count(*)
	FROM PRO_EUR1
	WHERE DUC_PNUM = @cod and DUC_EANO = @ano and DEC_CODI = '0'
-- se nao existe cria novo EUR1
	if @contador = 0
	begin
		insert into PRO_EUR1(DEC_CODI, DUC_EANO, DUC_PNUM, EUR_DATA, EUR_STAT, ALF_CODI, EUR_EXP1, EUR_ENOM, EUR_EMOR, EUR_ELOC, EUR_ECPO, 
			EUR_ELPO, EUR_ENIF, EUR_DST3, PAI_COD5, EUR_ENTB, EUR_DNOM, EUR_DMOR, EUR_DLOC, EUR_DCPO, EUR_DLPO, EUR_DNIF, EUR_MC10, UME_CO10, 
			EUR_PBTT, EUR_ENTA, EUR_PAI4, EUR_QT10, EUR_NUMD, EUR_NDGA, EUR_DDGA, EUR_TD1C)
		values('0', @ano, @cod, getdate(), @status, @codAlf, @codExp, @nomeExp, @morExp, @locExp, @codPosExp, @locPosExp, @nifExp, @codDest, 
			@paisDest, @nomePaisDest, @nomeDest, @morDest, @locDest, @codPosDest, @locPosDest, @nifDest, @marca, @natur, @pBruto, @casa2, 
			@casa4, @volumes, @NumsDocFact, @NumDGA, @DataDGA, @TipoDecl1Casa)
	end
	else
	begin
		update PRO_EUR1 SET DUC_EANO = @ano, DUC_PNUM = @cod, EUR_DATA = getdate(), ALF_CODI = @codAlf, EUR_EXP1 = @codExp, EUR_ENOM = @nomeExp, 
			EUR_EMOR = @morExp, EUR_STAT = @status, EUR_ELOC = @locExp, EUR_ECPO = @codPosExp, EUR_ELPO = @locPosExp, EUR_ENIF = @nifExp, 
			EUR_DST3 = @codDest, PAI_COD5 = @paisDest, EUR_ENTB = @nomePaisDest, EUR_DNOM = @nomeDest, EUR_DMOR = @morDest, EUR_DLOC = @locDest, 
			EUR_DCPO = @codPosDest, EUR_DLPO = @locPosDest, EUR_DNIF = @nifDest, EUR_MC10 = @marca, UME_CO10 = @natur, EUR_PBTT = @pBruto, 
			EUR_ENTA = @casa2, EUR_PAI4 = @casa4, EUR_QT10 = @volumes, EUR_NUMD = @NumsDocFact, EUR_NDGA = @NumDGA, EUR_DDGA = @DataDGA, EUR_TD1C = @TipoDecl1Casa
		where DUC_PNUM = @cod and DUC_EANO = @ano and DEC_CODI = '0'
	end
-- remove as linhas do EUR1
	delete from PRO_AEUR 
	where DUC_PNUM = @cod and DUC_EANO = @ano and DEC_CODI = '0'
-- busca adicoes do DU Importacao
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		select DUA_CODI, APA_CO33, DUA_DESG, DUA_MB35
		from PRO_DUAD
		where DUC_PNUM = @cod and DUC_EANO = @ano
	OPEN Detalhe
	FETCH NEXT from Detalhe into @codLinha, @codArtigo, @desArtigo, @masBruta
	WHILE @@FETCH_STATUS = 0
	BEGIN
		select @ParteResto = NULL
-- busca dados a Casa 31 da adicao
		select @quant = isnull(sum(D31_QNTD), 0)
		from PRO_DU31
		where DUC_PNUM = @cod and DUC_EANO = @ano and DUA_CODI = @codLinha
-- verifica se 1ª linha da Casa 31 da adicao e Parte ou Resto
		select @ParteResto = (case when D31_CASP = 1 then 1 else (case when D31_CASR = 1 then 2 else NULL end) end)
		from PRO_DU31
		where DUC_PNUM = @cod and DUC_EANO = @ano and DUA_CODI = @codLinha and D31_CODI = 1
-- busca dados ao Artigo Pautal da adicao
		select @assumEur1 = APA_EUR1, @desComercial = APA_DCOM
		from TAB_APAU
		where APA_CODI = @codArtigo	
-- insere nova linha de detalhe no EUR1	
		if ((@desComercial is not null) or (@desComercial = '')) and (@assumEur1 = 1)
		begin
			insert into PRO_AEUR(DEC_CODI, DUC_EANO, DUC_PNUM, AEU_CODI, APA_CODI, AEU_DPAU, AEU_PBRT, AEU_TVOL, AEU_PTRT)
			values('0', @ano, @cod, @codLinha, @codArtigo, @desComercial, @masBruta, @quant, @ParteResto)
		end
		else
		begin
			insert into PRO_AEUR(DEC_CODI, DUC_EANO, DUC_PNUM, AEU_CODI, APA_CODI, AEU_DPAU, AEU_PBRT, AEU_TVOL, AEU_PTRT)
			values('0', @ano, @cod, @codLinha, @codArtigo, @desArtigo, @masBruta, @quant, @ParteResto)
		end
		FETCH NEXT from Detalhe into @codLinha, @codArtigo, @desArtigo, @masBruta
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	set nocount off
END

ALTER AUTHORIZATION ON [SP_geraEUR1] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraEUR1] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraEUR1ExportXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_geraEUR1ExportXML] @CodRefIntXML int, @AnoXML int, @OperXML varchar(6) AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracoes de variaveis
	DECLARE @CodIntXML int, @CodEstXML varchar(8), @StatusXML int, @Casa2Pais varchar(6), @NomePais varchar(35), @CodExpeXML varchar(18), @CodDestXML varchar(18), @Casa4Pais varchar(6), 
		@PaisDestXML varchar(2), @MarcaXML varchar(20), @TotalVolsXML numeric(38, 6), @CodUnidXML varchar(3), @TotalMassaBrtXML numeric(38, 6), @NomeExpeXML varchar(70), 
		@MoradaExpeXML varchar(70), @LocExpeXML varchar(35), @CodPostalExpeXML varchar(12), @LocPostalExpeXML varchar(35), @ContrExpeXML varchar(18), @NomeDestXML varchar(70), 
		@MoradaDestXML varchar(70), @LocDestXML varchar(35), @CodPostalDestXML varchar(12), @LocPostalDestXML varchar(35), @ContrDestXML varchar(18), @NumLinhaAdi int, @CodArtAdi varchar(22), 
		@DescArtAdi varchar(150), @MassaBrtAdi numeric(38, 6), @TotalVolsAdi numeric(38, 6), @EUR1Art bit, @DescComArt varchar(150), @IdenAdi int, @NumsDocFact varchar(500), 
		@NumDGA varchar(40), @AuxCodDocumento varchar(70), @AuxDataDocumento datetime, @ParteResto int, @DataDGA datetime, @TipoProcedimento varchar(1), @TipoDecl1Casa varchar(5), 
		@NumsDatasDocFact varchar(2000), @PeriodoTransitorio bit, @IdDeclXML bigint, @CtxDeclXML tinyint
-- inicia variaveis
	SET @NumsDocFact = ''
	SET @NumsDatasDocFact = ''
-- obtem configuração do periodo transitório EXP-SAE dos Parâmetros de Despachos
	SELECT TOP 1 @PeriodoTransitorio = PDE_PTEX 
	FROM TAB_PDES WITH(NOLOCK)
-- obtém dados da Declaração Exportação/XML
	SELECT TOP 1 @CodIntXML = e.EXM_CODI, @CodEstXML = e.EAD_CODA, @StatusXML = e.EXM_STAT, @Casa2Pais = p.PAI_C2E1, @NomePais = p.PAI_NOME, @CodExpeXML = e.CLI_COD2, @CodDestXML = e.FOR_COD8, 
		@Casa4Pais = p.PAI_C4E1, @PaisDestXML = e.EXM_P17A, @TotalVolsXML = e.EXM_TVL6, @TotalMassaBrtXML = e.EXM_TMBR, @NomeExpeXML = e.CLI_NOM2, @MoradaExpeXML = e.CLI_MOR2, 
		@LocExpeXML = e.CLI_LOC2, @CodPostalExpeXML = e.CLI_CPO2, @LocPostalExpeXML = e.CLI_LPO2, @ContrExpeXML = e.CLI_NIF2, @NomeDestXML = e.FOR_NOM8, @MoradaDestXML = e.FOR_MOR8, 
		@LocDestXML = e.FOR_LOC8, @CodPostalDestXML = e.FOR_CPO8, @LocPostalDestXML = e.FOR_LPO8, @ContrDestXML = e.FOR_NIF8, @NumDGA = e.EXM_NDGA, @DataDGA = e.EXM_DDGA, 
		@TipoProcedimento = e.EXM_TPRO, @IdDeclXML = e.EXM_IDTY, @CtxDeclXML = e.EXM_CNTX, @TipoDecl1Casa = t.TDE_1CAS
	FROM PRO_EXML AS e WITH(NOLOCK) 
		INNER JOIN TAB_TDEC AS t WITH(NOLOCK) ON e.TDE_COD1 = t.TDE_CODI
		INNER JOIN TAB_PAIS AS p WITH(NOLOCK) ON e.EXM_P17A = p.PAI_CODI
	WHERE e.EXM_EANO = @AnoXML AND e.DEC_CODI = @OperXML AND e.EXM_NRII = @CodRefIntXML
-- obtém dados da 1ª marca da 1ª adicao do XML
	SELECT TOP 1 @MarcaXML = m.EXM_MARN, @CodUnidXML = m.TEM_CODI
	FROM PRO_EXMV AS m WITH(NOLOCK) 
		INNER JOIN PRO_EXAD AS a WITH(NOLOCK) ON m.EXA_CHVE = a.EXA_CHVE
	WHERE a.EXM_EANO = @AnoXML AND a.EXM_CODI = @CodIntXML AND a.EXM_COPE = @OperXML AND a.EXA_LINH = 1
-- obtem documentos de facturacao no detalhe de Documentos da declaração ou sub-detalhe de Documentos da 1ª adicao
	IF (@CtxDeclXML = 1) AND (@PeriodoTransitorio = 0)
	BEGIN
		DECLARE DocsFacturacao CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR			
			SELECT ddo.numero, ddo.dataValidade
			FROM tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY				
			WHERE ddo.id_declaracaoEXP = @IdDeclXML AND doc.DOC_CODI = 'N380' AND ISNULL(ddo.numero, '') <> '' 
	END
	ELSE
	BEGIN
		DECLARE DocsFacturacao CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR			
			SELECT d.EXD_NREF, d.EXD_DTEM
			FROM PRO_EXDA AS d WITH(NOLOCK) 
				INNER JOIN PRO_EXAD AS a WITH(NOLOCK) ON d.EXA_CHVE = a.EXA_CHVE
			WHERE a.EXM_EANO = @AnoXML AND a.EXM_CODI = @CodIntXML AND a.EXM_COPE = @OperXML AND a.EXA_LINH = 1 AND d.DOC_CODI = 'N380' AND ISNULL(d.EXD_NREF, '') <> '' 
	END
	OPEN DocsFacturacao
	FETCH NEXT FROM DocsFacturacao INTO @AuxCodDocumento, @AuxDataDocumento
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @NumsDocFact = @NumsDocFact + '; ' + @AuxCodDocumento
		SET @NumsDatasDocFact = @NumsDatasDocFact + '; ' + @AuxCodDocumento + ' * ' + ISNULL(CONVERT(varchar(10), @AuxDataDocumento, 105), '?')
		FETCH NEXT FROM DocsFacturacao INTO @AuxCodDocumento, @AuxDataDocumento
	END
	CLOSE DocsFacturacao
	DEALLOCATE DocsFacturacao
-- trata lista de documentos de facturacao
	IF @NumsDocFact <> '' 
		SET @NumsDocFact = STUFF(@NumsDocFact, 1, 2, '')
	IF @NumsDatasDocFact <> '' 
		SET @NumsDatasDocFact = STUFF(@NumsDatasDocFact, 1, 2, '')	
-- processa a inserção ou atualização dependendo se ja existe um modelo EUR1 associado
	IF EXISTS(SELECT * FROM PRO_EUR1 WITH(NOLOCK) WHERE DUC_EANO = @AnoXML AND DUC_PNUM = @CodRefIntXML AND DEC_CODI = @OperXML)
	BEGIN
		UPDATE PRO_EUR1 SET EUR_DATA = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), ALF_CODI = @CodEstXML, EUR_STAT = @StatusXML, EUR_ENTA = @Casa2Pais, EUR_ENTB = @NomePais, EUR_EXP1 = @CodExpeXML, 
			EUR_DST3 = @CodDestXML, EUR_PAI4 = @Casa4Pais, PAI_COD5 = @PaisDestXML, EUR_MC10 = @MarcaXML, EUR_QT10 = @TotalVolsXML, UME_CO10 = @CodUnidXML, EUR_PBTT = @TotalMassaBrtXML, 
			EUR_ENOM = @NomeExpeXML, EUR_EMOR = @MoradaExpeXML, EUR_ELOC = @LocExpeXML, EUR_ECPO = @CodPostalExpeXML, EUR_ELPO = @LocPostalExpeXML, EUR_ENIF = @ContrExpeXML, 
			EUR_DNOM = @NomeDestXML, EUR_DMOR = @MoradaDestXML, EUR_DLOC = @LocDestXML, EUR_DCPO = @CodPostalDestXML, EUR_DLPO = @LocPostalDestXML, EUR_DNIF = @ContrDestXML, 
			EUR_NUMD = @NumsDocFact, EUR_NDGA = @NumDGA, EUR_DDGA = @DataDGA, EUR_TPRO = @TipoProcedimento, EUR_TD1C = @TipoDecl1Casa, EUR_NUDD = @NumsDatasDocFact
		WHERE DUC_EANO = @AnoXML AND DUC_PNUM = @CodRefIntXML AND DEC_CODI = @OperXML
	END
	ELSE
	BEGIN
		INSERT INTO PRO_EUR1(DUC_EANO, DUC_PNUM, DEC_CODI, EUR_DATA, ALF_CODI, EUR_STAT, EUR_ENTA, EUR_ENTB, EUR_EXP1, EUR_DST3, EUR_PAI4, PAI_COD5, EUR_MC10, EUR_QT10, UME_CO10, EUR_PBTT, 
			EUR_ENOM, EUR_EMOR, EUR_ELOC, EUR_ECPO, EUR_ELPO, EUR_ENIF, EUR_DNOM, EUR_DMOR, EUR_DLOC, EUR_DCPO, EUR_DLPO, EUR_DNIF, EUR_NUMD, EUR_NDGA, EUR_DDGA, EUR_TPRO, EUR_TD1C, EUR_NUDD)
		VALUES(@AnoXML, @CodRefIntXML, @OperXML, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @CodEstXML, @StatusXML, @Casa2Pais, @NomePais, @CodExpeXML, @CodDestXML, @Casa4Pais, @PaisDestXML, @MarcaXML, @TotalVolsXML, @CodUnidXML, @TotalMassaBrtXML, 
			@NomeExpeXML, @MoradaExpeXML, @LocExpeXML, @CodPostalExpeXML, @LocPostalExpeXML, @ContrExpeXML, @NomeDestXML, @MoradaDestXML, @LocDestXML, @CodPostalDestXML, @LocPostalDestXML, @ContrDestXML, @NumsDocFact, @NumDGA, @DataDGA, @TipoProcedimento, @TipoDecl1Casa, @NumsDatasDocFact)
	END
-- remove as adicoes existentes do EUR1
	DELETE FROM PRO_AEUR 
	WHERE DUC_EANO = @AnoXML AND DUC_PNUM = @CodRefIntXML AND DEC_CODI = @OperXML
-- obtem dados das adicoes XML
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EXA_CHVE, EXA_LINH, APA_CO33, APA_DESG, EXA_MBRT
		FROM PRO_EXAD WITH(NOLOCK)
		WHERE EXM_EANO = @AnoXML AND EXM_CODI = @CodIntXML AND EXM_COPE = @OperXML
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @IdenAdi, @NumLinhaAdi, @CodArtAdi, @DescArtAdi, @MassaBrtAdi
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- busca dados do artigo
		SELECT @EUR1Art = APA_EUR1, @DescComArt = APA_DCOM
		FROM TAB_APAU WITH(NOLOCK)
		WHERE APA_CODI = @CodArtAdi
-- soma num volumes da adicao
		SELECT @TotalVolsAdi = ISNULL(SUM(EXM_NVOL), 0)
		FROM PRO_EXMV WITH(NOLOCK)
		WHERE EXA_CHVE = @IdenAdi
-- verifica se 1ª linha da Casa 31 da adicao é Parte ou Resto
		SELECT TOP 1 @ParteResto = (CASE EXM_PART WHEN 1 THEN 1 ELSE (CASE EXM_REST WHEN 1 THEN 2 ELSE NULL END) END)
		FROM PRO_EXMV WITH(NOLOCK)
		WHERE EXA_CHVE = @IdenAdi
-- verifica se utiliza descricao comercial
		IF (@EUR1Art = 1) AND (ISNULL(@DescComArt, '') <> '')
			SET @DescArtAdi = @DescComArt
-- insere adicao no EUR1	
		INSERT INTO PRO_AEUR(DUC_EANO, DUC_PNUM, DEC_CODI, AEU_CODI, APA_CODI, AEU_DPAU, AEU_PBRT, AEU_TVOL, AEU_PTRT)
		VALUES(@AnoXML, @CodRefIntXML, @OperXML, @NumLinhaAdi, @CodArtAdi, @DescArtAdi, @MassaBrtAdi, @TotalVolsAdi, @ParteResto)
		FETCH NEXT FROM Adicoes INTO @IdenAdi, @NumLinhaAdi, @CodArtAdi, @DescArtAdi, @MassaBrtAdi
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes
END

ALTER AUTHORIZATION ON [SP_geraEUR1ExportXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraEUR1ExportXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraG156]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraG156] @cod int, @ano int AS
-- declaracoes de variaveis -- ------------------------------------------------------------------------------
declare @contador int, @codAlf varchar(8), @status int, --@docDe varchar(15), @docTrans varchar(15),
	@codExp varchar(18), @nomeExp varchar(70), @morExp varchar(70), @locExp varchar(35), @codPosExp varchar(12),
	@locPosExp varchar(35), @nifExp varchar(18), @paisExp varchar(2), @codDest varchar(18), @nomeDest varchar(70),
	@morDest varchar(70), @locDest varchar(35), @codPosDest varchar(12), @locPosDest varchar(35),
	@nifDest varchar(18), @paisDest varchar(2), @marca varchar(20), @num varchar(20), @quant numeric(38, 6), @natur varchar(3),
	@pBruto numeric(38, 6), @codArtigo varchar(22), @desArtigo varchar(150), @desComercial varchar(150), 
	@codLinha int,  @contDesig varchar(20), @assumG156 bit, @trans varchar(2), @nomeTrans varchar(30),
	@tipoDecla int, @transOrig varchar(2), @conta int

	-- busca registo da tabela PRO_DUCG -----------------------------------------------------------------
	SELECT @codAlf = duc.ALF_CODI, @pBruto = duc.DUC_MBRT, @nomeTrans = duc.DUC_MT18, @status = duc.DUC_STAT,
	@codDest = duc.DUC_DST8, @paisDest = duc.PAI_P17A, @nomeDest = duc.DUC_DNOM, @morDest = duc.DUC_DMOR,
	@locDest = duc.DUC_DLOC, @codPosDest = duc.DUC_DCPO, @locPosDest = duc.DUC_DLPO, @nifDest = duc.DUC_DNIF,
	@codExp = DEC_CO14, @tipoDecla = duc.DUC_TIPO, @transOrig = duc.MTR_PT18, @quant = duc.DUC_TVL6
	FROM PRO_DUCG duc 
	WHERE duc.DUC_PNUM = @cod and duc.DUC_EANO = @ano

	-- verifica se o cliente tem armazens definidos -----------------------------------------------------
	SELECT @conta=COUNT(*)
	FROM TAB_CARM
	WHERE CLI_CODI=@codDest
	IF @conta>0
	BEGIN
		SELECT TOP 1 @morDest=CAR_MORA,@locDest=CAR_LOCA,@codPosDest=CAR_CPOS,@locPosDest=CAR_LPOS
		FROM TAB_CARM
		WHERE CLI_CODI=@codDest
	END
	
	IF @transOrig <> '10'
	BEGIN
		SELECT @nomeTrans = ''
	END

	SELECT @paisExp = PAI_CODI, @nomeExp = DEC_NOME, @morExp = DEC_MORA,
	@locExp = DEC_LOCA, @codPosExp = DEC_CPOS, @locPosExp = DEC_LPOS, @nifExp = DEC_NIF
	FROM TAB_DECL 
	WHERE DEC_CODI = @codExp 

	SELECT @marca = d31.D31_MARC, @num = d31.D31_NUME, @natur = d31.UME_CODI,
	@codArtigo = adi.APA_CO33, @desArtigo = adi.DUA_DESG
	FROM PRO_DUAD adi, PRO_DU31 d31
	WHERE adi.DUC_PNUM = @cod AND adi.DUC_EANO = @ano AND adi.DUA_CODI = 1 	
	AND d31.DUC_PNUM = adi.DUC_PNUM AND d31.DUC_EANO = adi.DUC_EANO AND d31.DUA_CODI = adi.DUA_CODI AND d31.D31_CODI = 1
	
	-- verifica se A GUIA G156 já foi gerada ------------------------------------------------------------
	SELECT @contador = count(*)
	FROM PRO_G156
	WHERE DUC_PNUM = @cod and DUC_EANO = @ano

	-- se nao foi gerado insere campos na PRO_ATRC ------------------------------------------------------
	IF @contador = 0
	BEGIN
		SET DATEFORMAT dmy
		
		SELECT @trans = MTR_CODI
		FROM TAB_MTRA
		WHERE MTR_CODI = '30'	
				

		SELECT @assumG156 = APA_G156, @desComercial = APA_DCOM
		FROM TAB_APAU
		WHERE APA_CODI = @codArtigo	
		
		IF ((@desComercial is not NULL) OR (@desComercial = '')) AND (@assumG156 = '1')
		BEGIN
			INSERT INTO PRO_G156(DUC_EANO, DUC_PNUM, G15_DATA, G15_STAT, ALF_CODI, G15_NNAV, G15_LDES,
				G15_DES1, G15_1NOM, G15_1MOR, G15_1LOC, G15_1CPO, G15_1LPO, G15_1NIF, PAI_COD1,
				G15_DEC2, G15_2NOM, G15_2MOR, G15_2LOC, G15_2CPO, G15_2LPO, G15_2NIF, PAI_COD2,
				G15_MARC, G15_NUME, G15_QUNT, UME_CODI, G15_PBTT, APA_CODI, G15_DESG, MTR_CODI,
				G15_TIPO)
			VALUES (@ano, @cod, getdate(), @status, @codAlf, @nomeTrans, @morDest,
				@codDest, @nomeDest, @morDest, @locDest, @codPosDest, @locPosDest, @nifDest, @paisDest,
				@codExp, @nomeExp, @morExp, @locExp, @codPosExp, @locPosExp, @nifExp, @paisExp,
				@marca, @num, @quant, @natur, @pBruto, @codArtigo, @desComercial, @trans,
				@tipoDecla)
		END
		ELSE
		BEGIN
			INSERT INTO PRO_G156(DUC_EANO, DUC_PNUM, G15_DATA, G15_STAT, ALF_CODI, G15_NNAV, G15_LDES,
				G15_DES1, G15_1NOM, G15_1MOR, G15_1LOC, G15_1CPO, G15_1LPO, G15_1NIF, PAI_COD1,
				G15_DEC2, G15_2NOM, G15_2MOR, G15_2LOC, G15_2CPO, G15_2LPO, G15_2NIF, PAI_COD2,
				G15_MARC, G15_NUME, G15_QUNT, UME_CODI, G15_PBTT, APA_CODI, G15_DESG, MTR_CODI,
				G15_TIPO)
			VALUES (@ano, @cod, getdate(), @status, @codAlf, @nomeTrans, @morDest,
				@codDest, @nomeDest, @morDest, @locDest, @codPosDest, @locPosDest, @nifDest, @paisDest,
				@codExp, @nomeExp, @morExp, @locExp, @codPosExp, @locPosExp, @nifExp, @paisExp,
				@marca, @num, @quant, @natur, @pBruto, @codArtigo, @desArtigo, @trans,
				@tipoDecla)
		END
	END
	ELSE
	-- se ja foi gerado altera campos do modelo PRO_GCIR ------------------------------------------------
	BEGIN
		SET DATEFORMAT dmy

		SELECT @assumG156 = APA_G156, @desComercial = APA_DCOM
		FROM TAB_APAU
		WHERE APA_CODI = @codArtigo	
		
		IF ((@desComercial is not NULL) OR (@desComercial = '')) AND (@assumG156 = '1')
		BEGIN
			UPDATE PRO_G156 SET DUC_EANO = @ano, DUC_PNUM = @cod, G15_DATA =  getdate(), ALF_CODI = @codAlf,
				G15_NNAV = @nomeTrans,	G15_LDES = @morDest, G15_STAT = @status,
				G15_DES1 = @codDest, G15_1NOM =  @nomeDest, G15_1MOR = @morDest, G15_1LOC = @locDest,
				G15_1CPO = @codPosDest, G15_1LPO = @locPosDest, G15_1NIF = @nifDest, PAI_COD1 = @paisDest,
				G15_DEC2 = @codExp, G15_2NOM = @nomeExp, G15_2MOR = @morExp, G15_2LOC = @locExp,
				G15_2CPO = @codPosExp, G15_2LPO = @locPosExp, G15_2NIF =@nifExp, PAI_COD2 = @paisExp,
				G15_MARC = @marca, G15_NUME = @num, G15_QUNT = @quant, UME_CODI = @natur,
				G15_PBTT = @pBruto, APA_CODI = @codArtigo, G15_DESG = @desComercial,
				G15_TIPO = @tipoDecla
			WHERE DUC_PNUM = @cod and DUC_EANO = @ano
		END
		ELSE
		BEGIN
			UPDATE PRO_G156 SET DUC_EANO = @ano, DUC_PNUM = @cod,   G15_DATA =  getdate(), ALF_CODI = @codAlf,
				G15_NNAV = @nomeTrans,  G15_LDES = @morDest,    G15_STAT = @status,
				G15_DES1 = @codDest,    G15_1NOM =  @nomeDest,  G15_1MOR = @morDest, G15_1LOC = @locDest,
				G15_1CPO = @codPosDest, G15_1LPO = @locPosDest, G15_1NIF = @nifDest, PAI_COD1 = @paisDest,
				G15_DEC2 = @codExp,     G15_2NOM = @nomeExp,    G15_2MOR = @morExp,  G15_2LOC = @locExp,
				G15_2CPO = @codPosExp,  G15_2LPO = @locPosExp,  G15_2NIF =@nifExp,   PAI_COD2 = @paisExp,
				G15_MARC = @marca,      G15_NUME = @num,        G15_QUNT = @quant,   UME_CODI = @natur,
				G15_PBTT = @pBruto,     APA_CODI = @codArtigo,  G15_DESG = @desArtigo,
				G15_TIPO = @tipoDecla
			WHERE DUC_PNUM = @cod and DUC_EANO = @ano
		END
	END

	-- obtem as adições do documento único --------------------------------------------------------------
	DELETE FROM PRO_CG15 WHERE DUC_PNUM = @cod and DUC_EANO = @ano	

	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT DCO_CODI, DCO_CNUM
	FROM PRO_DCON
	WHERE DUC_PNUM = @cod and DUC_EANO = @ano and DUA_CODI = '1'

	OPEN Detalhe
	FETCH NEXT from Detalhe into @codLinha, @contDesig

	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		INSERT INTO PRO_CG15(DUC_EANO, DUC_PNUM, CG1_LINH, CG1_DESG)
		VALUES(@ano, @cod, @codLinha, @contDesig)
		FETCH NEXT from Detalhe into @codLinha, @contDesig
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe

ALTER AUTHORIZATION ON [SP_geraG156] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraG156] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_AtualizaPROFECTDeclaracoesDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_AtualizaPROFECTDeclaracoesDHL] @NumDocTransporte varchar(35), @ValorFrete decimal(18, 2), @CodPaisFrete varchar(2), @Utilizador varchar(30), @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @IdUtilizador int, @MoedaPaisFrete varchar(3), @CambioMoedaFrete numeric(38, 6), @AnoDeclaracaoDUI2 int, @NumDeclaracaoDUI2 int, @Resultado int, 
		@Erros varchar(8000), @IdDeclaracaoDAR int, @IdDeclaracaoDUI2 bigint, @ContextoIMP int, @CambioMoedaOriginal numeric(38, 6), @MoedaFreteOriginal varchar(3)
-- inicia processo de atualização da declaração	DUI2/DAR
	BEGIN TRY	
		SET @NumErro = 0		
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- calcula a moeda do frete original p/ "XXX" quando o país do frete não tem um último câmbio válido
		IF NOT EXISTS(SELECT 1 FROM TAB_PAPL WITH(NOLOCK) WHERE PAI_CODI = @CodPaisFrete) 
		BEGIN
			SET @CambioMoedaOriginal = 0			
			SELECT TOP 1 @CambioMoedaOriginal = ISNULL(CPA_VEND, 0) 
			FROM TAB_CPAI WITH(NOLOCK) 
			WHERE PAI_CODI = @CodPaisFrete AND CAST(CONVERT(varchar(10), CPA_DATA, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)
			ORDER BY CPA_DATA DESC
			IF @CambioMoedaOriginal = 0
				SET @MoedaFreteOriginal = 'XXX'
			ELSE
				SET @MoedaFreteOriginal = 'EUR'
		END
		ELSE
			SET @MoedaFreteOriginal = 'EUR'
-- verifica se documento de transporte existe em DUI2
		IF EXISTS(SELECT DUC_IDTY FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_EANO IN (YEAR(@DataAtual), (YEAR(@DataAtual) - 1)) AND DUC_CPRT = @NumDocTransporte)
		BEGIN			
			SET @AnoDeclaracaoDUI2 = NULL
			SET @NumDeclaracaoDUI2 = NULL
			SET @ContextoIMP = NULL
-- obtem câmbio da moeda do país do frete
			SELECT @MoedaPaisFrete = PAI_PREF, @CambioMoedaFrete = dbo.FNT_Geral_ObtemCambio(0, PAI_CODI, @DataAtual)
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPaisFrete
-- obtem o ID da declaração de importação
			SELECT TOP 1 @ContextoIMP = DUC_DUNO, @IdDeclaracaoDUI2 = DUC_IDTY
			FROM PRO_DUCG WITH(NOLOCK) 
			WHERE DUC_EANO IN (YEAR(@DataAtual), (YEAR(@DataAtual) - 1)) AND DUC_CPRT = @NumDocTransporte
			ORDER BY DUC_IDTY DESC
-- atualiza frete da companhia da declaração de importação				
			UPDATE PRO_DUCG SET 
				DUC_VFRC = ROUND(@ValorFrete / @CambioMoedaFrete, 2), 
				DUC_MFRC = @MoedaFreteOriginal, 
				DUC_UALT = @Utilizador, 
				DUC_DTAL = @DataAtual
			WHERE DUC_IDTY = @IdDeclaracaoDUI2
-- se declaração for do tipo IMP-CAU, processa atualizações do frete se declaração satisfaz as condições de atualização
			IF @ContextoIMP = 2 
			BEGIN
				UPDATE PRO_DUCG SET 
					DUC_FRET = @ValorFrete, 
					PAI_FRET = @CodPaisFrete, 
					DUC_TXFR = @CambioMoedaFrete, 
					PAI_MOFT = @MoedaPaisFrete,											
					DUC_UALT = @Utilizador, 
					DUC_DTAL = @DataAtual
				WHERE DUC_IDTY = @IdDeclaracaoDUI2 AND DUC_STAT = 0 AND ((ISNULL(DUC_FRET, 0) > 0) OR ((ISNULL(DUC_FRET, 0) = 0) AND (ISNULL(CEN_CO20, '') IN ('FCA', 'EXW'))))
					AND NOT EXISTS(SELECT * 
									FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 
										INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY 
									WHERE ddo.id_declaracaoIMP = PRO_DUCG.DUC_IDTY AND doc.DOC_CODI = '9E33')				
			END
			ELSE
			BEGIN
-- verifica se a declaração DUI2 satisfaz as condições de atualização, obtendo o seu Número
				SELECT TOP 1 @AnoDeclaracaoDUI2 = duc.DUC_EANO, @NumDeclaracaoDUI2 = duc.DUC_PNUM 
				FROM PRO_DUCG AS duc WITH(NOLOCK) 
				WHERE duc.DUC_IDTY = @IdDeclaracaoDUI2 AND duc.DUC_STAT = 0 AND ((ISNULL(duc.DUC_FRET, 0) > 0) OR ((ISNULL(duc.DUC_FRET, 0) = 0) AND (ISNULL(duc.CEN_CO20, '') IN ('FCA', 'EXW'))))
					AND NOT EXISTS(SELECT * 
									FROM PRO_DDOC WITH(NOLOCK) 
									WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1 AND DOC_CODI = '9E33')				
-- se declaração DUI2 está válida, procede às atualizações
				IF @NumDeclaracaoDUI2 IS NOT NULL
				BEGIN				
					EXEC @Resultado = SP_DeclImportacao_AtualizaDadosDeclaracao @NumDeclaracaoDUI2, @AnoDeclaracaoDUI2, NULL, NULL, @Utilizador, @Erros OUTPUT, @ValorFrete, @CodPaisFrete
					IF @Resultado <> 0
						RAISERROR ('%s', 16, 1, @Erros)	
				END
			END
		END
		ELSE
-- verifica se documento de transporte existe em DAR
			IF EXISTS(SELECT id FROM tb_DeclaracoesDAR WITH(NOLOCK) WHERE ano IN (YEAR(@DataAtual), (YEAR(@DataAtual) - 1)) AND documentoTransporte = @NumDocTransporte)
			BEGIN
				SET @IdDeclaracaoDAR = NULL
-- verifica se a declaração DAR satisfaz as condições de atualização, obtendo o seu ID
				SELECT TOP 1 @IdDeclaracaoDAR = id 
				FROM tb_DeclaracoesDAR WITH(NOLOCK) 
				WHERE ano IN (YEAR(@DataAtual), (YEAR(@DataAtual) - 1)) AND documentoTransporte = @NumDocTransporte AND status = 0
-- se declaração DAR está válida, procede às atualizações				
				IF @IdDeclaracaoDAR IS NOT NULL
				BEGIN
-- obtem o ID do utilizador
					SELECT @IdUtilizador = UTI_IDTY
					FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
					WHERE UTI_UTIL = @Utilizador
-- atualiza a vossa referência e os dados do frete original
					UPDATE tb_DeclaracoesDAR SET 
						freteOriginal = ROUND(@ValorFrete / dbo.FNT_Geral_ObtemCambio(0, @CodPaisFrete, @DataAtual), 2), 
						moedaFreteOriginal = @MoedaFreteOriginal, 
						id_utilizadorControlo = @IdUtilizador,
						dataControlo = @DataAtual
					WHERE id = @IdDeclaracaoDAR
				END
			END
			ELSE
				SET @NumErro = 2
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro; 2: Doc. Transporte inexistente)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_Geral_AtualizaPROFECTDeclaracoesDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_AtualizaPROFECTDeclaracoesDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_EnviaDeclaracoesWSPortalERDO]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_EnviaDeclaracoesWSPortalERDO] @Endpoint varchar(500), @SOAPActionProcessoCab varchar(500), @SOAPActionProcessoAdi varchar(500), @SOAPActionProcessoCon varchar(500), 
	@SOAPActionProcessoDoc varchar(500), @HeaderToken varchar(8000), @IdIntegrationSystem int, @DataReferencia datetime, @DirLogFile varchar(500) AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variaveis	
	DECLARE @DataAtual datetime, @CtxProcesso varchar(1), @AnoProcesso int, @NumProcesso int, @IdProcesso int, @CodDeclarante varchar(6), @Data datetime, @NumOrdem varchar(21), 
		@DataOrdem datetime, @CodEstanciaA varchar(8), @TotalVols numeric(38, 6), @CodExportador varchar(18), @CodDestinatario varchar(18), @CodMeioTransporte varchar(2), 
		@CodCondEntrega varchar(3), @TotalMassaBrt numeric(38, 6), @NomeExportador varchar(70), @MoradaExportador varchar(70), @CodPostalExportador varchar(12), @LocalidadeExportador varchar(35), 
		@CodPaisExportador varchar(2), @NomeDestinatario varchar(70), @MoradaDestinatario varchar(70), @CodPostalDestinatario varchar(12), @LocalidadeDestinatario varchar(35), 
		@CodPaisDestinatario varchar(2), @TotalRecapitulativo numeric(38, 6), @ValorAduaneiroTotal numeric(38, 6), @Moeda varchar(3), @VossaReferencia varchar(50), @DataLiqRecapitulativa datetime, 
		@DataAS datetime, @NumCaucao varchar(24), @CodEstancia29 varchar(8), @DataCS datetime, @RegimePortal varchar(35), @EstadoProcessoPortal smallint, @Acao varchar(1), @Regime varchar(4),
		@DataContramarca datetime			
	DECLARE @NumAdicao int, @CodPautalArtigo varchar(22), @TxIVA numeric(38, 6), @MassaLiq numeric(38, 6), @QtdUnidades numeric(38, 6), @Valor numeric(38, 6), @Frete numeric(38, 6), 
		@Seguro numeric(38, 6), @VerbaTransitario numeric(38, 6), @Royalties numeric(38, 6), @Optativas numeric(38, 6), @ValorEstatistico numeric(38, 6), @ValorAduaneiro numeric(38, 6), 
		@TaxaValorDireitos numeric(38, 6), @MontanteDireitos numeric(38, 6), @MontanteIVA numeric(38, 6), @ValorEUR numeric(38, 6), @NomeUnidMedida varchar(35), @TxCambio numeric(38, 6)	
	DECLARE @NumContentor int, @Contentor varchar(50), @IdContentor int
	DECLARE @IdFicheiro int, @DescricaoFicheiroPDF varchar(150), @PathFicheiroPDF varchar(500), @NomeFicheiroPDF varchar(100), @TipoMsgFicheiroPDF varchar(8), @FicheiroBinarioPDF varbinary(MAX), 
		@FicheiroBase64 varchar(MAX)
	DECLARE @SQLString nvarchar(500), @SQLParams nvarchar(500)
	DECLARE @XMLDeclaracao xml, @XMLRequest xml, @XMLResponse xml, @Sucesso bit, @ErrorCode int, @ErrorMessage varchar(MAX)
	DECLARE @Comando nvarchar(4000), @PathLogFile varchar(600)
-- verfica se diretoria tem backslash no final
	IF SUBSTRING(REVERSE(@DirLogFile), 1, 1) <> '\'
		SET @DirLogFile = @DirLogFile + '\'
-- cria tabela temporária p/ guardar informação da exportação
	CREATE TABLE ##LogTableDeclsPortal(	
		ID int NOT NULL IDENTITY(1, 1), 	
		NUMPROCESSO int NOT NULL, 
		ANOPROCESSO int NOT NULL,
		CTXPROCESSO varchar(1) COLLATE Latin1_General_CI_AI NOT NULL, 
		LINHA varchar(120) COLLATE Latin1_General_CI_AI NULL, 
		INFO varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- efetua o log do inicio do processo de envio do CAB de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# INICIO ENVIO PROCESSOS-CAB ###############################################################################################################################')
	END
	BEGIN TRY
-- obtem os dados gerais das declarações IMP/EXP com n.º ordem e pendentes de envio para o Portal MyRangel
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT 'I' AS DUC_CTXT, duc.DUC_EANO, duc.DUC_PNUM, NULL AS DUC_IDEN, NULL AS DEC_CODI, duc.DUC_DATA, duc.DUC_NORD, duc.DUC_NDAT, duc.ALF_CODI, ISNULL(duc.DUC_TVL6, 0) AS DUC_TVL6, 
				duc.DUC_EXP2, duc.DUC_DST8, duc.MTR_PT18, duc.CEN_CO20, ISNULL(duc.DUC_MBRT, 0) AS DUC_MBRT, duc.DUC_ENOM, duc.DUC_EMOR, duc.DUC_ECPO, duc.DUC_ELOC, duc.PAI_ELIV, duc.DUC_DNOM, 
				duc.DUC_DMOR, duc.DUC_DCPO, duc.DUC_DLOC, duc.PAI_DLIV, ISNULL(duc.DUC_VLRC, 0) AS DUC_VLRC, ISNULL(duc.DUC_VATT, 0) AS DUC_VATT, duc.PAI_MO22, duc.DUC_NVRF, duc.DUC_DTRL, 
				duc.DUC_DTAS, duc.DUC_CAUC, NULL AS EAD_CO29, NULL AS EXM_DTCS, nde.NDE_WDES, 
				(CASE 					
					WHEN duc.DUC_STAT = 3 THEN 299 --status "Anulado"
					WHEN duc.DUC_ESTO IN ('CD', 'CFP', 'CAP') THEN 203 
					WHEN duc.DUC_ESTO = 'ND' THEN 205
					WHEN duc.DUC_ESTO = 'AS' THEN 206
					ELSE 202
				END) AS DUC_EPRP, 
				(CASE 
					WHEN duc.DUC_PMRD IS NULL THEN 'I'	
					WHEN duc.DUC_STAT = 3 THEN 'D' --status "Anulado"
					ELSE 'U'
				END) AS DUC_ACAO,
				(SELECT TOP 1 DUA_RG37 FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1) AS DUA_RG37,
				(SELECT TOP 1 DRA_APDT FROM PRO_DURA WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1 AND DRA_QUAL = 'X' AND DRA_AUTO = 0) AS DRA_APDT
			FROM PRO_DUCG AS duc WITH(NOLOCK)
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON duc.NDE_CODI = nde.NDE_CODI				
			WHERE duc.DUC_STAT > 0 AND ISNULL(duc.DUC_NORD, '') <> '' AND duc.DUC_PMRP = 1 AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), duc.DUC_NDAT, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			UNION ALL
			SELECT 'E' AS DUC_CTXT, exm.EXM_EANO, exm.EXM_NRII, exm.EXM_CODI, exm.DEC_CODI, exm.EXM_DATA, exm.EXM_NDGA, exm.EXM_DDGA, exm.EAD_CODA, ISNULL(exm.EXM_TVL6, 0) AS DUC_TVL6, 
				exm.CLI_COD2, exm.FOR_COD8, ISNULL(NULLIF(exm.MTR_CO18, ''), exm.MTR_CO21), exm.CEN_CO20, ISNULL(exm.EXM_TMBR, 0) AS DUC_MBRT, exm.CLI_NOM2, exm.CLI_MOR2, exm.CLI_CPO2, exm.CLI_LOC2, exm.CLI_PAI2, exm.FOR_NOM8, 
				exm.FOR_MOR8, exm.FOR_CPO8, exm.FOR_LOC8, exm.FOR_PAI8, ISNULL(exm.EXM_VLRC, 0) AS DUC_VLRC, ISNULL(exm.EXM_VATT, 0) AS DUC_VATT, exm.PAI_MO22, exm.EXM_NVRF, NULL AS DUC_DTRL, 
				exm.EXM_DTAS, NULL AS DUC_CAUC, exm.EAD_CO29, exm.EXM_DTCS, nde.NDE_WDES, 
				(CASE 					
					WHEN exm.EXM_STAT = 3 THEN 299 --status "Anulado"
					WHEN exm.EXM_ESTO IN ('CD', 'CFP', 'CAP', 'CFS', 'CF') THEN 203 					
					WHEN exm.EXM_ESTO = 'AS' THEN 206
					WHEN exm.EXM_ESTO = 'CS' THEN 209
					ELSE 202
				END) AS DUC_EPRP, 
				(CASE 
					WHEN exm.EXM_PMRD IS NULL THEN 'I'					
					WHEN exm.EXM_STAT = 3 THEN 'D' --status "Anulado"
					ELSE 'U'
				END) AS DUC_ACAO,
				(SELECT TOP 1 TDE_REGI FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI AND EXA_LINH = 1) AS DUA_RG37, 
				NULL AS DRA_APDT			
			FROM PRO_EXML AS exm WITH(NOLOCK)				
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON exm.NDE_CODI = nde.NDE_CODI				
			WHERE exm.EXM_STAT > 0 AND ISNULL(exm.EXM_NDGA, '') <> '' AND exm.EXM_PMRP = 1 AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), exm.EXM_DDGA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			ORDER BY DUC_CTXT, DUC_EANO, DUC_PNUM		
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @Data, @NumOrdem, @DataOrdem, @CodEstanciaA, @TotalVols, @CodExportador, 
			@CodDestinatario, @CodMeioTransporte, @CodCondEntrega, @TotalMassaBrt, @NomeExportador, @MoradaExportador, @CodPostalExportador, @LocalidadeExportador, @CodPaisExportador, 
			@NomeDestinatario, @MoradaDestinatario, @CodPostalDestinatario, @LocalidadeDestinatario, @CodPaisDestinatario, @TotalRecapitulativo, @ValorAduaneiroTotal, @Moeda, @VossaReferencia, 
			@DataLiqRecapitulativa, @DataAS, @NumCaucao, @CodEstancia29, @DataCS, @RegimePortal, @EstadoProcessoPortal, @Acao, @Regime,	@DataContramarca
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @XMLResponse = NULL
			SET @Sucesso = 0
			SET @ErrorCode = NULL
			SET @ErrorMessage = NULL
-- constroi o XML com os dados do documento
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1)
			SELECT @XMLDeclaracao =
				(SELECT 
					@Acao AS "fjs1:in_accao", 
					@IdIntegrationSystem AS "fjs1:in_IntegrationSystem", 
					LTRIM(STR(@NumProcesso, 20)) AS "fjs1:in_REM_IDPROCESSO_IS", 
					NULLIF(@CodDestinatario, '') AS "fjs1:in_CodCliente_IS", 
					LEFT(@CtxProcesso, 1) AS "fjs1:in_REM_Regime", 
					LEFT(@CodMeioTransporte, 1) AS "fjs1:in_REM_Via", 
					CONVERT(varchar(10), @Data, 120) AS "fjs1:in_REM_DataProcesso", 
					NULLIF(@VossaReferencia, '') AS "fjs1:in_REM_RefCliente", 
					(CASE 
						WHEN ISNUMERIC(RIGHT(@CodEstanciaA, 3)) = 1 THEN CAST(RIGHT(@CodEstanciaA, 3) AS int) 
						ELSE NULL
					END) AS "fjs1:in_REM_EstAduaneira", 
					NULLIF(@RegimePortal, '') AS "fjs1:in_REM_RegimeAduaneiro", 
					(CASE @CtxProcesso
						WHEN 'I' THEN NULLIF(@CodPaisExportador, '')
						ELSE NULLIF(@CodPaisDestinatario, '')
					END) AS "fjs1:in_REM_CODPais", 
					NULLIF(@CodExportador, '') AS "fjs1:in_REM_CODEXPEDIDOR", 
					NULLIF(@NomeExportador, '') AS "fjs1:in_REM_NOMEEXPEDIDOR", 
					NULLIF(@MoradaExportador, '') AS "fjs1:in_REM_MORADAEXPEDIDOR", 
					NULLIF(@CodPostalExportador, '') AS "fjs1:in_REM_CODPOSTALEXPEDIDOR", 
					NULLIF(@LocalidadeExportador, '') AS "fjs1:in_REM_LOCALIDADEEXPEDIDOR", 
					NULLIF(@CodPaisExportador, '') AS "fjs1:in_REM_CODPAISEXPEDIDOR", 					
					NULLIF(@CodDestinatario, '') AS "fjs1:in_REM_CODDESTINATARIO", 
					NULLIF(@NomeDestinatario, '') AS "fjs1:in_REM_NOMEDESTINATARIO", 
					NULLIF(@MoradaDestinatario, '') AS "fjs1:in_REM_MORADADESTINATARIO", 
					NULLIF(@CodPostalDestinatario, '') AS "fjs1:in_REM_CODPOSTALDESTINATARIO", 
					NULLIF(@LocalidadeDestinatario, '') AS "fjs1:in_REM_LOCALIDADEDESTINATARIO", 
					NULLIF(@CodPaisDestinatario, '') AS "fjs1:in_REM_CODPAISDESTINATARIO", 					
					NULLIF(@CodExportador, '') AS "fjs1:in_REM_CODIMPORTADOREXPORTADOR", 
					NULLIF(@NomeExportador, '') AS "fjs1:in_REM_NOMEIMPORTADOREXPORTADOR", 
					NULLIF(@MoradaExportador, '') AS "fjs1:in_REM_MORADAIMPORTADOREXPORTADOR", 
					NULLIF(@CodPostalExportador, '') AS "fjs1:in_REM_CODPOSTALIMPORTADOREXPORTADOR", 
					NULLIF(@LocalidadeExportador, '') AS "fjs1:in_REM_LOCALIDADEIMPORTADOREXPORTADOR", 
					NULLIF(@CodPaisExportador, '') AS "fjs1:in_REM_CODPAISIMPORTADOREXPORTADOR", 					
					@CodCondEntrega AS "fjs1:in_REM_CondEntrega", 					
					(CASE 
						WHEN ISNUMERIC(RIGHT(@CodEstancia29, 3)) = 1 THEN CAST(RIGHT(@CodEstancia29, 3) AS int) 
						ELSE NULL
					END) AS "fjs1:in_REM_AlfandegaSaida", 					
					CAST(@TotalMassaBrt AS decimal(18, 3)) AS "fjs1:in_REM_Peso", 
					FLOOR(@TotalVols) AS "fjs1:in_REM_NrVolumes", 
					CAST(@ValorAduaneiroTotal AS decimal(18, 2)) AS "fjs1:in_REM_ValorMercadoria", 
					NULLIF(@Moeda, '') AS "fjs1:in_REM_Moeda", 
					@EstadoProcessoPortal AS "fjs1:in_REM_CodEstado", 
					NULLIF(@Regime, '') AS "fjs1:in_REM_NotasDespachante", 
					CONVERT(varchar(10), @DataContramarca, 120) AS "fjs1:in_REM_DtChegadaMercadoria", 					
					(CASE @CtxProcesso
						WHEN 'E' THEN NULLIF(@NumOrdem, '')
						ELSE NULL
					END) AS "fjs1:in_REM_DAE", 
					(CASE @CtxProcesso
						WHEN 'E' THEN CONVERT(varchar(10), @DataOrdem, 120)
						ELSE NULL
					END) AS "fjs1:in_REM_DtDAE", 
					(CASE @CtxProcesso
						WHEN 'E' THEN CONVERT(varchar(10), @DataCS, 120)
						ELSE NULL
					END) AS "fjs1:in_REM_DtCertificacao", 
					(CASE @CtxProcesso
						WHEN 'I' THEN NULLIF(@NumOrdem, '')
						ELSE NULL
					END) AS "fjs1:in_REM_DU", 
					(CASE @CtxProcesso
						WHEN 'I' THEN  CONVERT(varchar(10), @DataAS, 120)
						ELSE NULL
					END) AS "fjs1:in_REM_DtDesalfandegamento", 
					(CASE @CtxProcesso
						WHEN 'I' THEN NULLIF(@NumCaucao, '')
						ELSE NULL
					END) AS "fjs1:in_REM_NumCaucao", 
					CAST(@TotalRecapitulativo AS decimal(18, 2)) AS "fjs1:in_ValDivida", 
					(CASE @CtxProcesso
						WHEN 'I' THEN  CONVERT(varchar(10), @DataLiqRecapitulativa, 120)
						ELSE NULL
					END) AS "fjs1:in_REM_DtLiquidacaoCaucao", 
					0 AS "fjs1:in_StatusDocumental"
				FOR XML PATH('fjs1:webserv_Portal_ProcessoCab_receiveERDO'), ELEMENTS)
-- constroi estrutura XML com os dados do pedido ao metodo webserv_Portal_ProcessoCab_receiveERDO a enviar
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")		
			SELECT @XMLRequest = 
				(SELECT 
					(SELECT 
						(SELECT
							NULLIF(@HeaderToken, '') AS "fjs1:Token"
						FOR XML PATH('fjs1:clsValidaCabecalhoSOAP'), TYPE)
					FOR XML PATH('SOAP-ENV:Header'), ELEMENTS, TYPE),
					(SELECT
						@XMLDeclaracao		
					FOR XML PATH('SOAP-ENV:Body'), ELEMENTS, TYPE)
				FOR XML PATH('SOAP-ENV:Envelope'), ELEMENTS)
-- efetua o log do XML Request a enviar p/ o WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, '## XML-REQUEST: ' + CAST(@XMLRequest AS varchar(MAX)))
			END
-- processa envio do XML para o WS do Portal MyRangel	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @XMLRequest, @Endpoint, @SOAPActionProcessoCab, '', '', 0, '', 0, '', '', @XMLResponse OUTPUT
-- efetua o log do XML Response obtido do WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, '## XML-RESPONSE: ' + CAST(@XMLResponse AS varchar(MAX)))
			END
-- obtem dados de resposta do WS
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS "tns3", 
				'http://www.example.com/namespaces/tns/1608830539372' AS "tns1", 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "soapenv")
			SELECT 
				@Sucesso = x.r.value('tns3:Sucesso[1]', 'bit'), 
				@ErrorCode = x.r.value('tns3:ErrorCode[1]', 'int'), 
				@ErrorMessage = x.r.value('tns3:ErrorMessage[1]', 'varchar(MAX)')
			FROM @XMLResponse.nodes('soapenv:Envelope/soapenv:Body/tns3:webserv_Portal_ProcessoCab_receiveERDOResponse/tns3:webserv_Portal_ProcessoCab_receiveERDOResult') AS x(r)
-- se resultado for de sucesso, atualiza declaração IMP/EXP como enviado para Portal MyRangel
			IF @Sucesso = 1
			BEGIN
				IF @CtxProcesso = 'I' 
				BEGIN
					UPDATE PRO_DUCG SET DUC_PMRP = 0, DUC_PMRD = @DataAtual
					WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso
				END
				ELSE
				BEGIN
					UPDATE PRO_EXML SET EXM_PMRP = 0, EXM_PMRD = @DataAtual
					WHERE EXM_EANO = @AnoProcesso AND EXM_CODI = @IdProcesso AND DEC_CODI = @CodDeclarante
				END
-- efetua o log da declaração IMP/EXP marcada como enviado para Portal MyRangel
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN
					INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)				
					VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, '## SQL-UPDATE: Declaracao marcada como enviada para o Portal MyRangel.')					
				END
			END
			FETCH NEXT FROM Declaracoes INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @Data, @NumOrdem, @DataOrdem, @CodEstanciaA, @TotalVols, @CodExportador, 
				@CodDestinatario, @CodMeioTransporte, @CodCondEntrega, @TotalMassaBrt, @NomeExportador, @MoradaExportador, @CodPostalExportador, @LocalidadeExportador, @CodPaisExportador, 
				@NomeDestinatario, @MoradaDestinatario, @CodPostalDestinatario, @LocalidadeDestinatario, @CodPaisDestinatario, @TotalRecapitulativo, @ValorAduaneiroTotal, @Moeda, @VossaReferencia, 
				@DataLiqRecapitulativa, @DataAS, @NumCaucao, @CodEstancia29, @DataCS, @RegimePortal, @EstadoProcessoPortal, @Acao, @Regime,	@DataContramarca
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, 0, '', '## ERRO: ' + ERROR_MESSAGE())							
		END
	END CATCH
-- efetua o log do fim do processo de envio do CAB de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# FIM ENVIO PROCESSOS-CAB ##################################################################################################################################')				
	END
-- efetua o log do inicio do processo de envio do ADI de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# INICIO ENVIO PROCESSOS-ADI ###############################################################################################################################')		
	END
	BEGIN TRY
-- obtem as adiçoes das declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT 'I' AS DUC_CTXT, adi.DUC_EANO, adi.DUC_PNUM, NULL AS DUC_IDEN, NULL AS DEC_CODI, adi.DUA_CODI, adi.APA_CP33, ISNULL(adi.DUA_TIVA, 0) AS DUA_TIVA, adi.DUA_ML38, 
				ISNULL(adi.DUA_US41, 0) AS DUA_US41, adi.DUA_VA42, ISNULL(adi.DUA_VFRE, 0) AS DUA_VFRE, ISNULL(adi.DUA_VSEG, 0) AS DUA_VSEG, ISNULL(adi.DUA_VTRA, 0) AS DUA_VTRA, 
				ISNULL(adi.DUA_VROY, 0) AS DUA_VROY, ISNULL(adi.DUA_VOPT, 0) AS DUA_VOPT, adi.DUA_VEST, ISNULL(adi.DUA_VATO, 0) AS DUA_VATO, ISNULL(adi.DUA_TXVL, 0) AS DUA_TXVL, 
				ISNULL(adi.DUA_MTRI, 0) AS DUA_MTRI, ISNULL(adi.DUA_VIVA, 0) AS DUA_VIVA, ISNULL(adi.DUA_VAEU, 0) AS DUA_VAEU, ISNULL(duc.DUC_TX23, 0) AS DUC_TX23, duc.PAI_MO22, 
				(CASE 
					WHEN adi.DUA_PMRD IS NULL THEN 'I'	
					ELSE 'U'
				END) AS DUC_ACAO, 
				(SELECT TOP 1 UME_NOME FROM PRO_DU31 WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND D31_CODI = 1) AS UME_NOME			
			FROM PRO_DUAD AS adi WITH(NOLOCK)				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON duc.NDE_CODI = nde.NDE_CODI				
			WHERE adi.DUA_PMRP = 1 AND duc.DUC_PMRD IS NOT NULL AND duc.DUC_STAT > 0 AND ISNULL(duc.DUC_NORD, '') <> '' AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), duc.DUC_NDAT, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			UNION ALL			
			SELECT 'E' AS DUC_CTXT, adi.EXM_EANO, exm.EXM_NRII, adi.EXM_CODI AS DUC_IDEN, adi.EXM_COPE AS DEC_CODI, adi.EXA_LINH, adi.APA_CP33, 0.00 AS DUA_TIVA, ISNULL(adi.EXA_MLQD, 0) AS DUA_ML38, 
				ISNULL(adi.EXA_QUSU, 0) AS DUA_US41, ISNULL(adi.EXA_VALO, 0) AS DUA_VA42, ISNULL(adi.EXA_VFRE, 0) AS DUA_VFRE, ISNULL(adi.EXA_VSEG, 0) AS DUA_VSEG, 0.00 AS DUA_VTRA, 
				0.00 AS DUA_VROY, 0.00 AS DUA_VOPT, ISNULL(adi.EXA_VEST, 0) AS DUA_VEST, ISNULL(adi.EXA_VEST, 0) AS DUA_VATO, 0.00 AS DUA_TXVL, 
				0.00 AS DUA_MTRI, 0.00 AS DUA_VIVA, ROUND((ISNULL(adi.EXA_VALO, 0) * ISNULL(exm.EXM_TX23, 0) / 100), 2) AS DUA_VAEU, ISNULL(exm.EXM_TX23, 0) AS DUC_TX23, exm.PAI_MO22, 
				(CASE 
					WHEN adi.EXA_PMRD IS NULL THEN 'I'	
					ELSE 'U'
				END) AS DUC_ACAO, 
				(SELECT TOP 1 TEM_NOME FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = adi.EXA_CHVE) AS UME_NOME
			FROM PRO_EXAD AS adi WITH(NOLOCK)				
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON adi.EXM_EANO = exm.EXM_EANO AND adi.EXM_CODI = exm.EXM_CODI AND adi.EXM_COPE = exm.DEC_CODI				
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON exm.NDE_CODI = nde.NDE_CODI				
			WHERE adi.EXA_PMRP = 1 AND exm.EXM_PMRD IS NOT NULL AND exm.EXM_STAT > 0 AND ISNULL(exm.EXM_NDGA, '') <> '' AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), exm.EXM_DDGA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)	
			ORDER BY DUC_CTXT, DUC_EANO, DUC_PNUM, DUA_CODI
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @NumAdicao, @CodPautalArtigo, @TxIVA, @MassaLiq, @QtdUnidades, @Valor, @Frete, 
			@Seguro, @VerbaTransitario, @Royalties, @Optativas, @ValorEstatistico, @ValorAduaneiro, @TaxaValorDireitos, @MontanteDireitos, @MontanteIVA, @ValorEUR, @TxCambio, @Moeda, @Acao, 
			@NomeUnidMedida
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @XMLResponse = NULL
			SET @Sucesso = 0
			SET @ErrorCode = NULL
			SET @ErrorMessage = NULL	
-- constroi o XML com os dados da linha
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1)
			SELECT @XMLDeclaracao =
				(SELECT 				
					@Acao AS "fjs1:in_Accao", 
					LTRIM(STR(@NumProcesso, 20)) AS "fjs1:in_ProcessoID", 
					@IdIntegrationSystem AS "fjs1:in_IntegrationSystem", 
					@NumAdicao AS "fjs1:in_Nr_Adicao", 
					NULLIF(@CodPautalArtigo, '') AS "fjs1:in_Pos_Pautal", 
					CAST(@MassaLiq AS decimal(18, 3)) AS "fjs1:in_Peso_liquido", 
					CAST(@QtdUnidades AS decimal(18, 3)) AS "fjs1:in_Unid_Suplemantares", 
					CAST(@Valor AS decimal(18, 3)) AS "fjs1:IN_Val_Mercadoria", 
					NULLIF(@Moeda, '') AS "fjs1:in_Moeda",
					CAST(@TxCambio AS decimal(18, 6)) AS "fjs1:in_Cambio", 
					CAST(@ValorEUR AS decimal(18, 2)) AS "fjs1:in_Val_Euros", 
					CAST(@ValorAduaneiro AS decimal(18, 2)) AS "fjs1:in_Val_Aduaneiro", 
					CAST(@Frete AS decimal(18, 3)) AS "fjs1:in_Val_Frete", 
					CAST(@Seguro AS decimal(18, 3)) AS "fjs1:in_Val_Seguro", 
					CAST(@Optativas AS decimal(18, 2)) AS "fjs1:in_Desp_Optativas", 
					CAST(@TaxaValorDireitos AS decimal(18, 4)) AS "fjs1:in_Tx_direitos", 
					CAST(@MontanteDireitos AS decimal(18, 2)) AS "fjs1:in_Val_Direitos", 
					CAST(@MontanteIVA AS decimal(18, 2)) AS "fjs1:in_IVA", 
					CAST(@ValorEstatistico AS decimal(18, 2)) AS "fjs1:in_Val_estatistico", 					
					CAST(@TxIVA AS decimal(18, 2)) AS "fjs1:in_TxIva", 
					CAST(@VerbaTransitario AS decimal(18, 2)) AS "fjs1:in_Val_OutrasDespesas", 
					CAST(@Royalties AS decimal(18, 2)) AS "fjs1:in_ValRoyalities", 
					NULLIF(@NomeUnidMedida, '') AS "fjs1:in_NaturezasMercadoria"										
				FOR XML PATH('fjs1:webserv_Portal_ProcessoMaterial_receiveERDO'), ELEMENTS)
-- constroi estrutura XML com os dados do pedido ao metodo webserv_Portal_ProcessoMaterial_receiveERDO a enviar
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")		
			SELECT @XMLRequest = 
				(SELECT 
					(SELECT 
						(SELECT
							NULLIF(@HeaderToken, '') AS "fjs1:Token"
						FOR XML PATH('fjs1:clsValidaCabecalhoSOAP'), TYPE)
					FOR XML PATH('SOAP-ENV:Header'), ELEMENTS, TYPE),
					(SELECT
						@XMLDeclaracao		
					FOR XML PATH('SOAP-ENV:Body'), ELEMENTS, TYPE)
				FOR XML PATH('SOAP-ENV:Envelope'), ELEMENTS)
-- efetua o log do XML Request a enviar p/ o WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('AD:' + CAST(@NumAdicao AS varchar(10))), '## XML-REQUEST: ' + CAST(@XMLRequest AS varchar(MAX)))				
			END
-- processa envio do XML para o WS do Portal MyRangel	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @XMLRequest, @Endpoint, @SOAPActionProcessoAdi, '', '', 0, '', 0, '', '', @XMLResponse OUTPUT
-- efetua o log do XML Response obtido do WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('AD:' + CAST(@NumAdicao AS varchar(10))), '## XML-RESPONSE: ' + CAST(@XMLResponse AS varchar(MAX)))
			END
-- obtem dados de resposta do WS		
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS "tns3", 
				'http://www.example.com/namespaces/tns/1608830539372' AS "tns1", 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "soapenv")
			SELECT 
				@Sucesso = x.r.value('tns3:Sucesso[1]', 'bit'), 
				@ErrorCode = x.r.value('tns3:ErrorCode[1]', 'int'), 
				@ErrorMessage = x.r.value('tns3:ErrorMessage[1]', 'varchar(MAX)')
			FROM @XMLResponse.nodes('soapenv:Envelope/soapenv:Body/tns3:webserv_Portal_ProcessoMaterial_receiveERDOResponse/tns3:webserv_Portal_ProcessoMaterial_receiveERDOResult') AS x(r)
-- se resultado for de sucesso, atualiza adição da declaração IMP/EXP como enviada para Portal MyRangel
			IF @Sucesso = 1
			BEGIN
				IF @CtxProcesso = 'I' 
				BEGIN
					UPDATE PRO_DUAD SET DUA_PMRP = 0, DUA_PMRD = @DataAtual
					WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao
				END
				ELSE
				BEGIN
					UPDATE PRO_EXAD SET EXA_PMRP = 0, EXA_PMRD = @DataAtual
					WHERE EXM_EANO = @AnoProcesso AND EXM_CODI = @IdProcesso AND EXM_COPE = @CodDeclarante AND EXA_LINH = @NumAdicao
				END
-- efetua o log da adição da declaração IMP/EXP marcada como enviado para Portal MyRangel
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN					
					INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
					VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('AD:' + CAST(@NumAdicao AS varchar(10))), '## SQL-UPDATE: Adicao marcada como enviada para o Portal MyRangel.')					
				END
			END
			FETCH NEXT FROM Adicoes INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @NumAdicao, @CodPautalArtigo, @TxIVA, @MassaLiq, @QtdUnidades, @Valor, @Frete, 
				@Seguro, @VerbaTransitario, @Royalties, @Optativas, @ValorEstatistico, @ValorAduaneiro, @TaxaValorDireitos, @MontanteDireitos, @MontanteIVA, @ValorEUR, @TxCambio, @Moeda, @Acao, 
				@NomeUnidMedida
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de envio do ADI de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# FIM ENVIO PROCESSOS-ADI ##################################################################################################################################')		
	END
-- efetua o log do inicio do processo de envio do CON de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# INICIO ENVIO PROCESSOS-CON ###############################################################################################################################')		
	END
	BEGIN TRY
-- obtem os contentores das declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
		DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT 'I' AS DUC_CTXT, con.DUC_EANO, con.DUC_PNUM, NULL AS DUC_IDEN, NULL AS DEC_CODI, con.DUA_CODI, con.DCO_CODI, con.DCO_CNUM, con.DCO_IDEN, 			
				(CASE 
					WHEN con.DCO_PMRD IS NULL THEN 'I'	
					ELSE 'U'
				END) AS DUC_ACAO
			FROM PRO_DCON AS con WITH(NOLOCK) 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK)	ON con.DUC_EANO = adi.DUC_EANO AND con.DUC_PNUM = adi.DUC_PNUM AND con.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON duc.NDE_CODI = nde.NDE_CODI				
			WHERE con.DCO_PMRP = 1 AND adi.DUA_PMRD IS NOT NULL AND duc.DUC_PMRD IS NOT NULL AND duc.DUC_STAT > 0 AND ISNULL(duc.DUC_NORD, '') <> '' AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), duc.DUC_NDAT, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			UNION ALL			
			SELECT 'E' AS DUC_CTXT, con.EXM_EANO, exm.EXM_NRII, con.EXM_CODI AS DUC_IDEN, con.EXM_COPE AS DEC_CODI, adi.EXA_LINH, con.EXC_LINH, con.EXC_CONT, con.EXC_CHVE, 
				(CASE 
					WHEN con.EXC_PMRD IS NULL THEN 'I'	
					ELSE 'U'
				END) AS DUC_ACAO
			FROM PRO_EXCT AS con WITH(NOLOCK) 
				INNER JOIN PRO_EXAD AS adi WITH(NOLOCK)	ON con.EXM_EANO = adi.EXM_EANO AND con.EXM_CODI = adi.EXM_CODI AND con.EXM_COPE = adi.EXM_COPE AND adi.EXA_LINH = 1
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON adi.EXM_EANO = exm.EXM_EANO AND adi.EXM_CODI = exm.EXM_CODI AND adi.EXM_COPE = exm.DEC_CODI				
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON exm.NDE_CODI = nde.NDE_CODI				
			WHERE con.EXC_PMRP = 1 AND adi.EXA_PMRD IS NOT NULL AND exm.EXM_PMRD IS NOT NULL AND exm.EXM_STAT > 0 AND ISNULL(exm.EXM_NDGA, '') <> '' AND nde.NDE_FEDI = 1
				AND CAST(CONVERT(varchar(10), exm.EXM_DDGA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)	
			ORDER BY DUC_CTXT, DUC_EANO, DUC_PNUM, DUA_CODI
		OPEN Contentores
		FETCH NEXT FROM Contentores INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @NumAdicao, @NumContentor, @Contentor, @IdContentor, @Acao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @XMLResponse = NULL
			SET @Sucesso = 0
			SET @ErrorCode = NULL
			SET @ErrorMessage = NULL	
-- constroi o XML com os dados da linha
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1)
			SELECT @XMLDeclaracao =
				(SELECT 		
					@Acao AS "fjs1:in_Accao", 
					LTRIM(STR(@NumProcesso, 20)) AS "fjs1:in_ProcessoID", 
					@IdIntegrationSystem AS "fjs1:in_IntegrationSystem", 
					@NumAdicao AS "fjs1:in_NrAdicao", 
					@IdContentor AS "fjs1:in_IDinIS", 
					NULLIF(@Contentor, '') AS "fjs1:IN_Nr_Contentor"																																	
				FOR XML PATH('fjs1:webserv_Portal_ProcessoContentores_receiveERDO'), ELEMENTS)
-- constroi estrutura XML com os dados do pedido ao metodo webserv_Portal_ProcessoContentores_receiveERDO a enviar
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")		
			SELECT @XMLRequest = 
				(SELECT 
					(SELECT 
						(SELECT
							NULLIF(@HeaderToken, '') AS "fjs1:Token"
						FOR XML PATH('fjs1:clsValidaCabecalhoSOAP'), TYPE)
					FOR XML PATH('SOAP-ENV:Header'), ELEMENTS, TYPE),
					(SELECT
						@XMLDeclaracao		
					FOR XML PATH('SOAP-ENV:Body'), ELEMENTS, TYPE)
				FOR XML PATH('SOAP-ENV:Envelope'), ELEMENTS)
-- efetua o log do XML Request a enviar p/ o WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('CT:' + CAST(@NumContentor AS varchar(10)) + '/AD:' + CAST(@NumAdicao AS varchar(10))), '## XML-REQUEST: ' + CAST(@XMLRequest AS varchar(MAX)))				
			END
-- processa envio do XML para o WS do Portal MyRangel	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @XMLRequest, @Endpoint, @SOAPActionProcessoCon, '', '', 0, '', 0, '', '', @XMLResponse OUTPUT
-- efetua o log do XML Response obtido do WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('CT:' + CAST(@NumContentor AS varchar(10)) + '/AD:' + CAST(@NumAdicao AS varchar(10))), '## XML-RESPONSE: ' + CAST(@XMLResponse AS varchar(MAX)))
			END
-- obtem dados de resposta do WS		
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS "tns3", 
				'http://www.example.com/namespaces/tns/1608830539372' AS "tns1", 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "soapenv")
			SELECT 
				@Sucesso = x.r.value('tns3:Sucesso[1]', 'bit'), 
				@ErrorCode = x.r.value('tns3:ErrorCode[1]', 'int'), 
				@ErrorMessage = x.r.value('tns3:ErrorMessage[1]', 'varchar(MAX)')
			FROM @XMLResponse.nodes('soapenv:Envelope/soapenv:Body/tns3:webserv_Portal_ProcessoContentores_receiveERDOResponse/tns3:webserv_Portal_ProcessoContentores_receiveERDOResult') AS x(r)
-- se resultado for de sucesso, atualiza contentor da declaração IMP/EXP como enviada para Portal MyRangel
			IF @Sucesso = 1
			BEGIN
				IF @CtxProcesso = 'I' 
				BEGIN
					UPDATE PRO_DCON SET DCO_PMRP = 0, DCO_PMRD = @DataAtual
					WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao AND DCO_CODI = @NumContentor
				END
				ELSE
				BEGIN
					UPDATE PRO_EXCT SET EXC_PMRP = 0, EXC_PMRD = @DataAtual
					WHERE EXC_CHVE = @IdContentor
				END
-- efetua o log do contentor da declaração IMP/EXP marcada como enviado para Portal MyRangel
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN					
					INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
					VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('CT:' + CAST(@NumContentor AS varchar(10)) + '/AD:' + CAST(@NumAdicao AS varchar(10))), '## SQL-UPDATE: Contentor marcado como enviado para o Portal MyRangel.')					
				END
			END
			FETCH NEXT FROM Contentores INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @NumAdicao, @NumContentor, @Contentor, @IdContentor, @Acao
		END
		CLOSE Contentores
		DEALLOCATE Contentores
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de envio do CON de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# FIM ENVIO PROCESSOS-CON ##################################################################################################################################')		
	END
-- efetua o log do inicio do processo de envio do ARQ de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# INICIO ENVIO PROCESSOS-ARQ ###############################################################################################################################')		
	END
	BEGIN TRY
-- obtem os ficheiros do arquivo das declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
		DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT 'I' AS DUC_CTXT, fch.DUC_EANO, fch.DUC_PNUM, NULL AS DUC_IDEN, NULL AS DEC_CODI, fch.DUC_IDEN AS DUF_IDEN, fch.DUF_DESC, fch.DUF_NOMF, fch.DUF_LINK, fch.DUF_TMSG, fch.DUF_FICH, 
				(CASE 
					WHEN fch.DUF_PMRD IS NULL THEN 'I'	
					ELSE 'U'
				END) AS DUC_ACAO
			FROM PRO_DUFI AS fch WITH(NOLOCK)				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON fch.DUC_EANO = duc.DUC_EANO AND fch.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON duc.NDE_CODI = nde.NDE_CODI				
			WHERE fch.DUF_PMRP = 1 AND fch.DUF_TMSG IN ('IM003A', 'IM004A', 'IM005A', 'IM006A.0', 'IM006A.1', 'IM006A.2', 'ARC', 'BSC', 'COO', 'DAU', 'EDA', 'T1', 'T2', 'T2F', 'T2L', 'T2LF', 'FITO', 'CE', 'EUR1', 'SGS', 'COA', 'DTC', 'EP', 'FP', 'EURMED', 'PF', 'DASE', 'eATR', 'RI', 'DASI', 'PAR', 'DIC', 'PA', 'DSSNR', 'AGNAV', 'ARM', 'AWB', 'BL', 'BOLINFO', 'CERTTAB', 'CERTFUM', 'CMR', 'FATCOM', 'DECSEG', 'DECFRE', 'DECSIMP', 'DELNOTE', 'DME', 'DOCPROC', 'XATR', 'DCS', 'EDAAPU', 'EDAXML', 'EMAIL', 'FORMA', 'GARANTIA', 'GUIATRP', 'XEP', 'XT1', 'XT2', 'IPRTAB', 'PACKLST', 'FATPROF', 'RELDESC', 'XREQ', 'SEAW', 'SHIPCRT', 'XARC', 'XBSC', 'XCO', 'XCOA', 'XEUR1', 'XFITO', 'XSGS', 'XT2L', 'XT2LF', 'GUIAEMOL') 
				AND duc.DUC_PMRD IS NOT NULL AND duc.DUC_STAT > 0 AND ISNULL(duc.DUC_NORD, '') <> '' AND nde.NDE_FEDI = 1 
				AND CAST(CONVERT(varchar(10), duc.DUC_NDAT, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)
			UNION ALL			
			SELECT 'E' AS DUC_CTXT, fch.EXM_EANO, exm.EXM_NRII, fch.EXM_CODI AS DUC_IDEN, fch.DEC_CODI, fch.EXF_IDEN, fch.EXF_DESC, fch.EXF_NOMF, fch.EXF_LINK, fch.EXF_TMSG, fch.EXF_FICH, 
				(CASE 
					WHEN fch.EXF_PMRD IS NULL THEN 'I'	
					ELSE 'U'
				END) AS DUC_ACAO
			FROM PRO_EXFI AS fch WITH(NOLOCK)				
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON fch.EXM_EANO = exm.EXM_EANO AND fch.EXM_CODI = exm.EXM_CODI AND fch.DEC_CODI = exm.DEC_CODI				
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON exm.NDE_CODI = nde.NDE_CODI				
			WHERE fch.EXF_PMRP = 1 AND fch.EXF_TMSG IN ('EX006A', 'EX009A', 'EX00CCE', 'ARC', 'BSC', 'COO', 'DAU', 'EDA', 'T1', 'T2', 'T2F', 'T2L', 'T2LF', 'FITO', 'CE', 'EUR1', 'SGS', 'COA', 'DTC', 'EP', 'FP', 'EURMED', 'PF', 'DASE', 'eATR', 'RI', 'DASI', 'PAR', 'DIC', 'PA', 'DSSNR', 'AGNAV', 'ARM', 'AWB', 'BL', 'BOLINFO', 'CERTTAB', 'CERTFUM', 'CMR', 'FATCOM', 'DECSEG', 'DECFRE', 'DECSIMP', 'DELNOTE', 'DME', 'DOCPROC', 'XATR', 'DCS', 'EDAAPU', 'EDAXML', 'EMAIL', 'FORMA', 'GARANTIA', 'GUIATRP', 'XEP', 'XT1', 'XT2', 'IPRTAB', 'PACKLST', 'FATPROF', 'RELDESC', 'XREQ', 'SEAW', 'SHIPCRT', 'XARC', 'XBSC', 'XCO', 'XCOA', 'XEUR1', 'XFITO', 'XSGS', 'XT2L', 'XT2LF', 'GUIAEMOL') 
				AND exm.EXM_PMRD IS NOT NULL AND exm.EXM_STAT > 0 AND ISNULL(exm.EXM_NDGA, '') <> '' AND nde.NDE_FEDI = 1 
				AND CAST(CONVERT(varchar(10), exm.EXM_DDGA, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataReferencia, 105) AS datetime)	
			ORDER BY DUC_CTXT, DUC_EANO, DUC_PNUM, DUF_IDEN
		OPEN Ficheiros
		FETCH NEXT FROM Ficheiros INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @IdFicheiro, @DescricaoFicheiroPDF, @NomeFicheiroPDF, @PathFicheiroPDF, 
			@TipoMsgFicheiroPDF, @FicheiroBinarioPDF, @Acao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @XMLResponse = NULL
			SET @Sucesso = 0
			SET @ErrorCode = NULL
			SET @ErrorMessage = NULL	
-- carrega ficheiro PDF para binário
			IF (@FicheiroBinarioPDF IS NULL) AND (ISNULL(@PathFicheiroPDF, '') <> '')
			BEGIN
-- inicia variaveis para executar o SQL dinamicamente
				SET @SQLString = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiroPDF + ''', SINGLE_BLOB) AS t)'
				SET @SQLParams = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'			
-- obtem o ficheiro em binario
				EXECUTE sp_executesql @SQLString, @SQLParams, @OUTFicheiroBinario = @FicheiroBinarioPDF OUTPUT
			END			
-- converte ficheiro PDF para base64						
			SET @FicheiroBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinarioPDF")))', 'varchar(MAX)')	
-- constroi o XML com os dados da linha
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1)
			SELECT @XMLDeclaracao =
				(SELECT 				
					@Acao AS "fjs1:in_Accao", 
					LTRIM(STR(@NumProcesso, 20)) AS "fjs1:in_ProcessoID", 
					@IdIntegrationSystem AS "fjs1:in_IntegrationSystem", 
					0 AS "fjs1:in_NrAdicao", 
					@IdFicheiro AS "fjs1:in_DocIDinIS", 
					(CASE @TipoMsgFicheiroPDF 						
						WHEN 'IM006A.0' THEN 'DPD'
						WHEN 'IM006A.1' THEN 'IM006A'
						WHEN 'IM006A.2' THEN 'IM006A'
						WHEN 'EX00CCE' THEN 'CCE'
						WHEN 'EURMED' THEN 'EUR MED'
						WHEN 'AGNAV' THEN 'AgNav'
						WHEN 'ARM' THEN 'Armazenag'
						WHEN 'BOLINFO' THEN 'Bol.Info'
						WHEN 'CERTTAB' THEN 'Cert. Aut'
						WHEN 'CERTFUM' THEN 'Cert. Fumi'
						WHEN 'FATCOM' THEN 'FatCom'
						WHEN 'DECSEG' THEN 'DecSeguro'
						WHEN 'DECFRE' THEN 'DecFrete'
						WHEN 'DECSIMP' THEN 'DecSimpl'
						WHEN 'DELNOTE' THEN 'DelNote'
						WHEN 'DOCPROC' THEN 'DocProc'
						WHEN 'EDAAPU' THEN 'EDAapu'
						WHEN 'EDAXML' THEN 'EDAxml'
						WHEN 'EMAIL' THEN 'Email'
						WHEN 'FORMA' THEN 'FormA'
						WHEN 'GARANTIA' THEN 'Garantias'
						WHEN 'GUIATRP' THEN 'GuiaTransp'
						WHEN 'IPRTAB' THEN 'IPRtab'
						WHEN 'PACKLST' THEN 'PackList'
						WHEN 'FATPROF' THEN 'FatProForm'
						WHEN 'RELDESC' THEN 'RelDesc'
						WHEN 'XREQ' THEN 'XReq'
						WHEN 'SEAW' THEN 'SeaW'
						WHEN 'SHIPCRT' THEN 'ShipCert'
						WHEN 'GUIAEMOL' THEN 'GuiaEmol'
						ELSE @TipoMsgFicheiroPDF
					END) AS "fjs1:in_Tipo_Documento", 
					NULLIF(@DescricaoFicheiroPDF, '') AS "fjs1:in_Desc_Tipo_Documento", 
					'A' AS "fjs1:in_Desc_Tipo_Origem", 
					NULL AS "fjs1:in_NR_documento", 
					@FicheiroBase64 AS "fjs1:in_file", 
					RIGHT(NULLIF(@NomeFicheiroPDF, ''), 3) AS "fjs1:in_file_ext", 
					NULLIF(@NomeFicheiroPDF, '') AS "fjs1:in_filename"													
				FOR XML PATH('fjs1:webserv_Portal_ProcessoDocumentos_receiveERDO'), ELEMENTS)
-- constroi estrutura XML com os dados do pedido ao metodo webserv_Portal_ProcessoMaterial_receiveERDO a enviar
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS fjs1, 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")		
			SELECT @XMLRequest = 
				(SELECT 
					(SELECT 
						(SELECT
							NULLIF(@HeaderToken, '') AS "fjs1:Token"
						FOR XML PATH('fjs1:clsValidaCabecalhoSOAP'), TYPE)
					FOR XML PATH('SOAP-ENV:Header'), ELEMENTS, TYPE),
					(SELECT
						@XMLDeclaracao		
					FOR XML PATH('SOAP-ENV:Body'), ELEMENTS, TYPE)
				FOR XML PATH('SOAP-ENV:Envelope'), ELEMENTS)
-- efetua o log do XML Request a enviar p/ o WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('AR:' + CAST(@IdFicheiro AS varchar(10)) + '/' + @NomeFicheiroPDF), '## XML-REQUEST: ' + CAST(@XMLRequest AS varchar(MAX)))				
			END
-- processa envio do XML para o WS do Portal MyRangel	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @XMLRequest, @Endpoint, @SOAPActionProcessoDoc, '', '', 0, '', 0, '', '', @XMLResponse OUTPUT
-- efetua o log do XML Response obtido do WS do Portal MyRangel
			IF ISNULL(@DirLogFile, '') <> ''
			BEGIN
				INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
				VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('AR:' + CAST(@IdFicheiro AS varchar(10)) + '/' + @NomeFicheiroPDF), '## XML-RESPONSE: ' + CAST(@XMLResponse AS varchar(MAX)))
			END
-- obtem dados de resposta do WS		
			;WITH XMLNAMESPACES ('http://tempuri.org/' AS "tns3", 
				'http://www.example.com/namespaces/tns/1608830539372' AS "tns1", 
				'http://schemas.xmlsoap.org/soap/envelope/' AS "soapenv")
			SELECT 
				@Sucesso = x.r.value('tns3:Sucesso[1]', 'bit'), 
				@ErrorCode = x.r.value('tns3:ErrorCode[1]', 'int'), 
				@ErrorMessage = x.r.value('tns3:ErrorMessage[1]', 'varchar(MAX)')
			FROM @XMLResponse.nodes('soapenv:Envelope/soapenv:Body/tns3:webserv_Portal_ProcessoDocumentos_receiveERDOResponse/tns3:webserv_Portal_ProcessoDocumentos_receiveERDOResult') AS x(r)
-- se resultado for de sucesso, atualiza adição da declaração IMP/EXP como enviada para Portal MyRangel
			IF @Sucesso = 1
			BEGIN
				IF @CtxProcesso = 'I' 
				BEGIN
					UPDATE PRO_DUFI SET DUF_PMRP = 0, DUF_PMRD = @DataAtual
					WHERE DUC_IDEN = @IdFicheiro
				END
				ELSE
				BEGIN
					UPDATE PRO_EXFI SET EXF_PMRP = 0, EXF_PMRD = @DataAtual
					WHERE EXF_IDEN = @IdFicheiro
				END
-- efetua o log do ficheiro do arquivo da declaração IMP/EXP marcada como enviado para Portal MyRangel
				IF ISNULL(@DirLogFile, '') <> ''
				BEGIN					
					INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO)				
					VALUES(@NumProcesso, @AnoProcesso, @CtxProcesso, ('AR:' + CAST(@IdFicheiro AS varchar(10)) + '/' + @NomeFicheiroPDF), '## SQL-UPDATE: Ficheiro marcado como enviado para o Portal MyRangel.')					
				END
			END
			FETCH NEXT FROM Ficheiros INTO @CtxProcesso, @AnoProcesso, @NumProcesso, @IdProcesso, @CodDeclarante, @IdFicheiro, @DescricaoFicheiroPDF, @NomeFicheiroPDF, @PathFicheiroPDF, 
				@TipoMsgFicheiroPDF, @FicheiroBinarioPDF, @Acao
		END
		CLOSE Ficheiros
		DEALLOCATE Ficheiros
	END TRY
	BEGIN CATCH
		IF ISNULL(@DirLogFile, '') <> ''
		BEGIN		
			INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
			VALUES(0, 0, '', '## ERRO: ' + ERROR_MESSAGE())				
		END
	END CATCH
-- efetua o log do fim do processo de envio do ARQ de declarações IMP/EXP com n.º ordem e pendentes de envio p/ Portal MyRangel
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
		INSERT INTO ##LogTableDeclsPortal(NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, INFO)
		VALUES(0, 0, '', '############# FIM ENVIO PROCESSOS-ARQ ##################################################################################################################################')		
	END
-- se diretoria p/ log file especificada, grava ficheiro de log
	IF ISNULL(@DirLogFile, '') <> ''
	BEGIN
-- constroi full path para geração do ficheiro XML
		SET @PathLogFile = @DirLogFile + 'LOG_PR_GIDWin2MYRANGEL_' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), @DataAtual, 121), '-', ''), ' ', ''), ':', ''), '.', '') + '.TXT'
-- gera o ficheiro TXT p/ ficheiro log
		SET @Comando = 'bcp "SELECT NUMPROCESSO, ANOPROCESSO, CTXPROCESSO, LINHA, INFO FROM ##LogTableDeclsPortal ORDER BY ID" QUERYOUT "' + @PathLogFile + '" -c -T -S' + @@servername			
		EXEC master..xp_cmdshell @Comando, NO_OUTPUT			
	END	
-- remove a tabela temporária	
	DROP TABLE ##LogTableDeclsPortal
END

ALTER AUTHORIZATION ON [SP_Geral_EnviaDeclaracoesWSPortalERDO] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_EnviaDeclaracoesWSPortalERDO] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_EnviaFicheirosIMPeEXPParaFTPOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_EnviaFicheirosIMPeEXPParaFTPOGMA] @ServidorFTP varchar(100), @UtilizadorFTP varchar(100), @PasswordFTP varchar(100), @DirFTPIN varchar(100), @DirFTPNOT_DIV varchar(100), 
	@DirFTPCSAI varchar(100), @DirFTPSIGMA varchar(100), @DirLocalFicheiroErros varchar(500), @DirLocalFicheiroTmp varchar(500), @NIFClienteDestinatario varchar(18), @DataReferencia datetime, 
	@Ambiente varchar(3), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @DataAtual datetime, @NumErro int, @i int, @ListaErros varchar(MAX), @Erros varchar(MAX), @PathFicheiroErro varchar(500), @Linha varchar(MAX), @ComandoSQL varchar(1500), 
		@FicheiroTXT varchar(MAX), @FicheiroXML xml, @IdUtilizador int, @DirLocalFicheirosBkpEXP varchar(150), @IntegracaoIMPCAUAtiva bit, @TipoDeclaracao varchar(3), @AnoDeclaracao int, 
		@NumDeclaracao int, @CodDeclarante varchar(6), @NIFDeclarante varchar(18), @NumDeclaracaoEXP varchar(7), @NumOrdem varchar(21), @DataOrdem datetime, @Versao int, @Revisao int, 
		@Pacote varchar(3), @NomeFicheiroOGMA varchar(100), @DataCS datetime, @IdFicheiro int, @TipoMensagem varchar(6), @PathFicheiroPDFLocal varchar(500), @PathFicheiroXMLLocal varchar(500), 
		@PathFicheiroACKLocal varchar(500), @Ordem int, @PathFicheiroLocal varchar(500), @ExtensaoFicheiroLocal varchar(5), @NomeFicheiroFTP varchar(250), @PathFicheiroFTP varchar(500), 
		@PrefixoFicheiroFTP varchar(4), @TipoMensagemXML varchar(6), @OperacaoXML varchar(3)
	DECLARE @TblTmpFicheiros TABLE(id int NOT NULL IDENTITY(1, 1), ordem int NOT NULL, prefixo varchar(4) NOT NULL, fullPath varchar(500) NOT NULL)
-- cria tabela temporária p/ conteudo de cada ficheiro
	CREATE TABLE #ConteudoFicheiro(CONTEUDO varchar(MAX) COLLATE Latin1_General_CI_AI)
-- obtem a data atual
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- substitui caracteres especiais p/ utilização no comando "echo"
	SET @ServidorFTP = REPLACE(REPLACE(REPLACE(REPLACE(@ServidorFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @UtilizadorFTP = REPLACE(REPLACE(REPLACE(REPLACE(@UtilizadorFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @PasswordFTP = REPLACE(REPLACE(REPLACE(REPLACE(@PasswordFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirFTPIN = REPLACE(REPLACE(REPLACE(REPLACE(@DirFTPIN, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirFTPNOT_DIV = REPLACE(REPLACE(REPLACE(REPLACE(@DirFTPNOT_DIV, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirFTPCSAI = REPLACE(REPLACE(REPLACE(REPLACE(@DirFTPCSAI, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirFTPSIGMA = REPLACE(REPLACE(REPLACE(REPLACE(@DirFTPSIGMA, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
-- verifica se diretorias FTP tem separador no início e fim
	IF SUBSTRING(@DirFTPIN, 1, 1) <> '/'
		SET @DirFTPIN = '/' + @DirFTPIN
	IF SUBSTRING(REVERSE(@DirFTPIN), 1, 1) <> '/'
		SET @DirFTPIN = @DirFTPIN + '/'		
	IF SUBSTRING(@DirFTPNOT_DIV, 1, 1) <> '/'
		SET @DirFTPNOT_DIV = '/' + @DirFTPNOT_DIV
	IF SUBSTRING(REVERSE(@DirFTPNOT_DIV), 1, 1) <> '/'
		SET @DirFTPNOT_DIV = @DirFTPNOT_DIV + '/'
	IF SUBSTRING(@DirFTPCSAI, 1, 1) <> '/'
		SET @DirFTPCSAI = '/' + @DirFTPCSAI
	IF SUBSTRING(REVERSE(@DirFTPCSAI), 1, 1) <> '/'
		SET @DirFTPCSAI = @DirFTPCSAI + '/'
	IF SUBSTRING(REVERSE(@DirFTPSIGMA), 1, 1) <> '/'
		SET @DirFTPSIGMA = @DirFTPSIGMA + '/'
-- verifica se diretorias locais tem backslash no final	
	IF SUBSTRING(REVERSE(@DirLocalFicheiroErros), 1, 1) <> '\'
		SET @DirLocalFicheiroErros = @DirLocalFicheiroErros + '\'	
	IF SUBSTRING(REVERSE(@DirLocalFicheiroTmp), 1, 1) <> '\'
		SET @DirLocalFicheiroTmp = @DirLocalFicheiroTmp + '\'
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador
-- obtem a diretoria de backup de ficheiros EXP
	SELECT @DirLocalFicheirosBkpEXP = PDE_XPBK, @IntegracaoIMPCAUAtiva = PDE_ICAU
	FROM TAB_PDES WITH(NOLOCK)						
-- obtem os ficheiros das declarações IMP e EXP pendentes de envio
	DECLARE Arquivos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 		
		SELECT 'IMP' AS DUC_CNTX, duc.DUC_EANO, duc.DUC_PNUM, NULL AS DEC_CODI, NULL AS DEC_NIF, NULL AS EXM_NRII, duc.DUC_NORD, duc.DUC_NDAT, duc.DUC_VERS, duc.DUC_REVI, duc.DUC_PENV, 
			duc.DUC_FUPS, NULL AS EXM_DTCS, 			   
			dfi.DUC_IDEN, dfi.DUF_LINK, LEFT(dfi.DUF_TMSG, 6) AS DUF_TMSG, 
			(CASE dfi.DUF_TMSG 
				WHEN 'IM002A' THEN (SELECT TOP 1 DRP_FICH FROM PRO_DURP WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DRP_OPER = 5 AND DRP_CODI < rsp.DRP_CODI ORDER BY DRP_CODI DESC) 
				WHEN 'IM006A.0' THEN r1a.DRP_FICH 
				ELSE rsp.DRP_FICH 
			END) AS DRP_FICH, 
			(CASE dfi.DUF_TMSG 
				WHEN 'IM005A' THEN 'DIV' 
				ELSE 'IMP' 
			END) AS DUC_PRFX, 		 
			(CASE dfi.DUF_TMSG 
				WHEN 'IM006A.0' THEN rsp.DRP_FICH 
				ELSE NULL 
			END) AS DUC_FACK, 
			(CASE dfi.DUF_TMSG WHEN 'IM002A' THEN 2 WHEN 'IM005A' THEN 1 ELSE 0 END) AS DUC_ORDE
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			CROSS APPLY (SELECT TOP 1 DRP_FICH 
						FROM PRO_DURP WITH(NOLOCK) 
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DRP_OPER = 0
						ORDER BY DRP_CODI DESC) AS r1a
			OUTER APPLY (SELECT TOP 1 DUC_IDEN 
						FROM PRO_DUFI WITH(NOLOCK) 
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUF_TMSG = 'IM005A'
						ORDER BY DUC_IDEN) AS a5a	
			CROSS APPLY (SELECT TOP 1 DUC_IDEN 
						FROM PRO_DUFI WITH(NOLOCK) 
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUF_TMSG = 'IM006A.0'
						ORDER BY DUC_IDEN) AS a6a			
			INNER JOIN PRO_DUFI AS dfi WITH(NOLOCK) ON duc.DUC_EANO = dfi.DUC_EANO AND duc.DUC_PNUM = dfi.DUC_PNUM 
				AND (dfi.DUC_IDEN IN (a5a.DUC_IDEN, a6a.DUC_IDEN) OR (dfi.DUF_TMSG = 'IM002A' AND dfi.DUC_IDEN > a6a.DUC_IDEN)) AND dfi.DUF_ENVI = 0
			INNER JOIN PRO_DURP AS rsp WITH(NOLOCK) ON duc.DUC_EANO = rsp.DUC_EANO AND duc.DUC_PNUM = rsp.DUC_PNUM 
				AND (rsp.DRP_OPER IN (15, 16) OR (DRP_OPER = 12 AND DRP_ESTO = 'AP')) AND ISNULL(rsp.DRP_FICH, '') <> ''
				AND LEFT(dfi.DUF_NOMF, 55) = LEFT(REVERSE(LEFT(REVERSE(rsp.DRP_FICH), CHARINDEX('\', REVERSE(rsp.DRP_FICH)) - 1)), 55)	
		WHERE ISNULL(duc.DUC_DNIF, '') = ISNULL(NULLIF(@NIFClienteDestinatario, ''), ISNULL(duc.DUC_DNIF, '')) AND duc.DUC_ASAI = 1 AND duc.DUC_DTAS >= @DataReferencia
			AND NOT EXISTS(SELECT 1 FROM PRO_DUFI WITH(NOLOCK) WHERE DUC_PNUM = duc.DUC_PNUM AND DUC_EANO = duc.DUC_EANO AND DUF_TMSG = 'IM006A.0' AND DUF_ENVI = 1 AND dfi.DUF_TMSG IN ('IM005A', 'IM006A.0'))
		UNION ALL
		SELECT 'EXP' AS DUC_CNTX, exm.EXM_EANO, exm.EXM_CODI, exm.DEC_CODI, dcl.DEC_NIF, (REPLICATE('0', (7 - LEN(LTRIM(STR(exm.EXM_NRII, 7))))) + LTRIM(STR(exm.EXM_NRII, 7))), exm.EXM_NDGA, exm.EXM_DDGA, exm.EXM_VERS, exm.EXM_REVI, exm.EXM_PENV, 
			exm.EXM_FUPS, exm.EXM_DTCS, 
			dfi.EXF_IDEN, dfi.EXF_LINK, LEFT(dfi.EXF_TMSG, 6) AS DUF_TMSG, 
			NULL AS DRP_FICH, 
			(CASE dfi.EXF_TMSG 
				WHEN 'EX009A' THEN 'CSAI' 
				ELSE 'EXP' 
			END) AS DUC_PRFX, 		 
			NULL AS DUC_FACK, 
			0 AS DUC_ORDE
		FROM PRO_EXML AS exm WITH(NOLOCK)
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CODI = dcl.DEC_CODI	
			OUTER APPLY (SELECT TOP 1 EXF_IDEN 
						FROM PRO_EXFI WITH(NOLOCK) 
						WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND DEC_CODI = exm.DEC_CODI AND EXF_TMSG = 'EX009A'
						ORDER BY EXF_IDEN) AS a9a	
			CROSS APPLY (SELECT TOP 1 EXF_IDEN 
						FROM PRO_EXFI WITH(NOLOCK) 
						WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND DEC_CODI = exm.DEC_CODI AND EXF_TMSG = 'EX006A'
						ORDER BY EXF_IDEN) AS a6a			
			INNER JOIN PRO_EXFI AS dfi WITH(NOLOCK) ON exm.EXM_EANO = dfi.EXM_EANO AND exm.EXM_CODI = dfi.EXM_CODI AND exm.DEC_CODI = dfi.DEC_CODI
				AND dfi.EXF_IDEN IN (a9a.EXF_IDEN, a6a.EXF_IDEN) AND dfi.EXF_ENVI = 0
		WHERE exm.CLI_NIF2 = ISNULL(NULLIF(@NIFClienteDestinatario, ''), exm.CLI_NIF2) AND exm.EXM_ASAI = 1 AND exm.EXM_DTAS >= @DataReferencia
			AND NOT EXISTS(SELECT 1 FROM PRO_EXFI WITH(NOLOCK) WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND DEC_CODI = exm.DEC_CODI AND EXF_ENVI = 1 AND EXF_TMSG = 'EX006A' AND dfi.EXF_TMSG = 'EX006A')
		ORDER BY DUC_CNTX, DUC_EANO, DUC_PNUM, DUC_ORDE
	OPEN Arquivos
	FETCH NEXT FROM Arquivos INTO @TipoDeclaracao, @AnoDeclaracao, @NumDeclaracao, @CodDeclarante, @NIFDeclarante, @NumDeclaracaoEXP, @NumOrdem, @DataOrdem, @Versao, @Revisao, @Pacote, 
		@NomeFicheiroOGMA, @DataCS, @IdFicheiro, @PathFicheiroPDFLocal, @TipoMensagem, @PathFicheiroXMLLocal, @PrefixoFicheiroFTP, @PathFicheiroACKLocal, @Ordem
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''		
		BEGIN TRY			
-- remove todos os ficheiros da tabela tmp
			DELETE FROM @TblTmpFicheiros	
-- insere os ficheiros obtidos na tabela tmp
			INSERT INTO @TblTmpFicheiros(ordem, prefixo, fullPath)
			SELECT t.ordem, t.prefixo, t.ficheiro
			FROM (
				SELECT 0 AS ordem, @PrefixoFicheiroFTP AS prefixo, @PathFicheiroXMLLocal AS ficheiro				
				UNION ALL
				SELECT 1 AS ordem, @PrefixoFicheiroFTP AS prefixo, @PathFicheiroPDFLocal AS ficheiro
				UNION ALL
				SELECT 2 AS ordem, 'ACK' AS prefixo, @PathFicheiroACKLocal AS ficheiro
			) AS t
			WHERE ISNULL(t.ficheiro, '') <> ''
			ORDER BY t.ordem				
-- para declarações de exportação, obtem os ficheiros de envio/resposta da declaração na diretoria configurada
			IF @TipoDeclaracao = 'EXP'
			BEGIN
				DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
					SELECT fullName
					FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirLocalFicheirosBkpEXP, '*' + @NIFDeclarante + '.' + @NumDeclaracaoEXP + @Pacote + '.*')
					ORDER BY lastWriteTime DESC
				OPEN Ficheiros
				FETCH NEXT FROM Ficheiros INTO @PathFicheiroLocal
				WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @FicheiroTXT = NULL
					SET @TipoMensagemXML = NULL
					SET @OperacaoXML = NULL
-- processa a importação dos dados do ficheiro na tabela temporária
					SET @ComandoSQL = 'BULK INSERT #ConteudoFicheiro FROM ''' + @PathFicheiroLocal + ''''
					EXEC (@ComandoSQL)
-- obtem o xml do ficheiro importado (se xml não minified, torna-o minified)
					SELECT @FicheiroTXT = COALESCE(@FicheiroTXT, '') + CONTEUDO
					FROM #ConteudoFicheiro
-- converte p/ xml c/ a remoção do encoding
					SET @FicheiroXML = REPLACE(@FicheiroTXT, ' encoding="UTF-8"', '')
-- remove tabela de conteudos de cada ficheiro
					DELETE FROM #ConteudoFicheiro
-- obtem nome da mensagem XML do ficheiro
					SELECT @TipoMensagemXML = t.c.value('fn:local-name(./*[1])', 'varchar(100)'), @OperacaoXML = t.c.value('(ex001a/cabecalho/operacao)[1]', 'varchar(3)')		
					FROM @FicheiroXML.nodes('ficheiro/mensagens') AS t(c)
-- insere dados do ficheiro na tabela tmp
					IF (@TipoMensagem = 'EX006A') AND (UPPER(@TipoMensagemXML) = 'EX001A') AND (UPPER(@OperacaoXML) IN ('9', '4')) AND (NOT EXISTS(SELECT 1 FROM @TblTmpFicheiros WHERE ordem = 0 AND prefixo = @PrefixoFicheiroFTP))
					BEGIN
						INSERT INTO @TblTmpFicheiros(ordem, prefixo, fullPath)
						VALUES(0, @PrefixoFicheiroFTP, @PathFicheiroLocal)
					END
					ELSE
						IF (@TipoMensagem = 'EX006A') AND (UPPER(@TipoMensagemXML) = 'EX006A') AND (NOT EXISTS(SELECT 1 FROM @TblTmpFicheiros WHERE ordem = 2 AND prefixo = 'ACK'))
						BEGIN
							INSERT INTO @TblTmpFicheiros(ordem, prefixo, fullPath)
							VALUES(2, 'ACK', @PathFicheiroLocal)
						END
						ELSE
							IF (@TipoMensagem = 'EX009A') AND (UPPER(@TipoMensagemXML) = 'EX001A') AND (UPPER(@OperacaoXML) = '13') AND (NOT EXISTS(SELECT 1 FROM @TblTmpFicheiros WHERE ordem = 0 AND prefixo = 'EXP'))
							BEGIN
								INSERT INTO @TblTmpFicheiros(ordem, prefixo, fullPath)
								VALUES(0, 'EXP', @PathFicheiroLocal)
							END
					FETCH NEXT FROM Ficheiros INTO @PathFicheiroLocal
				END
				CLOSE Ficheiros
				DEALLOCATE Ficheiros
			END
-- obtem os arquivos PDF e respetivos XML das várias mensagens de "Autorização de Saída (Doc. Probatório)", "Notificação de Dívida", "Revisão" e "Certificação de Saída" da declaração
			DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 				
				SELECT prefixo, fullPath
				FROM @TblTmpFicheiros
				ORDER BY ordem
			OPEN Ficheiros
			FETCH NEXT FROM Ficheiros INTO @PrefixoFicheiroFTP, @PathFicheiroLocal
			WHILE @@FETCH_STATUS = 0
			BEGIN		
				SET @Erros = NULL
-- obtem a extensão do ficheiro local
				SET @ExtensaoFicheiroLocal = REVERSE(@PathFicheiroLocal)
				SET @ExtensaoFicheiroLocal = REVERSE(SUBSTRING(@ExtensaoFicheiroLocal, 1, (CHARINDEX('.', @ExtensaoFicheiroLocal) - 1)))
-- constroi nome para o ficheiro FTP					
				SET @NomeFicheiroFTP = @PrefixoFicheiroFTP + '_' + @Ambiente + '_' + @NumOrdem + '_' 
				IF @TipoMensagem = 'EX009A'
					SET @NomeFicheiroFTP = @NomeFicheiroFTP + CONVERT(varchar(10), @DataCS, 112)
				ELSE
					SET @NomeFicheiroFTP = @NomeFicheiroFTP + CONVERT(varchar(10), @DataOrdem, 112)
				SET @NomeFicheiroFTP = @NomeFicheiroFTP + '_V' + CAST(@Versao AS varchar(5)) + '_R' + CAST(@Revisao AS varchar(5)) + '.' + @ExtensaoFicheiroLocal
-- constroi full path para ficheiro FTP
				IF @TipoMensagem = 'IM005A'
					SET @PathFicheiroFTP = @DirFTPNOT_DIV + @NomeFicheiroFTP
				ELSE
					IF @TipoMensagem = 'EX009A'
						SET @PathFicheiroFTP = @DirFTPCSAI + @NomeFicheiroFTP
					ELSE	
						SET @PathFicheiroFTP = @DirFTPIN + @NomeFicheiroFTP
-- processa o upload do ficheiro da diretoria local tmp p/ o FTP 		
				EXEC GIDWIN.dbo.SP_Externo_UploadFicheiroFTP @ServidorFTP, @UtilizadorFTP, @PasswordFTP, @PathFicheiroLocal, @PathFicheiroFTP, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível efetuar o upload do ficheiro "%s" da declaração "%s" para o servidor FTP "%s"! ERRO: "%s".', 16, 1, @NomeFicheiroFTP, @NumOrdem, @ServidorFTP, @Erros)				
				FETCH NEXT FROM Ficheiros INTO @PrefixoFicheiroFTP, @PathFicheiroLocal
			END
			CLOSE Ficheiros
			DEALLOCATE Ficheiros							
-- atualiza arquivo como exportado para FTP-OGMA
			IF @TipoDeclaracao = 'IMP'
			BEGIN
				UPDATE PRO_DUFI SET DUF_ENVI = 1
				WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao AND DUC_IDEN = @IdFicheiro
			END
			ELSE
			BEGIN
				UPDATE PRO_EXFI SET EXF_ENVI = 1
				WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND DEC_CODI = @CodDeclarante AND EXF_IDEN = @IdFicheiro
			END
-- se declaração originada em ficheiro OGMA e apenas para os ficheiros de A.S., processa a geração do ficheiro MDT 
			IF (ISNULL(@NomeFicheiroOGMA, '') <> '') AND (@TipoMensagem IN ('IM006A', 'EX006A'))
			BEGIN
				SET @FicheiroXML = NULL
				SET @Erros = NULL
-- processa geração do ficheiro MDT relativamente às mesmas declarações DUI2/IMP-CAU/EXP 
				IF @TipoDeclaracao = 'IMP'										
				BEGIN
-- verifica se todas as declarações DUI2/IMP-CAU associadas ao ficheiro MDT já receberam A.S.
					IF EXISTS(SELECT 1
							FROM PRO_DUCG AS duc WITH(NOLOCK) 			
								INNER JOIN PRO_DUFI AS dfm WITH(NOLOCK) ON duc.DUC_EANO = dfm.DUC_EANO AND duc.DUC_PNUM = dfm.DUC_PNUM AND duc.DUC_FUPS = dfm.DUF_NOMF AND dfm.DUF_ORIG = 3 AND dfm.DUF_ENVI = 0
								LEFT OUTER JOIN PRO_DUFI AS df6 WITH(NOLOCK) ON duc.DUC_EANO = df6.DUC_EANO AND duc.DUC_PNUM = df6.DUC_PNUM AND df6.DUF_TMSG = 'IM006A.0'
							WHERE duc.DUC_FUPS = @NomeFicheiroOGMA
							GROUP BY duc.DUC_FUPS
							HAVING COUNT(*) = COUNT(NULLIF(df6.DUF_ENVI, 0)))
					BEGIN
-- processa geração da declaração DUI2 ou IMP-CAU em função da configuração
						IF @IntegracaoIMPCAUAtiva = 0
						BEGIN							
							EXEC @NumErro = SP_DeclImportacao_ExportaFicheiroOGMA @NomeFicheiroOGMA, @Utilizador, @FicheiroXML OUTPUT, @Erros OUTPUT						
							IF @NumErro <> 0
								RAISERROR ('Erro na exportação da(s) declaração(ões) DUI2 para ficheiro MDT "%s"! ERRO: "%s".', 16, 2, @NomeFicheiroOGMA, @Erros)						
						END		
						ELSE
						BEGIN									
							EXEC @NumErro = sp_IMP_Declaracoes_ExportaFicheiroOGMA @NomeFicheiroOGMA, @IdUtilizador, @FicheiroXML OUTPUT, @Erros OUTPUT						
							IF @NumErro <> 0
								RAISERROR ('Erro na exportação da(s) declaração(ões) IMP-CAU para ficheiro MDT "%s"! ERRO: "%s".', 16, 3, @NomeFicheiroOGMA, @Erros)						
						END
					END
				END
				ELSE
				BEGIN
-- verifica se todas as declarações EXP associadas ao ficheiro MDT já receberam A.S.
					IF EXISTS(SELECT 1
							FROM PRO_EXML AS exm WITH(NOLOCK) 			
								INNER JOIN PRO_EXFI AS dfm WITH(NOLOCK) ON exm.EXM_EANO = dfm.EXM_EANO AND exm.EXM_CODI = dfm.EXM_CODI AND exm.DEC_CODI = dfm.DEC_CODI AND exm.EXM_FUPS = dfm.EXF_NOMF AND dfm.EXF_ORIG = 2 AND dfm.EXF_ENVI = 0
								LEFT OUTER JOIN PRO_EXFI AS df6 WITH(NOLOCK) ON exm.EXM_EANO = dfm.EXM_EANO AND exm.EXM_CODI = dfm.EXM_CODI AND exm.DEC_CODI = dfm.DEC_CODI AND df6.EXF_TMSG = 'EX006A'
							WHERE exm.EXM_FUPS = @NomeFicheiroOGMA
							GROUP BY exm.EXM_FUPS
							HAVING COUNT(*) = COUNT(NULLIF(df6.EXF_ENVI, 0)))
					BEGIN
						EXEC @NumErro = SP_ExportacaoXML_ExportaFicheiroOGMA @NomeFicheiroOGMA, @Utilizador, @FicheiroXML OUTPUT, @Erros OUTPUT						
						IF @NumErro <> 0
							RAISERROR ('Erro na exportação da(s) declaração(ões) EXP para ficheiro MDT "%s"! ERRO: "%s".', 16, 4, @NomeFicheiroOGMA, @Erros)					
					END
				END		
-- processa a geração do ficheiro XML local tmp no formato MDT para posterior envio p/ FTP
				IF @FicheiroXML IS NOT NULL
				BEGIN
-- constroi full path para geração do ficheiro XML local tmp
					SET @PathFicheiroLocal = @DirLocalFicheiroTmp + 'MDT_' + @NomeFicheiroOGMA
-- constroi full path para ficheiro FTP				
					SET @PathFicheiroFTP = @DirFTPSIGMA + 'MDT_' + @NomeFicheiroOGMA
-- gera o ficheiro XML c/ encoding UTF-8
					EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroLocal
-- processa o upload do ficheiro da diretoria local tmp p/ o FTP 		
					EXEC GIDWIN.dbo.SP_Externo_UploadFicheiroFTP @ServidorFTP, @UtilizadorFTP, @PasswordFTP, @PathFicheiroLocal, @PathFicheiroFTP, @Erros OUTPUT
					IF ISNULL(@Erros, '') <> ''
						RAISERROR ('Não foi possível efetuar o upload do ficheiro "%s" da declaração "%s" para o servidor FTP "%s"! ERRO: "%s".', 16, 1, @NomeFicheiroFTP, @NumOrdem, @ServidorFTP, @Erros)				
-- remove o ficheiro XML local tmp					
					EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiroLocal, @Erros OUTPUT
					IF ISNULL(@Erros, '') <> ''
						RAISERROR ('Não foi possível remover o ficheiro "%s" da declaração "%s"! ERRO: "%s".', 16, 5, @PathFicheiroLocal, @NumOrdem, @Erros)
-- atualiza arquivo como exportado para FTP-OGMA
					IF @TipoDeclaracao = 'IMP'
					BEGIN
						DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
							SELECT dfm.DUC_EANO, dfm.DUC_PNUM, dfm.DUC_IDEN				
							FROM PRO_DUCG AS duc WITH(NOLOCK) 											
								INNER JOIN PRO_DUFI AS dfm WITH(NOLOCK) ON duc.DUC_EANO = dfm.DUC_EANO AND duc.DUC_PNUM = dfm.DUC_PNUM AND duc.DUC_FUPS = dfm.DUF_NOMF AND dfm.DUF_ORIG = 3 AND dfm.DUF_ENVI = 0								
							WHERE duc.DUC_FUPS = @NomeFicheiroOGMA
						OPEN Ficheiros
						FETCH NEXT FROM Ficheiros INTO @AnoDeclaracao, @NumDeclaracao, @IdFicheiro
						WHILE @@FETCH_STATUS = 0
						BEGIN		
							UPDATE PRO_DUFI SET DUF_ENVI = 1
							WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao AND DUC_IDEN = @IdFicheiro
							FETCH NEXT FROM Ficheiros INTO @AnoDeclaracao, @NumDeclaracao, @IdFicheiro
						END
						CLOSE Ficheiros
						DEALLOCATE Ficheiros
					END
					ELSE
					BEGIN
						DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
							SELECT dfm.EXM_EANO, dfm.EXM_CODI, dfm.DEC_CODI, dfm.EXF_IDEN				
							FROM PRO_EXML AS exm WITH(NOLOCK) 			
								INNER JOIN PRO_EXFI AS dfm WITH(NOLOCK) ON exm.EXM_EANO = dfm.EXM_EANO AND exm.EXM_CODI = dfm.EXM_CODI AND exm.DEC_CODI = dfm.DEC_CODI AND exm.EXM_FUPS = dfm.EXF_NOMF AND dfm.EXF_ORIG = 2 AND dfm.EXF_ENVI = 0																	
							WHERE exm.EXM_FUPS = @NomeFicheiroOGMA
						OPEN Ficheiros
						FETCH NEXT FROM Ficheiros INTO @AnoDeclaracao, @NumDeclaracao, @CodDeclarante, @IdFicheiro
						WHILE @@FETCH_STATUS = 0
						BEGIN		
							UPDATE PRO_EXFI SET EXF_ENVI = 1
							WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND DEC_CODI = @CodDeclarante AND EXF_IDEN = @IdFicheiro
							FETCH NEXT FROM Ficheiros INTO @AnoDeclaracao, @NumDeclaracao, @CodDeclarante, @IdFicheiro
						END
						CLOSE Ficheiros
						DEALLOCATE Ficheiros
					END
				END
			END
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO ENVIO DE FICHEIROS PARA FTP *******************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Numero DAU:  ' + @NumOrdem + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @PathFicheiroErro = @DirLocalFicheiroErros + @NumOrdem + '.err'
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroErro, @Erros)	
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END		
		FETCH NEXT FROM Arquivos INTO @TipoDeclaracao, @AnoDeclaracao, @NumDeclaracao, @CodDeclarante, @NIFDeclarante, @NumDeclaracaoEXP, @NumOrdem, @DataOrdem, @Versao, @Revisao, @Pacote, 
			@NomeFicheiroOGMA, @DataCS, @IdFicheiro, @PathFicheiroPDFLocal, @TipoMensagem, @PathFicheiroXMLLocal, @PrefixoFicheiroFTP, @PathFicheiroACKLocal, @Ordem
	END
	CLOSE Arquivos
	DEALLOCATE Arquivos
-- remove as tabelas temporárias	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_Geral_EnviaFicheirosIMPeEXPParaFTPOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_EnviaFicheirosIMPeEXPParaFTPOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_ExportaFicheirosXMLDARP]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_ExportaFicheirosXMLDARP] @DataASReferencia datetime AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @DeclaracaoDAR bit, @AnoDeclaracao int, @NumDeclaracao int, @NumOrdem varchar(20), @Id bigint, @FicheiroXML xml, @LinhaXMLEncoding varchar(200), @DirGeracaoFicheiro nvarchar(500), 
		@PathFicheiroTmpXML nvarchar(4000)
-- obtem a diretoria p/ geração do ficheiro XML
	SELECT @DirGeracaoFicheiro = PFC_PENV 
	FROM TAB_PFCT WITH(NOLOCK)
-- obtem a lista de declarações de importação DUI2 e IMP-CAU c/ Nº. Ordem, A.S., tenha em Arquivo registo do tipo "IM006A.1" e que ainda não tenha sido exportado
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT 0, duc.DUC_EANO, duc.DUC_PNUM, duc.DUC_NORD, duc.DUC_IDTY
		FROM PRO_DUCG AS duc WITH(NOLOCK)
		WHERE duc.DUC_DUNO IN (1, 2) AND ISNULL(duc.DUC_NORD, '') <> '' AND duc.DUC_ASAI = 1 AND duc.DUC_EXPO = 0 
			AND EXISTS(SELECT DUC_IDEN FROM PRO_DUFI WITH(NOLOCK) WHERE DUC_PNUM = duc.DUC_PNUM AND DUC_EANO = duc.DUC_EANO AND DUF_TMSG = 'IM006A.1')
			AND CAST(CONVERT(varchar(10), duc.DUC_DTAS, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataASReferencia, duc.DUC_DTAS), 105) AS datetime)
		UNION
		SELECT 1, dar.ano, dar.numero, dar.numeroNRM, dar.id
		FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK)
		WHERE ISNULL(dar.numeroNRM, '') <> '' AND dar.autorizacaoSaida = 1 AND dar.exportado = 0 			
			AND CAST(CONVERT(varchar(10), dar.dataAutorizacaoSaida, 105) AS datetime) >= CAST(CONVERT(varchar(10), ISNULL(@DataASReferencia, dar.dataAutorizacaoSaida), 105) AS datetime)
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @DeclaracaoDAR, @AnoDeclaracao, @NumDeclaracao, @NumOrdem, @Id
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- constroi XML para ficheiro DARP
		IF @DeclaracaoDAR = 1
			EXEC sp_DeclaracoesDAR_ExportaFicheiroDARP @Id, @FicheiroXML OUTPUT, @LinhaXMLEncoding OUTPUT
		ELSE
			EXEC SP_DeclImportacao_ExportaFicheiroDARP @AnoDeclaracao, @NumDeclaracao, @FicheiroXML OUTPUT, @LinhaXMLEncoding OUTPUT 	
-- constroi full path para geração do ficheiro XML
		SET @PathFicheiroTmpXML = @DirGeracaoFicheiro + '\' + @NumOrdem + '.XML'
-- gera o ficheiro XML DARP c/ encoding UTF-8
		EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroTmpXML				
-- atualiza declaração p/ sinalizar como já enviada
		IF @DeclaracaoDAR = 1
		BEGIN
			UPDATE tb_DeclaracoesDAR SET exportado = 1
			WHERE id = @Id
		END
		ELSE
		BEGIN
			UPDATE PRO_DUCG SET DUC_EXPO = 1
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
		END
		FETCH NEXT FROM Declaracoes INTO @DeclaracaoDAR, @AnoDeclaracao, @NumDeclaracao, @NumOrdem, @Id
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER AUTHORIZATION ON [SP_Geral_ExportaFicheirosXMLDARP] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_ExportaFicheirosXMLDARP] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_ExportaFicheirosXMLRTRIAM]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_ExportaFicheirosXMLRTRIAM] @DirFicheirosRTRIAM varchar(500), @DirFicheirosEX006A varchar(500), @NIFClienteRT varchar(18), @NIFClienteRIAM varchar(18), @NIFClientesRTRIAM xml, 
	@DataReferencia datetime, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @NumErro int, @Erros varchar(MAX), @SQLString nvarchar(500), @SQLParams nvarchar(500), @DirFicheirosBkpEXP varchar(150), @TipoDeclaracao varchar(3), @AnoDeclaracao int, 
		@NumDeclaracao int, @CodDeclarante varchar(6), @NIFDeclarante varchar(18), @NumDeclaracaoEXP varchar(7), @DataDeclaracao datetime, @NumOrdem varchar(21), @DataOrdem datetime, 
		@Pacote varchar(3), @VossaReferencia varchar(50), @IdFicheiro int, @PathFicheiroPDF varchar(500), @NomeFicheiroPDF varchar(100), @TipoMensagem varchar(8), @FicheiroBinario varbinary(MAX), 
		@NumReferenciaN830 varchar(70), @CodClienteRTRIAM varchar(18), @FicheiroBase64 varchar(MAX), @FicheiroTXT varchar(MAX), @FicheiroXML xml, @PathFicheiroXML nvarchar(4000), 
		@TipoMensagemXML varchar(8), @NomeFicheiro varchar(100), @PathFicheiro varchar(500), @MsgErro varchar(MAX)
	BEGIN TRY
-- verifica se diretorias locais tem backslash no final	
		IF RIGHT(@DirFicheirosRTRIAM, 1) <> '\'
			SET @DirFicheirosRTRIAM = @DirFicheirosRTRIAM + '\'	
		IF RIGHT(@DirFicheirosEX006A, 1) <> '\'
			SET @DirFicheirosEX006A = @DirFicheirosEX006A + '\'	
-- obtem a diretoria de backup de ficheiros EXP
		SELECT @DirFicheirosBkpEXP = PDE_XPBK
		FROM TAB_PDES WITH(NOLOCK)
-- obtem os ficheiros PDF das mensagens IM006A/EX006A pendentes de envio das declarações IMP e EXP
		DECLARE Arquivos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 		
			SELECT 'IMP' AS DUC_CNTX, duc.DUC_EANO, duc.DUC_PNUM, NULL AS DEC_CODI, NULL AS DEC_NIF, NULL AS EXM_NRII, duc.DUC_DATA, duc.DUC_NORD, duc.DUC_NDAT, duc.DUC_PENV, duc.DUC_NVRF, 
				dfi.DUC_IDEN, dfi.DUF_LINK, dfi.DUF_NOMF, dfi.DUF_FICH, dfi.DUF_TMSG, 
				NULL AS EXD_NREF, 
				(CASE 
					WHEN NULLIF(ccc.CLI_NIF, '') = NULLIF(@NIFClienteRIAM, '') OR NULLIF(csr.CLI_NIF, '') = NULLIF(@NIFClienteRIAM, '') OR LEN(RTRIM(LTRIM(duc.DUC_NVRF))) <> 15 OR ISNUMERIC(RTRIM(LTRIM(duc.DUC_NVRF))) = 0 THEN 'RIAM'
					WHEN NULLIF(ccc.CLI_NIF, '') = NULLIF(@NIFClienteRT, '') OR NULLIF(csr.CLI_NIF, '') = NULLIF(@NIFClienteRT, '') OR (LEN(RTRIM(LTRIM(duc.DUC_NVRF))) = 15 AND ISNUMERIC(RTRIM(LTRIM(duc.DUC_NVRF))) = 1) THEN 'RT'					
					ELSE NULL
				END) AS CLI_CODI
			FROM PRO_DUCG AS duc WITH(NOLOCK) 						
				INNER JOIN PRO_DUFI AS dfi WITH(NOLOCK) ON duc.DUC_EANO = dfi.DUC_EANO AND duc.DUC_PNUM = dfi.DUC_PNUM AND dfi.DUF_TMSG IN ('IM006A.0', 'IM006A.1') AND dfi.DUF_ENVI = 0	
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
				LEFT OUTER JOIN TAB_CLIE AS ccc WITH(NOLOCK) ON cli.CLI_CCOR = ccc.CLI_CODI
				LEFT OUTER JOIN TAB_CLIE AS csr WITH(NOLOCK) ON duc.CLI_CODI = csr.CLI_CODI
			WHERE ISNULL(duc.DUC_NVRF, '') <> '' AND duc.DUC_ASAI = 1 AND duc.DUC_DTAS >= @DataReferencia 
				AND (NULLIF(ccc.CLI_NIF, '') IN (NULLIF(@NIFClienteRT, ''), NULLIF(@NIFClienteRIAM, '')) 
					OR NULLIF(csr.CLI_NIF, '') IN (NULLIF(@NIFClienteRT, ''), NULLIF(@NIFClienteRIAM, ''))
					OR (LEN(RTRIM(LTRIM(duc.DUC_NVRF))) = 15 AND ISNUMERIC(RTRIM(LTRIM(duc.DUC_NVRF))) = 1) AND EXISTS(SELECT 1 FROM @NIFClientesRTRIAM.nodes('Clientes/NIF') AS t(c) WHERE t.c.value('.', 'varchar(18)') = NULLIF(duc.DUC_DNIF, '')))				
			UNION ALL
			SELECT 'EXP' AS DUC_CNTX, exm.EXM_EANO, exm.EXM_CODI, exm.DEC_CODI, dcl.DEC_NIF, (REPLICATE('0', (7 - LEN(LTRIM(STR(exm.EXM_NRII, 7))))) + LTRIM(STR(exm.EXM_NRII, 7))), exm.EXM_DATA, exm.EXM_NDGA, exm.EXM_DDGA, exm.EXM_PENV, exm.EXM_NVRF, 
				dfi.EXF_IDEN, dfi.EXF_LINK, dfi.EXF_NOMF, dfi.EXF_FICH, dfi.EXF_TMSG, 
				(SELECT TOP 1 EXD_NREF FROM PRO_EXDA WITH(NOLOCK) WHERE EXM_EANO = exm.EXM_EANO AND EXM_CODI = exm.EXM_CODI AND EXM_COPE = exm.DEC_CODI AND EXA_LINH = 1) AS EXD_NREF, 
				(CASE 
					WHEN NULLIF(ccc.CLI_NIF, '') = NULLIF(@NIFClienteRIAM, '') OR NULLIF(csr.CLI_NIF, '') = NULLIF(@NIFClienteRIAM, '') OR LEN(RTRIM(LTRIM(exm.EXM_NVRF))) <> 15 AND ISNUMERIC(RTRIM(LTRIM(exm.EXM_NVRF))) = 0 THEN 'RIAM'
					WHEN NULLIF(ccc.CLI_NIF, '') = NULLIF(@NIFClienteRT, '') OR NULLIF(csr.CLI_NIF, '') = NULLIF(@NIFClienteRT, '') OR (LEN(RTRIM(LTRIM(exm.EXM_NVRF))) = 15 AND ISNUMERIC(RTRIM(LTRIM(exm.EXM_NVRF))) = 1) THEN 'RT'					
					ELSE NULL
				END) AS CLI_CODI
			FROM PRO_EXML AS exm WITH(NOLOCK)		
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CODI = dcl.DEC_CODI		
				INNER JOIN PRO_EXFI AS dfi WITH(NOLOCK) ON exm.EXM_EANO = dfi.EXM_EANO AND exm.EXM_CODI = dfi.EXM_CODI AND exm.DEC_CODI = dfi.DEC_CODI AND dfi.EXF_TMSG IN ('EX006A', 'EX009A', 'EX00CCE') AND dfi.EXF_ENVI = 0
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON exm.CLI_COD2 = cli.CLI_CODI
				LEFT OUTER JOIN TAB_CLIE AS ccc WITH(NOLOCK) ON cli.CLI_CCOR = ccc.CLI_CODI
				LEFT OUTER JOIN TAB_CLIE AS csr WITH(NOLOCK) ON exm.CLI_CODI = csr.CLI_CODI
			WHERE ISNULL(exm.EXM_NVRF, '') <> '' AND exm.EXM_ASAI = 1 AND exm.EXM_DTAS >= @DataReferencia 
				AND (NULLIF(ccc.CLI_NIF, '') IN (NULLIF(@NIFClienteRT, ''), NULLIF(@NIFClienteRIAM, '')) 
					OR NULLIF(csr.CLI_NIF, '') IN (NULLIF(@NIFClienteRT, ''), NULLIF(@NIFClienteRIAM, ''))
					OR (LEN(RTRIM(LTRIM(exm.EXM_NVRF))) = 15 AND ISNUMERIC(RTRIM(LTRIM(exm.EXM_NVRF))) = 1) AND EXISTS(SELECT 1 FROM @NIFClientesRTRIAM.nodes('Clientes/NIF') AS t(c) WHERE t.c.value('.', 'varchar(18)') = NULLIF(exm.CLI_NIF2, ''))) 							
			ORDER BY DUC_CNTX, DUC_EANO, DUC_PNUM, DUC_IDEN
		OPEN Arquivos
		FETCH NEXT FROM Arquivos INTO @TipoDeclaracao, @AnoDeclaracao, @NumDeclaracao, @CodDeclarante, @NIFDeclarante, @NumDeclaracaoEXP, @DataDeclaracao, @NumOrdem, @DataOrdem, @Pacote, 
			@VossaReferencia, @IdFicheiro, @PathFicheiroPDF, @NomeFicheiroPDF, @FicheiroBinario, @TipoMensagem, @NumReferenciaN830, @CodClienteRTRIAM
		WHILE @@FETCH_STATUS = 0
		BEGIN					
			BEGIN TRY	
-- carrega ficheiro PDF para binário
				IF @FicheiroBinario IS NULL
				BEGIN
-- inicia variaveis para executar o SQL dinamicamente
					SET @SQLString = N'SET @OUTFicheiroBinario = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiroPDF + ''', SINGLE_BLOB) AS t)'
					SET @SQLParams = N'@OUTFicheiroBinario varbinary(MAX) OUTPUT'			
-- obtem o ficheiro em binario
					EXECUTE sp_executesql @SQLString, @SQLParams, @OUTFicheiroBinario = @FicheiroBinario OUTPUT
				END			
-- converte ficheiro PDF para base64						
				SET @FicheiroBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinario")))', 'varchar(MAX)')		
-- constroi XML para formato RT-RIAM
				;WITH XMLNAMESPACES ('http://www.rangel.com/DespachoInfo' AS tns)		
				SELECT @FicheiroXML = 
					(SELECT					
						NULL AS "tns:DespachoID", 
						ISNULL(@CodClienteRTRIAM, '') AS "tns:DespachoCliente", 
						(CONVERT(varchar(10), @DataDeclaracao, 127) + 'Z') AS "tns:DespachoDataProc", 
						ISNULL(@NumDeclaracaoEXP, @NumDeclaracao) AS "tns:DespachoNumProc", 
						@AnoDeclaracao AS "tns:DespachoAno", 
						NULLIF(@VossaReferencia, '') AS "tns:DespachoReferencia", 
						NULLIF(@NumReferenciaN830, '') AS "tns:DespachoRefDME", 
						(CONVERT(varchar(10), @DataOrdem, 127) + 'Z') AS "tns:DespachoDataOrdem", 
						NULLIF(@NumOrdem, '') AS "tns:DespachoDAU", 
						(CASE @TipoMensagem
							WHEN 'EX009A' THEN 'CSAI'
							WHEN 'EX00CCE' THEN 'CCE'
							WHEN 'IM006A.1' THEN 'DPD'
							ELSE 'CC'											
						END) AS "tns:DocumentoTipo", 
						NULLIF(@NomeFicheiroPDF, '') AS "tns:DocumentoNome", 
						@FicheiroBase64 AS "tns:DocumentoContent"									
					FOR XML PATH('tns:Message'), ELEMENTS)						
-- constroi full path para geração do ficheiro XML				
				SET @PathFicheiroXML = @DirFicheirosRTRIAM + @NumOrdem + @TipoMensagem +'.XML'
-- gera o ficheiro XML RT-RIAM c/ encoding UTF-8
				EXEC GIDWIN.dbo.SP_Externo_GeraFicheiroXMLEncodingUTF8 @FicheiroXML, @PathFicheiroXML
-- para declarações de exportação, obtem os ficheiros de envio/resposta da declaração na diretoria configurada
				IF (@TipoDeclaracao = 'EXP') AND (@TipoMensagem = 'EX006A')
				BEGIN
					DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
						SELECT [fileName], fullName
						FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirFicheirosBkpEXP, '*' + @NIFDeclarante + '.' + @NumDeclaracaoEXP + @Pacote + '.*')
						ORDER BY lastWriteTime DESC
					OPEN Ficheiros
					FETCH NEXT FROM Ficheiros INTO @NomeFicheiro, @PathFicheiro
					WHILE @@FETCH_STATUS = 0
					BEGIN
						SET @FicheiroTXT = NULL
						SET @TipoMensagemXML = NULL			
-- inicia variaveis para executar o SQL dinamicamente
						SET @SQLString = N'SET @OUTFicheiroTXT = (SELECT * FROM OPENROWSET (BULK N''' + @PathFicheiro + ''', SINGLE_BLOB) AS t)'
						SET @SQLParams = N'@OUTFicheiroTXT varchar(MAX) OUTPUT'			
-- obtem o ficheiro em binario
						EXECUTE sp_executesql @SQLString, @SQLParams, @OUTFicheiroTXT = @FicheiroTXT OUTPUT	
-- converte p/ xml c/ a remoção do encoding
						SET @FicheiroXML = REPLACE(@FicheiroTXT, ' encoding="UTF-8"', '')
-- obtem nome da mensagem XML do ficheiro
						SELECT @TipoMensagemXML = t.c.value('fn:local-name(./*[1])', 'varchar(100)')
						FROM @FicheiroXML.nodes('ficheiro/mensagens') AS t(c)
-- copia ficheiro XML EX006A da declaração
						IF UPPER(@TipoMensagemXML) = 'EX006A'	
						BEGIN
-- constroi full path para cópia do ficheiro XML
							SET @PathFicheiroXML = @DirFicheirosEX006A + @NumOrdem + '_' + @NomeFicheiro
-- processa a cópia do ficheiro XML EX006A
							EXEC GIDWIN.dbo.SP_Externo_CopiaFicheiro @PathFicheiro, @PathFicheiroXML, @MsgErro OUTPUT										
							IF ISNULL(@MsgErro, '') <> ''
								RAISERROR ('Não foi possível copiar o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @MsgErro)
						END
						FETCH NEXT FROM Ficheiros INTO @NomeFicheiro, @PathFicheiro
					END
					CLOSE Ficheiros
					DEALLOCATE Ficheiros
				END
-- atualiza arquivo como exportado para RT-RIAM
				IF @TipoDeclaracao = 'IMP'
				BEGIN
					UPDATE PRO_DUFI SET DUF_ENVI = 1
					WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao AND DUC_IDEN = @IdFicheiro
				END
				ELSE
				BEGIN
					UPDATE PRO_EXFI SET EXF_ENVI = 1
					WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND DEC_CODI = @CodDeclarante AND EXF_IDEN = @IdFicheiro
				END
			END TRY
			BEGIN CATCH
-- constroi mensagem de erro detalhada
				SET @Erros = ISNULL(@Erros, '') + 
									   '**********************************************************************************************************' + CHAR(12) +
									   '** ERRO NA GERACAO DE FICHEIRO RT-RIAM *******************************************************************' + CHAR(12) + 
									   '**********************************************************************************************************' + CHAR(12) + 
									   '.Numero DAU:  ' + @NumOrdem + CHAR(12) +								   
									   '.Detalhe Erro:       ' + CHAR(12) +
									   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
									   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
									   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
									   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
									   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
									   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
									   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
			END CATCH	
			FETCH NEXT FROM Arquivos INTO @TipoDeclaracao, @AnoDeclaracao, @NumDeclaracao, @CodDeclarante, @NIFDeclarante, @NumDeclaracaoEXP, @DataDeclaracao, @NumOrdem, @DataOrdem, @Pacote, 
				@VossaReferencia, @IdFicheiro, @PathFicheiroPDF, @NomeFicheiroPDF, @FicheiroBinario, @TipoMensagem, @NumReferenciaN830, @CodClienteRTRIAM
		END
		CLOSE Arquivos
		DEALLOCATE Arquivos
-- se houve erros na geração de algum ficheiro RT-RIAM, gera erro genérico para detalhar os erros ocorridos na geração
		IF ISNULL(@Erros, '') <> ''
			RAISERROR ('%s', 16, 99, @Erros)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro			
END

ALTER AUTHORIZATION ON [SP_Geral_ExportaFicheirosXMLRTRIAM] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_ExportaFicheirosXMLRTRIAM] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_ObtemFicheirosIMPeEXPDoFTPOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_ObtemFicheirosIMPeEXPDoFTPOGMA] @ServidorFTP varchar(100), @UtilizadorFTP varchar(100), @PasswordFTP varchar(100), @DirFTPIN varchar(100), @DirFTPOUT varchar(100), 
	@DirLocalIN varchar(500), @DirLocalOUT varchar(500), @DirLocalErros varchar(500), @Ambiente varchar(3), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @NumErro int, @i int, @ListaErros varchar(MAX), @Erros varchar(MAX), @PathFicheiroErro varchar(500), @Linha varchar(MAX), @ComandoSQL varchar(1500), @IdUtilizador int, 
		@IntegracaoIMPCAUAtiva bit, @PathFicheiroFTP varchar(500), @NomeFicheiroFTP varchar(250), @PathFicheiroDestinoFTP varchar(500), @PathFicheiroLocal varchar(500), 
		@NomeFicheiroLocal varchar(250), @FicheiroTXT varchar(MAX), @FicheiroXML xml, @XMLCtxDeclaracao varchar(1), @XMLNumDocTransporte varchar(25)
-- cria tabela temporária p/ conteudo de cada ficheiro .XML
	CREATE TABLE #ConteudoFicheiro(CONTEUDO varchar(MAX) COLLATE Latin1_General_CI_AI)
-- substitui caracteres especiais p/ utilização no comando "echo"
	SET @ServidorFTP = REPLACE(REPLACE(REPLACE(REPLACE(@ServidorFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @UtilizadorFTP = REPLACE(REPLACE(REPLACE(REPLACE(@UtilizadorFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @PasswordFTP = REPLACE(REPLACE(REPLACE(REPLACE(@PasswordFTP, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirFTPIN = REPLACE(REPLACE(REPLACE(REPLACE(@DirFTPIN, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
	SET @DirFTPOUT = REPLACE(REPLACE(REPLACE(REPLACE(@DirFTPOUT, '|', '^|'), '<', '^<'), '>', '^>'), '&', '^&')
-- verifica se diretorias FTP tem separador no início e fim
	IF SUBSTRING(@DirFTPIN, 1, 1) <> '/'
		SET @DirFTPIN = '/' + @DirFTPIN
	IF SUBSTRING(REVERSE(@DirFTPIN), 1, 1) <> '/'
		SET @DirFTPIN = @DirFTPIN + '/'		
	IF (ISNULL(@DirFTPOUT, '') <> '') AND (SUBSTRING(@DirFTPOUT, 1, 1) <> '/')
		SET @DirFTPOUT = '/' + @DirFTPOUT
	IF (ISNULL(@DirFTPOUT, '') <> '') AND (SUBSTRING(REVERSE(@DirFTPOUT), 1, 1) <> '/')
		SET @DirFTPOUT = @DirFTPOUT + '/'	
-- verifica se diretorias locais tem backslash no final	
	IF SUBSTRING(REVERSE(@DirLocalIN), 1, 1) <> '\'
		SET @DirLocalIN = @DirLocalIN + '\'
	IF SUBSTRING(REVERSE(@DirLocalOUT), 1, 1) <> '\'
		SET @DirLocalOUT = @DirLocalOUT + '\'
	IF SUBSTRING(REVERSE(@DirLocalErros), 1, 1) <> '\'
		SET @DirLocalErros = @DirLocalErros + '\'	
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador	
-- obtem se integração IMP-CAU ativa
	SELECT TOP 1 @IntegracaoIMPCAUAtiva = PDE_ICAU
	FROM TAB_PDES WITH(NOLOCK)					
-- obtem os ficheiros das declarações IMP e EXP disponíveis para importar
	DECLARE Arquivos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 		
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheirosFTP(@ServidorFTP, @UtilizadorFTP, @PasswordFTP, @DirFTPIN)
		WHERE [fileName] LIKE '%_' + @Ambiente + '_%.xml'		
	OPEN Arquivos
	FETCH NEXT FROM Arquivos INTO @PathFicheiroFTP, @NomeFicheiroFTP
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''		
		BEGIN TRY			
-- constroi path completa do ficheiro local .XML
			SET @PathFicheiroLocal = @DirLocalIN + @NomeFicheiroFTP			
-- processa ligação FTP p/ download do ficheiro .XML
			EXEC GIDWIN.dbo.SP_Externo_DownloadFicheiroFTP @ServidorFTP, @UtilizadorFTP, @PasswordFTP, @PathFicheiroFTP, @PathFicheiroLocal, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível efetuar o download do ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiroFTP, @Erros)																							
-- se diretoria de destino de ficheiros no FTP definida, processa o mover do ficheiro
			IF ISNULL(@DirFTPOUT, '') <> ''
			BEGIN
-- constroi path completa do ficheiro FTP .XML a mover
				SET @PathFicheiroDestinoFTP = @DirFTPOUT + @NomeFicheiroFTP
-- processa ligação FTP p/ mover o ficheiro .XML
				EXEC GIDWIN.dbo.SP_Externo_MoveFicheiroFTP @ServidorFTP, @UtilizadorFTP, @PasswordFTP, @PathFicheiroFTP, @PathFicheiroDestinoFTP, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 2, @PathFicheiroFTP, @Erros)
			END
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NA OBTENÇÃO DE FICHEIRO DO FTP *******************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Ficheiro FTP:  ' + @NomeFicheiroFTP + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @PathFicheiroErro = @DirLocalErros + @NomeFicheiroFTP + '.err'
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 3, @PathFicheiroErro, @Erros)	
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END		
		FETCH NEXT FROM Arquivos INTO @PathFicheiroFTP, @NomeFicheiroFTP
	END
	CLOSE Arquivos
	DEALLOCATE Arquivos
-- obtem os ficheiros das declarações IMP e EXP descarregados para importar
	DECLARE Arquivos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirLocalIN, '*_' + @Ambiente + '_*.xml')
		ORDER BY [lastWriteTime]		
	OPEN Arquivos
	FETCH NEXT FROM Arquivos INTO @PathFicheiroLocal, @NomeFicheiroLocal
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''		
		BEGIN TRY	
			SET @NumErro = 0
			SET @Erros = NULL
			SET @FicheiroTXT = NULL
			SET @XMLCtxDeclaracao = NULL
			SET @XMLNumDocTransporte = NULL
-- processa a importação dos dados do ficheiro na tabela temporária
			SET @ComandoSQL = 'BULK INSERT #ConteudoFicheiro FROM ''' + @PathFicheiroLocal + ''''
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiroLocal, @DirLocalOUT, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 4, @PathFicheiroLocal, @Erros)						
-- obtem o xml do ficheiro importado (se xml não minified, torna-o minified)
			SELECT @FicheiroTXT = COALESCE(@FicheiroTXT, '') + CONTEUDO
			FROM #ConteudoFicheiro
-- converte p/ xml c/ a remoção do encoding
			SET @FicheiroXML = REPLACE(@FicheiroTXT, ' encoding="UTF-8"', '')
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- obtem contexto e AWB da declaração do ficheiro
			SELECT @XMLCtxDeclaracao = t.c.value('TIPO[1]', 'varchar(1)'), @XMLNumDocTransporte = t.c.value('AWB[1]', 'varchar(25)')	
			FROM @FicheiroXML.nodes('FICH_DESPCHANTE/FICH_DESPCHANTE_LINE') AS t(c)
-- processa geração da declaração DUI2/IMP-CAU /EXP conforme o contexto da declaração no ficheiro
			IF @XMLCtxDeclaracao = 'I'
			BEGIN
-- processa geração da declaração DUI2 ou IMP-CAU em função da configuração
				IF @IntegracaoIMPCAUAtiva = 0
				BEGIN							
					EXEC @NumErro = SP_DeclImportacao_ImportaFicheiroOGMA @FicheiroXML, @NomeFicheiroLocal, @Utilizador, @Erros OUTPUT						
					IF @NumErro <> 0
						RAISERROR ('Erro na importação da declaração DUI2 "%s"! ERRO: "%s".', 16, 5, @XMLNumDocTransporte, @Erros)						
				END		
				ELSE
				BEGIN									
					EXEC @NumErro = sp_IMP_Declaracoes_ImportaFicheiroOGMA @FicheiroXML, @NomeFicheiroLocal, @IdUtilizador, @Erros OUTPUT						
					IF @NumErro <> 0
						RAISERROR ('Erro na importação da declaração IMP-CAU "%s"! ERRO: "%s".', 16, 6, @XMLNumDocTransporte, @Erros)						
				END
			END
			ELSE
			BEGIN
				EXEC @NumErro = SP_ExportacaoXML_ImportaFicheiroOGMA @FicheiroXML, @NomeFicheiroLocal, @Utilizador, @Erros OUTPUT						
				IF @NumErro <> 0
					RAISERROR ('Erro na importação da declaração EXP "%s"! ERRO: "%s".', 16, 7, @XMLNumDocTransporte, @Erros)					
			END					
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NA IMPORTAÇÃO DE FICHEIRO DO FTP *****************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Ficheiro FTP:  ' + @NomeFicheiroLocal + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN						
			SET @PathFicheiroErro = @DirLocalErros + @NomeFicheiroLocal + '.err'
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 8, @PathFicheiroErro, @Erros)	
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END		
		FETCH NEXT FROM Arquivos INTO @PathFicheiroLocal, @NomeFicheiroLocal
	END
	CLOSE Arquivos
	DEALLOCATE Arquivos
-- remove as tabelas temporárias	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_Geral_ObtemFicheirosIMPeEXPDoFTPOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_ObtemFicheirosIMPeEXPDoFTPOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_ProcessaFicheirosASCIIDeclaracoesUPS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_ProcessaFicheirosASCIIDeclaracoesUPS] @TipoImportacao tinyint, @DirectoriaFicheiros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @IdUtilizador int, @IntegracaoIMPCAUAtiva bit, @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @PathNovoFicheiro varchar(500), 
		@ComandoSQL varchar(1500), @FicheiroXML xml, @ErroFicheiro varchar(MAX), @i int, @XMLCodPaisMoedaFatura varchar(2), @XMLMontanteTotal numeric(38, 6), @XMLNumDocTransporte varchar(18), 
		@XMLNIFDestinatario varchar(9), @XMLIdentificacaoIOSS varchar(12), @DeclaracaoXML xml, @Cambio numeric(38, 6), @ErroImportacao varchar(MAX), @Erros varchar(MAX), 
		@PathFicheiroErro varchar(500), @Linha varchar(MAX)
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador	
-- obtem se integração IMP-CAU ativa
	SELECT TOP 1 @IntegracaoIMPCAUAtiva = PDE_ICAU
	FROM TAB_PDES WITH(NOLOCK)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirectoriaFicheiros), 1, 1) <> '\'
		SET @DirectoriaFicheiros = @DirectoriaFicheiros + '\'
-- obtem data atual GMT
	SET @DataAtual = CAST(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 127) + ' 23:58:58' AS datetime)	
-- cria tabela temporária p/ conteudo de cada ficheiro ascii	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO varchar(MAX))
-- obtem lista de ficheiros UPS a importar (considera apenas ficheiros cuja extensão é numérica se tipo importação for "0" ou "1"; ou apenas ficheiros cuja extensão for "str" se tipo importação for "2")
	DECLARE FicheirosUPS CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName], ([fullName] + (CASE @TipoImportacao WHEN 1 THEN '.str' ELSE '.sin' END))
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirectoriaFicheiros, '*.*')
		WHERE (@TipoImportacao IN (0, 1) AND ISNUMERIC(RIGHT([extension], 3)) = 1) OR (@TipoImportacao = 2 AND [extension] = '.str')
		ORDER BY [lastWriteTime]		
	OPEN FicheirosUPS
	FETCH NEXT from FicheirosUPS into @PathFicheiro, @NomeFicheiro, @PathNovoFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN										
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária
			SET @ComandoSQL = 'BULK INSERT #ConteudoFicheiro FROM ''' + @PathFicheiro + ''''
			EXEC (@ComandoSQL)
-- move o ficheiro importado (apenas p/ renomear)
			SET @Erros = ''
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @PathNovoFicheiro, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível renomear o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)	
-- remove o ficheiro importado
			SET @Erros = ''
			EXEC GIDWIN.dbo.SP_Externo_RemoveFicheiro @PathFicheiro, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível remover o ficheiro "%s"! ERRO: "%s".', 16, 2, @PathFicheiro, @Erros)
-- obtem o xml do ficheiro ascii importado					
			SET @FicheiroXML = 
				(SELECT 					
					(SELECT @NomeFicheiro AS "nomeFicheiro", 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(cab.CONTEUDO) AS "linha"
						FOR XML PATH('b100000'), TYPE), 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 200000 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b200000'), TYPE), 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 202000 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b202000'), TYPE), 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 300000 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b300000'), TYPE), 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 400000 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b400000'), TYPE), 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 500000 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b500000'), TYPE), 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) >= 600000 AND CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) < 700000 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b600xxx'), TYPE), 
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 701000 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b701000'), TYPE),
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 701001 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b701001'), TYPE),
						(SELECT dbo.FNT_Geral_RemoveCaracteresXMLInvalidos(det.CONTEUDO) AS "linha"
						FROM #ConteudoFicheiro AS det
						WHERE CAST(SUBSTRING(det.CONTEUDO, 45, 6) AS int) = 701002 AND SUBSTRING(det.CONTEUDO, 1, 2) = SUBSTRING(cab.CONTEUDO, 1, 2) 
							AND SUBSTRING(det.CONTEUDO, 3, 4) = SUBSTRING(cab.CONTEUDO, 3, 4) AND SUBSTRING(det.CONTEUDO, 7, 2) = SUBSTRING(cab.CONTEUDO, 7, 2) 
							AND SUBSTRING(det.CONTEUDO, 9, 4) = SUBSTRING(cab.CONTEUDO, 9, 4) AND SUBSTRING(det.CONTEUDO, 13, 6) = SUBSTRING(cab.CONTEUDO, 13, 6) 
							AND SUBSTRING(det.CONTEUDO, 33, 1) = SUBSTRING(cab.CONTEUDO, 33, 1) AND SUBSTRING(det.CONTEUDO, 34, 11) = SUBSTRING(cab.CONTEUDO, 34, 11) 						
						FOR XML PATH('b701002'), TYPE)
					FROM #ConteudoFicheiro AS cab INNER JOIN #ConteudoFicheiro AS sec ON SUBSTRING(cab.CONTEUDO, 1, 2) = SUBSTRING(sec.CONTEUDO, 1, 2) AND SUBSTRING(cab.CONTEUDO, 3, 4) = SUBSTRING(sec.CONTEUDO, 3, 4) AND SUBSTRING(cab.CONTEUDO, 7, 2) = SUBSTRING(sec.CONTEUDO, 7, 2) AND SUBSTRING(cab.CONTEUDO, 9, 4) = SUBSTRING(sec.CONTEUDO, 9, 4) AND SUBSTRING(cab.CONTEUDO, 13, 6) = SUBSTRING(sec.CONTEUDO, 13, 6) AND SUBSTRING(cab.CONTEUDO, 33, 1) = SUBSTRING(sec.CONTEUDO, 33, 1) AND SUBSTRING(cab.CONTEUDO, 34, 11) = SUBSTRING(sec.CONTEUDO, 34, 11) AND CAST(SUBSTRING(sec.CONTEUDO, 45, 6) AS int) = 200000
					WHERE CAST(SUBSTRING(cab.CONTEUDO, 45, 6) AS int) = 100000 
						AND (
							(@TipoImportacao = 0 AND RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 133, 2))) IN ('01', '02', '03') AND RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 260, 5))) IN ('T1', 'TD', 'TF')) -- se tipo de importação for "Toda a carga" (0)
							OR (@TipoImportacao = 1 AND (SUBSTRING(cab.CONTEUDO, 1, 2) NOT IN ('GB', 'XU', 'XI') OR RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 353, 8))) = 'SRR6646') AND RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 133, 2))) IN ('01', '02', '03') AND RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 260, 5))) IN ('T1', 'TD', 'TF')) -- se tipo de importação for "Toda carga exceto terrestre" (1) 
							OR (@TipoImportacao = 2 AND SUBSTRING(cab.CONTEUDO, 1, 2) IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 353, 8))) <> 'SRR6646' AND RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 133, 2))) IN ('01', '02', '03') AND RTRIM(LTRIM(SUBSTRING(sec.CONTEUDO, 260, 5))) in ('T1', 'TD', 'TF', 'T2'))  -- se tipo de importação for ""Só carga terrestre" (2)
						)
					FOR XML PATH('declaracaoUPS'), TYPE)
				FOR XML PATH('declaracoesUPS'), ELEMENTS)
-- inicia variaveis
			SET @Erros = ''
-- obtem lista de declarações existentes dentro do ficheiro XML
			DECLARE DeclaracoesUPS CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 176, 2))), ''),
					(CAST(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))) as numeric(38, 6)) / 100.00), 
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), ''),		
					NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9))), ''), 			
					(CASE 
						WHEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701001/linha)[1]', 'varchar(MAX)'), 105, 12))), '')
						WHEN RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 51, 29))) = 'VCI VENDOR COLLECT ID NUMBER' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(XML_DECL.DCL_DATA.value('(b701002/linha)[1]', 'varchar(MAX)'), 105, 12))), '')
						ELSE NULL
					END),
					XML_DECL.DCL_DATA.query('.')
				FROM @FicheiroXML.nodes('declaracoesUPS/declaracaoUPS') AS XML_DECL(DCL_DATA)
			OPEN DeclaracoesUPS
			FETCH NEXT FROM DeclaracoesUPS INTO @XMLCodPaisMoedaFatura, @XMLMontanteTotal, @XMLNumDocTransporte, @XMLNIFDestinatario, @XMLIdentificacaoIOSS, @DeclaracaoXML
			WHILE @@FETCH_STATUS = 0
			BEGIN							
				SET @ErroImportacao = ''
-- obtem o câmbio do país (não utilizar a função dbo.FNT_Geral_ObtemCambio(0, @XMLCodPaisMoedaFatura, @DataAtual) por causa do formato da data YMD)
				SET @Cambio = ISNULL((CASE (SELECT TOP 1 PAI_CODI FROM TAB_PAPL WITH(NOLOCK)) 
										WHEN @XMLCodPaisMoedaFatura THEN (SELECT ISNULL(PAP_TAXA, 1) FROM TAB_PAPL WITH(NOLOCK))
										ELSE (SELECT TOP 1 ISNULL(CPA_VEND, 1) 
											FROM TAB_CPAI WITH(NOLOCK)
											WHERE PAI_CODI = @XMLCodPaisMoedaFatura AND CPA_DATA <= @DataAtual
											ORDER BY CPA_DATA DESC) 
										END), 1)
-- processa a geração da declaração DAR se vier identificado como "Regime IOSS" ou NIF destinatário é "Singular" ou "Empresa" e o montante total EUR é maior que "0" e menor/igual a "150"			
				IF (ISNULL(@XMLIdentificacaoIOSS, '') <> '') OR ((LEFT(@XMLNIFDestinatario, 1) IN ('1', '2', '3', '4', '5', '6', '7', '8', '9')) AND (ROUND((@XMLMontanteTotal / @Cambio), 2) > 0) AND (ROUND((@XMLMontanteTotal / @Cambio), 2) <= 150))
				BEGIN					
					EXEC @NumErro = sp_DeclaracoesDAR_ImportaFicheiroUPS @DeclaracaoXML, 0, NULL, @IdUtilizador, @ErroImportacao OUTPUT					
					IF @NumErro <> 0
						SET @Erros = @Erros + 'Erro na importação da declaração DAR "' + @XMLNumDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)
				END
				ELSE
-- processa geração da declaração DUI2 ou IMP-CAU em função da configuração
					IF @IntegracaoIMPCAUAtiva = 0
					BEGIN							
						EXEC @NumErro = SP_DeclImportacao_ImportaFicheirosUPS @DeclaracaoXML, @Utilizador, @ErroImportacao OUTPUT						
						IF @NumErro <> 0
							SET @Erros = @Erros + 'Erro na importação da declaração DUI2 "' + @XMLNumDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)
					END		
					ELSE
					BEGIN									
						EXEC @NumErro = sp_IMP_Declaracoes_ImportaFicheiroUPS @DeclaracaoXML, 0, NULL, @IdUtilizador, @ErroImportacao OUTPUT						
						IF @NumErro <> 0
							SET @Erros = @Erros + 'Erro na importação da declaração IMP-CAU "' + @XMLNumDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)
					END							
				FETCH NEXT FROM DeclaracoesUPS INTO @XMLCodPaisMoedaFatura, @XMLMontanteTotal, @XMLNumDocTransporte, @XMLNIFDestinatario, @XMLIdentificacaoIOSS, @DeclaracaoXML
			END
			CLOSE DeclaracoesUPS
			DEALLOCATE DeclaracoesUPS	
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('%s', 16, 3, @Erros)						
		END TRY
		BEGIN CATCH			
-- constroi mensagem de erro detalhada p/ gerar ficheiro de erro
			SET @ErroFicheiro = '**********************************************************************************************************' + CHAR(12) +
								'** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								'**********************************************************************************************************' + CHAR(12) + 
								'.Nome Ficheiro UPS:  ' + @NomeFicheiro + CHAR(12) +								   
								'.Detalhe Erro:       ' + CHAR(12) +
								'		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
								'		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								'		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								'		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								'		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								'		*N. Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								'		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH		
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ErroFicheiro, '') <> ''
		BEGIN									
			SET @PathFicheiroErro = @DirectoriaFicheiros + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ErroFicheiro, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ErroFicheiro = STUFF(@ErroFicheiro, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			END								
		END		
		FETCH NEXT from FicheirosUPS into @PathFicheiro, @NomeFicheiro, @PathNovoFicheiro
	END
	CLOSE FicheirosUPS
	DEALLOCATE FicheirosUPS
-- remove a tabela temporária	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_Geral_ProcessaFicheirosASCIIDeclaracoesUPS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_ProcessaFicheirosASCIIDeclaracoesUPS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_ProcessaFicheirosXMLDeclaracoesCTT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_ProcessaFicheirosXMLDeclaracoesCTT] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdUtilizador int, @IntegracaoIMPCAUAtiva bit, @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml, 
		@ErroFicheiro varchar(MAX), @i int, @XMLCodNatureza varchar(3), @XMLNumDocTransporte varchar(18), @ErroImportacao varchar(MAX), @Erros varchar(MAX), @PathFicheiroErro varchar(500), 
		@Linha varchar(MAX)
-- obtem o ID do utilizador
	SELECT @IdUtilizador = UTI_IDTY
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_UTIL = @Utilizador	
-- obtem se integração IMP-CAU ativa
	SELECT TOP 1 @IntegracaoIMPCAUAtiva = PDE_ICAU
	FROM TAB_PDES WITH(NOLOCK)
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros CTT a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE FicheirosCTT CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]	
	OPEN FicheirosCTT
	FETCH NEXT FROM FicheirosCTT INTO @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN										
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'			
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			SET @Erros = ''
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)	
-- obtem o xml do ficheiro xml importado					
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- inicia variaveis
			SET @Erros = ''
-- obtem lista de declarações existentes dentro do ficheiro XML
			DECLARE DeclaracoesCTT CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT NULLIF(XML_DECL.DCL_DATA.value('CodNatureza[1]', 'varchar(3)'), ''), 
					NULLIF(XML_DECL.DCL_DATA.value('NumDocTransporte[1]', 'varchar(18)'), '')
				FROM @FicheiroXML.nodes('DeclaracoesImpToGIDWin/Declaracao') AS XML_DECL(DCL_DATA)
			OPEN DeclaracoesCTT
			FETCH NEXT FROM DeclaracoesCTT INTO @XMLCodNatureza, @XMLNumDocTransporte
			WHILE @@FETCH_STATUS = 0
			BEGIN							
				SET @ErroImportacao = ''
-- processa a geração da declaração DAR, DUI2 ou IMP-CAU em função da sua natureza 
				IF @XMLCodNatureza = 'DDR'
				BEGIN
					EXEC @NumErro = sp_DeclaracoesDAR_ImportaFicheiroCTT @FicheiroXML, @IdUtilizador, @ErroImportacao OUTPUT					
					IF @NumErro <> 0
						SET @Erros = @Erros + 'Erro na importação da declaração DAR "' + @XMLNumDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)					
				END
				ELSE
					IF @IntegracaoIMPCAUAtiva = 0
					BEGIN
						EXEC @NumErro = SP_DeclImportacao_ImportaFicheirosCTT @FicheiroXML, @Utilizador, @ErroImportacao OUTPUT						
						IF @NumErro <> 0
							SET @Erros = @Erros + 'Erro na importação da declaração DUI2 "' + @XMLNumDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)					
					END		
					ELSE
					BEGIN
						EXEC @NumErro = sp_IMP_Declaracoes_ImportaFicheiroCTT @FicheiroXML, @IdUtilizador, @ErroImportacao OUTPUT						
						IF @NumErro <> 0
							SET @Erros = @Erros + 'Erro na importação da declaração IMP-CAU "' + @XMLNumDocTransporte + '": ' + CHAR(13) + @ErroImportacao + CHAR(13)					
					END							
-- espera 5 segundos para evitar que haja um bloqueio massivo dos objetos da BD (deadlocks)
				WAITFOR DELAY '00:00:05.000'										
				FETCH NEXT FROM DeclaracoesCTT INTO @XMLCodNatureza, @XMLNumDocTransporte
			END
			CLOSE DeclaracoesCTT
			DEALLOCATE DeclaracoesCTT		
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('%s', 16, 2, @Erros)						
		END TRY
		BEGIN CATCH			
-- constroi mensagem de erro detalhada p/ gerar ficheiro de erro
			SET @ErroFicheiro = '**********************************************************************************************************' + CHAR(12) +
								'** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								'**********************************************************************************************************' + CHAR(12) + 
								'.Nome Ficheiro CTT:  ' + @NomeFicheiro + CHAR(12) +								   
								'.Detalhe Erro:       ' + CHAR(12) +
								'		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
								'		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								'		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								'		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								'		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								'		*N. Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								'		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH		
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ErroFicheiro, '') <> ''
		BEGIN									
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ErroFicheiro, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ErroFicheiro = STUFF(@ErroFicheiro, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			END								
		END		
		FETCH NEXT FROM FicheirosCTT INTO @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosCTT
	DEALLOCATE FicheirosCTT
-- remove a tabela temporária	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_Geral_ProcessaFicheirosXMLDeclaracoesCTT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_ProcessaFicheirosXMLDeclaracoesCTT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Geral_ProcessaFicheirosXMLEntradasAEXExportacaoXMLDeclaracoesDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Geral_ProcessaFicheirosXMLEntradasAEXExportacaoXMLDeclaracoesDHL] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), 
	@DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @Erros varchar(MAX), @FicheiroXML xml, @XMLData datetime, 
		@XMLNumDocTransporte varchar(18), @AnoDeclaracao int, @DeclaracaoAEX xml, @ErroFicheiro varchar(MAX), @i int, @PathFicheiroErro varchar(500), @Linha varchar(MAX)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'	
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros DHL a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE FicheirosDHL CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]	
	OPEN FicheirosDHL
	FETCH NEXT FROM FicheirosDHL INTO @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN										
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'			
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			SET @Erros = ''
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)	
-- obtem o xml do ficheiro xml importado					
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- remove o namespace existente na raiz <DeclaracoesExpToGIDWin> do XML 
			SET @FicheiroXML = STUFF(CAST(@FicheiroXML as varchar(MAX)), 1, CHARINDEX('>', CAST(@FicheiroXML as varchar(MAX))), '<DeclaracoesExpToGIDWin>')				
-- obtem dados da declaração existentes dentro do ficheiro XML
			SELECT @XMLData = XML_DECL.DCL_DATA.value('Data[1]', 'datetime'), @XMLNumDocTransporte = XML_DECL.DCL_DATA.value('NumeroCPA[1]', 'varchar(18)')
			FROM @FicheiroXML.nodes('DeclaracoesExpToGIDWin/Declaracao') AS XML_DECL(DCL_DATA)
-- inicia variaveis	da declaração Entrada AEX / Exportação/XML
			SET @AnoDeclaracao = YEAR(@XMLData)			
-- verifica se o Nº. CPA definido no ficheiro XML não existe para efetuar a geração da declaração de Entrada AEX e Exportação/XML carregada no XML
			IF NOT EXISTS(SELECT EDG_NUME FROM AEX_ENDG WITH(NOLOCK) WHERE EDG_EANO = @AnoDeclaracao AND EDG_REFI = @XMLNumDocTransporte)
			BEGIN	
-- constroi o xml da declaração de Entrada AEX a partir do ficheiro xml original
				SET @DeclaracaoAEX =
					(SELECT 
						(SELECT
							NULLIF(XML_DECL.DCL_DATA.value('(Destinatario/Nome)[1]', 'varchar(70)'), '') AS "NomeDestinatario", 
							NULLIF(XML_DECL.DCL_DATA.value('(Destinatario/Morada)[1]', 'varchar(70)'), '') AS "MoradaDestinatario", 
							NULLIF(XML_DECL.DCL_DATA.value('(Destinatario/Localidade)[1]', 'varchar(35)'), '') AS "LocalidadeDestinatario",
							NULLIF(XML_DECL.DCL_DATA.value('(Destinatario/CodPais)[1]', 'varchar(2)'), '') AS "PaisDestinatario"
						FOR XML PATH('InfoDestinatario'), TYPE),
						(SELECT
							NULLIF(XML_DECL.DCL_DATA.value('(Expedidor/Nome)[1]', 'varchar(70)'), '') AS "NomeRemetente",
							NULLIF(XML_DECL.DCL_DATA.value('(Expedidor/Morada)[1]', 'varchar(70)'), '') AS "MoradaRemetente",
							NULLIF(XML_DECL.DCL_DATA.value('(Expedidor/CodPostal)[1]', 'varchar(12)'), '') AS "CpostalRemetente",
							NULLIF(XML_DECL.DCL_DATA.value('(Expedidor/Localidade)[1]', 'varchar(35)'), '') AS "LocalidadeRemetente",
							NULLIF(XML_DECL.DCL_DATA.value('(Expedidor/NIF)[1]', 'varchar(18)'), '') AS "NIFRemetente"
						FOR XML PATH('InfoRemetente'), TYPE),
						NULLIF(XML_DECL.DCL_DATA.value('(LocalizacaoMercadorias/CodLocalAutorizado)[1]', 'varchar(17)'), '') AS "codigoEstancia",
						XML_DECL.DCL_DATA.value('(Adicoes/Adicao/MarcasEVolumes/MarcaEVolume/NumeroVols)[1]', 'int') AS "volumes",
						NULLIF(XML_DECL.DCL_DATA.value('(Adicoes/Adicao/MarcasEVolumes/MarcaEVolume/CodNaturezaVols)[1]', 'varchar(2)'), '') AS "tipoEmbalagem",
						NULLIF(XML_DECL.DCL_DATA.value('(Adicoes/Adicao/DesignacaoArtigo)[1]', 'varchar(150)'), '') AS "descricaoMercadoria",
						XML_DECL.DCL_DATA.query('sum(Adicoes/Adicao/MassaBruta)') AS "peso",
						XML_DECL.DCL_DATA.query('sum(Adicoes/Adicao/ValorAdicao)') AS "valorMercadoria", 
						NULLIF(XML_DECL.DCL_DATA.value('NumeroCPA[1]', 'varchar(18)'), '') AS "Notas", 
						NULLIF(XML_DECL.DCL_DATA.value('VossaReferencia[1]', 'varchar(50)'), '') AS "Observacoes"
					FROM @FicheiroXML.nodes('DeclaracoesExpToGIDWin/Declaracao') AS XML_DECL(DCL_DATA)
					FOR XML PATH('RequestDocumento'), ELEMENTS)
-- processa a geração da declaração de Entrada AEX
				EXEC @NumErro = SP_EntradasAEX_GeraDeclaracoesDeXML @DeclaracaoAEX, NULL, @Utilizador, @Erros OUTPUT	
				IF @NumErro <> 0
					RAISERROR ('Erro na importação da declaração AEX "%s": %s', 16, 2, @XMLNumDocTransporte, @Erros)			
-- processa a geração da declaração de Exportação/XML
				EXEC @NumErro = SP_ExportacaoXML_GeraDeclaracoesDeXML @FicheiroXML, @Utilizador, @Erros OUTPUT
				IF @NumErro <> 0
					RAISERROR ('Erro na importação da declaração EXP "%s": %s', 16, 3, @XMLNumDocTransporte, @Erros)
-- atualiza os campos extra na declaração de Exportação/XML com os dados da declaração de Entrada AEX
				UPDATE PRO_EXML SET EXM_CMPX = (SELECT 
													(SELECT EXT_CODI AS "CodigoCampoExtra", 
														EXT_VALO AS "ValorCampoExtra"
													FROM (
														SELECT 'EDG_EANO' AS EXT_CODI, CAST(aex.EDG_EANO AS varchar(4)) AS EXT_VALO
														UNION
														SELECT 'LME_CODI' AS EXT_CODI, aex.LME_CODI AS EXT_VALO
														UNION
														SELECT 'EDG_NUME' AS EXT_CODI, CAST(aex.EDG_NUME AS varchar(10)) AS EXT_VALO
														UNION
														SELECT 'EDG_NEXT' AS EXT_CODI, ISNULL(aex.EDG_NEXT, '') AS EXT_VALO
														) AS t
													FOR XML PATH('CampoExtra'), TYPE)
												FOR XML PATH('CamposExtra'), TYPE)
				FROM PRO_EXML AS exm WITH(NOLOCK) INNER JOIN AEX_ENDG AS aex WITH(NOLOCK) ON exm.EXM_EANO = aex.EDG_EANO AND exm.EXM_CPRT = aex.EDG_REFI
				WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CPRT = @XMLNumDocTransporte
-- insere ou edita documento "N830" na declaração de Exportação/XML com o número e data da declaração de Entrada AEX
				IF NOT EXISTS(SELECT eda.EXD_CHVE 
							FROM PRO_EXML AS exm WITH(NOLOCK) INNER JOIN PRO_EXAD AS ead WITH(NOLOCK) ON exm.EXM_EANO = ead.EXM_EANO AND exm.EXM_CODI = ead.EXM_CODI AND exm.DEC_CODI = ead.EXM_COPE AND ead.EXA_LINH = 1
								INNER JOIN PRO_EXDA AS eda WITH(NOLOCK) ON ead.EXA_CHVE = eda.EXA_CHVE AND eda.DOC_CODI = 'N830'			
							WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CPRT = @XMLNumDocTransporte)
				BEGIN
					INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EXD_MONT, EXD_QNTD, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH)
					SELECT ead.EXA_CHVE, doc.DOC_CODI, doc.DOC_NOME, CAST(aex.EDG_NUME AS varchar(10)), CAST(CONVERT(varchar(10), aex.EDG_DATA, 105) AS datetime), 0, 0, ead.EXM_EANO, ead.EXM_CODI, ead.EXM_COPE, ead.EXA_LINH 
					FROM PRO_EXML AS exm WITH(NOLOCK) INNER JOIN PRO_EXAD AS ead WITH(NOLOCK) ON exm.EXM_EANO = ead.EXM_EANO AND exm.EXM_CODI = ead.EXM_CODI AND exm.DEC_CODI = ead.EXM_COPE AND ead.EXA_LINH = 1
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N830' AND doc.DOC_EXPT = 1
						INNER JOIN AEX_ENDG AS aex WITH(NOLOCK) ON exm.EXM_EANO = aex.EDG_EANO AND exm.EXM_CPRT = aex.EDG_REFI
					WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CPRT = @XMLNumDocTransporte 
				END	
				ELSE
				BEGIN
					UPDATE PRO_EXDA SET EXD_NREF = CAST(aex.EDG_NUME AS varchar(10)), EXD_DTEM = CAST(CONVERT(varchar(10), aex.EDG_DATA, 105) AS datetime)
					FROM PRO_EXDA AS eda WITH(NOLOCK) INNER JOIN PRO_EXAD AS ead WITH(NOLOCK) ON eda.EXA_CHVE = ead.EXA_CHVE AND eda.DOC_CODI = 'N830' AND ead.EXA_LINH = 1
						INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ead.EXM_EANO = exm.EXM_EANO AND ead.EXM_CODI = exm.EXM_CODI AND ead.EXM_COPE = exm.DEC_CODI
						INNER JOIN AEX_ENDG AS aex WITH(NOLOCK) ON exm.EXM_EANO = aex.EDG_EANO AND exm.EXM_CPRT = aex.EDG_REFI
					WHERE exm.EXM_EANO = @AnoDeclaracao AND exm.EXM_CPRT = @XMLNumDocTransporte
				END
			END							
		END TRY
		BEGIN CATCH			
-- constroi mensagem de erro detalhada p/ gerar ficheiro de erro
			SET @ErroFicheiro = '**********************************************************************************************************' + CHAR(12) +
								'** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								'**********************************************************************************************************' + CHAR(12) + 
								'.Nome Ficheiro DHL:  ' + @NomeFicheiro + CHAR(12) +								   
								'.Detalhe Erro:       ' + CHAR(12) +
								'		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
								'		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								'		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								'		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								'		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								'		*N. Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								'		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH		
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ErroFicheiro, '') <> ''
		BEGIN									
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ErroFicheiro, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ErroFicheiro = STUFF(@ErroFicheiro, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ErroFicheiro, 0)
			END								
		END		
		FETCH NEXT FROM FicheirosDHL INTO @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosDHL
	DEALLOCATE FicheirosDHL
-- remove a tabela temporária	
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_Geral_ProcessaFicheirosXMLEntradasAEXExportacaoXMLDeclaracoesDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Geral_ProcessaFicheirosXMLEntradasAEXExportacaoXMLDeclaracoesDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraLancamentoFCaixas]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_geraLancamentoFCaixas] @ndoc int, @data datetime, @ano int, @utic varchar(30), @dtcria datetime, @utia varchar(30), @dtalter datetime, @impresso bit AS
BEGIN
-- declaracoes de variaveis
declare @nreg int, @tdoc varchar(4), @ctxt int, @tipo varchar(1), @npro varchar(18), @dori varchar(60), @vtot numeric(38,6), @sina varchar(2), @ccod varchar(18), @nif varchar(18), @tiva bit, 
	@txiv numeric(38,6), @lpro bit, @ndes varchar(3), @envi bit, @domo varchar(10), @desc varchar(50), @ptdoc varchar(4), @piden int, @pdlinh int, @maxAdic int, @somaCab numeric(38,6), 
	@soma numeric(38,6), @linha int, @somaIne numeric(38,6), @somaHon numeric(38,6), @somaIVA numeric(38,6), @somaTot numeric(38,6), @nomeDoc varchar(20), @Complemento varchar(50), 
	@Fornecedor varchar(50), @IdenLinha int
set nocount on
-- busca detalhes da Folha de Caixa
DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	select FCD_NREG, FCD_TDOC, FCD_CTXT, FCD_TIPO, FCD_NPRO, FCD_DORI, FCD_VTOT, FCD_SINA, FCD_CCOD, FCD_CNIF, FCD_TIVA, FCD_TXIV, FCD_LPRO, FCD_NDES, FCD_ENVI, FCD_DOMO, FCD_DESC, FCD_COMP, 
		FCD_FORN, FCD_IDEN
	from FAC_FCDT
	where FCX_NDOC = @ndoc and FCX_DATA = @data and FCX_EANO = @ano
OPEN Detalhe
FETCH NEXT FROM Detalhe INTO @nreg, @tdoc, @ctxt, @tipo, @npro, @dori, @vtot, @sina, @ccod, @nif, @tiva, @txiv, @lpro, @ndes, @envi, @domo, @desc, @Complemento, @Fornecedor, @IdenLinha
WHILE @@FETCH_STATUS = 0
BEGIN
-- busca decricao do tipo documento
	select @nomeDoc = TDO_DESC 
	from TAB_TDOC
	where TDO_DOCU = @tdoc	
-- se for cliente manda para conta corrente
	if (@tipo = 'C') and (@envi = 0) 
	begin			
		INSERT INTO FAC_MVCC(MVC_TDOC, MVC_NDOC, MVC_EANO, MVC_DATA, MVC_TMOV, MVC_TENT, MVC_ENTI, MVC_NCON, MVC_NDES, MVC_NPRO, MVC_VTOT, MVC_VDEB, MVC_VIVA, MVC_VI01, MVC_VI02, MVC_VI03, 
			MVC_VI04, MVC_IN01, MVC_IN02, MVC_IN03, MVC_IN04, MVC_RECA, MVC_UTIC, MVC_DTCR, MVC_UTIA, MVC_DTAL, MVC_CTXT, MVC_IMPR, MVC_DORI, MVC_DINT, MVC_COMP)
		VALUES(@tdoc, @IdenLinha, @ano, @data, @sina, 0, @ccod, @nif, @ndes, @npro, @vtot, @vtot, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @utic, @dtcria, @utia, @dtalter, @ctxt, @impresso, 
			@nomeDoc + ' N.º ' + cast(@ndoc as varchar) + '/Reg.' + cast(@nreg as varchar), '', @Complemento)
	end
	else
-- se for fornecedor manda para conta corrente
	if (@tipo = 'F') and (@envi = 0) 
	begin
		INSERT INTO FAC_MVCC(MVC_TDOC, MVC_NDOC, MVC_EANO, MVC_DATA, MVC_TMOV, MVC_TENT, MVC_ENTI, MVC_NCON, MVC_NDES, MVC_NPRO, MVC_VTOT, MVC_VDEB, MVC_VIVA, MVC_VI01, MVC_VI02, MVC_VI03, 
			MVC_VI04, MVC_IN01, MVC_IN02, MVC_IN03, MVC_IN04, MVC_RECA, MVC_UTIC, MVC_DTCR, MVC_UTIA, MVC_DTAL, MVC_CTXT, MVC_IMPR, MVC_DORI, MVC_DINT, MVC_COMP)
		VALUES(@tdoc, @IdenLinha, @ano, @data, @sina, 1, @ccod, @nif, @ndes, @npro, @vtot, @vtot, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @utic, @dtcria, @utia, @dtalter, @ctxt, @impresso, 
			@nomeDoc + ' N.º ' + cast(@ndoc as varchar) + '/Reg.' + cast(@nreg as varchar), '', @Complemento)	
	end
	else
-- se for processo e se liga ao processo envia para a conta CDO
	if (@tipo = 'P') and (@envi = 0) and (@lpro = 1) 
	begin	
-- inicia variaveis
		select @pdlinh = NULL
		select @maxAdic = NULL
		select @piden = NULL
-- procura processo na conta cdo (FAC_CDOC) atraves da Natureza + Num Processo + Ano
		select @ptdoc = CDO_TDOC, @piden = CDO_IDEN
		from FAC_CDOC
		where CDO_NPRO = @npro and NDE_CODI = @ndes and CDO_EANO = @ano and (CDO_STAT = 0 or CDO_STAT = 1)
-- se processo existe na Conta, vai verificar linhas documentadas
		if @piden is not null
		begin
-- procurar no detalhe das documentadas se esse registo existe(FAC_DCDO)
			select @pdlinh = DCD_LINH
			from FAC_DCDO
			where CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden and DDO_CODI = @domo
-- se registo nao se encontra nas documentadas
			if @pdlinh is null
			begin
-- busca o min das documentadas para inserir registo
				select @pdlinh = min(DCD_LINH)
				from FAC_DCDO
				where CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden and DDO_CODI is null
-- altera registo nas despesas documentadas(FAC_DCDO)
				if @pdlinh is null
					select @pdlinh = 1
				UPDATE FAC_DCDO set DDO_CODI = @domo, DCD_DESC = @desc, DCD_VTOT = 0
				WHERE DCD_LINH = @pdlinh and CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden
			end
-- busca o max do detalhe das documentadas para inserir registo
			select @maxAdic = max(DDC_ADIC)
			from FAC_DDCD
			where CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden and DCD_LINH = @pdlinh
-- insere novo registo (FAC_DDCD)
			if @maxAdic is null
				select @maxAdic = 1
			else
				select @maxAdic = @maxAdic + 1
			INSERT INTO FAC_DDCD(CDO_EANO, CDO_TDOC, CDO_IDEN, DCD_LINH, DDC_ADIC, DDC_DORI, DDC_DATA, DDC_IVA, DDC_TIVA, DDC_VALO, DDC_FORN)
			VALUES(@ano, @ptdoc, @piden, @pdlinh, @maxAdic, @dori, @data, @tiva, @txiv, @vtot, @Fornecedor)
-- efectua a soma do valor do detalhe das documentadas
			select @soma = sum(DDC_VALO)
			from FAC_DDCD
			where CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden and DCD_LINH = @pdlinh
-- actualiza valor da documentada com a soma obtida
			UPDATE FAC_DCDO set DCD_VTOT = @soma, DCD_VFCX = 1
			WHERE CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden and DCD_LINH = @pdlinh
-- faz o somatório total do valor das documentadas
			select @somaCab = sum(DCD_VTOT)
			from FAC_DCDO
			where CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden
-- busca valores totais da Conta do Processo
			select @somaIne = CDO_TTIN, @somaHon = CDO_TTHO, @somaIVA = CDO_IVA
			FROM FAC_CDOC
			WHERE CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden
-- actualiza valores totais da Conta CDO	
			select @somaTot = @somaCab + @somaIne + @somaHon + @somaIVA
			UPDATE FAC_CDOC set CDO_TTDC = @somaCab, CDO_TTPR = @somaTot
			WHERE CDO_EANO = @ano and CDO_TDOC = @ptdoc and CDO_IDEN = @piden
		end	
	end
-- actualiza o campo envia do detalhe de Folha de Caixa
	UPDATE FAC_FCDT set FCD_ENVI = 1
	WHERE FCX_NDOC = @ndoc and FCX_DATA = @data and FCX_EANO = @ano and FCD_NREG = @nreg
-- actualiza o campo status do cabecalho para o estado fechado
	UPDATE FAC_FCXA set FCX_STAT = 1 
	WHERE FCX_NDOC = @ndoc and FCX_DATA = @data and FCX_EANO = @ano

	FETCH NEXT FROM Detalhe INTO @nreg, @tdoc, @ctxt, @tipo, @npro, @dori, @vtot, @sina, @ccod, @nif, @tiva, @txiv, @lpro, @ndes, @envi, @domo, @desc, @Complemento, @Fornecedor, @IdenLinha
END
CLOSE Detalhe
DEALLOCATE Detalhe
set nocount off
END

ALTER AUTHORIZATION ON [SP_geraLancamentoFCaixas] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraLancamentoFCaixas] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_geraT5]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE proc [SP_geraT5] @cod int, @ano int as
--declaracoes de variaveis --
declare @maximo int, @contador int, 
	--declaracao das variaveis do cabeçalho
	@nde_codi varchar(3), @tde_codi varchar(4), @t5t_adic int, @t5t_tvol int,
	@t5t_ref7 varchar(30), @cli_expe varchar(18), @for_dest varchar(18), @dec_codi varchar(6),
	@pai_expe varchar(2), @pai_dest varchar(2), @mtr_codi varchar(2), @t5t_matr varchar(30), 
	@pai_naci varchar(2), @t5t_cont int, @t5t_mlto numeric(38,6), @t5t_mbto numeric(38,6),
	@t5t_pdno varchar(70), @t5t_pdmo varchar(70), @t5t_pdlo varchar(35), @t5t_pdcp varchar(12), 
	@t5t_pdlp varchar(35), @t5t_pdnf varchar(18), @pai_pdpl varchar(2), @t5t_peno varchar(70), 
	@t5t_pemo varchar(70), @t5t_pelo varchar(35), @t5t_pecp varchar(12), @t5t_pelp varchar(35), 
	@t5t_penf varchar(18), @pai_pepl varchar(2), @alf_codi varchar(8),
	--declaracao das variaveis do adicao
	@adi_t5a_codi int, @adi_apa_codi varchar(22), @adi_t5a_desg varchar(150), @adi_t5a_cpau varchar(22),
	@adi_t5a_mbrt numeric(38,6), @adi_t5a_mliq numeric(38,6), @adi_t5a_dpre_num varchar(6), 
	@adi_t5a_dpre_dat datetime, @adi_t5a_unsq numeric(38,6), @adi_usu_codi varchar(10), 
	@adi_t5a_marc varchar(20), @adi_t5a_nume varchar(20), @adi_t5a_quan int, @adi_ume_natu varchar(2),
	--declaracao das variaveis do contentores
	@con_t5c_codi int, @con_t5c_cnum varchar(20)

--busca registo da tabela PRO_DUCG
	SELECT @nde_codi = duc.NDE_CODI, @tde_codi = duc.TDE_CODI, @t5t_adic = duc.DUC_ADI5,
		@t5t_tvol = duc.DUC_TVL6, @t5t_ref7 = duc.DUC_REF7, @cli_expe = duc.DUC_EXP2, 
		@for_dest = duc.DUC_DST8, @dec_codi = duc.DEC_CO14, @pai_expe = duc.PAI_PA15, 
		@pai_dest = duc.PAI_PA17, @mtr_codi = duc.MTR_PT18, @t5t_matr = duc.DUC_MT18, 
		@pai_naci = duc.PAI_PA18, @t5t_cont = duc.DUC_CT19, @t5t_mlto = duc.DUC_MLQT, 
		@t5t_mbto = duc.DUC_MBRT, @t5t_pdno = duc.DUC_DNOM, @t5t_pdmo = duc.DUC_DMOR, 
		@t5t_pdlo = duc.DUC_DLOC, @t5t_pdcp = duc.DUC_DCPO, @t5t_pdlp = duc.DUC_DLPO, 
		@t5t_pdnf = duc.DUC_DNIF, @pai_pdpl = duc.PAI_DLIV, @t5t_peno = duc.DUC_ENOM, 
		@t5t_pemo = duc.DUC_EMOR, @t5t_pelo = duc.DUC_ELOC, @t5t_pecp = duc.DUC_ECPO, 
		@t5t_pelp = duc.DUC_ELPO, @t5t_penf = duc.DUC_ENIF, @pai_pepl = duc.PAI_ELIV,
		@alf_codi = duc.ALF_CODI
	FROM PRO_DUCG duc
	WHERE duc.DUC_PNUM = @cod and duc.DUC_EANO = @ano
	
--verifica se T5 ja foi gerada	
	select @contador = count(*)
	from PRO_T5TR
	where DUC_PNUM = @cod and DUC_EANO = @ano
--se nao foi gerado insere campos na PRO_T5TR

	if @contador = 0
	begin
		--calcula max da tabela PRO_T5TR
		--verifica se CRA PRO_T5TR ja foi gerada	
		select @contador = count(*)
		from PRO_T5TR
		if @contador > 0
		begin
			SELECT @maximo = MAX(T5T_CODI) 
			FROM PRO_T5TR 
			WHERE T5T_EANO = @ano
		        select @maximo = @maximo + 1
		end
		else select @maximo=1
			set dateformat dmy
			insert into PRO_T5TR(T5T_CODI, T5T_EANO, T5T_DATA, NDE_CODI, T5T_STAT, DUC_PNUM, DUC_EANO, 
				T5T_NCON, TDE_CODI, EAD_CODI, T5T_LCRG, T5T_ADIC, T5T_TVOL, T5T_REF7, CLI_EXPE, 
				FOR_DEST, DEC_CODI, PAI_EXPE, PAI_DEST, MTR_CODI, T5T_MATR, PAI_NACI, T5T_CONT, 
				T5T_MLTO, T5T_MBTO, T5T_PDNO, T5T_PDMO, T5T_PDLO, T5T_PDCP, T5T_PDLP, T5T_PDNF, 
				PAI_PDPL, T5T_PENO, T5T_PEMO, T5T_PELO, T5T_PECP, T5T_PELP, T5T_PENF, PAI_PEPL) 
			VALUES (@maximo, @ano, cast(DATENAME(dd, getdate()) + '/'+ cast(DATEpart(mm, getdate()) as varchar) +'/'+DATENAME(yy, getdate()) as datetime),
				@nde_codi, 0, @cod, @ano, 0, @tde_codi, @alf_codi, '', @t5t_adic, 
				@t5t_tvol, @t5t_ref7, @cli_expe, @for_dest, @dec_codi, @pai_expe, @pai_dest, 
				@mtr_codi, @t5t_matr, @pai_naci, @t5t_cont, @t5t_mlto, @t5t_mbto, @t5t_pdno, 
				@t5t_pdmo, @t5t_pdlo, @t5t_pdcp, @t5t_pdlp, @t5t_pdnf, @pai_pdpl, @t5t_peno, 
				@t5t_pemo, @t5t_pelo, @t5t_pecp, @t5t_pelp, @t5t_penf, @pai_pepl)
			
		
	end
	else
--se ja foi gerado altera campos do modelo PRO_T5TR
	begin
		select @maximo = T5T_CODI
		from PRO_T5TR
		where DUC_PNUM = @cod and DUC_EANO = @ano

			update PRO_T5TR set T5T_DATA = getdate(), NDE_CODI = @nde_codi, T5T_STAT = 0, T5T_NCON = 0, 
				TDE_CODI = @tde_codi, EAD_CODI = @alf_codi, T5T_LCRG = '', T5T_ADIC = @t5t_adic, 
				T5T_TVOL = @t5t_tvol, T5T_REF7 = @t5t_ref7, CLI_EXPE = @cli_expe, FOR_DEST = @for_dest, 
				DEC_CODI = @dec_codi, PAI_EXPE = @pai_expe, PAI_DEST = @pai_dest, MTR_CODI = @mtr_codi, 
				T5T_MATR = @t5t_matr, PAI_NACI = @pai_naci, T5T_CONT = @t5t_cont, T5T_MLTO = @t5t_mlto, 
				T5T_MBTO = @t5t_mbto, T5T_PDNO = @t5t_pdno, T5T_PDMO = @t5t_pdmo, T5T_PDLO = @t5t_pdlo, 
				T5T_PDCP = @t5t_pdcp, T5T_PDLP = @t5t_pdlp, T5T_PDNF = @t5t_pdnf, PAI_PDPL = @pai_pdpl, 
				T5T_PENO = @t5t_peno, T5T_PEMO = @t5t_pemo, T5T_PELO = @t5t_pelo, T5T_PECP = @t5t_pecp, 
				T5T_PELP = @t5t_pelp, T5T_PENF = @t5t_penf, PAI_PEPL = @pai_pepl
			WHERE DUC_PNUM = @cod and DUC_EANO = @ano		
	end


	--APAGA TODAS AS ADICOES

	DELETE FROM PRO_T5AD WHERE T5T_CODI = @maximo and T5T_EANO = @ano	

	--COPIA TODAS AS ADICOES DO DOCUMENTO UNICO
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT DUA_CODI, APA_CO33, DUA_DESG, APA_CP33, DUA_MB35, DUA_ML38, 
		DUA_DNUM, DUA_DDAT, DUA_US41, USU_CO41
	FROM PRO_DUAD
	WHERE DUC_PNUM = @cod and DUC_EANO = @ano
	OPEN Detalhe
	FETCH NEXT from Detalhe into @adi_t5a_codi, @adi_apa_codi, @adi_t5a_desg, @adi_t5a_cpau,
		@adi_t5a_mbrt, @adi_t5a_mliq, @adi_t5a_dpre_num, @adi_t5a_dpre_dat, @adi_t5a_unsq, 
		@adi_usu_codi
	WHILE @@FETCH_STATUS = 0
	BEGIN

		-- BUSCA A 1ªMarca da ADIÇÃO
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT D31_MARC, D31_NUME, D31_QNTD, UME_CODI
			FROM PRO_DU31
			WHERE DUC_PNUM = @cod and DUC_EANO = @ano and DUA_CODI = @adi_t5a_codi
		OPEN Marcas
		FETCH NEXT from Marcas into @adi_t5a_marc, @adi_t5a_nume, @adi_t5a_quan, @adi_ume_natu
---------------------------------------------------


		set dateformat dmy
		INSERT INTO PRO_T5AD(T5A_CODI, T5T_CODI, T5T_EANO, APA_CODI, T5A_DESG, T5A_CPAU,
			T5A_MBRT, T5A_MLIQ, T5A_DPRE, T5A_UNSQ, USU_CODI, T5A_MARC,
			T5A_NUME, T5A_QUAN, UME_NATU, T5A_STAD, T5A_FORP, T5A_FORB, T5A_FFAR, T5A_OUTR)
		VALUES(@adi_t5a_codi, @maximo, @ano, @adi_apa_codi, @adi_t5a_desg, @adi_t5a_cpau,
			@adi_t5a_mbrt, @adi_t5a_mliq, @adi_t5a_dpre_num + ' de ' +
			cast(day(@adi_t5a_dpre_dat) as varchar)+'-'+cast(month(@adi_t5a_dpre_dat) as varchar)+'-'+cast(year(@adi_t5a_dpre_dat) as varchar),
			@adi_t5a_unsq, @adi_usu_codi, @adi_t5a_marc, @adi_t5a_nume, @adi_t5a_quan, @adi_ume_natu,
			0,0,0,0,0)
		
		CLOSE Marcas
		DEALLOCATE Marcas
		--APAGA TODOS OS CONTENTORES DE CADA ADICAO
		DELETE FROM PRO_T5CO WHERE T5T_CODI = @cod and T5T_EANO = @ano	

		--COPIA TODOS OS CONTENTORES DE CADA ADICAO
		DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT DCO_CODI, DCO_CNUM
		FROM PRO_DCON
		WHERE DUC_PNUM = @cod and DUC_EANO = @ano and DUA_CODI = @adi_t5a_codi

		OPEN Contentores
		FETCH NEXT from Contentores into @con_t5c_codi, @con_t5c_cnum
		
			WHILE @@FETCH_STATUS = 0
			BEGIN
				INSERT INTO PRO_T5CO(T5C_CODI, T5A_CODI, T5T_CODI, T5T_EANO, T5C_CNUM)
				VALUES(@con_t5c_codi, @adi_t5a_codi, @maximo, @ano, @con_t5c_cnum)
	
				FETCH NEXT from Contentores into @con_t5c_codi, @con_t5c_cnum
			END
			CLOSE Contentores
			DEALLOCATE Contentores


		FETCH NEXT from Detalhe into @adi_t5a_codi, @adi_apa_codi, @adi_t5a_desg, @adi_t5a_cpau,
		@adi_t5a_mbrt, @adi_t5a_mliq, @adi_t5a_dpre_num, @adi_t5a_dpre_dat, @adi_t5a_unsq, 
		@adi_usu_codi
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
------------------------------------------------------------

ALTER AUTHORIZATION ON [SP_geraT5] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_geraT5] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_Adicoes_ContentoresCopia]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_Adicoes_ContentoresCopia] @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @Contentor varchar(20), @Tipo varchar(10), @NumAdicaoSup1 int, @NumContentor int
-- inicia transacção para inserção dos contentores
	BEGIN TRANSACTION TspIMPCopiaContentores
	BEGIN TRY	
-- obtem os contentores da adição a copiar
		DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT aco.DCO_CNUM, aco.DCO_TIPO, da1.DUA_CODI
			FROM PRO_DUAD AS dad WITH(NOLOCK) 
				INNER JOIN PRO_DCON AS aco WITH(NOLOCK) ON dad.DUC_EANO = aco.DUC_EANO AND dad.DUC_PNUM = aco.DUC_PNUM AND dad.DUA_CODI = aco.DUA_CODI
				INNER JOIN PRO_DUAD AS da1 WITH(NOLOCK) ON dad.DUC_EANO = da1.DUC_EANO AND dad.DUC_PNUM = da1.DUC_PNUM AND da1.DUA_CODI > dad.DUA_CODI
				LEFT OUTER JOIN PRO_DCON AS ac1 WITH(NOLOCK) ON da1.DUC_EANO = ac1.DUC_EANO AND da1.DUC_PNUM = ac1.DUC_PNUM AND da1.DUA_CODI = ac1.DUA_CODI AND aco.DCO_CNUM = ac1.DCO_CNUM
			WHERE dad.DUC_EANO = @AnoDeclaracao AND dad.DUC_PNUM = @NumDeclaracao AND dad.DUA_CODI = @NumAdicao AND ac1.DCO_IDEN IS NULL			
		OPEN Contentores
		FETCH NEXT FROM Contentores INTO @Contentor, @Tipo, @NumAdicaoSup1
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- obtem o número p/ novo contentor a inserir na adição
			SET @NumContentor = ISNULL((SELECT COUNT(*)
												FROM PRO_DCON WITH(NOLOCK)
												WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicaoSup1), 0) + 1
-- insere o contentor na adição onde ele ainda não existe
			INSERT INTO PRO_DCON(DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicaoSup1, @NumContentor, @Contentor, @Tipo)			
			FETCH NEXT FROM Contentores INTO @Contentor, @Tipo, @NumAdicaoSup1
		END
		CLOSE Contentores
		DEALLOCATE Contentores
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPCopiaContentores
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPCopiaContentores
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_Adicoes_ContentoresCopia] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_Adicoes_ContentoresCopia] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_Adicoes_ContentoresImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_Adicoes_ContentoresImportaXLSX] @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @UltimoNumContentores int
-- inicia transacção para a inserção dos contentores
	BEGIN TRANSACTION TspIMPImportaXLSXContentores
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- obtem o número de contentores atualmente existentes na adição
		SET @UltimoNumContentores = ISNULL((SELECT COUNT(*)
											FROM PRO_DCON WITH(NOLOCK)
											WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao), 0)
-- insere os contentores do ficheiro na adição
		INSERT INTO PRO_DCON(DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM)
		SELECT @AnoDeclaracao, @NumDeclaracao, @NumAdicao, (@UltimoNumContentores + ROW_NUMBER() OVER(ORDER BY t.c.value('CONT[1]', 'varchar(20)'))), t.c.value('CONT[1]', 'varchar(20)')
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 
			LEFT OUTER JOIN PRO_DCON AS dac WITH(NOLOCK) ON dac.DUC_EANO = @AnoDeclaracao AND dac.DUC_PNUM = @NumDeclaracao AND dac.DUA_CODI = @NumAdicao AND t.c.value('CONT[1]', 'varchar(20)') = dac.DCO_CNUM	
		WHERE dac.DCO_IDEN IS NULL
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPImportaXLSXContentores
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPImportaXLSXContentores
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_Adicoes_ContentoresImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_Adicoes_ContentoresImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_Adicoes_MarcasInsercaoRapida]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_Adicoes_MarcasInsercaoRapida] @AnoDeclaracao int, @NumDeclaracao int, @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @SQLVariaveis nvarchar(MAX), @SQLAExecutar nvarchar(MAX)
	DECLARE @NumAdicao int, @IdMarca int, @Marcas varchar(512), @Numeros varchar(20), @Volumes numeric(38, 6), @CodUnidadeMedida varchar(3), @CodigoBarras varchar(30), 
		@NomeUnidadeMedida varchar(35), @VolsAZero bit
	DECLARE @TblTmpMarcas TABLE(Estado int NOT NULL, NumAdicao int NULL, Marcas varchar(512) NULL, Numeros varchar(20) NULL, Volumes numeric(38, 6) NOT NULL, 
		CodUnidadeMedida varchar(3) NULL, IdMarcas int NULL, CodigoBarras varchar(30) NULL)
-- inicia transacção para a inserção das marcas e volumes
	BEGIN TRANSACTION TspIMPInsercaoRapidaMarcas
	BEGIN TRY	
		SET @NumErro = 0
-- constroi a lista de variáveis
		SET @SQLVariaveis = '@INMarcas varchar(512), @INNumeros varchar(20), @INVolumes numeric(38, 6), @INCodUnidadeMedida varchar(3), @INNomeUnidadeMedida varchar(35), @INVolsAZero bit, '
		SET @SQLVariaveis = @SQLVariaveis + '@INCodigoBarras varchar(30), @INIdMarca int'
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- insere todos os dados das marcas e volumes na tabela tmp
		INSERT INTO @TblTmpMarcas(Estado, NumAdicao, Marcas, Numeros, Volumes, CodUnidadeMedida, IdMarcas, CodigoBarras)
		SELECT t.c.value('ESTADO[1]', 'int'), t.c.value('DUA_CODI[1]', 'int'), t.c.value('D31_MARC[1]', 'varchar(512)'), t.c.value('D31_NUME[1]', 'varchar(20)'), 
			ISNULL(t.c.value('D31_QNTD[1]', 'numeric(38, 6)'), 0), t.c.value('UME_CODI[1]', 'varchar(3)'), t.c.value('D31_IDEN[1]', 'int'), 
			t.c.value('D31_LOPT[1]', 'varchar(30)')
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
-- obtem as marcas e volumes removidas
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT IdMarcas
			FROM @TblTmpMarcas
			WHERE Estado = 3			
		OPEN Marcas
		FETCH NEXT FROM Marcas INTO @IdMarca
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove a marca e volume
			DELETE FROM PRO_DU31
			WHERE D31_IDEN = @IdMarca
			FETCH NEXT FROM Marcas INTO @IdMarca
		END
		CLOSE Marcas
		DEALLOCATE Marcas
-- obtem as marcas e volumes editadas
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT tmp.IdMarcas, tmp.Marcas, tmp.Numeros, tmp.Volumes, tmp.CodUnidadeMedida, tmp.CodigoBarras, ume.UME_NOME, ume.UME_TVOL,  
				((CASE ISNULL(amv.D31_MARC, '') WHEN ISNULL(tmp.Marcas, '') THEN '' ELSE 'D31_MARC = @INMarcas, ' END) 
					+ (CASE ISNULL(amv.D31_NUME, '') WHEN ISNULL(tmp.Numeros, '') THEN '' ELSE 'D31_NUME = @INNumeros, ' END)
					+ (CASE amv.D31_QNTD WHEN tmp.Volumes THEN '' ELSE 'D31_QNTD = @INVolumes, ' END)
					+ (CASE ISNULL(amv.UME_CODI, '') WHEN ISNULL(tmp.CodUnidadeMedida, '') THEN '' ELSE 'UME_CODI = @INCodUnidadeMedida, UME_NOME = @INNomeUnidadeMedida, D31_TTVL = @INVolsAZero, ' END)
					+ (CASE ISNULL(amv.D31_LOPT, '') WHEN ISNULL(tmp.CodigoBarras, '') THEN '' ELSE 'D31_LOPT = @INCodigoBarras, ' END))
			FROM @TblTmpMarcas AS tmp 
				INNER JOIN PRO_DU31 AS amv WITH(NOLOCK) ON tmp.IdMarcas = amv.D31_IDEN
				LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON tmp.CodUnidadeMedida = ume.UME_CODI
			WHERE tmp.Estado = 2			
		OPEN Marcas
		FETCH NEXT FROM Marcas INTO @IdMarca, @Marcas, @Numeros, @Volumes, @CodUnidadeMedida, @CodigoBarras, @NomeUnidadeMedida, @VolsAZero, @SQLAExecutar
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove o caracter "," existente no final
			SET @SQLAExecutar = REVERSE(@SQLAExecutar)
			SET @SQLAExecutar = STUFF(@SQLAExecutar, 2, 1, '')
			SET @SQLAExecutar = REVERSE(@SQLAExecutar)
-- constroi o SQL p/ UPDATE
			SET @SQLAExecutar = 'UPDATE PRO_DU31 SET ' + @SQLAExecutar + 'WHERE D31_IDEN = @INIdMarca'
-- edita a marca e volume
			EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INMarcas = @Marcas, @INNumeros = @Numeros, @INVolumes = @Volumes, @INCodUnidadeMedida = @CodUnidadeMedida, 
				@INNomeUnidadeMedida = @NomeUnidadeMedida, @INVolsAZero = @VolsAZero, @INCodigoBarras = @CodigoBarras, @INIdMarca = @IdMarca
			FETCH NEXT FROM Marcas INTO @IdMarca, @Marcas, @Numeros, @Volumes, @CodUnidadeMedida, @CodigoBarras, @NomeUnidadeMedida, @VolsAZero, @SQLAExecutar
		END
		CLOSE Marcas
		DEALLOCATE Marcas
-- obtem as marcas e volumes inseridas
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT tmp.NumAdicao, tmp.Marcas, tmp.Numeros, tmp.Volumes, tmp.CodUnidadeMedida, tmp.CodigoBarras, ume.UME_NOME, ume.UME_TVOL
			FROM @TblTmpMarcas AS tmp 				
				LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON tmp.CodUnidadeMedida = ume.UME_CODI
			WHERE tmp.Estado = 1			
		OPEN Marcas
		FETCH NEXT FROM Marcas INTO  @NumAdicao, @Marcas, @Numeros, @Volumes, @CodUnidadeMedida, @CodigoBarras, @NomeUnidadeMedida, @VolsAZero
		WHILE @@FETCH_STATUS = 0
		BEGIN			
-- insere a marca e volume
			INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_TTVL, D31_LOPT)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, 1, @Marcas, @Numeros, @Volumes, @CodUnidadeMedida, @NomeUnidadeMedida, @VolsAZero, @CodigoBarras)
			FETCH NEXT FROM Marcas INTO  @NumAdicao, @Marcas, @Numeros, @Volumes, @CodUnidadeMedida, @CodigoBarras, @NomeUnidadeMedida, @VolsAZero
		END
		CLOSE Marcas
		DEALLOCATE Marcas
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPInsercaoRapidaMarcas
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPInsercaoRapidaMarcas
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_Adicoes_MarcasInsercaoRapida] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_Adicoes_MarcasInsercaoRapida] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_Adicoes_Veiculos_ChassisImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_Adicoes_Veiculos_ChassisImportaXLSX] @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @NumVeiculo int, @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml
-- inicia transacção para a inserção dos chassis
	BEGIN TRANSACTION TspIMPImportaXLSXChassis
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- remove os chassis atualmente existentes no veículo da adição
		DELETE FROM PRO_DUVE
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DBT_CODI = @NumVeiculo
-- insere os chassis do ficheiro no veículo da adição
		INSERT INTO PRO_DUVE(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DVC_CODI, DVC_CHAS, DVC_DCHA)
		SELECT @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo, (ROW_NUMBER() OVER(ORDER BY t.c.value('VIN[1]', 'varchar(22)'))), t.c.value('VIN[1]', 'varchar(22)'), 
			CAST(NULLIF(t.c.value('Data[1]', 'varchar(10)'), '') AS datetime)
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 					
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPImportaXLSXChassis
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPImportaXLSXChassis
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_Adicoes_Veiculos_ChassisImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_Adicoes_Veiculos_ChassisImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_Adicoes_VeiculosImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_Adicoes_VeiculosImportaXLSX] @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @UltimoNumVeiculos int, @IdVeiculo varchar(20), @Qualificador varchar(4), @Modelo varchar(20), @CodTipoVeiculo varchar(3), @CodCategoria varchar(2), 
		@CodTipoCombustivel varchar(2), @Cilindrada numeric(38, 6), @EmissaoCo2 int, @EmissaoParticulas varchar(10), @Marca varchar(20), @AdicionalISV varchar(4), @TipoCO2 varchar(4), 
		@DocIMT varchar(5), @Autonomia int, @Tabela varchar(1), @Homologacao varchar(20)
	DECLARE @TblTmpVeiculos TABLE(Qualificador varchar(4) NULL, Modelo varchar(20) NOT NULL, CodTipoVeiculo varchar(3) NULL, CodCategoria varchar(2) NULL, CodTipoCombustivel varchar(2) NULL, 
		Cilindrada numeric(38, 6) NOT NULL, EmissaoCo2 int NOT NULL, EmissaoParticulas varchar(10) NOT NULL, Marca varchar(20) NOT NULL, AdicionalISV varchar(4) NULL, Matricula varchar(10) NULL, 
		Chassis varchar(22) NULL, [Data] datetime, TipoCO2 varchar(4) NULL, DocIMT varchar(5) NULL, Autonomia int NULL, Tabela varchar(1) NULL, Homologacao varchar(20) NULL)
-- inicia transacção para a inserção dos veículos
	BEGIN TRANSACTION TspIMPImportaXLSXVeiculos
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- insere todos os dados do veículos do ficheiro na tabela tmp
		INSERT INTO @TblTmpVeiculos(Qualificador, Modelo, CodTipoVeiculo, CodCategoria, CodTipoCombustivel, Cilindrada, EmissaoCo2, EmissaoParticulas, Marca, AdicionalISV, Matricula, Chassis, 
			[Data], TipoCO2, DocIMT, Autonomia, Tabela, Homologacao)
		SELECT t.c.value('qualificadorVeiculo[1]', 'varchar(4)'), t.c.value('modelo[1]', 'varchar(20)'), t.c.value('tipoVeiculo[1]', 'varchar(3)'), t.c.value('categoria[1]', 'varchar(2)'), 
			t.c.value('combustivel[1]', 'varchar(2)'), ISNULL(t.c.value('cilindrada[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('emissaoCo2[1]', 'int'), 0), 
			ISNULL(NULLIF(t.c.value('emissaoParticulas[1]', 'varchar(10)'), ''), '0'), t.c.value('marcaVeiculo[1]', 'varchar(20)'), t.c.value('adicionalISV[1]', 'varchar(4)'), 
			t.c.value('matricula[1]', 'varchar(10)'), t.c.value('chassis[1]', 'varchar(22)'), CAST(NULLIF(t.c.value('data[1]', 'varchar(10)'), '') AS datetime), 
			t.c.value('tipoCO2[1]', 'varchar(4)'), t.c.value('docIMT[1]', 'varchar(5)'), t.c.value('autonomia[1]', 'int'), t.c.value('tabela[1]', 'varchar(1)'), 
			t.c.value('homologacao[1]', 'varchar(20)')
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
-- obtem o número de veículos atualmente existentes na adição
		SET @UltimoNumVeiculos = ISNULL((SELECT COUNT(*)
										FROM PRO_DUBT WITH(NOLOCK)
										WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao), 0)
-- obtem apenas os veículos do ficheiro
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT Qualificador, Modelo, CodTipoVeiculo, CodCategoria, CodTipoCombustivel, Cilindrada, EmissaoCo2, EmissaoParticulas, Marca, AdicionalISV, TipoCO2, DocIMT, Autonomia, Tabela, 
				Homologacao
			FROM @TblTmpVeiculos
			GROUP BY Qualificador, Modelo, CodTipoVeiculo, CodCategoria, CodTipoCombustivel, Cilindrada, EmissaoCo2, EmissaoParticulas, Marca, AdicionalISV, TipoCO2, DocIMT, Autonomia, Tabela, 
				Homologacao
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @Qualificador, @Modelo, @CodTipoVeiculo, @CodCategoria, @CodTipoCombustivel, @Cilindrada, @EmissaoCo2, @EmissaoParticulas, @Marca, @AdicionalISV, @TipoCO2, 
			@DocIMT, @Autonomia, @Tabela, @Homologacao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @UltimoNumVeiculos = @UltimoNumVeiculos + 1
-- obtem ID p/ veículo
			SET @IdVeiculo = REPLACE(CAST(CONVERT(numeric(38, 12), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) as varchar(20)), '.', ',')
-- insere o veículo 
			INSERT INTO PRO_DUBT(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DBT_QTDE, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, DBT_MARC, DBT_MODE, DBT_IDCR, 
				DBT_HOMO, DBT_TABE, DBT_TCO2, DBT_AUTN, DBT_DIMT)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @UltimoNumVeiculos, @Cilindrada, @CodTipoVeiculo, @Qualificador, @AdicionalISV, @EmissaoCo2, @CodCategoria, @CodTipoCombustivel, 
				@EmissaoParticulas, @Marca, @Modelo, @IdVeiculo, @Homologacao, @Tabela, @TipoCO2, @Autonomia, @DocIMT)
-- insere os chassis no veículo inserido
			INSERT INTO PRO_DUVE(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS, DVC_DMAT, DVC_DCHA)
			SELECT @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @UltimoNumVeiculos, (ROW_NUMBER() OVER(ORDER BY MaTricula, Chassis)), Matricula, Chassis, 
				(CASE WHEN ISNULL(Matricula, '') <> '' THEN [Data] ELSE NULL END), 
				(CASE WHEN ISNULL(Chassis, '') <> '' THEN [Data] ELSE NULL END)
			FROM @TblTmpVeiculos
			WHERE ISNULL(Qualificador, '') = ISNULL(@Qualificador, '') AND Modelo = @Modelo AND ISNULL(CodTipoVeiculo, '') = ISNULL(@CodTipoVeiculo, '') 
				AND ISNULL(CodCategoria, '') = ISNULL(@CodCategoria, '') AND ISNULL(CodTipoCombustivel, '') = ISNULL(@CodTipoCombustivel, '') AND Cilindrada = @Cilindrada 
				AND EmissaoCo2 = @EmissaoCo2 AND EmissaoParticulas = @EmissaoParticulas AND Marca = @Marca AND ISNULL(AdicionalISV, '') = ISNULL(@AdicionalISV, '') 
				AND ISNULL(TipoCO2, '') = ISNULL(@TipoCO2, '') AND ISNULL(DocIMT, '') = ISNULL(@DocIMT, '') AND ISNULL(Autonomia, 0) = ISNULL(@Autonomia, 0) 
				AND ISNULL(Tabela, '') = ISNULL(@Tabela, '') AND ISNULL(Homologacao, '') = ISNULL(@Homologacao, '')
			FETCH NEXT FROM Veiculos INTO @Qualificador, @Modelo, @CodTipoVeiculo, @CodCategoria, @CodTipoCombustivel, @Cilindrada, @EmissaoCo2, @EmissaoParticulas, @Marca, @AdicionalISV, @TipoCO2, 
				@DocIMT, @Autonomia, @Tabela, @Homologacao
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPImportaXLSXVeiculos
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPImportaXLSXVeiculos
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_Adicoes_VeiculosImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_Adicoes_VeiculosImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_AdicoesEdita]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_AdicoesEdita] @IdAdicao int, @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @CodArtigo varchar(22), @PesoLiquido numeric(38, 6), 
	@PesoBruto numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), @CodPreferencia varchar(3), @CodPaisOrigem varchar(2), @DireitosDDP numeric(38, 6), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @ValorFormatado varchar(40)
	DECLARE @CodUnidSuplementar varchar(10), @Desdobramento1 varchar(3), @TipoTributacao int, @CodUnidMedida varchar(3), @BaseManual bit, @BaseTributacaoDireitos numeric(38, 6), 
		@ArtigoTxComposta bit, @TaxaValorDireitos numeric(38, 6), @MontanteDireitos numeric(38, 6), @ValorISV numeric(38, 6), @AjusteBTI numeric(38, 6), @TaxaIVA numeric(38, 6), 
		@MontanteIVAImposicoes numeric(38, 6), @Acrescimos numeric(38, 6), @Deducoes numeric(38, 6), @CodPaisOrigemPreferencial varchar(2), @TaxaPreferencia numeric(38, 6), 
		@ArtigoAlterado bit, @PaisOrigemAlterado bit, @PesoBrutoAlterado bit, @PreferenciaAlterada bit, @PesoLiquidoAlterado bit, @UnidadesAlterada bit, 
		@MontanteAlterado bit, @DireitosDDPAlterado bit
-- inicia processo de inserção da adição
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem dados atuais da adição e verifica que colunas da adição é para editar
		SELECT @CodUnidSuplementar = adi.USU_CO41, @Desdobramento1 = adi.DUA_R37B, @TipoTributacao = adi.DUA_TRIB, @CodUnidMedida = adi.UME_CODI, @BaseManual = adi.DUA_BMAN, 
			@BaseTributacaoDireitos = ISNULL(adi.DUA_BTRI, 0), @ArtigoTxComposta = adi.DUA_TXCO, @TaxaValorDireitos = ISNULL(DUA_TXVL, 0), @MontanteDireitos = ISNULL(adi.DUA_MTRI, 0), 
			@ValorISV = ISNULL(adi.DUA_IVAV, 0), @AjusteBTI = adi.DUA_ABTI, @TaxaIVA = ISNULL(DUA_TIVA, 0), @MontanteIVAImposicoes = adi.DUA_MIVI, @Acrescimos = adi.DUA_ACRE, 
			@Deducoes = adi.DUA_DEDU, @CodPaisOrigemPreferencial = adi.PAI_CODI5, @TaxaPreferencia = pre.PRE_TAXA, 
			@ArtigoAlterado = (CASE ISNULL(adi.APA_CO33, '') WHEN ISNULL(@CodArtigo, '') THEN 0 ELSE 1 END), 
			@PaisOrigemAlterado = (CASE ISNULL(adi.PAI_CO34, '') WHEN ISNULL(@CodPaisOrigem, '') THEN 0 ELSE 1 END), 
			@PesoBrutoAlterado = (CASE adi.DUA_MB35 WHEN ISNULL(@PesoBruto, 0) THEN 0 ELSE 1 END), 
			@PreferenciaAlterada = (CASE ISNULL(adi.PRE_CO36, '') WHEN ISNULL(@CodPreferencia, '') THEN 0 ELSE 1 END), 
			@PesoLiquidoAlterado = (CASE adi.DUA_ML38 WHEN ISNULL(@PesoLiquido, 0) THEN 0 ELSE 1 END), 
			@UnidadesAlterada = (CASE ISNULL(adi.DUA_US41, 0) WHEN ISNULL(@Unidades, 0) THEN 0 ELSE 1 END), 
			@MontanteAlterado = (CASE adi.DUA_VA42 WHEN ISNULL(@Montante, 0) THEN 0 ELSE 1 END), 
			@DireitosDDPAlterado = (CASE ISNULL(adi.DUA_VDIR, 0) WHEN ISNULL(@DireitosDDP, 0) THEN 0 ELSE 1 END)
		FROM PRO_DUAD AS adi WITH(NOLOCK)
			INNER JOIN TAB_PREF AS pre WITH(NOLOCK) ON adi.PRE_CO36 = pre.PRE_CODI
		WHERE adi.DUA_IDEN = @IdAdicao
-- valida artigo
		IF (@ArtigoAlterado = 1) AND (NOT EXISTS(SELECT 1 FROM TAB_APAU WITH(NOLOCK) WHERE APA_CODI = @CodArtigo AND APA_INAC = 0 AND APA_FLUX IN (0, 1) AND APA_EDAR = 0 AND LEN(APA_CPAU) >= 10))
			RAISERROR ('Código do artigo "%s" inexistente ou não está devidamente configurado.', 16, 1, @CodArtigo)
-- valida preferência
		IF (@PreferenciaAlterada = 1) AND (ISNULL(@CodPreferencia, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PREF WITH(NOLOCK) WHERE PRE_CODI = @CodPreferencia))
			RAISERROR ('Código da preferência "%s" inexistente.', 16, 2, @CodPreferencia)
-- valida país de origem
		IF (@PaisOrigemAlterado = 1) AND (ISNULL(@CodPaisOrigem, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem))
			RAISERROR ('Código do país de origem "%s" inexistente.', 16, 3, @CodPaisOrigem)
-- valida peso bruto
		IF (@PesoBrutoAlterado = 1) AND (ISNULL(@PesoBruto, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoBruto, 38, 6))
			RAISERROR ('Peso bruto "%s" inválido.', 16, 4, @ValorFormatado)
		END
-- valida montante
		IF (@MontanteAlterado = 1) AND (ISNULL(@Montante, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR ('Montante "%s" inválido.', 16, 5, @ValorFormatado)
		END
-- obtem dados da declaração
		DECLARE @MontanteTotal numeric(38, 6), @CambioMontante numeric(38, 6), @FreteTotal numeric(38, 6), @CambioFrete numeric(38, 6), @SeguroTotal numeric(38, 6), @CambioSeguro numeric(38, 6), 
			@VerbaTransitarioTotal numeric(38, 6), @MassaBrutaTotal numeric(38, 6), @ValorAduaneiroTotal numeric(38, 6), @TotalAdicoes int, @TotalVolumes numeric(38, 6), 
			@FormulaCondEntrega varchar(70), @TaxaFDA numeric(38, 6), @CodMeioTransporteChegada varchar(2), @TotalOptativas numeric(38, 6), @AnexoB varchar(2), @Regime varchar(4), 
			@TotalDireitosDDP numeric(38, 6)
		SELECT @MontanteTotal = ISNULL(DUC_MT22, 0), @CambioMontante = ISNULL(DUC_TX23, 0), @FreteTotal = ISNULL(DUC_FRET, 0), @CambioFrete = ISNULL(DUC_TXFR, 0), 
			@SeguroTotal = ISNULL(DUC_SEGU, 0), @CambioSeguro = ISNULL(DUC_TxSE, 0), @VerbaTransitarioTotal = ISNULL(DUC_VTRN, 0), @MassaBrutaTotal = ISNULL(DUC_MBRT, 0), 
			@ValorAduaneiroTotal = ISNULL(DUC_VATT, 0), @TotalAdicoes = DUC_ADI5, @TotalVolumes = ISNULL(DUC_TVL6, 0), @FormulaCondEntrega = ISNULL(DUC_FR20, ''), @TaxaFDA = ISNULL(DUC_TFDA, 0), 
			@CodMeioTransporteChegada = MTR_PT18, @TotalOptativas = ISNULL(DUC_OP18, 0), @AnexoB = DUC_ANXB, @Regime = DUC_REGI, @TotalDireitosDDP = ISNULL(DUC_DIRT, 0)
		FROM PRO_DUCG WITH(NOLOCK) 									
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao 
-- valida peso líquido
		IF (@PesoLiquidoAlterado = 1) AND (@AnexoB NOT IN ('H2', 'H3', 'I2')) AND (ISNULL(@PesoLiquido, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoLiquido, 38, 6))
			RAISERROR ('Peso líquido "%s" inválido.', 16, 6, @ValorFormatado)
		END
-- valida direitos DDP
		IF (@DireitosDDPAlterado = 1) AND (@TotalDireitosDDP = 0) AND (ISNULL(@DireitosDDP, 0) > 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@DireitosDDP, 38, 6))
			RAISERROR ('Direitos DDP "%s" inválido.', 16, 7, @ValorFormatado)
		END
		ELSE
			IF (@DireitosDDPAlterado = 1) AND (@TotalDireitosDDP > 0) AND (ISNULL(@DireitosDDP, 0) <= 0)
			BEGIN
				SET @ValorFormatado = LTRIM(STR(@DireitosDDP, 38, 6))
				RAISERROR ('Direitos DDP "%s" inválido.', 16, 8, @ValorFormatado)
			END
-- obtem dados das adições já existentes
		DECLARE @SomaMontantesAdicoes numeric(38, 6), @SomaFretesAdicoes numeric(38, 6), @SomaSegurosAdicoes numeric(38, 6), @SomaVerbasTransitarioAdicoes numeric(38, 6)
		SELECT @SomaMontantesAdicoes = ISNULL(SUM(DUA_VA42), 0), @SomaFretesAdicoes = ISNULL(SUM(ISNULL(DUA_VFRE, 0)), 0), @SomaSegurosAdicoes = ISNULL(SUM(ISNULL(DUA_VSEG, 0)), 0), 
			@SomaVerbasTransitarioAdicoes = ISNULL(SUM(ISNULL(DUA_VTRA, 0)), 0)
		FROM PRO_DUAD WITH(NOLOCK)
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI <> @NumAdicao
-- valida se montante é válido na declaração
		IF (@MontanteAlterado = 1) AND ((@MontanteTotal - @SomaMontantesAdicoes - @Montante) < 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR ('Montante "%s" inválido porque é superior ao montante total disponível', 16, 9, @ValorFormatado)
		END
-- obtem dados do artigo
		IF @ArtigoAlterado = 1
		BEGIN
			DECLARE @CodigoPautal varchar(22), @Designacao varchar(150), @CodigoATAR varchar(10), @CodigoIC1 varchar(4), @CodigoIC2 varchar(4), @CodigoIC3 varchar(4), @CodigoIC4 varchar(4), 
				@CodigoIC5 varchar(4), @CodigoCCUS varchar(9), @TipoMercadoria varchar(3)
			SELECT @CodigoPautal = APA_CPAU, @Designacao = APA_DESG, @TipoTributacao = APA_TRIB, @CodUnidSuplementar = USU_CODI, @CodigoATAR = APA_ATAR, 
				@CodigoIC1 = (CASE 
								WHEN @AnexoB NOT IN ('H6', 'I2') THEN APA_AIC1 
								ELSE NULL 
							END),
				@CodigoIC2 = (CASE 
								WHEN @AnexoB NOT IN ('H6', 'I2') THEN APA_AIC2 
								ELSE NULL 
							END), 
				@CodigoIC3 = (CASE 
								WHEN @AnexoB NOT IN ('H6', 'I2') THEN APA_AIC3 
								ELSE NULL 
							END),
				@CodigoIC4 = (CASE 
								WHEN @AnexoB NOT IN ('H6', 'I2') THEN APA_AIC4 
								ELSE NULL 
							END),
				@CodigoIC5 = (CASE 
								WHEN @AnexoB NOT IN ('H6', 'I2') THEN APA_AIC5 
								ELSE NULL 
							END),
				@CodigoCCUS = (CASE 
								WHEN @AnexoB NOT IN ('H6', 'I2') THEN APA_CCUS
								ELSE NULL 
							END),
				@TipoMercadoria = (CASE 
								WHEN @AnexoB NOT IN ('HI', 'H2', 'H3', 'H4', 'H5', 'I1') THEN APA_TMER
								ELSE NULL 
							END),
				@CodUnidMedida = (CASE 
										WHEN ISNULL(APA_TRIB, 0) IN (0, 1) THEN UME_CODI 
										ELSE NULL 
									END),
				@TaxaIVA = (CASE 						
							WHEN (LEFT(ISNULL(@Regime, ''), 2) IN ('42', '51', '53', '71')) OR (ISNULL(@Desdobramento1, '') = '4II') OR (ISNULL(@Desdobramento1, '') = 'C01') OR (ISNULL(@Desdobramento1, '') = 'F48') OR (ISNUMERIC(@Desdobramento1) = 1 AND CAST(@Desdobramento1 AS int) >= 401 AND CAST(@Desdobramento1 AS int) <= 459) THEN 0 
							WHEN (ISNULL(@Regime, '') = '6123') AND (ISNULL(@Desdobramento1, '') = 'F01') THEN 0 
							ELSE ISNULL(APA_TIVA, 0) 
						END), 
				@ArtigoTxComposta = (CASE APA_TRIB 
										WHEN 0 THEN ~(APA_TXCO) 
										WHEN 1 THEN 1 
										ELSE 0 
									END)			
			FROM TAB_APAU WITH(NOLOCK)
			WHERE APA_CODI = @CodArtigo		
-- obtem dados da unidade de medida
			DECLARE @NomeUnidMedida varchar(35)
			SELECT @NomeUnidMedida = UME_NOME
			FROM TAB_UMED WITH(NOLOCK)
			WHERE UME_CODI = @CodUnidMedida
-- obtem dados do IVA
			DECLARE @CodRubricaIVA int, @NomeRubricaIVA varchar(35), @ImposicaoIVA varchar(3)
			SELECT @CodRubricaIVA = rre.RRE_CODI, @NomeRubricaIVA = rre.RRE_NOME, @ImposicaoIVA = rre.RRE_IMPO
			FROM (SELECT PAP_TXIS, RRE_CDIS 
					FROM TAB_PAPL WITH(NOLOCK) 
					UNION 
					SELECT PAP_TXRD, RRE_CDRD 
					FROM TAB_PAPL WITH(NOLOCK) 
					UNION 
					SELECT PAP_TXIN, RRE_CDIN 
					FROM TAB_PAPL WITH(NOLOCK) 
					UNION 
					SELECT PAP_TXNR, RRE_CDNR 
					FROM TAB_PAPL WITH(NOLOCK)) AS t 
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON t.RRE_CDIS = rre.RRE_CODI
			WHERE t.PAP_TXIS = @TaxaIVA
		END
-- valida unidades
		IF (@UnidadesAlterada = 1) AND (@AnexoB IN ('H6', 'I2')) AND (ISNULL(@Unidades, 0) > 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
			RAISERROR ('Unidades "%s" inválida.', 16, 10, @ValorFormatado)
		END
		ELSE
			IF (@UnidadesAlterada = 1) AND (@AnexoB NOT IN ('H6', 'I2')) AND (ISNULL(@CodUnidSuplementar, '') <> '') AND (ISNULL(@Unidades, 0) <= 0)
			BEGIN
				SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
				RAISERROR ('Unidades "%s" inválida.', 16, 11, @ValorFormatado)
			END
-- obtem dados do país de origem
		IF @PaisOrigemAlterado = 1
		BEGIN
			DECLARE @NomePaisOrigem varchar(35)
			SELECT @NomePaisOrigem = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @CodPaisOrigem
		END
-- obtem dados da preferência
		IF @PreferenciaAlterada = 1
		BEGIN
			DECLARE @NomePreferencia varchar(70), @CodRubricaDireitos int, @NomeRubricaDireitos varchar(35), @ImposicaoDireitos varchar(3)
			SELECT @NomePreferencia = pre.PRE_NOME, @TaxaPreferencia = pre.PRE_TAXA, @CodRubricaDireitos = rre.RRE_CODI, @NomeRubricaDireitos = rre.RRE_NOME, @ImposicaoDireitos = rre.RRE_IMPO
			FROM TAB_PREF AS pre WITH(NOLOCK)
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON pre.RRE_CODI = rre.RRE_CODI
			WHERE pre.PRE_CODI = @CodPreferencia
		END
-- calcula os valores da adição
		DECLARE @Frete numeric(38, 6), @Seguro numeric(38, 6), @VerbaTransitario numeric(38, 6), @Optativas numeric(38, 6), @ValorEUR numeric(38, 6), @Ajustamento numeric(38, 6), 
			@ValorEstatistico numeric(38, 6), @ValorAduaneiro numeric(38, 6), @BaseTributacaoIVA numeric(38, 6), @MontanteIVA numeric(38, 6), @QtdDireitos numeric(38, 6)		
		IF (@PesoLiquidoAlterado = 1) AND (@AnexoB IN ('H2', 'H3', 'I2')) AND (@PesoLiquido > 0)
			SET @PesoLiquido = 0
		IF (@UnidadesAlterada = 1) AND (@AnexoB IN ('H6', 'I2')) AND (ISNULL(@Unidades, 0) > 0)
			SET @Unidades = 0	
		IF (@DireitosDDPAlterado = 1) AND (@TotalDireitosDDP = 0) AND (ISNULL(@DireitosDDP, 0) > 0)
			SET @DireitosDDP = 0	
		SET @Frete = ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
								WHEN 0 THEN (@FreteTotal - @SomaFretesAdicoes) 
								ELSE (@PesoBruto * @FreteTotal / @MassaBrutaTotal) 
							END), 3)
		SET @Seguro = ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
								WHEN 0 THEN (@SeguroTotal - @SomaSegurosAdicoes) 
								ELSE (@Montante * @SeguroTotal / @MontanteTotal) 
							END), 3)
		SET @VerbaTransitario = ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
								WHEN 0 THEN (@VerbaTransitarioTotal - @SomaVerbasTransitarioAdicoes) 
								ELSE (@PesoBruto * @VerbaTransitarioTotal / @MassaBrutaTotal) 
							END), 3)		
		SET @ValorEUR = ROUND(@Montante / @CambioMontante, 2)
		SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro, @Frete, @Seguro, @DireitosDDP, @Acrescimos, @Deducoes)
		SET @ValorEstatistico = dbo.fn_IMP_CalculaValorEstatistico(@ValorEUR, @Ajustamento)
		SET @ValorAduaneiro = @ValorEstatistico
		SET @Optativas = dbo.fn_IMP_CalculaValorOptativas(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodMeioTransporteChegada, @TotalAdicoes, @TotalVolumes, @TotalOptativas, @MassaBrutaTotal, @ValorAduaneiroTotal, @PesoBruto, @ValorAduaneiro)
		SET @BaseTributacaoDireitos = dbo.fn_IMP_CalculaBaseTributacaoDireitos(@BaseManual, @BaseTributacaoDireitos, @TipoTributacao, @PesoLiquido, @Unidades, @ValorEstatistico, @CodUnidMedida) 		                              
		IF (@ArtigoAlterado = 1) OR (@PaisOrigemAlterado = 1) OR (@PreferenciaAlterada = 1) OR ((@UnidadesAlterada = 1) AND (@TipoTributacao = 0))
			SET @TaxaValorDireitos = dbo.fn_IMP_CalculaTaxaValorDireitos(@DataAtual, @CodArtigo, @CodPaisOrigem, @CodPaisOrigemPreferencial, @TaxaPreferencia, @Unidades, @Regime, @Desdobramento1) 
		SET @MontanteDireitos = dbo.fn_IMP_CalculaMontanteDireitos(@BaseManual, @MontanteDireitos, ~(@ArtigoTxComposta), @TaxaValorDireitos, @BaseTributacaoDireitos)
		SET @BaseTributacaoIVA = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, @Frete, @Ajustamento, @ValorEstatistico, @VerbaTransitario, @Optativas, @MontanteDireitos, @ValorISV, @AjusteBTI, @MontanteIVAImposicoes)
		SET @MontanteIVA = ROUND(@BaseTributacaoIVA * @TaxaIVA / 100, 2)
		SET @QtdDireitos = dbo.fn_IMP_CalculaBaseTributacaoDireitos(0, 0, @TipoTributacao, @PesoLiquido, @Unidades, 0, @CodUnidMedida)
-- constroi a lista de variáveis
		DECLARE @SQLVariaveis nvarchar(MAX), @SQLAExecutar nvarchar(MAX)
		SET @SQLVariaveis = '@INCodArtigo varchar(22), @INCodigoPautal varchar(22), @INDesignacao varchar(150), @INTipoTributacao int, @INCodUnidSuplementar varchar(10), @INCodigoATAR varchar(10), '
		SET @SQLVariaveis = @SQLVariaveis + '@INCodigoIC2 varchar(4), @INCodigoIC3 varchar(4), @INCodigoIC1 varchar(4), @INCodigoIC4 varchar(4), @INCodigoIC5 varchar(4), @INCodigoCCUS varchar(9), '
		SET @SQLVariaveis = @SQLVariaveis + '@INTipoMercadoria varchar(3), @INCodUnidMedida varchar(3), @INNomeUnidMedida varchar(35), @INArtigoTxComposta bit, @INTaxaIVA numeric(38, 6), '
		SET @SQLVariaveis = @SQLVariaveis + '@INCodRubricaIVA int, @INNomeRubricaIVA varchar(35), @INImposicaoIVA varchar(3), @INCodPaisOrigem varchar(2), @INNomePaisOrigem varchar(35), '
		SET @SQLVariaveis = @SQLVariaveis + '@INCodPreferencia varchar(3), @INNomePreferencia varchar(70), @INCodRubricaDireitos int, @INNomeRubricaDireitos varchar(35), '
		SET @SQLVariaveis = @SQLVariaveis + '@INImposicaoDireitos varchar(3), @INPesoBruto numeric(38, 6), @INFrete numeric(38, 6), @INVerbaTransitario numeric(38, 6), '
		SET @SQLVariaveis = @SQLVariaveis + '@INPesoLiquido numeric(38, 6), @INMontante numeric(38, 6), @INSeguro numeric(38, 6), @INValorEUR numeric(38, 6), @INUnidades numeric(38, 6), '
		SET @SQLVariaveis = @SQLVariaveis + '@INAjustamento numeric(38, 6), @INValorEstatistico numeric(38, 6), @INValorAduaneiro numeric(38, 6), @INOptativas numeric(38, 6), '
		SET @SQLVariaveis = @SQLVariaveis + '@INQtdDireitos numeric(38, 6), @INBaseTributacaoDireitos numeric(38, 6), @INTaxaValorDireitos numeric(38, 6), @INMontanteDireitos numeric(38, 6), '
		SET @SQLVariaveis = @SQLVariaveis + '@INBaseTributacaoIVA numeric(38, 6), @INMontanteIVA numeric(38, 6), @INIdAdicao int, @INDireitosDDP numeric(38, 6)'
-- constroi o SQL p/ UPDATE
		SET @SQLAExecutar = 'UPDATE PRO_DUAD SET '
		IF @ArtigoAlterado = 1		
		BEGIN
			SET @SQLAExecutar = @SQLAExecutar + 'APA_CO33 = @INCodArtigo, APA_CP33 = @INCodigoPautal, DUA_DESG = @INDesignacao, DUA_TRIB = @INTipoTributacao, USU_CO41 = @INCodUnidSuplementar, '
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_ATAR = @INCodigoATAR, DUA_2TAR = @INCodigoIC2, DUA_3TAR = @INCodigoIC3, DUA_1TAR = @INCodigoIC1, DUA_4TAR = @INCodigoIC4, '
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_5TAR = @INCodigoIC5, APA_CCUS = @INCodigoCCUS, DUA_TMER = @INTipoMercadoria, UME_CODI = @INCodUnidMedida, UME_NOTR = @INNomeUnidMedida, '
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_TXCO = @INArtigoTxComposta, DUA_TIVA = @INTaxaIVA, RRE_CODI = @INCodRubricaIVA, RRE_NOME = @INNomeRubricaIVA, DUA_IMPI = @INImposicaoIVA, '
		END
		IF @PaisOrigemAlterado = 1
			SET @SQLAExecutar = @SQLAExecutar + 'PAI_CO34 = @INCodPaisOrigem, PAI_NOME = @INNomePaisOrigem, '		
		IF @PreferenciaAlterada = 1
		BEGIN
			SET @SQLAExecutar = @SQLAExecutar + 'PRE_CO36 = @INCodPreferencia, PRE_NOME = @INNomePreferencia, RRE_PREF = @INCodRubricaDireitos, RRE_NOME1 = @INNomeRubricaDireitos, '
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_IMPO = @INImposicaoDireitos, '
		END
		IF @PesoBrutoAlterado = 1		
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_MB35 = @INPesoBruto, DUA_VFRE = @INFrete, DUA_VTRA = @INVerbaTransitario, '		
		IF @PesoLiquidoAlterado = 1
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_ML38 = @INPesoLiquido, '		
		IF @MontanteAlterado = 1		
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_VA42 = @INMontante, DUA_VSEG = @INSeguro, DUA_VAEU = @INValorEUR, '		
		IF @UnidadesAlterada = 1
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_US41 = @INUnidades, '		
		IF @DireitosDDPAlterado = 1
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_VDIR = @INDireitosDDP, '					 							 					
		IF (@PesoBrutoAlterado = 1) OR (@MontanteAlterado = 1) OR (@DireitosDDPAlterado = 1)
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_AJUS = @INAjustamento, DUA_VEST = @INValorEstatistico, DUA_VATO = @INValorAduaneiro, DUA_VOPT = @INOptativas, '
		IF (@ArtigoAlterado = 1) OR (@PesoLiquidoAlterado = 1) OR (@UnidadesAlterada = 1)
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_QTDD = @INQtdDireitos, '
		IF (@ArtigoAlterado = 1) OR (@PesoBrutoAlterado = 1) OR (@PesoLiquidoAlterado = 1) OR (@MontanteAlterado = 1) OR (@UnidadesAlterada = 1) OR (@DireitosDDPAlterado = 1)
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_BTRI = @INBaseTributacaoDireitos, '
		IF (@ArtigoAlterado = 1) OR (@PaisOrigemAlterado = 1) OR (@PreferenciaAlterada = 1) OR ((@UnidadesAlterada = 1) AND (@TipoTributacao = 0))
			SET @SQLAExecutar = @SQLAExecutar + 'DUA_TXVL = @INTaxaValorDireitos, '
		SET @SQLAExecutar = @SQLAExecutar + 'DUA_MTRI = @INMontanteDireitos, DUA_BTIV = @INBaseTributacaoIVA, DUA_VIVA = @INMontanteIVA '
		SET @SQLAExecutar = @SQLAExecutar + 'WHERE DUA_IDEN = @INIdAdicao'
-- edita a adição
		EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INCodArtigo = @CodArtigo, @INCodigoPautal = @CodigoPautal, @INDesignacao = @Designacao, @INTipoTributacao = @TipoTributacao, 
			@INCodUnidSuplementar = @CodUnidSuplementar, @INCodigoATAR = @CodigoATAR, @INCodigoIC2 = @CodigoIC2, @INCodigoIC3 = @CodigoIC3, @INCodigoIC1 = @CodigoIC1, @INCodigoIC4 = @CodigoIC4, 
			@INCodigoIC5 = @CodigoIC5, @INCodigoCCUS = @CodigoCCUS, @INTipoMercadoria = @TipoMercadoria, @INCodUnidMedida = @CodUnidMedida, @INNomeUnidMedida = @NomeUnidMedida, 
			@INArtigoTxComposta = @ArtigoTxComposta, @INTaxaIVA = @TaxaIVA, @INCodRubricaIVA = @CodRubricaIVA, @INNomeRubricaIVA = @NomeRubricaIVA, @INImposicaoIVA = @ImposicaoIVA, 
			@INCodPaisOrigem = @CodPaisOrigem, @INNomePaisOrigem = @NomePaisOrigem, @INCodPreferencia = @CodPreferencia, @INNomePreferencia = @NomePreferencia, 
			@INCodRubricaDireitos = @CodRubricaDireitos, @INNomeRubricaDireitos = @NomeRubricaDireitos, @INImposicaoDireitos = @ImposicaoDireitos, @INPesoBruto = @PesoBruto, @INFrete = @Frete, 
			@INVerbaTransitario = @VerbaTransitario, @INPesoLiquido = @PesoLiquido, @INMontante = @Montante, @INSeguro = @Seguro, @INValorEUR = @ValorEUR, @INUnidades = @Unidades, 
			@INAjustamento = @Ajustamento, @INValorEstatistico = @ValorEstatistico, @INValorAduaneiro = @ValorAduaneiro, @INOptativas = @Optativas, @INQtdDireitos = @QtdDireitos, 
			@INBaseTributacaoDireitos = @BaseTributacaoDireitos, @INTaxaValorDireitos = @TaxaValorDireitos, @INMontanteDireitos = @MontanteDireitos, @INBaseTributacaoIVA = @BaseTributacaoIVA, 
			@INMontanteIVA = @MontanteIVA, @INIdAdicao = @IdAdicao, @INDireitosDDP = @DireitosDDP
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_AdicoesEdita] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_AdicoesEdita] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_AdicoesGeraDeLinhasOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_AdicoesGeraDeLinhasOGMA] @Ano int, @Numero int, @ParteResto bit, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @DocumentoXML xml(XMLSC_DeclaracoesIMPCAUToGIDWin)
	DECLARE @TblTmpLinhas TABLE(
		LIN_IDEN int NOT NULL IDENTITY(1, 1), 
		APA_CODI varchar(22) NOT NULL,
		APA_CPAU varchar(22) NOT NULL,
		APA_DESG varchar(150) NOT NULL, 
		PAI_CODI varchar(2) NULL,
		PRE_CODI varchar(3) NOT NULL, 
		LIN_MBRT decimal(28, 6) NOT NULL,
		LIN_MLIQ decimal(28, 6) NOT NULL,
		LIN_REGI varchar(4) NOT NULL,
		LIN_QUNI decimal(28, 6) NOT NULL,
		LIN_MONT decimal(28, 6) NOT NULL,
		UME_CODI varchar(2) NOT NULL,
		LIN_VOLS int NOT NULL)
	DECLARE @TblTmpPrecedentes TABLE(
		PRE_IDEN int NOT NULL IDENTITY(1, 1),	
		LIN_IDEN int NOT NULL, 
		PRE_NDOC varchar(20) NOT NULL,
		PRE_DDOC datetime NOT NULL)	
	DECLARE @IdLinha bigint, @TotalPrecedentes int, @NumPrecedentesIguais int, @CodArtigo varchar(22), @CodPautalArtigo varchar(22), @DesignacaoArtigo varchar(150), @CodPaisOrigem varchar(2), 
		@CodPreferencia varchar(3), @MassaBrt decimal(28, 6), @MassaLiq decimal(28, 6), @Regime varchar(4), @QtdUnidades decimal(28, 6), @Montante decimal(28, 6), @CodUnidMedida varchar(2), 
		@Volumes int, @NumeroDocPrecedente varchar(20), @DataDocPrecedente datetime, @NumAdicao int, @TotalAdicoes int
-- inicia processo para geração de adições a partir de linhas OGMA
	BEGIN TRY	
		SET @NumErro = 0
		SET @TotalAdicoes = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem as linhas OGMA da declaração já associadas a artigo pautal para globalização
		DECLARE Linhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT apa.APA_CODI, apa.APA_CPAU, apa.APA_DESG, pai.PAI_CODI, pre.PRE_CODI, lin.massaBruta, lin.massaLiquida, lin.observacoes, lin.unidades, lin.montante, ume.UME_CODI, lin.volumes, 
				lin.numeroOrdem, lin.dataOrdem
			FROM PRO_DUCG AS duc WITH(NOLOCK)
				INNER JOIN tb_TBL_LinhasOGMA AS lin WITH(NOLOCK) ON duc.DUC_IDTY = lin.id_declaracaoIMP
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON lin.id_artigo = apa.APA_IDTY
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON lin.id_paisOrigem = pai.PAI_IDTY
				INNER JOIN TAB_PREF AS pre WITH(NOLOCK) ON lin.id_preferencia = pre.PRE_IDTY
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON lin.id_unidadeMedida = ume.UME_IDTY
			WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero AND lin.id_artigo IS NOT NULL
			ORDER BY apa.APA_CODI, pai.PAI_CODI, pre.PRE_CODI, lin.observacoes, ume.UME_CODI
		OPEN Linhas
		FETCH NEXT FROM Linhas INTO @CodArtigo, @CodPautalArtigo, @DesignacaoArtigo, @CodPaisOrigem, @CodPreferencia, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, 
			@Volumes, @NumeroDocPrecedente, @DataDocPrecedente
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @IdLinha = NULL
			SET @TotalPrecedentes = 0
			SET @NumPrecedentesIguais = 0			
-- obtem dados referente ao artigo/pais origem/preferência/regime/unidade medida para globalização
			SELECT @IdLinha = MAX(lin.LIN_IDEN), @TotalPrecedentes = COUNT(*), @NumPrecedentesIguais = COUNT((CASE WHEN (pre.PRE_NDOC = @NumeroDocPrecedente) AND (pre.PRE_DDOC = @DataDocPrecedente) THEN 1 ELSE NULL END))
			FROM @TblTmpLinhas AS lin
				LEFT OUTER JOIN @TblTmpPrecedentes AS pre ON lin.LIN_IDEN = pre.LIN_IDEN
			WHERE APA_CODI = @CodArtigo AND PAI_CODI = @CodPaisOrigem AND PRE_CODI = @CodPreferencia AND LIN_REGI = @Regime AND UME_CODI = @CodUnidMedida
			GROUP BY lin.LIN_IDEN		
-- se artigo/pais origem/preferência/regime/unidade medida ainda não existe ou já existe mas já tem 99 precedentes associados, insere nova linha
			IF (@IdLinha IS NULL) OR ((@TotalPrecedentes = 99) AND (@NumPrecedentesIguais = 0))
			BEGIN		
				INSERT INTO @TblTmpLinhas(APA_CODI, APA_CPAU, APA_DESG, PAI_CODI, PRE_CODI, LIN_MBRT, LIN_MLIQ, LIN_REGI, LIN_QUNI, LIN_MONT, UME_CODI, LIN_VOLS)		
				VALUES(@CodArtigo, @CodPautalArtigo, @DesignacaoArtigo, @CodPaisOrigem, @CodPreferencia, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, @Volumes)		
				SET @IdLinha = SCOPE_IDENTITY()
			END
			ELSE
			BEGIN
				UPDATE @TblTmpLinhas SET 
					LIN_MBRT = LIN_MBRT + @MassaBrt, 
					LIN_MLIQ = LIN_MLIQ + @MassaLiq, 
					LIN_QUNI = LIN_QUNI + @QtdUnidades, 
					LIN_MONT = LIN_MONT + @Montante, 
					LIN_VOLS = LIN_VOLS + @Volumes
				WHERE LIN_IDEN = @IdLinha
			END	
-- insere precedente se este ainda não existe na linha
			IF NOT EXISTS(SELECT PRE_IDEN FROM @TblTmpPrecedentes WHERE LIN_IDEN = @IdLinha AND PRE_NDOC = @NumeroDocPrecedente AND PRE_DDOC = @DataDocPrecedente)
			BEGIN
				INSERT @TblTmpPrecedentes(LIN_IDEN, PRE_NDOC, PRE_DDOC)
				VALUES(@IdLinha, @NumeroDocPrecedente, @DataDocPrecedente)
			END
			FETCH NEXT FROM Linhas INTO @CodArtigo, @CodPautalArtigo, @DesignacaoArtigo, @CodPaisOrigem, @CodPreferencia, @MassaBrt, @MassaLiq, @Regime, @QtdUnidades, @Montante, @CodUnidMedida, 
				@Volumes, @NumeroDocPrecedente, @DataDocPrecedente
		END
		CLOSE Linhas
		DEALLOCATE Linhas
-- obtem o total de adições apuradas
		SELECT @TotalAdicoes = COUNT(*)
		FROM @TblTmpLinhas
-- constroi XML para edição da declaração IMP-CAU com adições sendo as linhas OGMA
		SELECT @DocumentoXML = 
			(SELECT
				(SELECT 'U' AS "@acao",
					(CONVERT(varchar(10), duc.DUC_DATA, 127) + 'Z') AS "data",	 
					duc.DUC_DCEN AS "despachoCentralizado", 
					duc.DUC_ANXB AS "anexoB", 
					duc.NDE_CODI AS "natureza", 
					NULLIF(duc.DUC_CPRT, '') AS "documentoTransporte", 
					NULLIF(duc.DUC_DGEN, '') AS "descricaoGenerica", 
					(SELECT 
						NULLIF(duc.PAI_PA15, '') AS "paisExpedicao", 
						(SELECT 
							NULLIF(duc.DUC_DNIF, '') AS "nif",
							duc.DUC_TPDS AS "tipoNIF",
							NULLIF(duc.DUC_DNOM, '') AS "nome",
							NULLIF(duc.DUC_DMOR, '') AS "morada",
							NULLIF(duc.DUC_DLOC, '') AS "localidade",
							NULLIF(duc.DUC_DCPO, '') AS "codigoPostal",
							NULLIF(duc.DUC_DLPO, '') AS "localidadePostal",
							NULLIF(duc.PAI_DLIV, '') AS "pais"
						FOR XML PATH('importador'), TYPE), 
						NULLIF(duc.PAI_PA17, '') AS "paisDestino", 
						(SELECT 
							NULLIF(duc.DEC_CO14, '') AS "codigoDeclarante"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE), 					
					duc.ALF_CODI AS "estancia", 		
					duc.TDE_CODI AS "tipoDeclaracao", 																												
					NULLIF(duc.CEN_CO20, '') AS "condicaoEntrega", 
					(SELECT
						NULLIF(duc.DUC_DE20, '') AS "localidadeCE", 
						NULLIF(duc.PAI_CODI2, '') AS "paisCE"
					HAVING ISNULL(duc.DUC_DE20, '') <> ''
					FOR XML PATH('localizacao'), TYPE), 					
					NULLIF(duc.PAE_CODI, '') AS "portoAeroporto", 				
					(SELECT
						(SELECT
							NULLIF(duc.PAI_PR22, '') AS "pais", 
							CAST(ISNULL(duc.DUC_MT22, 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							NULLIF(duc.PAI_FRET, '') AS "pais", 
							CAST(ISNULL(duc.DUC_FRET, 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							NULLIF(duc.PAI_SEGU, '') AS "pais", 
							CAST(ISNULL(duc.DUC_SEGU, 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT
							CAST(ISNULL(duc.DUC_MLQT, 0) AS decimal(18, 6)) AS "massaLiquida", 
							CAST(ISNULL(duc.DUC_MBRT, 0) AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT 
						NULLIF(duc.MTR_PT18, '') AS "meioTransporteChegada", 
						duc.DUC_CT19 AS "contentorizada"
					FOR XML PATH('transporte'), TYPE), 					 					
					(SELECT 
						(SELECT 
							'DUC_PNUM' AS "codigoCampoExtra", 
							duc.DUC_PNUM AS "valorCampoExtra"
						FOR XML PATH('campoExtra'), TYPE)
					FOR XML PATH('camposExtra'), TYPE),										
					(SELECT 'I' AS "@acao",
						adi.LIN_NUME AS "numeroAdicao", 
						adi.APA_CPAU AS "codigoPautal", 
						adi.APA_DESG AS "designacao",
						adi.PAI_CODI AS "paisOrigem",  
						adi.PRE_CODI AS "preferencia", 																			
						CAST(adi.LIN_MLIQ AS decimal(18, 6)) AS "massaLiquida",												
						CAST(adi.LIN_MBRT AS decimal(18, 6)) AS "massaBruta", 						
						CAST(adi.LIN_QUNI AS decimal(18, 6)) AS "unidades", 
						CAST(adi.LIN_MONT AS decimal(18, 3)) AS "montanteAd", 
						(SELECT 
							CAST(doc.DOC_TRAN AS int) AS "tipoDocumento", 
							doc.DOC_CODI AS "codigoDocumento",
							NULLIF(pre.PRE_NDOC, '') AS "numeroDocumento", 
							(CONVERT(varchar(10), pre.PRE_DDOC, 127) + 'Z') AS "dataValidade"
						FROM @TblTmpPrecedentes AS pre
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = '9D06' AND doc.DOC_DESP = 1
						WHERE pre.LIN_IDEN = adi.LIN_IDEN AND adi.LIN_REGI IN ('4051', '4071', '5171', '7171')						
						FOR XML PATH('documento'), ROOT('documentosECertificados'), TYPE),
						(SELECT 																
							doc.DOC_CODI AS "codigoDocumento", 						
							pre.PRE_NDOC AS "numeroDocumento"
						FROM @TblTmpPrecedentes AS pre
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'IM' AND doc.DOC_CA40 = 1
						WHERE pre.LIN_IDEN = adi.LIN_IDEN
						FOR XML PATH('documentoPrecedente'), ROOT('documentosPrecedentes'), TYPE), 
						(SELECT 					
							ume.UME_CODI AS "unidadeMedida", 
							adi.LIN_VOLS AS "volumes", 																								
							(CASE WHEN (@ParteResto = 1) AND (adi.LIN_NUME <> @TotalAdicoes) THEN 1 ELSE 0 END) AS "parte"
						FROM TAB_UMED AS ume WITH(NOLOCK)
						WHERE ume.UME_CODI = adi.UME_CODI AND ume.UME_IMPT = 1	
						FOR XML PATH('marcaEVolume'), ROOT('marcasEVolumes'), TYPE)											
					FROM (SELECT ROW_NUMBER() OVER(ORDER BY LIN_IDEN) AS LIN_NUME, LIN_IDEN, APA_CPAU, APA_DESG, PAI_CODI, PRE_CODI, LIN_MBRT, LIN_MLIQ, LIN_REGI, LIN_QUNI, LIN_MONT, LIN_VOLS, UME_CODI
						FROM @TblTmpLinhas) AS adi
					FOR XML PATH('adicao'), ROOT('adicoes'), TYPE)
				FROM PRO_DUCG AS duc WITH(NOLOCK) 
				WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a atualização da declaração para inserir as adições apuradas
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @DocumentoXML, @IdUtilizador, @Erro OUTPUT
		IF @NumErro > 0
			RAISERROR ('Erro na inserção de adições na declaração: %s', 16, 1, @Erro)		
-- inicia o número da adição em todas as linhas OGMA
		UPDATE tb_TBL_LinhasOGMA SET numeroAdicao = NULL
		FROM tb_TBL_LinhasOGMA AS lin WITH(NOLOCK)
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON lin.id_declaracaoIMP = duc.DUC_IDTY
		WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero AND lin.numeroAdicao IS NOT NULL
-- atribui a todas as linhas OGMA o respetivo número de adição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dua.DUA_CODI, lin.id
			FROM PRO_DUCG AS duc WITH(NOLOCK)
				INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM
				INNER JOIN tb_IMP_DeclaracoesAdicoesPrecedentes AS dap WITH(NOLOCK) ON dua.DUA_IDEN = dap.id_adicao
				INNER JOIN PRO_DU31 AS amv WITH(NOLOCK) ON dua.DUC_EANO = amv.DUC_EANO AND dua.DUC_PNUM = amv.DUC_PNUM AND dua.DUA_CODI = amv.DUA_CODI
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON dua.APA_CO33 = apa.APA_CODI
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dua.PAI_CO34 = pai.PAI_CODI
				INNER JOIN TAB_PREF AS pre WITH(NOLOCK) ON dua.PRE_CO36 = pre.PRE_CODI
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON amv.UME_CODI = ume.UME_CODI
				INNER JOIN tb_TBL_LinhasOGMA AS lin WITH(NOLOCK) ON duc.DUC_IDTY = lin.id_declaracaoIMP AND apa.APA_IDTY = lin.id_artigo AND pai.PAI_IDTY = lin.id_paisOrigem AND pre.PRE_IDTY = lin.id_preferencia AND dua.DUA_RG37 = lin.observacoes AND ume.UME_IDTY = lin.id_unidadeMedida AND dap.numero = lin.numeroOrdem
			WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdLinha
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			UPDATE tb_TBL_LinhasOGMA SET numeroAdicao = @NumAdicao
			WHERE id = @IdLinha
			FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdLinha
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes					
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_AdicoesGeraDeLinhasOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_AdicoesGeraDeLinhasOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_AdicoesImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_AdicoesImportaXLSX] @AnoDeclaracao int, @NumDeclaracao int, @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @CodArtigo varchar(22), @PesoLiq numeric(38, 6), @PesoBrt numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), 
		@CodPreferencia varchar(3), @CodPaisOrigem varchar(2), @Resultado int, @MsgErro varchar(MAX)
	DECLARE @TblTmpAdicoes TABLE(CodArtigo varchar(22) NOT NULL, PesoLiq numeric(38, 6) NOT NULL, PesoBrt numeric(38, 6) NOT NULL, Montante numeric(38, 6) NOT NULL, 
		Unidades numeric(38, 6) NOT NULL, CodPreferencia varchar(3) NOT NULL, CodPaisOrigem varchar(2) NOT NULL)
-- inicia transacção para a inserção das adições
	BEGIN TRANSACTION TspIMPImportaXLSXAdicoes
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- insere todos os dados das adições do ficheiro na tabela tmp
		INSERT INTO @TblTmpAdicoes(CodArtigo, PesoLiq, PesoBrt, Montante, Unidades, CodPreferencia, CodPaisOrigem)
		SELECT t.c.value('CODIGO[1]', 'varchar(22)'), ISNULL(t.c.value('PLIQUIDO[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('PBRUTO[1]', 'numeric(38, 6)'), 0), 
			ISNULL(t.c.value('MONTANTE[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('UNIDADES[1]', 'numeric(38, 6)'), 0), t.c.value('PREFERENCIA[1]', 'varchar(3)'), 
			t.c.value('PO[1]', 'varchar(2)')
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
-- obtem as adições do ficheiro agrupadas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT CodArtigo, CodPreferencia, CodPaisOrigem, SUM(PesoLiq), SUM(PesoBrt), SUM(Montante), SUM(Unidades)
			FROM @TblTmpAdicoes
			GROUP BY CodArtigo, CodPreferencia, CodPaisOrigem
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPreferencia, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- insere a adição
			EXEC @Resultado = sp_IMP_Declaracoes_AdicoesInsere @AnoDeclaracao, @NumDeclaracao, NULL, @CodArtigo, @PesoLiq, @PesoBrt, @Montante, @Unidades, @CodPreferencia, @CodPaisOrigem, NULL, NULL, NULL, NULL, NULL, NULL, NULL, @MsgErro OUTPUT
			IF @Resultado > 0
				RAISERROR ('Erro na inserção da adição! ERRO: "%s".', 16, 1, @MsgErro)	
			FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPreferencia, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPImportaXLSXAdicoes
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPImportaXLSXAdicoes
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_AdicoesImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_AdicoesImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_AdicoesInsercaoRapida]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_AdicoesInsercaoRapida] @AnoDeclaracao int, @NumDeclaracao int, @FicheiroXLSX varchar(MAX), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @FicheiroXML xml, @GlobalizaAdicoes bit, @CodArtigo varchar(22), @PesoLiq numeric(38, 6), @PesoBrt numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), 
		@CodPreferencia varchar(3), @CodPaisOrigem varchar(2), @NumAdicao int, @IdAdicao int, @DireitosDDP numeric(38, 6), @Resultado int, @MsgErro varchar(MAX)
	DECLARE @TblTmpAdicoes TABLE(Estado int NOT NULL, CodArtigo varchar(22) NOT NULL, PesoLiq numeric(38, 6) NOT NULL, PesoBrt numeric(38, 6) NOT NULL, Montante numeric(38, 6) NOT NULL, 
		Unidades numeric(38, 6) NOT NULL, CodPreferencia varchar(3) NOT NULL, CodPaisOrigem varchar(2) NOT NULL, NumAdicao int NULL, IdAdicao int NULL, DireitosDDP numeric(38, 6) NOT NULL)
-- inicia transacção para a inserção das adições
	BEGIN TRANSACTION TspIMPAdicoesInsercaoRapida
	BEGIN TRY	
		SET @NumErro = 0
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- obtem se utilizador globaliza as adições
		SELECT @GlobalizaAdicoes = UTI_GLBA
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- insere todos os dados das adições na tabela tmp
		INSERT INTO @TblTmpAdicoes(Estado, CodArtigo, PesoLiq, PesoBrt, Montante, Unidades, CodPreferencia, CodPaisOrigem, NumAdicao, IdAdicao, DireitosDDP)
		SELECT t.c.value('ESTADO[1]', 'int'), t.c.value('APA_CO33[1]', 'varchar(22)'), ISNULL(t.c.value('DUA_ML38[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('DUA_MB35[1]', 'numeric(38, 6)'), 0), 
			ISNULL(t.c.value('DUA_VA42[1]', 'numeric(38, 6)'), 0), ISNULL(t.c.value('DUA_US41[1]', 'numeric(38, 6)'), 0), t.c.value('PRE_CO36[1]', 'varchar(3)'), 
			t.c.value('PAI_CO34[1]', 'varchar(2)'), t.c.value('DUA_CODI[1]', 'int'), t.c.value('DUA_IDEN[1]', 'int'), ISNULL(t.c.value('DUA_VDIR[1]', 'numeric(38, 6)'), 0)
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
-- obtem as adições removidas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT IdAdicao
			FROM @TblTmpAdicoes
			WHERE Estado = 3			
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- remove a adição
			DELETE FROM PRO_DUAD
			WHERE DUA_IDEN = @IdAdicao			
			FETCH NEXT FROM Adicoes INTO @IdAdicao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem as adições editadas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT IdAdicao, NumAdicao, CodArtigo, CodPreferencia, CodPaisOrigem, PesoLiq, PesoBrt, Montante, Unidades, DireitosDDP
			FROM @TblTmpAdicoes
			WHERE Estado = 2			
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumAdicao, @CodArtigo, @CodPreferencia, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades, @DireitosDDP
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- edita a adição
			EXEC @Resultado = sp_IMP_Declaracoes_AdicoesEdita @IdAdicao, @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodArtigo, @PesoLiq, @PesoBrt, @Montante, @Unidades, @CodPreferencia, @CodPaisOrigem, @DireitosDDP, @MsgErro OUTPUT
			IF @Resultado > 0
				RAISERROR ('Erro na edição da adição! ERRO: "%s".', 16, 1, @MsgErro)	
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumAdicao, @CodArtigo, @CodPreferencia, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades, @DireitosDDP
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem as adições inseridas agrupadas ou não conforme a configuraçãpo do utilizador
		IF @GlobalizaAdicoes = 1
		BEGIN
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT CodArtigo, CodPreferencia, CodPaisOrigem, SUM(PesoLiq), SUM(PesoBrt), SUM(Montante), SUM(Unidades)
				FROM @TblTmpAdicoes
				WHERE Estado = 1
				GROUP BY CodArtigo, CodPreferencia, CodPaisOrigem
		END
		ELSE
		BEGIN
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT CodArtigo, CodPreferencia, CodPaisOrigem, PesoLiq, PesoBrt, Montante, Unidades
				FROM @TblTmpAdicoes
				WHERE Estado = 1				
		END
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPreferencia, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @MsgErro = NULL
-- insere a adição
			EXEC @Resultado = sp_IMP_Declaracoes_AdicoesInsere @AnoDeclaracao, @NumDeclaracao, NULL, @CodArtigo, @PesoLiq, @PesoBrt, @Montante, @Unidades, @CodPreferencia, @CodPaisOrigem, NULL, NULL, NULL, NULL, NULL, NULL, NULL, @MsgErro OUTPUT
			IF @Resultado > 0
				RAISERROR ('Erro na inserção da adição! ERRO: "%s".', 16, 2, @MsgErro)	
			FETCH NEXT FROM Adicoes INTO @CodArtigo, @CodPreferencia, @CodPaisOrigem, @PesoLiq, @PesoBrt, @Montante, @Unidades
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPAdicoesInsercaoRapida
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPAdicoesInsercaoRapida
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_AdicoesInsercaoRapida] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_AdicoesInsercaoRapida] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_AdicoesInsere]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_AdicoesInsere] @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @CodArtigo varchar(22), @PesoLiquido numeric(38, 6), 
	@PesoBruto numeric(38, 6), @Montante numeric(38, 6), @Unidades numeric(38, 6), @CodPreferencia varchar(3), @CodPaisOrigem varchar(2), @Designacao varchar(150), 
	@Desdobramento1 varchar(3), @MetodoAvaliacao int, @Frete numeric(38, 6), @Seguro numeric(38, 6), @TaxaIVA numeric(38, 6), @IdAdicao int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID int NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @ValorFormatado varchar(40)
	DECLARE @1CasaTipoDeclaracao varchar(5), @CodCliente varchar(18), @CodDeclarante varchar(6), @MontanteTotal numeric(38, 6), @CambioMontante numeric(38, 6), @FreteTotal numeric(38, 6), 
		@CambioFrete numeric(38, 6), @SeguroTotal numeric(38, 6), @CambioSeguro numeric(38, 6), @VerbaTransitarioTotal numeric(38, 6), @MassaBrutaTotal numeric(38, 6), 
		@ValorAduaneiroTotal numeric(38, 6), @TotalAdicoes int, @TotalVolumes numeric(38, 6), @FormulaCondEntrega varchar(70), @TaxaFDA numeric(38, 6), @CodMeioTransporteChegada varchar(2), 
		@TotalOptativas numeric(38, 6), @AnexoB varchar(2), @Regime varchar(4), @BeneficiarioIVA bit, @GarantiaGlobal bit, @NumeroNRG varchar(24), @AnoNRG varchar(4), @TipoNRG varchar(1), 
		@EntidadeNRG int, @CodAlfandegaNRG varchar(8), @CodigoAcessoNRG varchar(4), @OutrasReferenciasNRG varchar(35), @NIFResponsavel varchar(17), @DesdobramentoTipoDeclaracao varchar(3), 
		@AdicionalIVA int
	DECLARE @SomaMontantesAdicoes numeric(38, 6), @SomaFretesAdicoes numeric(38, 6), @SomaSegurosAdicoes numeric(38, 6), @SomaVerbasTransitarioAdicoes numeric(38, 6)
	DECLARE @IdDesdobramento int, @Desdobramento2 varchar(3)
	DECLARE @CodUnidMedida varchar(3), @TipoTributacao int, @CodUnidSuplementar varchar(10), @CodigoPautal varchar(22), @ArtigoTxComposta bit, @CodigoATAR varchar(10), @CodigoIC1 varchar(4), 
		@CodigoIC2 varchar(4), @CodigoIC3 varchar(4), @CodigoIC4 varchar(4), @CodigoIC5 varchar(4), @CodigoCCUS varchar(9), @TipoMercadoria varchar(3)
	DECLARE @NomeUnidMedida varchar(35)
	DECLARE @NomePaisOrigem varchar(35)
	DECLARE @NomeUnidSuplementar varchar(10)
	DECLARE @NomePreferencia varchar(70), @CodRubricaDireitos int, @TaxaPreferencia numeric(38, 6), @NomeRubricaDireitos varchar(35), @ImposicaoDireitos varchar(3)
	DECLARE @CodRubricaIVA int, @NomeRubricaIVA varchar(35), @ImposicaoIVA varchar(3)
	DECLARE @NumeroNRGDireitos varchar(24), @AnoNRGDireitos varchar(4), @TipoNRGDireitos varchar(1), @EntidadeNRGDireitos int, @CodAlfandegaNRGDireitos varchar(8), 
		@CodigoAcessoNRGDireitos varchar(4), @OutrasReferenciasNRGDireitos varchar(35), @NIFResponsavelDireitos varchar(17),  @NumeroNRGIVA varchar(24), @AnoNRGIVA varchar(4), 
		@TipoNRGIVA varchar(1), @EntidadeNRGIVA int, @CodAlfandegaNRGIVA varchar(8), @CodigoAcessoNRGIVA varchar(4), @OutrasReferenciasNRGIVA varchar(35), @NIFResponsavelIVA varchar(17)
	DECLARE @VerbaTransitario numeric(38, 6), @Optativas numeric(38, 6), @ValorEUR numeric(38, 6), @Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @ValorAduaneiro numeric(38, 6), 
		@BaseTributacaoDireitos numeric(38, 6), @TaxaValorDireitos numeric(38, 6), @MontanteDireitos numeric(38, 6), @BaseTributacaoIVA numeric(38, 6), @MontanteIVA numeric(38, 6), 
		@QtdDireitos numeric(38, 6)
-- inicia processo de inserção da adição
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- valida artigo
		IF NOT EXISTS(SELECT 1 FROM TAB_APAU WITH(NOLOCK) WHERE APA_CODI = @CodArtigo AND APA_INAC = 0 AND APA_FLUX IN (0, 1) AND APA_EDAR = 0 AND LEN(APA_CPAU) >= 10)
			RAISERROR('Código do artigo "%s" inexistente ou não está devidamente configurado.', 16, 1, @CodArtigo)
-- valida preferência
		IF (ISNULL(@CodPreferencia, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PREF WITH(NOLOCK) WHERE PRE_CODI = @CodPreferencia))
			RAISERROR('Código da preferência "%s" inexistente.', 16, 2, @CodPreferencia)
-- valida país de origem
		IF (ISNULL(@CodPaisOrigem, '') <> '') AND (NOT EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = @CodPaisOrigem))
			RAISERROR('Código do país de origem "%s" inexistente.', 16, 3, @CodPaisOrigem)
-- valida peso bruto
		IF ISNULL(@PesoBruto, 0) <= 0
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoBruto, 38, 6))
			RAISERROR('Peso bruto "%s" inválido.', 16, 4, @ValorFormatado)
		END
-- valida montante
		IF ISNULL(@Montante, 0) <= 0
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR('Montante "%s" inválido.', 16, 5, @ValorFormatado)
		END
-- obtem dados da declaração		
		SELECT @1CasaTipoDeclaracao = duc.TDE_1CAS, @CodCliente = duc.DUC_DST8, @CodDeclarante = duc.DEC_CO14, @MontanteTotal = ISNULL(duc.DUC_MT22, 0), @CambioMontante = ISNULL(duc.DUC_TX23, 0), 
			@FreteTotal = ISNULL(duc.DUC_FRET, 0), @CambioFrete = ISNULL(duc.DUC_TXFR, 0), @SeguroTotal = ISNULL(duc.DUC_SEGU, 0), @CambioSeguro = ISNULL(duc.DUC_TxSE, 0), 
			@VerbaTransitarioTotal = ISNULL(duc.DUC_VTRN, 0), @MassaBrutaTotal = ISNULL(duc.DUC_MBRT, 0), @ValorAduaneiroTotal = ISNULL(duc.DUC_VATT, 0), @TotalAdicoes = duc.DUC_ADI5, 
			@TotalVolumes = ISNULL(duc.DUC_TVL6, 0), @FormulaCondEntrega = ISNULL(duc.DUC_FR20, ''), @TaxaFDA = ISNULL(duc.DUC_TFDA, 0), @CodMeioTransporteChegada = duc.MTR_PT18, 
			@TotalOptativas = ISNULL(duc.DUC_OP18, 0), @AnexoB = duc.DUC_ANXB, @Regime = duc.DUC_REGI, @BeneficiarioIVA = duc.DUC_BIVA, @GarantiaGlobal = duc.DUC_CGLB, @NumeroNRG = duc.DUC_CAUC, 
			@AnoNRG = duc.DUC_CANO, @TipoNRG = duc.DUC_CTIP, @EntidadeNRG = duc.DUC_CENT, @CodAlfandegaNRG = duc.ALF_CODI2, @CodigoAcessoNRG = duc.DUC_CCAC, @OutrasReferenciasNRG = duc.DUC_CORF, 
			@NIFResponsavel = duc.DUC_CNIR, 
			@DesdobramentoTipoDeclaracao = tde.TDE_DESD, 
			@CodPaisOrigem = (CASE duc.DUC_ANXB 
								WHEN 'I2' THEN NULL 
								WHEN 'H6' THEN ISNULL(@CodPaisOrigem, duc.PAI_ELIV)
								ELSE ISNULL(@CodPaisOrigem, duc.PAI_PA15) 
							END), 
			@CodPreferencia = (CASE 
								WHEN duc.DUC_ANXB IN ('H2', 'H5', 'H6') THEN (SELECT PRE_CODI FROM TAB_PREF WITH(NOLOCK) WHERE PRE_CODI = '000')
								ELSE ISNULL(@CodPreferencia, tde.PRE_CODI) 
							END), 
			@AdicionalIVA = (CASE 
								WHEN (LEFT(duc.DUC_REGI, 2) <> '42') AND (duc.DUC_BIVA = 0) THEN cli.CLI_AIVA
								ELSE NULL
							END)
		FROM PRO_DUCG AS duc WITH(NOLOCK) 			
			INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON duc.TDE_CODI = tde.TDE_CODI			
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
		WHERE duc.DUC_EANO = @AnoDeclaracao AND duc.DUC_PNUM = @NumDeclaracao 
-- valida peso líquido
		IF (@AnexoB NOT IN ('H2', 'H3', 'I2')) AND (ISNULL(@PesoLiquido, 0) <= 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@PesoLiquido, 38, 6))
			RAISERROR('Peso líquido "%s" inválido.', 16, 6, @ValorFormatado)
		END
-- obtem dados das adições já existentes		
		SELECT @SomaMontantesAdicoes = ISNULL(SUM(DUA_VA42), 0), @SomaFretesAdicoes = ISNULL(SUM(ISNULL(DUA_VFRE, 0)), 0), @SomaSegurosAdicoes = ISNULL(SUM(ISNULL(DUA_VSEG, 0)), 0), 
			@SomaVerbasTransitarioAdicoes = ISNULL(SUM(ISNULL(DUA_VTRA, 0)), 0)
		FROM PRO_DUAD WITH(NOLOCK)
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao 
-- valida se montante é válido na declaração
		IF (@MontanteTotal - @SomaMontantesAdicoes - @Montante) < 0
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Montante, 38, 3))
			RAISERROR('Montante "%s" inválido porque é superior ao montante total disponível', 16, 7, @ValorFormatado)
		END
-- obtem dados do desdobramento de regime		
		SELECT @IdDesdobramento = id, @Desdobramento1 = desdobramento1, @Desdobramento2 = desdobramento2
		FROM tb_TBL_Desdobramentos WITH(NOLOCK) 
		WHERE tipoDeclaracao = @1CasaTipoDeclaracao AND regime = @Regime AND desdobramento1 = ISNULL(NULLIF(@Desdobramento1, ''), @DesdobramentoTipoDeclaracao)
-- valida se regime adicional é válido
		IF (LEFT(@Regime, 2) = '53') AND (@IdDesdobramento IS NULL)
			RAISERROR('O regime "%s" obriga ao preenchimento do regime adicional.', 16, 8, @Regime)
-- obtem dados do artigo		
		SELECT @CodigoPautal = apa.APA_CPAU, @TipoTributacao = apa.APA_TRIB, @CodUnidSuplementar = apa.USU_CODI, @CodigoATAR = apa.APA_ATAR, 
			@Designacao = ISNULL(NULLIF(@Designacao, ''), apa.APA_DESG), 
			@CodigoIC1 = (CASE 
							WHEN @AnexoB NOT IN ('H6', 'I2') THEN apa.APA_AIC1 
							ELSE NULL 
						END),
			@CodigoIC2 = (CASE 
							WHEN @AnexoB NOT IN ('H6', 'I2') THEN apa.APA_AIC2 
							ELSE NULL 
						END), 
			@CodigoIC3 = (CASE 
							WHEN @AnexoB NOT IN ('H6', 'I2') THEN apa.APA_AIC3 
							ELSE NULL 
						END),
			@CodigoIC4 = (CASE 
							WHEN @AnexoB NOT IN ('H6', 'I2') THEN apa.APA_AIC4 
							ELSE NULL 
						END),
			@CodigoIC5 = (CASE 
							WHEN @AnexoB NOT IN ('H6', 'I2') THEN apa.APA_AIC5 
							ELSE NULL 
						END),
			@CodigoCCUS = (CASE 
							WHEN @AnexoB NOT IN ('H6', 'I2') THEN apa.APA_CCUS
							ELSE NULL 
						END),
			@TipoMercadoria = (CASE 
							WHEN @AnexoB NOT IN ('HI', 'H2', 'H3', 'H4', 'H5', 'I1') THEN apa.APA_TMER
							ELSE NULL 
						END),
			@CodUnidMedida = (CASE 
									WHEN ISNULL(apa.APA_TRIB, 0) IN (0, 1) THEN apa.UME_CODI 
									ELSE NULL 
								END),
			@TaxaIVA = (CASE 						
						WHEN (LEFT(ISNULL(@Regime, ''), 2) IN ('42', '51', '53', '71')) OR (ISNULL(@Desdobramento1, '') = '4II') OR (ISNULL(@Desdobramento1, '') = 'C01') OR (ISNULL(@Desdobramento1, '') = 'F48') OR (ISNUMERIC(@Desdobramento1) = 1 AND CAST(@Desdobramento1 AS int) >= 401 AND CAST(@Desdobramento1 AS int) <= 459) THEN 0 
						WHEN (ISNULL(@Regime, '') = '6123') AND (ISNULL(@Desdobramento1, '') = 'F01') THEN 0 
						ELSE ISNULL(@TaxaIVA, ISNULL(apa.APA_TIVA, 0))
					END), 
			@ArtigoTxComposta = (CASE apa.APA_TRIB 
									WHEN 0 THEN ~(apa.APA_TXCO) 
									WHEN 1 THEN 1 
									ELSE 0 
								END)			
		FROM TAB_APAU AS apa WITH(NOLOCK)
		WHERE APA_CODI = @CodArtigo
-- valida unidades
		IF (@AnexoB IN ('H6', 'I2')) AND (ISNULL(@Unidades, 0) > 0)
		BEGIN
			SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
			RAISERROR('Unidades "%s" inválida.', 16, 9, @ValorFormatado)
		END
		ELSE
			IF (@AnexoB NOT IN ('H6', 'I2')) AND (ISNULL(@CodUnidSuplementar, '') <> '') AND (ISNULL(@Unidades, 0) <= 0)
			BEGIN
				SET @ValorFormatado = LTRIM(STR(@Unidades, 38, 6))
				RAISERROR('Unidades "%s" inválida.', 16, 10, @ValorFormatado)
			END
-- obtem dados da unidade de medida		
		SELECT @NomeUnidMedida = UME_NOME
		FROM TAB_UMED WITH(NOLOCK)
		WHERE UME_CODI = @CodUnidMedida
-- obtem dados do país de origem		
		SELECT @NomePaisOrigem = PAI_NOME
		FROM TAB_PAIS WITH(NOLOCK)
		WHERE PAI_CODI = @CodPaisOrigem
-- obtem dados da unidade suplementar
		SELECT @NomeUnidSuplementar = USU_SIGL
		FROM TAB_USUP WITH(NOLOCK)
		WHERE USU_CODI = @CodUnidSuplementar
-- obtem dados da preferência		
		SELECT @NomePreferencia = pre.PRE_NOME, @TaxaPreferencia = pre.PRE_TAXA, @CodRubricaDireitos = rre.RRE_CODI, @NomeRubricaDireitos = rre.RRE_NOME, @ImposicaoDireitos = rre.RRE_IMPO
		FROM TAB_PREF AS pre WITH(NOLOCK)
			INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON pre.RRE_CODI = rre.RRE_CODI
		WHERE pre.PRE_CODI = @CodPreferencia
-- obtem dados do IVA		
		SELECT @CodRubricaIVA = rre.RRE_CODI, @NomeRubricaIVA = rre.RRE_NOME, @ImposicaoIVA = rre.RRE_IMPO
		FROM (SELECT PAP_TXIS, RRE_CDIS 
				FROM TAB_PAPL WITH(NOLOCK) 
				UNION 
				SELECT PAP_TXRD, RRE_CDRD 
				FROM TAB_PAPL WITH(NOLOCK) 
				UNION 
				SELECT PAP_TXIN, RRE_CDIN 
				FROM TAB_PAPL WITH(NOLOCK) 
				UNION 
				SELECT PAP_TXNR, RRE_CDNR 
				FROM TAB_PAPL WITH(NOLOCK)) AS t 
			INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON t.RRE_CDIS = rre.RRE_CODI
		WHERE t.PAP_TXIS = @TaxaIVA
-- calcula a garantia de direitos e IVA		
		IF (@GarantiaGlobal = 0) AND (@AnexoB NOT IN ('H2', 'I1', 'I2'))
		BEGIN			
			SELECT @EntidadeNRG = 1, @NIFResponsavel = CLI_CNIF, 
				@NumeroNRG = (CASE 
								WHEN ISNULL(CLI_NCA1, '') <> '' AND CLI_INA1 = 0 THEN (ISNULL(RIGHT(CLI_ANO1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(CLI_NCA1))) + CLI_NCA1)
								WHEN ISNULL(CLI_NCA2, '') <> '' AND CLI_INA2 = 0 THEN (ISNULL(RIGHT(CLI_ANO2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(CLI_NCA2))) + CLI_NCA2)
								WHEN ISNULL(CLI_NCA3, '') <> '' AND CLI_INA3 = 0 THEN (ISNULL(RIGHT(CLI_ANO3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(CLI_NCA3))) + CLI_NCA3)
								WHEN ISNULL(CLI_NCA4, '') <> '' AND CLI_INA4 = 0 THEN (ISNULL(RIGHT(CLI_ANO4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(CLI_NCA4))) + CLI_NCA4)
								WHEN ISNULL(CLI_NCA5, '') <> '' AND CLI_INA5 = 0 THEN (ISNULL(RIGHT(CLI_ANO5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(CLI_NCA5))) + CLI_NCA5)
								ELSE NULL
							END), 
				@AnoNRG = (CASE 
								WHEN ISNULL(CLI_NCA1, '') <> '' AND CLI_INA1 = 0 THEN CLI_ANO1 
								WHEN ISNULL(CLI_NCA2, '') <> '' AND CLI_INA2 = 0 THEN CLI_ANO2
								WHEN ISNULL(CLI_NCA3, '') <> '' AND CLI_INA3 = 0 THEN CLI_ANO3 
								WHEN ISNULL(CLI_NCA4, '') <> '' AND CLI_INA4 = 0 THEN CLI_ANO4
								WHEN ISNULL(CLI_NCA5, '') <> '' AND CLI_INA5 = 0 THEN CLI_ANO5
								ELSE NULL
							END), 
				@TipoNRG = (CASE 
								WHEN ISNULL(CLI_NCA1, '') <> '' AND CLI_INA1 = 0 THEN CLI_TCA1
								WHEN ISNULL(CLI_NCA2, '') <> '' AND CLI_INA2 = 0 THEN CLI_TCA2
								WHEN ISNULL(CLI_NCA3, '') <> '' AND CLI_INA3 = 0 THEN CLI_TCA3 
								WHEN ISNULL(CLI_NCA4, '') <> '' AND CLI_INA4 = 0 THEN CLI_TCA4
								WHEN ISNULL(CLI_NCA5, '') <> '' AND CLI_INA5 = 0 THEN CLI_TCA5
								ELSE NULL
							END), 
				@CodAlfandegaNRG = (CASE 
										WHEN ISNULL(CLI_NCA1, '') <> '' AND CLI_INA1 = 0 THEN ALF_CODI1
										WHEN ISNULL(CLI_NCA2, '') <> '' AND CLI_INA2 = 0 THEN ALF_CODI2
										WHEN ISNULL(CLI_NCA3, '') <> '' AND CLI_INA3 = 0 THEN ALF_CODI3
										WHEN ISNULL(CLI_NCA4, '') <> '' AND CLI_INA4 = 0 THEN ALF_CODI4
										WHEN ISNULL(CLI_NCA5, '') <> '' AND CLI_INA5 = 0 THEN ALF_CODI5
										ELSE NULL
									END), 
				@CodigoAcessoNRG = (CASE 
										WHEN ISNULL(CLI_NCA1, '') <> '' AND CLI_INA1 = 0 THEN CLI_CCA1
										WHEN ISNULL(CLI_NCA2, '') <> '' AND CLI_INA2 = 0 THEN CLI_CCA2
										WHEN ISNULL(CLI_NCA3, '') <> '' AND CLI_INA3 = 0 THEN CLI_CCA3
										WHEN ISNULL(CLI_NCA4, '') <> '' AND CLI_INA4 = 0 THEN CLI_CCA4
										WHEN ISNULL(CLI_NCA5, '') <> '' AND CLI_INA5 = 0 THEN CLI_CCA5
										ELSE NULL
									END), 
				@OutrasReferenciasNRG = (CASE 
											WHEN ISNULL(CLI_NCA1, '') <> '' AND CLI_INA1 = 0 THEN CLI_OCA1
											WHEN ISNULL(CLI_NCA2, '') <> '' AND CLI_INA2 = 0 THEN CLI_OCA2
											WHEN ISNULL(CLI_NCA3, '') <> '' AND CLI_INA3 = 0 THEN CLI_OCA3
											WHEN ISNULL(CLI_NCA4, '') <> '' AND CLI_INA4 = 0 THEN CLI_OCA4
											WHEN ISNULL(CLI_NCA5, '') <> '' AND CLI_INA5 = 0 THEN CLI_OCA5
											ELSE NULL
										END)				
			FROM TAB_CLIE WITH(NOLOCK)
			WHERE CLI_CODI = @CodCliente
			IF ISNULL(@NumeroNRG, '') = ''
			BEGIN
				SELECT @EntidadeNRG = 0, 
					@NumeroNRG = (CASE 
									WHEN ISNULL(DEC_NCA1, '') <> '' AND DEC_INA1 = 0 THEN (ISNULL(RIGHT(DEC_ACA1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(DEC_NCA1))) + DEC_NCA1)
									WHEN ISNULL(DEC_NCA2, '') <> '' AND DEC_INA2 = 0 THEN (ISNULL(RIGHT(DEC_ACA2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(DEC_NCA2))) + DEC_NCA2)
									WHEN ISNULL(DEC_NCA3, '') <> '' AND DEC_INA3 = 0 THEN (ISNULL(RIGHT(DEC_ACA3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(DEC_NCA3))) + DEC_NCA3)
									WHEN ISNULL(DEC_NCA4, '') <> '' AND DEC_INA4 = 0 THEN (ISNULL(RIGHT(DEC_ACA4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(DEC_NCA4))) + DEC_NCA4)
									WHEN ISNULL(DEC_NCA5, '') <> '' AND DEC_INA5 = 0 THEN (ISNULL(RIGHT(DEC_ACA5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(DEC_NCA5))) + DEC_NCA5)
									ELSE NULL
								END), 
					@AnoNRG = (CASE 
									WHEN ISNULL(DEC_NCA1, '') <> '' AND DEC_INA1 = 0 THEN DEC_ACA1 
									WHEN ISNULL(DEC_NCA2, '') <> '' AND DEC_INA2 = 0 THEN DEC_ACA2
									WHEN ISNULL(DEC_NCA3, '') <> '' AND DEC_INA3 = 0 THEN DEC_ACA3 
									WHEN ISNULL(DEC_NCA4, '') <> '' AND DEC_INA4 = 0 THEN DEC_ACA4
									WHEN ISNULL(DEC_NCA5, '') <> '' AND DEC_INA5 = 0 THEN DEC_ACA5
									ELSE NULL
								END), 
					@TipoNRG = (CASE 
									WHEN ISNULL(DEC_NCA1, '') <> '' AND DEC_INA1 = 0 THEN DEC_TCA1
									WHEN ISNULL(DEC_NCA2, '') <> '' AND DEC_INA2 = 0 THEN DEC_TCA2
									WHEN ISNULL(DEC_NCA3, '') <> '' AND DEC_INA3 = 0 THEN DEC_TCA3 
									WHEN ISNULL(DEC_NCA4, '') <> '' AND DEC_INA4 = 0 THEN DEC_TCA4
									WHEN ISNULL(DEC_NCA5, '') <> '' AND DEC_INA5 = 0 THEN DEC_TCA5
									ELSE NULL
								END), 
					@CodAlfandegaNRG = (CASE 
											WHEN ISNULL(DEC_NCA1, '') <> '' AND DEC_INA1 = 0 THEN ALF_CODI1
											WHEN ISNULL(DEC_NCA2, '') <> '' AND DEC_INA2 = 0 THEN ALF_CODI2
											WHEN ISNULL(DEC_NCA3, '') <> '' AND DEC_INA3 = 0 THEN ALF_CODI3
											WHEN ISNULL(DEC_NCA4, '') <> '' AND DEC_INA4 = 0 THEN ALF_CODI4
											WHEN ISNULL(DEC_NCA5, '') <> '' AND DEC_INA5 = 0 THEN ALF_CODI5
											ELSE NULL
										END), 
					@CodigoAcessoNRG = (CASE 
											WHEN ISNULL(DEC_NCA1, '') <> '' AND DEC_INA1 = 0 THEN DEC_CCA1
											WHEN ISNULL(DEC_NCA2, '') <> '' AND DEC_INA2 = 0 THEN DEC_CCA2
											WHEN ISNULL(DEC_NCA3, '') <> '' AND DEC_INA3 = 0 THEN DEC_CCA3
											WHEN ISNULL(DEC_NCA4, '') <> '' AND DEC_INA4 = 0 THEN DEC_CCA4
											WHEN ISNULL(DEC_NCA5, '') <> '' AND DEC_INA5 = 0 THEN DEC_CCA5
											ELSE NULL
										END), 
					@OutrasReferenciasNRG = (CASE 
												WHEN ISNULL(DEC_NCA1, '') <> '' AND DEC_INA1 = 0 THEN DEC_OCA1
												WHEN ISNULL(DEC_NCA2, '') <> '' AND DEC_INA2 = 0 THEN DEC_OCA2
												WHEN ISNULL(DEC_NCA3, '') <> '' AND DEC_INA3 = 0 THEN DEC_OCA3
												WHEN ISNULL(DEC_NCA4, '') <> '' AND DEC_INA4 = 0 THEN DEC_OCA4
												WHEN ISNULL(DEC_NCA5, '') <> '' AND DEC_INA5 = 0 THEN DEC_OCA5
												ELSE NULL
											END), 
					@NIFResponsavel = NULL
				FROM TAB_DECL WITH(NOLOCK)
				WHERE DEC_CODI = @CodDeclarante
			END				
		END
		SET @NumeroNRGDireitos = @NumeroNRG
		SET @AnoNRGDireitos = @AnoNRG
		SET @TipoNRGDireitos = @TipoNRG
		SET @EntidadeNRGDireitos = @EntidadeNRG
		SET @CodAlfandegaNRGDireitos = @CodAlfandegaNRG
		SET @CodigoAcessoNRGDireitos = @CodigoAcessoNRG
		SET @OutrasReferenciasNRGDireitos = @OutrasReferenciasNRG
		SET @NIFResponsavelDireitos = @NIFResponsavel
		IF @BeneficiarioIVA = 0
		BEGIN
			SET @NumeroNRGIVA = @NumeroNRG
			SET @AnoNRGIVA = @AnoNRG
			SET @TipoNRGIVA = @TipoNRG
			SET @EntidadeNRGIVA = @EntidadeNRG
			SET @CodAlfandegaNRGIVA = @CodAlfandegaNRG
			SET @CodigoAcessoNRGIVA = @CodigoAcessoNRG
			SET @OutrasReferenciasNRGIVA = @OutrasReferenciasNRG
			SET @NIFResponsavelIVA = @NIFResponsavel
		END
		ELSE
		BEGIN
			SET @NumeroNRGIVA = NULL
			SET @AnoNRGIVA = NULL
			SET @TipoNRGIVA = NULL
			SET @EntidadeNRGIVA = NULL
			SET @CodAlfandegaNRGIVA = NULL
			SET @CodigoAcessoNRGIVA = NULL
			SET @OutrasReferenciasNRGIVA = NULL
			SET @NIFResponsavelIVA = NULL
		END
-- calcula os valores da adição		
		IF @NumAdicao IS NULL
			SET @NumAdicao = @TotalAdicoes + 1
		IF (@AnexoB IN ('H2', 'H3', 'I2')) AND (@PesoLiquido > 0)
			SET @PesoLiquido = 0
		IF (@AnexoB IN ('H6', 'I2')) AND (ISNULL(@Unidades, 0) > 0)
			SET @Unidades = 0	
		IF @AnexoB IN ('H1', 'H3', 'H4', 'H5')
			SET @MetodoAvaliacao = ISNULL(@MetodoAvaliacao, 1)
		ELSE
			SET @MetodoAvaliacao = NULL
		SET @Frete = ISNULL(@Frete, ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
											WHEN 0 THEN (@FreteTotal - @SomaFretesAdicoes) 
											ELSE (@PesoBruto * @FreteTotal / @MassaBrutaTotal) 
										END), 3))
		SET @Seguro = ISNULL(@Seguro, ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
												WHEN 0 THEN (@SeguroTotal - @SomaSegurosAdicoes) 
												ELSE (@Montante * @SeguroTotal / @MontanteTotal) 
											END), 3))
		SET @VerbaTransitario = ROUND((CASE (@MontanteTotal - @SomaMontantesAdicoes - @Montante) 
										WHEN 0 THEN (@VerbaTransitarioTotal - @SomaVerbasTransitarioAdicoes) 
										ELSE (@PesoBruto * @VerbaTransitarioTotal / @MassaBrutaTotal) 
									END), 3)		
		SET @ValorEUR = ROUND(@Montante / @CambioMontante, 2)
		SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro, @Frete, @Seguro, 0, 0, 0)
		SET @ValorEstatistico = dbo.fn_IMP_CalculaValorEstatistico(@ValorEUR, @Ajustamento)
		SET @ValorAduaneiro = @ValorEstatistico
		SET @Optativas = dbo.fn_IMP_CalculaValorOptativas(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodMeioTransporteChegada, @TotalAdicoes, @TotalVolumes, @TotalOptativas, @MassaBrutaTotal, @ValorAduaneiroTotal, @PesoBruto, @ValorAduaneiro)
		SET @BaseTributacaoDireitos = dbo.fn_IMP_CalculaBaseTributacaoDireitos(0, 0, @TipoTributacao, @PesoLiquido, @Unidades, @ValorEstatistico, @CodUnidMedida) 		                              
		SET @TaxaValorDireitos = dbo.fn_IMP_CalculaTaxaValorDireitos(@DataAtual, @CodArtigo, @CodPaisOrigem, NULL, @TaxaPreferencia, @Unidades, @Regime, @Desdobramento1) 
		SET @MontanteDireitos = dbo.fn_IMP_CalculaMontanteDireitos(0, 0, ~(@ArtigoTxComposta), @TaxaValorDireitos, @BaseTributacaoDireitos)
		SET @BaseTributacaoIVA = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, @Frete, @Ajustamento, @ValorEstatistico, @VerbaTransitario, @Optativas, @MontanteDireitos, 0, 0, 0)
		SET @MontanteIVA = ROUND(@BaseTributacaoIVA * @TaxaIVA / 100, 2)
		SET @QtdDireitos = dbo.fn_IMP_CalculaBaseTributacaoDireitos(0, 0, @TipoTributacao, @PesoLiquido, @Unidades, 0, @CodUnidMedida)
-- insere a adição
		INSERT INTO PRO_DUAD(DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, DUA_ML38, DUA_US41, USU_CO41, 
			DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_VEST, DUA_AJUS, DUA_DANO, DUA_VATO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, 
			DUA_BTIV, RRE_CODI, DUA_MPAG, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, PAI_NOME, PRE_NOME, USU_NOME, RRE_NOME, UME_NOTR, DUA_MTPR, DUA_QUAL, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, 
			DUA_R37C, DUA_2TAR, DUA_3TAR, DUA_MAVA, RRE_NOME1, DUA_IMPI, DUA_1TAR, DUA_4TAR, DUA_5TAR, id_desdobramento, APA_CCUS, DUA_TMER, DUA_QTDD, DUA_CAUC, DUA_CANO, DUA_CTIP, DUA_CENT, 
			DUA_CAUD, DUA_CAND, DUA_CTID, DUA_CEND, ALF_CODI, DUA_CCAD, DUA_CORD, DUA_CNRD, DUA_CAUI, DUA_CANI, DUA_CTII, DUA_CENI, ALF_CODI1, DUA_CCAI, DUA_CORI, DUA_CNRI)
		OUTPUT inserted.DUA_IDEN INTO @TblID
		VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodArtigo, @CodUnidMedida, @TaxaIVA, @TipoTributacao, @CodPaisOrigem, @PesoBruto, @CodPreferencia, @CodRubricaDireitos, @Regime, @Desdobramento1, @PesoLiquido, @Unidades, @CodUnidSuplementar, 
			@Montante, @Frete, @Seguro, @VerbaTransitario, 0, 0, 0, @Optativas, @Designacao, @ValorEstatistico, @Ajustamento, @AnoDeclaracao, @ValorAduaneiro, @BaseTributacaoDireitos, @ArtigoTxComposta, @TaxaValorDireitos, @MontanteDireitos, 0, 
			@BaseTributacaoIVA, @CodRubricaIVA, '0', 0, @MontanteIVA, @ValorEUR, @CodigoPautal, @NomePaisOrigem, @NomePreferencia, @NomeUnidSuplementar, @NomeRubricaIVA, @NomeUnidMedida, 0, 'X', @ImposicaoDireitos, @CodigoATAR, @AdicionalIVA, 0, 
			@Desdobramento2, @CodigoIC2, @CodigoIC3, @MetodoAvaliacao, @NomeRubricaDireitos, @ImposicaoIVA, @CodigoIC1, @CodigoIC4, @CodigoIC5, @IdDesdobramento, @CodigoCCUS, @TipoMercadoria, @QtdDireitos, @NumeroNRGDireitos, @AnoNRGDireitos, @TipoNRGDireitos, @EntidadeNRGDireitos, 
			@NumeroNRGDireitos, @AnoNRGDireitos, @TipoNRGDireitos, @EntidadeNRGDireitos, @CodAlfandegaNRGDireitos, @CodigoAcessoNRGDireitos, @OutrasReferenciasNRGDireitos, @NIFResponsavelDireitos, @NumeroNRGIVA, @AnoNRGIVA, @TipoNRGIVA, @EntidadeNRGIVA, @CodAlfandegaNRGIVA, @CodigoAcessoNRGIVA, @OutrasReferenciasNRGIVA, @NIFResponsavelIVA)
-- obtem o ID da nova adição
		SELECT @IdAdicao = ID
		FROM @TblID
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_AdicoesInsere] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_AdicoesInsere] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ConverteDAR]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ConverteDAR] @Id bigint, @IdUtilizador int, @IdDeclaracaoDAR int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracaoDAR xml(XMLSC_DeclaracoesDARToGIDWin)
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para declaração DAR a partir da declaração IMP-CAU
		SET @XMLDeclaracaoDAR = 
			(SELECT
				(SELECT 
					'I' AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data",
					(CASE duc.DUC_TPDS WHEN 0 THEN 3 ELSE 2 END) AS "regimeIVA",  
					'C07' AS "adicionalRegime", 
					NULLIF(nat.NDE_CODI3, '') AS "natureza", 
					NULLIF(duc.DUC_CPRT, '') AS "documentoTransporte",
					(SELECT 
						NULLIF(duc.DUC_ENIF, '') AS "nif", 
						NULLIF(duc.DUC_ENOM, '') AS "nome", 
						NULLIF(duc.DUC_EMOR, '') AS "morada", 
						NULLIF(duc.DUC_ELOC, '') AS "localidade", 
						NULLIF(duc.DUC_ECPO, '') AS "codigoPostal", 
						NULLIF(duc.DUC_ELPO, '') AS "localidadePostal", 
						NULLIF(duc.PAI_ELIV, '') AS "pais"
					HAVING ISNULL(duc.DUC_ENOM, '') <> ''
					FOR XML PATH('exportador'), TYPE),
					(SELECT 
						ISNULL(NULLIF(duc.DUC_DNIF, ''), '999999990') AS "nif", 
						NULLIF(duc.DUC_DNOM, '') AS "nome", 
						NULLIF(duc.DUC_DMOR, '') AS "morada", 
						NULLIF(duc.DUC_DLOC, '') AS "localidade", 
						NULLIF(duc.DUC_DCPO, '') AS "codigoPostal", 
						NULLIF(duc.DUC_DLPO, '') AS "localidadePostal", 
						NULLIF(duc.PAI_DLIV, '') AS "pais", 
						NULLIF(duc.DUC_DTEL, '') AS "telefone", 
						NULLIF(duc.DUC_DEMA, '') AS "email"					
					FOR XML PATH('importador'), TYPE),
					(SELECT 
						NULLIF(duc.DEC_CO14, '') AS "codigoDeclarante",					
						(CASE duc.DUC_TPDC WHEN 2 THEN 1 ELSE NULL END) AS "estatuto"
					FOR XML PATH('declarante'), TYPE),
					duc.ALF_CODI AS "estancia", 
					'A' AS "tipoDeclaracao", 
					NULLIF(duc.DUC_NVRF, '') AS "vossaReferencia", 
					NULLIF(duc.CEN_CO20, '') AS "condEntrega",
					NULLIF(duc.MTR_PT18, '') AS "meioTransporte", 
					(SELECT 						
						ISNULL(NULLIF(duc.DUC_TLOC, ''), (CASE alf.ALF_TLOC WHEN 'EA' THEN 'A' WHEN 'LA' THEN 'B' ELSE NULL END)) AS "tipoLocalizacao", 
						ISNULL(NULLIF(duc.DUC_QUAL, ''), (CASE alf.ALF_TLOC WHEN 'EA' THEN 'V' WHEN 'LA' THEN 'Y' ELSE NULL END)) AS "qualificador", 
						ISNULL(NULLIF(duc.LME_CO30, ''), (CASE WHEN (alf.ALF_TLOC = 'LA') AND (ISNULL(duc.DUC_QUAL, '') = '') THEN NULLIF(alf.LME_CODI, '') ELSE NULL END)) AS "armazemDTP", 
						ISNULL(NULLIF(duc.ALF_CODI1, ''), (CASE WHEN (alf.ALF_TLOC = 'EA') AND (ISNULL(duc.DUC_QUAL, '') = '') THEN duc.ALF_CODI ELSE NULL END)) AS "estancia"			
					FOR XML PATH('localizacaoMercadorias'), TYPE),
					NULLIF(duc.PAI_PR22, '') AS "paisMoedaFatura", 
					NULLIF(duc.PAI_FRET, '') AS "paisMoedaCustosTransporte", 	
					ISNULL(nda.FUP_CODI, duc.FUP_CODI) AS "followUp", 
					NULLIF(duc.DUC_UNMD, '') AS "utilizadorNomeado", 	
					duc.DUC_NPDT AS "depositoTemporario/numeroPDDT", 
					duc.DUC_NPDD AS "depositoTemporario/numeroPDDTDEV", 
					duc.DUC_NTDP AS "depositoTemporario/numeroTD", 
					duc.DUC_NACT AS "depositoTemporario/numeroACTM", 
					duc.DUC_NSEQ AS "depositoTemporario/numeroSequencia", 
					NULLIF(duc.DUC_DELG, '') AS "dadosEspecificos/locID", 
					NULLIF(duc.DUC_GTWY, '') AS "dadosEspecificos/gateway", 
					duc.DUC_NVSR AS "dadosEspecificos/serviceLevel", 
					NULLIF(duc.DUC_CIDE, '') AS "dadosEspecificos/portesAcc", 
					NULLIF(duc.DUC_POSA, '') AS "dadosEspecificos/portes", 
					NULLIF(duc.DUC_REF1, '') AS "dadosEspecificos/despachoAcc", 
					NULLIF(duc.DUC_VFRC, 0) AS "dadosEspecificos/freteOriginal", 
					NULLIF(duc.DUC_MFRC, '') AS "dadosEspecificos/moedafreteOriginal", 
					NULLIF(duc.DUC_VDES, 0) AS "dadosEspecificos/despesas", 
					NULLIF(duc.DUC_PPFC, '') AS "dadosEspecificos/condicaoEntrega", 
					NULLIF(duc.DUC_FUPS, '') AS "dadosEspecificos/nomeFicheiro", 
					NULLIF(duc.DUC_CIEX, '') AS "dadosEntidades/numeroContaExpedidor", 
					NULLIF(duc.DUC_CIDE, '') AS "dadosEntidades/numeroContaDestinatario", 
					NULLIF(duc.DUC_D2NO, '') AS "dadosEntidades/nomeOriginalDestinatario", 
					NULLIF(duc.DUC_D2MO, '') AS "dadosEntidades/moradaOriginalDestinatario", 
					NULLIF(duc.DUC_D2LO, '') AS "dadosEntidades/localidadeOriginalDestinatario", 
					NULLIF(duc.DUC_D2CP, '') AS "dadosEntidades/codigoPostalOriginalDestinatario", 
					NULLIF(duc.DUC_D2LP, '') AS "dadosEntidades/localidadePostalOriginalDestinatario", 
					NULLIF(duc.DUC_REF1, '') AS "dadosEntidades/referenciaExterna1", 
					NULLIF(duc.DUC_REF2, '') AS "dadosEntidades/referenciaExterna2", 
					NULLIF(duc.DUC_SHIP, '') AS "dadosEntidades/shipID", 
					NULLIF(duc.DUC_MCPA, '') AS "dadosAWB/miniCPA", 
					(CONVERT(varchar(10), duc.DUC_DTVO, 127) + 'Z') AS "dadosAWB/dataVoo", 
					NULLIF(duc.DUC_AERO, '') AS "dadosAWB/aeroportoOrigem", 
					NULLIF(duc.DUC_NVOO, '') AS "dadosAWB/numeroVoo", 
					NULLIF(duc.DUC_POSA, '') AS "dadosAWB/posicaoAviao", 
					NULLIF(duc.DUC_TRAC, '') AS "dadosAWB/tracking", 
					NULLIF(duc.DUC_TPCG, '') AS "dadosAWB/tipoCarga", 
					NULLIF(duc.DUC_DTYP, '') AS "outrosDados/dutyType", 
					NULLIF(duc.DUC_PAYM, '') AS "outrosDados/payment", 																					
					(SELECT 
						ddo.tipo AS "tipoDocumento", 
						doc.DOC_CODI AS "codigoDocumento",
						ISNULL(NULLIF(ddo.numero, ''), '*****N/A*****') AS "numeroDocumento"						
					FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY																	
					WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.origem IN (0, 13) -- 0: Manual; 13: Importação Ficheiro XLSX										
					FOR XML PATH('documento'), ROOT('documentosECertificados'), TYPE), 									
					(SELECT 
						doc.DOC_CODI AS "codigoDocumento", 
						dpr.numero AS "numeroDocumento"									
					FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
					WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY AND doc.DOC_CODI = 'N337' AND doc.DOC_CA40 = 1					
					FOR XML PATH('documentoPrecedente'), ROOT('documentosPrecedentes'), TYPE), 				
					(SELECT
						(SELECT 
							adi.DUA_CODI AS "numeroAdicao", 
							NULLIF(adi.APA_CP33, '') AS "codigoPautal", 
							NULLIF(adi.DUA_DESG, '') AS "designacao", 							
							NULLIF(adi.PAI_CO34, '') AS "paisOrigem",							
							CAST(adi.DUA_MB35 AS decimal(18, 6)) AS "massaBruta",														
							CAST(ISNULL(adi.DUA_US41, 0) AS decimal(18, 6)) AS "unidades",							
							(CASE adi.DUA_CODI WHEN 1 THEN CAST(duc.DUC_TVL6 AS int) ELSE 0 END) AS "volumes", 
							NULLIF(duc.PAI_PR22, '') AS "paisMoedaFatura", 
							CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "montante", 
							NULLIF(duc.PAI_FRET, '') AS "paisMoedaCustosTransporte", 
							CAST(ISNULL(adi.DUA_VFRE, 0) AS decimal(18, 2)) AS "custosTransporte", 
							(SELECT TOP 1 ISNULL(D31_LOPT, '') FROM PRO_DU31 WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI) AS "codigoBarras", 
							(SELECT TOP 1 ISNULL(D31_NUME, '') FROM PRO_DU31 WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI) AS "numeroObjeto"
						FROM PRO_DUAD AS adi WITH(NOLOCK) 
						WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE),		
					(SELECT 
						SIN_CODI AS "codigoIncidencia", 
						(CONVERT(varchar(23), CAST(CONVERT(varchar(10), DUI_DINI, 105) + ' ' + CONVERT(varchar(12), DUI_HINI, 114) AS datetime), 127) + 'Z') AS "dataInicio",
						(CONVERT(varchar(23), CAST(CONVERT(varchar(10), DUI_DFIM, 105) + ' ' + CONVERT(varchar(12), DUI_HFIM, 114) AS datetime), 127) + 'Z')AS "dataFim",	
						CAST(DUI_OBSR AS varchar(500)) AS "observacoes", 
						(CASE DUI_REHO WHEN 0 THEN 'R' WHEN 1 THEN 'H' ELSE NULL END) AS "tipoIncidencia"					
					FROM PRO_DUIN WITH(NOLOCK)
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM					
					FOR XML PATH('incidencia'), ROOT('incidencias'), TYPE),					
					(SELECT 
						DUO_TIPO AS "tipoManifesto", 
						NULLIF(PAI_CODI, '') AS "paisManifesto",
						NULLIF(RTRIM(LTRIM(DUO_DESC)), '') AS "descricao",	
						CAST(ISNULL(DUO_VALO, 0) AS decimal(18, 3)) AS "valor", 						
						SUBSTRING(NULLIF(DUO_MOED, ''), 1, 2) AS "paisMoedaManifesto",							
						CAST(ISNULL(DUO_TFAC, 0) AS decimal(18, 3)) AS "totalFatura",
						RTRIM(LTRIM(DUO_CPA2)) AS "numeroCPA", 
						CAST(ISNULL(DUO_PES2, 0) AS decimal(18, 3)) AS "peso"							
					FROM PRO_DUOD WITH(NOLOCK)
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND ISNULL(RTRIM(LTRIM(DUO_CPA2)), '') <> ''					
					FOR XML PATH('manifesto'), ROOT('manifestos'), TYPE),					
					(SELECT 
						FUP_CODI AS "codigoFollowUp", 
						UTI_UTIL AS "utilizadorFollowUp",							
						(CONVERT(varchar(23), DFW_DATA, 127) + 'Z') AS "dataFollowUp"							
					FROM PRO_DUFW WITH(NOLOCK)
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM										 
					FOR XML PATH('followUpData'), ROOT('followUps'), TYPE),					
					(SELECT 
						DCN_TEXT AS "descricaoContacto", 
						DCN_UCRI AS "utilizadorContacto",							
						(CONVERT(varchar(23), DCN_DTCR, 127) + 'Z') AS "dataContacto"							
					FROM PRO_DUCN WITH(NOLOCK)
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
					FOR XML PATH('contacto'), ROOT('contactos'), TYPE)
				FROM PRO_DUCG AS duc WITH(NOLOCK) 
					INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI	
					INNER JOIN TAB_NDES AS nda WITH(NOLOCK) ON nat.NDE_CODI3 = nda.NDE_CODI
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON duc.ALF_CODI = alf.ALF_CODI
				WHERE duc.DUC_IDTY = @Id
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesDARToGIDWin'), ELEMENTS)
-- processa a geração da declaração DAT
		SET @Erro = ''
		EXEC @NumErro = sp_DeclaracoesDAR_ImportaRegistosDeXML @XMLDeclaracaoDAR, @IdUtilizador, @Erro OUTPUT				
-- senão houver erros na geração, efetua processamentos finais
		IF @NumErro = 0
		BEGIN
			SET @IdDeclaracaoDAR = NULL
-- obtem o id da declaração DAR gerada
			SELECT @IdDeclaracaoDAR = id
			FROM tb_DeclaracoesDAR WITH(NOLOCK)
			WHERE ano = YEAR(@DataAtual) AND documentoTransporte = (SELECT DUC_CPRT FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_IDTY = @Id)
-- verifica se a declaração DAR foi corretamente gerada
			IF @IdDeclaracaoDAR IS NULL
				RAISERROR('Declaração DAR não foi gerada.', 16, 1)
-- atualiza o número dos documento automáticos de origem da alfândega
			UPDATE tb_DeclaracoesDARDocumentos SET numero = ISNULL(did.numero, '')
			FROM tb_DeclaracoesDARDocumentos AS ddd WITH(NOLOCK) 				
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS did WITH(NOLOCK) ON did.id_declaracaoIMP = @Id AND did.origem = 6 AND ddd.id_documento = did.id_documento
			WHERE ddd.id_declaracaoDAR = @IdDeclaracaoDAR AND ddd.origem = 1 AND ddd.numero <> ISNULL(did.numero, '')
-- remove o primeiro registo de follow-up criado pelo automatismo existente nos dados gerais das DAR p/ evitar duplicação
			DELETE FROM tb_DeclaracoesDARFollowUps
			WHERE id = (SELECT MIN(id) 
						FROM tb_DeclaracoesDARFollowUps WITH(NOLOCK) 
						WHERE id_declaracaoDAR = @IdDeclaracaoDAR)
-- remove a declaração IMP-CAU se for possível; caso contrário coloca a declaração IMP-CAU no status de "Anulado"
			BEGIN TRY
				DELETE FROM PRO_DUCG 
				WHERE DUC_IDTY = @Id
			END TRY
			BEGIN CATCH
				UPDATE PRO_DUCG SET DUC_CPRT = (DUC_CPRT + '_ANULADO'), DUC_STAT = 3 --Anulado
				WHERE DUC_IDTY = @Id
			END CATCH
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ConverteDAR] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ConverteDAR] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_DocumentosImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_DocumentosImportaXLSX] @IdDeclaracao bigint, @DataDeclaracao datetime, @IdDocumento int, @FicheiroXLSX varchar(MAX), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @FicheiroXML xml
-- inicia transacção para a inserção dos documentos
	BEGIN TRANSACTION TspIMPImportaXLSXDocumentos
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX	
-- insere os documentos do ficheiro como "Suporte" na declaração
		INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, dataValidade, origem, id_utilizadorControlo, dataControlo)
		SELECT @IdDeclaracao, 0, @IdDocumento, t.c.value('Numero[1]', 'varchar(70)'), CAST(NULLIF(t.c.value('Data[1]', 'varchar(10)'), '') AS datetime), 13, @IdUtilizador, @DataAtual
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 						
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPImportaXLSXDocumentos
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPImportaXLSXDocumentos
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_DocumentosImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_DocumentosImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_Duplica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_Duplica] @Id bigint, @NovoNumero int, @DuplicaOutrosIntervenientes bit, @DuplicaReferenciasFiscais bit, @DuplicaAcrescimosEDeducoes bit, 
	@DuplicaProprietarios bit, @DuplicaEstanciasApuramento bit, @DuplicaLocaisTransformacao bit, @DuplicaProdutosTransformados bit, @DuplicaIdentificacaoMercadorias bit, 
	@DuplicaTaxasRendimento bit, @DuplicaCondicoesEconomicas bit, @DuplicaDocumentos bit, @DuplicaPrecedentes bit, @DuplicaPedidos bit, @DuplicaAdicoes bit, @DuplicaImposicoes bit, 
	@DuplicaMarcasEVolumes bit, @DuplicaDocumentosAdicoes bit, @DuplicaPrecedentesAdicoes bit, @DuplicaPedidosAdicoes bit, @DuplicaContentores bit, @DuplicaReferenciasFiscaisAdicoes bit, 
	@DuplicaAcrescimosEDeducoesAdicoes bit, @DuplicaEntrepostosEAutorizacoes bit, @DuplicaVeiculos bit, @DuplicaChassis bit, @DuplicaMercadoriasIEC bit, @DuplicaTributacaoIEC bit, 
	@DuplicaElementosTributacao bit, @IdUtilizador int, @NovoId bigint OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID int NOT NULL, NUMERO int NOT NULL)
	DECLARE @TblRelacao table(ID_ORIGEM bigint NOT NULL, ID_DESTINO bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @Ano smallint, @Numero int, @NIFDeclarante varchar(17), @NRL varchar(22), @NovoAno smallint, 
		@NumAdicao int, @IdAdicao bigint, @NovoIdAdicao bigint, @UltCodTabela int
-- inicia transacção para duplicação da declaração IMP-CAU
	BEGIN TRANSACTION TspIMPDuplicacao
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem dados da declaração IMP-CAU de origem
		SELECT @Ano = DUC_EANO, @Numero = DUC_PNUM, @NIFDeclarante = DEC_NIF
		FROM PRO_DUCG WITH(NOLOCK)
		WHERE DUC_IDTY = @Id
-- calcula o ano da nova declaração
		IF (@Ano < YEAR(@DataAtual)) AND (EXISTS(SELECT EMP_CODI FROM GIDWIN.dbo.FAP_EANO WITH(NOLOCK) WHERE EMP_CODI = DB_NAME() and EAN_ANO = YEAR(@DataAtual)))		
			SET @NovoAno = YEAR(@DataAtual)
		ELSE
			SET @NovoAno = @Ano
-- obtem o número para a nova declaração
		SELECT @NovoNumero = (CASE PDE_NPRO WHEN 0 THEN ISNULL(@NovoNumero, 0) ELSE PDE_NPRO END)
		FROM TAB_PDES		
-- verifica se o número é válido
		IF @NovoNumero = 0
			RAISERROR('Número da declaração não foi especificado.', 16, 1)	
-- constroi NRL
		SET @NRL = RIGHT(STR(@NovoAno, 4), 2) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 9 - LEN(LTRIM(STR(@NovoNumero, 9)))) + LTRIM(STR(@NovoNumero, 9))
-- insere os dados gerais da nova declaração IMP-CAU
		INSERT INTO PRO_DUCG(DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, DUC_STAT, TDE_CODI, DUC_TIPO, ALF_CODI, DUC_ADI5, DUC_TVL6, DUC_REF7, DUC_EXP2, DUC_DST8, 
			DEC_CO14, PAI_PA15, PAI_P15A, PAI_PA16, PAI_PA17, PAI_P17A, PAI_P17B, MTR_PT18, DUC_MT18, DUC_OP18, DUC_CT18, MTR_FT21, PAI_PA21, DUC_CT19, CEN_CO20, DUC_FR20, 
			DUC_DE20, NTR_CO24, LME_CO30, DUC_LC30, PAI_PR22, DUC_MT22, DUC_TX23, DUC_FRET, PAI_FRET, DUC_TXFR, DUC_SEGU, PAI_SEGU, DUC_TXSE, DUC_MLQT, DUC_MBRT, DUC_VTRN, 
			PAI_VTRN, DUC_TXVT, DUC_VEUR, DUC_UFOB, DUC_VFOB, DUC_DIRT, DUC_TFDA, DUC_ENOM, DUC_EMOR, DUC_ELOC, DUC_ECPO, DUC_ELPO, DUC_ENIF, PAI_ELIV, DUC_DNOM, DUC_DMOR, 
			DUC_DLOC, DUC_DCPO, DUC_DLPO, DUC_DNIF, PAI_DLIV, DUC_HIST, DUC_VLRC, DUC_VLRE, DUC_VATT, DUC_UCRI, DUC_DTCR, DUC_UALT, DUC_DTAL, NDE_NOME, TDE_NOME, ALF_NOME, 
			PAI_NO15, PAI_NO16, PAI_NO17, PAI_MO22, PAI_MOFT, PAI_MOSG, PAI_MOVT, DEC_NOME, DEC_CENI, MTR_NO18, MTR_NO21, DUC_MASC, DUC_NREQ, DUC_NDUR, DUC_T1RE, DEC_CEDE, 
			DUC_CNOM, DUC_CMOR, DUC_CLOC, DUC_CCPO, DUC_CLPO, DUC_CNIF, PAI_CLIV, DUC_FUNC, DUC_DCED, DUC_DTVO, DUC_PAYM, DUC_PARM, DUC_NVRF, DUC_TREM, DUC_CIEX, DUC_CIDE, 
			DUC_AERO, DUC_PPFC, DUC_NVOO, DUC_MCPA, DUC_REF1, DUC_REF2, DUC_SHIP, DUC_TRAC, DUC_DTYP, DUC_POSA, DUC_TPCG, DUC_VDIR, DUC_VCLE, FIN_CODI, DUC_ARTI, DUC_TPDS, 
			DUC_TPDC, TDE_1CAS, TDE_2CAS, DUC_GTWY, DUC_DELG, DUC_TMSF, TDO_DOCU, CLI_CODI, CLI_NOME, DUC_CGLB, DUC_CAUC, DUC_CANO, DUC_CTIP, DUC_TLOC, ALF_CODI1, ALF_NOME1, 
			DUC_LAMO, DUC_LALO, DUC_LACP, ARM_CODI, ARM_NOME, TAR_CODI, TAR_DESC, DUC_NRLO, DUC_DUNO, DUC_CENT, NTR_NOME, DUC_VBAT, DUC_VSCA, DUC_VFRC, DUC_MFRC, DUC_NVSR, 
			DUC_COBR, DUC_BIVA, DUC_VDES, DUC_DTEL, DUC_DEMA, DUC_DCEN, DUC_ANXB, DUC_DGEN, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, FOR_NIF, PAI_CODI, 
			CLI_CODI1, CLI_NOME1, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_NIF, PAI_CODI1, DEC_NIF, DUC_CNIR, ALF_CODI2, DUC_CCAC, DUC_CORF, ALF_CODI3, ALF_CODI4, 
			PAI_CODI2, PAE_CODI, MTR_CODI, MTR_TIPO, DUC_CONT, DUC_QUAL, DUC_IADI, DUC_ONIF, DOC_CODI, DUC_NRAU, DUC_EORI, DUC_REGI, DUC_SERV, DUC_ATLO, DUC_AQUA, LME_CODI, 
			DUC_AMOR, DUC_ALOC, DUC_ACPO, PAI_CODI3, DUC_APRZ, DUC_APPR, DUC_ATXT, DUC_AAPR, DUC_AIAD, DUC_ACMD)	
		OUTPUT inserted.DUC_IDTY, inserted.DUC_PNUM INTO @TblID
		SELECT @NovoNumero, @NovoAno, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), NDE_CODI, DUC_CPRT, 0, TDE_CODI, DUC_TIPO, ALF_CODI, 0, 0, DUC_REF7, DUC_EXP2, DUC_DST8, 
			DEC_CO14, PAI_PA15,	PAI_P15A, PAI_PA16, PAI_PA17, PAI_P17A, PAI_P17B, MTR_PT18, DUC_MT18, DUC_OP18, DUC_CT18, MTR_FT21, PAI_PA21, DUC_CT19, CEN_CO20, DUC_FR20, 
			DUC_DE20, NTR_CO24, LME_CO30, DUC_LC30, PAI_PR22, DUC_MT22, DUC_TX23, DUC_FRET, PAI_FRET, DUC_TXFR, DUC_SEGU, PAI_SEGU, DUC_TXSE, DUC_MLQT, DUC_MBRT, DUC_VTRN, 
			PAI_VTRN, DUC_TXVT, DUC_VEUR, DUC_UFOB, DUC_VFOB, DUC_DIRT, DUC_TFDA, DUC_ENOM, DUC_EMOR, DUC_ELOC, DUC_ECPO, DUC_ELPO, DUC_ENIF, PAI_ELIV, DUC_DNOM, DUC_DMOR, 
			DUC_DLOC, DUC_DCPO, DUC_DLPO, DUC_DNIF, PAI_DLIV, DUC_HIST, 0, 'Zero euros', 0, @CodUtilizador, @DataAtual, @CodUtilizador, @DataAtual, NDE_NOME, TDE_NOME, ALF_NOME, 
			PAI_NO15, PAI_NO16, PAI_NO17, PAI_MO22, PAI_MOFT, PAI_MOSG, PAI_MOVT, DEC_NOME, DEC_CENI, MTR_NO18, MTR_NO21, DUC_MASC, DUC_NREQ, DUC_NDUR, DUC_T1RE, DEC_CEDE, 
			DUC_CNOM, DUC_CMOR, DUC_CLOC, DUC_CCPO, DUC_CLPO, DUC_CNIF, PAI_CLIV, DUC_FUNC, DUC_DCED, (CASE WHEN DUC_DTVO IS NULL THEN NULL ELSE CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime) END), DUC_PAYM, DUC_PARM, DUC_NVRF, DUC_TREM, DUC_CIEX, DUC_CIDE, 
			DUC_AERO, DUC_PPFC, DUC_NVOO, DUC_MCPA, DUC_REF1, DUC_REF2, DUC_SHIP, DUC_TRAC, DUC_DTYP, DUC_POSA, DUC_TPCG, 0, 0, FIN_CODI, DUC_ARTI, DUC_TPDS, 
			DUC_TPDC, TDE_1CAS, TDE_2CAS, DUC_GTWY, DUC_DELG, DUC_TMSF, TDO_DOCU, CLI_CODI, CLI_NOME, DUC_CGLB, DUC_CAUC, DUC_CANO, DUC_CTIP, DUC_TLOC, ALF_CODI1, ALF_NOME1, 
			DUC_LAMO, DUC_LALO, DUC_LACP, ARM_CODI, ARM_NOME, TAR_CODI, TAR_DESC, @NRL, DUC_DUNO, DUC_CENT, NTR_NOME, DUC_VBAT, 0, DUC_VFRC, DUC_MFRC, DUC_NVSR, 
			DUC_COBR, DUC_BIVA, DUC_VDES, DUC_DTEL, DUC_DEMA, DUC_DCEN, DUC_ANXB, DUC_DGEN, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, FOR_NIF, PAI_CODI, 
			CLI_CODI1, CLI_NOME1, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_NIF, PAI_CODI1, DEC_NIF, DUC_CNIR, ALF_CODI2, DUC_CCAC, DUC_CORF, ALF_CODI3, ALF_CODI4, 
			PAI_CODI2, PAE_CODI, MTR_CODI, MTR_TIPO, DUC_CONT, DUC_QUAL, DUC_IADI, DUC_ONIF, DOC_CODI, DUC_NRAU, DUC_EORI, DUC_REGI, DUC_SERV, DUC_ATLO, DUC_AQUA, LME_CODI, 
			DUC_AMOR, DUC_ALOC, DUC_ACPO, PAI_CODI3, DUC_APRZ, DUC_APPR, DUC_ATXT, DUC_AAPR, DUC_AIAD, DUC_ACMD
		FROM PRO_DUCG WITH(NOLOCK)
		WHERE DUC_IDTY = @Id
-- obtem o ID da nova declaração IMP-CAU
		SELECT @NovoId = ID , @NovoNumero = NUMERO
		FROM @TblID
-- gere o detalhe de outros intervenientes na nova declaração IMP-CAU
		IF @DuplicaOutrosIntervenientes = 1
		BEGIN
-- remove o detalhe de outros intervenientes já criado por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesIntervenientes
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de outros intervenientes na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesIntervenientes(id_declaracaoIMP, funcao, nif, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, funcao, nif, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesIntervenientes WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END
-- gere o detalhe de referências fiscais na nova declaracao IMP-CAU
		IF @DuplicaReferenciasFiscais = 1
		BEGIN
-- remove o detalhe de referências fiscais já criado por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesReferenciasFiscais
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de referências fiscais na nova declaracao IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesReferenciasFiscais(id_declaracaoIMP, funcao, nif, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, funcao, nif, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesReferenciasFiscais WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id 
		END
-- insere o detalhe de acréscimos e deduções na nova declaracao IMP-CAU
		IF @DuplicaAcrescimosEDeducoes = 1
		BEGIN
-- remove o detalhe de acréscimos e deduções já criado por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesAcrescimosDeducoes
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de acréscimos e deduções na nova declaracao IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesAcrescimosDeducoes(id_declaracaoIMP, tipo, codigo, montante, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, tipo, codigo, montante, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesAcrescimosDeducoes WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id 
		END
-- gere o detalhe de proprietários das mercadorias na nova declaração IMP-CAU
		IF @DuplicaProprietarios = 1
		BEGIN
-- remove o detalhe de proprietários das mercadorias já criados por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesProprietarios
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de proprietários das mercadorias na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesProprietarios(id_declaracaoIMP, id_cliente, nome, morada, localidade, codigoPostal, id_pais, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_cliente, nome, morada, localidade, codigoPostal, id_pais, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesProprietarios WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END
-- gere o detalhe de estâncias de apuramento na nova declaração IMP-CAU
		IF @DuplicaEstanciasApuramento = 1
		BEGIN
-- remove o detalhe de estâncias de apuramento já criadas por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesEstancias
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de estâncias de apuramento na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesEstancias(id_declaracaoIMP, id_estancia, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_estancia, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesEstancias WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END
-- gere o detalhe de locais de transformação na nova declaração IMP-CAU
		IF @DuplicaLocaisTransformacao = 1
		BEGIN
-- remove o detalhe de locais de transformação já criados por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesLocaisTransformacao
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de locais de transformação na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesLocaisTransformacao(id_declaracaoIMP, tipo, qualificador, id_localAutorizado, morada, localidade, codigoPostal, id_pais, origem, id_utilizadorControlo, 
				dataControlo)
			SELECT @NovoId, tipo, qualificador, id_localAutorizado, morada, localidade, codigoPostal, id_pais, origem, @IdUtilizador, 
				@DataAtual
			FROM tb_IMP_DeclaracoesLocaisTransformacao WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END		
-- gere o detalhe de produtos transformados na nova declaração IMP-CAU
		IF @DuplicaProdutosTransformados = 1
		BEGIN
-- remove o detalhe de produtos transformados já criados por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesProdutosTransformados
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de produtos transformados na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesProdutosTransformados(id_declaracaoIMP, id_artigo, codigoPautal, designacao, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_artigo, codigoPautal, designacao, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesProdutosTransformados WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END	
-- gere o detalhe de identificação das mercadorias na nova declaração IMP-CAU
		IF @DuplicaIdentificacaoMercadorias = 1
		BEGIN
-- remove o detalhe de identificação das mercadorias já criadas por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesMeiosIdentificacao
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de identificação das mercadorias na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesMeiosIdentificacao(id_declaracaoIMP, id_meioIdentificacao, descricao, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_meioIdentificacao, descricao, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesMeiosIdentificacao WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END		
-- gere o detalhe de taxas de rendimento na nova declaração IMP-CAU
		IF @DuplicaTaxasRendimento = 1
		BEGIN
-- remove o detalhe de taxas de rendimento já criadas por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesTaxasRendimento
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de taxas de rendimento na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesTaxasRendimento(id_declaracaoIMP, taxaRendimento, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, taxaRendimento, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesTaxasRendimento WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END						
-- gere o detalhe de condições económicas na nova declaração IMP-CAU
		IF @DuplicaCondicoesEconomicas = 1
		BEGIN
-- remove o detalhe de condições económicas já criadas por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesCondicoesEconomicas
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de condições económicas na nova declaração IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesCondicoesEconomicas(id_declaracaoIMP, codigo, texto, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, codigo, texto, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesCondicoesEconomicas WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id
		END				   
-- gere o detalhe de pedidos na nova declaracao IMP-CAU
		IF @DuplicaPedidos = 1
		BEGIN
-- remove o detalhe de pedidos já criado por algum automatismo da nova declaração IMP-CAU
			DELETE FROM PRO_DUPD
			WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero						
-- insere o detalhe de pedidos na nova declaracao IMP-CAU
			INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC, DPD_QUAL, DPD_ORIG)
			SELECT @NovoAno, @NovoNumero, DPD_CODI, TXM_CODI, DPD_DESC, DPD_QUAL, DPD_ORIG
			FROM PRO_DUPD WITH(NOLOCK)				
			WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero
			ORDER BY DPD_CODI
		END
-- gere o detalhe de documentos e certificados na nova declaracao IMP-CAU
		IF @DuplicaDocumentos = 1
		BEGIN
-- remove o detalhe de documentos e certificados já criado por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesDocumentos
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de documentos e certificados na nova declaracao IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, qualificador, dataValidade, id_paisMoeda, montante, entidadeEmissora, 
				id_unidadeMedida, quantidade, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, tipo, id_documento, numero, qualificador, dataValidade, id_paisMoeda, montante, entidadeEmissora, 
				id_unidadeMedida, quantidade, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesDocumentos WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id 
		END
-- gere o detalhe de documentos precedentes na nova declaracao IMP-CAU
		IF @DuplicaPrecedentes = 1
		BEGIN
-- remove o detalhe de documentos precedentes já criado por algum automatismo da nova declaração IMP-CAU
			DELETE FROM tb_IMP_DeclaracoesPrecedentes
			WHERE id_declaracaoIMP = @NovoId
-- insere o detalhe de documentos precedentes na nova declaracao IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesPrecedentes(id_declaracaoIMP, id_documento, numero, qualificador, dataContramarca, origem, id_utilizadorControlo, dataControlo)
			SELECT @NovoId, id_documento, numero, qualificador, dataContramarca, origem, @IdUtilizador, @DataAtual
			FROM tb_IMP_DeclaracoesPrecedentes WITH(NOLOCK)
			WHERE id_declaracaoIMP = @Id	
		END
-- obtem o detalhe de adições na declaracao de origem
		IF @DuplicaAdicoes = 1 
		BEGIN
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT DUA_CODI, DUA_IDEN
				FROM PRO_DUAD WITH(NOLOCK)
				WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero
			OPEN Adicoes
			FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdAdicao
			WHILE @@FETCH_STATUS = 0
			BEGIN	
-- remove o ID existente
				DELETE FROM @TblID									
-- insere a adição na nova declaracao IMP-CAU				
				INSERT INTO PRO_DUAD(DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, DUA_ML38, 
					DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_CAUC, DUA_CANO, DUA_CTIP, 
					DUA_CENT, DUA_VEST, DUA_AJUS, DUA_DANO, DUA_VATO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, DUA_VSEL, DUA_VIVA, 
					DUA_VAEU, APA_CP33, PAI_NOME, PRE_NOME, USU_NOME, RRE_NOME, UME_NOTR, DUA_MTPR, DUA_QUAL, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, DUA_2TAR, 
					DUA_3TAR, DUA_MAVA, RRE_NOME1, DUA_BMAN, DUA_CAUD, DUA_CAND, DUA_CTID, DUA_CEND, DUA_IMPI, DUA_CAUI, DUA_CANI, DUA_CTII, DUA_CENI, DUA_1TAR, DUA_ABTI, 
					DUA_4TAR, DUA_5TAR, id_desdobramento, APA_CCUS, NTR_CODI, DUA_NRUR, DUA_TMER, DUA_IAVA, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, 
					FOR_NIF, PAI_CODI, PAI_CODI1, PAI_CODI2, RES_CODI, FOR_CODI1, FOR_NOME1, FOR_MORA1, FOR_LOCA1, FOR_CPOS1, FOR_LPOS1, FOR_NIF1, PAI_CODI3, CLI_CODI, 
					CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_NIF, PAI_CODI4, DUA_ACRE, DUA_DEDU, DUA_CNRD, ALF_CODI, DUA_CCAD, DUA_CORD, DUA_CNRI, ALF_CODI1, DUA_CCAI, 
					DUA_CORI, DUA_MIVI, DUA_QTDD, PAI_CODI5)
				OUTPUT inserted.DUA_IDEN, inserted.DUA_CODI INTO @TblID
				SELECT @NovoAno, @NovoNumero, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, DUA_ML38, 
					DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_CAUC, DUA_CANO, DUA_CTIP, 
					DUA_CENT, DUA_VEST, DUA_AJUS, DUA_DANO, DUA_VATO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, DUA_VSEL, DUA_VIVA, 
					DUA_VAEU, APA_CP33, PAI_NOME, PRE_NOME, USU_NOME, RRE_NOME, UME_NOTR, DUA_MTPR, DUA_QUAL, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, DUA_2TAR, 
					DUA_3TAR, DUA_MAVA, RRE_NOME1, DUA_BMAN, DUA_CAUD, DUA_CAND, DUA_CTID, DUA_CEND, DUA_IMPI, DUA_CAUI, DUA_CANI, DUA_CTII, DUA_CENI, DUA_1TAR, DUA_ABTI, 
					DUA_4TAR, DUA_5TAR, id_desdobramento, APA_CCUS, NTR_CODI, DUA_NRUR, DUA_TMER, DUA_IAVA, FOR_CODI, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, 
					FOR_NIF, PAI_CODI, PAI_CODI1, PAI_CODI2, RES_CODI, FOR_CODI1, FOR_NOME1, FOR_MORA1, FOR_LOCA1, FOR_CPOS1, FOR_LPOS1, FOR_NIF1, PAI_CODI3, CLI_CODI, 
					CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_NIF, PAI_CODI4, 0, 0, DUA_CNRD, ALF_CODI, DUA_CCAD, DUA_CORD, DUA_CNRI, ALF_CODI1, DUA_CCAI, 
					DUA_CORI, 0, DUA_QTDD, PAI_CODI5
				FROM PRO_DUAD WITH(NOLOCK)
				WHERE DUA_IDEN = @IdAdicao				
-- obtem o ID da nova adição
				SELECT @NovoIdAdicao = ID 
				FROM @TblID
-- gere o detalhe de marcas e volumes na nova adição
				IF @DuplicaMarcasEVolumes = 1 
				BEGIN
-- remove o detalhe de marcas e volumes já criado por algum automatismo da nova adição
					DELETE FROM PRO_DU31
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao
-- insere o detalhe de marcas e volumes na nova adição (excepto os registos originados do sub-detalhe de Matrículas/Chassis)
					INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_CASR, D31_CASC, D31_TTVL, 
						D31_AUTO, D31_LOPT)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_CASR, D31_CASC, D31_TTVL, 
						D31_AUTO, D31_LOPT
					FROM PRO_DU31 WITH(NOLOCK) 
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao AND D31_AUTO <> 2
					ORDER BY D31_CODI
				END
-- gere o detalhe de veículos na nova adição
				IF @DuplicaVeiculos = 1 
				BEGIN			
-- remove o detalhe de veículos já criado por algum automatismo da nova adição
					DELETE FROM PRO_DUBT
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao	
-- insere o detalhe de veículos na nova adição						
					INSERT INTO PRO_DUBT(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, 
						DBT_AUTO, DBT_VLIA, DBT_MARC, DBT_MODE, DBT_CODR, DBT_IDCR, HTE_CODI, DBT_HOMO, DBT_TABE, DBT_TCO2, DBT_AUTN, DBT_DIMT)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DBT_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, 
						DBT_AUTO, DBT_VLIA, DBT_MARC, DBT_MODE, DBT_CODR, REPLACE(CONVERT(numeric(38, 10), DATEADD(MS, (DBT_CODI * 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())), '.', ','), HTE_CODI, DBT_HOMO, DBT_TABE, DBT_TCO2, DBT_AUTN, DBT_DIMT
					FROM PRO_DUBT WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
					ORDER BY DBT_CODI
				END
-- gere o detalhe de chassis na nova adição
				IF @DuplicaChassis = 1 
				BEGIN		
-- remove o detalhe de chassis já criado por algum automatismo da nova adição
					DELETE FROM PRO_DUVE
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao	
-- insere o detalhe de chassis na nova adição							
					INSERT INTO PRO_DUVE(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS, DVC_DMAT, DVC_DCHA)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS, DVC_DMAT, DVC_DCHA
					FROM PRO_DUVE WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
					ORDER BY DBT_CODI, DVC_CODI
				END
-- gere o detalhe de mercadorias IEC na nova adição
				IF @DuplicaMercadoriasIEC = 1 
				BEGIN	
-- remove o detalhe de mercadorias IEC já criado por algum automatismo da nova adição
					DELETE FROM PRO_DUMI
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao	
-- insere o detalhe de mercadorias IEC na nova adição								
					INSERT INTO PRO_DUMI(DUC_EANO, DUC_PNUM, DUA_CODI, DMI_CODI, DMI_TIPO, DMI_AIEC, DMI_MARC, DMI_CAPA, DMI_NEMB, DMI_TEOR, TEM_CODI, DMI_CPED, DMI_TABH, 
						DMI_SELA)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DMI_CODI, DMI_TIPO, DMI_AIEC, DMI_MARC, DMI_CAPA, DMI_NEMB, DMI_TEOR, TEM_CODI, DMI_CPED, DMI_TABH, 
						DMI_SELA
					FROM PRO_DUMI WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao 
					ORDER BY DMI_CODI
				END
-- gere o detalhe de pedidos na nova adição
				IF @DuplicaPedidosAdicoes = 1
				BEGIN	
-- remove o detalhe de pedidos já criado por algum automatismo da nova adição
					DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de pedidos na nova adição						
					INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo, id_mercadoriaIEC, id_chassi)
					SELECT @NovoIdAdicao, dap.id_pedido, dap.numero, dap.origem, @IdUtilizador, @DataAtual, nve.DBT_IDEN, nmi.DMI_IDEN, nch.DVC_IDEN
					FROM tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK)
						LEFT OUTER JOIN PRO_DUBT AS dve WITH(NOLOCK) ON dap.id_veiculo = dve.DBT_IDEN
						LEFT OUTER JOIN PRO_DUBT AS nve WITH(NOLOCK) ON nve.DUC_EANO = @NovoAno AND nve.DUC_PNUM = @NovoNumero AND dve.DUA_CODI = nve.DUA_CODI AND dve.DBT_CODI = nve.DBT_CODI
						LEFT OUTER JOIN PRO_DUMI AS dmi WITH(NOLOCK) ON dap.id_mercadoriaIEC = dmi.DMI_IDEN
						LEFT OUTER JOIN PRO_DUMI AS nmi WITH(NOLOCK) ON nmi.DUC_EANO = @NovoAno AND nmi.DUC_PNUM = @NovoNumero AND dmi.DUA_CODI = nmi.DUA_CODI AND dmi.DMI_CODI = nmi.DMI_CODI
						LEFT OUTER JOIN PRO_DUVE AS dch WITH(NOLOCK) ON dap.id_chassi = dch.DVC_IDEN
						LEFT OUTER JOIN PRO_DUVE AS nch WITH(NOLOCK) ON nch.DUC_EANO = @NovoAno AND nch.DUC_PNUM = @NovoNumero AND dch.DUA_CODI = nch.DUA_CODI AND dch.DBT_CODI = nch.DBT_CODI AND dch.DVC_CODI = nch.DVC_CODI
					WHERE dap.id_adicao = @IdAdicao
				END
-- gere o detalhe de documentos e certificados na nova adição
				IF @DuplicaDocumentosAdicoes = 1
				BEGIN			
-- remove o detalhe de documentos e certificados já criado por algum automatismo da nova adição
					DELETE FROM PRO_DDOC
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao									
-- insere o detalhe de documentos e certificados na nova adição
					INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_NINV, DDO_AUTO, 
						DDO_TIPO, DDO_EEMI, UME_CODI, DDO_QTDE, DDO_DEST)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_NINV, DDO_AUTO, 
						DDO_TIPO, DDO_EEMI, UME_CODI, DDO_QTDE, DDO_DEST
					FROM PRO_DDOC WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
					ORDER BY DDO_CODI						
				END
-- gere o detalhe de documentos precedentes na nova adição
				IF @DuplicaPrecedentesAdicoes = 1
				BEGIN		
-- remove o detalhe de documentos precedentes já criado por algum automatismo da nova adição
					DELETE FROM tb_IMP_DeclaracoesAdicoesPrecedentes
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de documentos precedentes na nova adição															
					INSERT INTO tb_IMP_DeclaracoesAdicoesPrecedentes(id_adicao, id_documento, numero, id_unidadeMedidaVolumes, volumes, id_unidadeMedidaQualificador, 
						quantidade, numeroAdicao, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, id_documento, numero, id_unidadeMedidaVolumes, volumes, id_unidadeMedidaQualificador, 
						quantidade, numeroAdicao, origem, @IdUtilizador, @DataAtual
					FROM tb_IMP_DeclaracoesAdicoesPrecedentes WITH(NOLOCK)
					WHERE id_adicao = @IdAdicao						
				END
-- gere o detalhe de contentores na nova adição
				IF @DuplicaContentores = 1 
				BEGIN
-- remove o detalhe de contentores já criado por algum automatismo da nova adição
					DELETE FROM PRO_DCON
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao	
-- insere o detalhe de contentores na nova adição
					INSERT INTO PRO_DCON(DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DCO_CODI, DCO_CNUM, DCO_TIPO
					FROM PRO_DCON WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao
					ORDER BY DCO_CODI
				END
-- gere o detalhe de referências fiscais na nova adição
				IF @DuplicaReferenciasFiscaisAdicoes = 1 
				BEGIN
-- remove o detalhe de referências fiscais já criado por algum automatismo da nova adição
					DELETE FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de referências fiscais na nova adição
					INSERT INTO tb_IMP_DeclaracoesAdicoesReferenciasFiscais(id_adicao, funcao, nif, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, funcao, nif, origem, @IdUtilizador, @DataAtual
					FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais WITH(NOLOCK)
					WHERE id_adicao = @IdAdicao
				END
-- gere o detalhe de acréscimos e deduções na nova adição
				IF @DuplicaAcrescimosEDeducoesAdicoes = 1 
				BEGIN
-- remove o detalhe de acréscimos e deduções já criado por algum automatismo da nova adição
					DELETE FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de acréscimos e deduções na nova adição
					INSERT INTO tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes(id_adicao, tipo, codigo, montante, origem, id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, tipo, codigo, montante, origem, @IdUtilizador, @DataAtual
					FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK)
					WHERE id_adicao = @IdAdicao
				END
-- gere o detalhe de entrepostos e autorizações na nova adição
				IF @DuplicaEntrepostosEAutorizacoes = 1 
				BEGIN
-- remove o detalhe de entrepostos e autorizações já criado por algum automatismo da nova adição
					DELETE FROM tb_IMP_DeclaracoesAdicoesEntrepostos
					WHERE id_adicao = @NovoIdAdicao	
-- insere o detalhe de entrepostos e autorizações na nova adição
					INSERT INTO tb_IMP_DeclaracoesAdicoesEntrepostos(id_adicao, id_armazem, id_tipoArmazem, id_documento, numeroReferencia, numeroEORI, origem, 
						id_utilizadorControlo, dataControlo)
					SELECT @NovoIdAdicao, id_armazem, id_tipoArmazem, id_documento, numeroReferencia, numeroEORI, origem, 
						@IdUtilizador, @DataAtual
					FROM tb_IMP_DeclaracoesAdicoesEntrepostos WITH(NOLOCK)
					WHERE id_adicao = @IdAdicao
				END
-- gere o detalhe de tributação IEC na nova adição
				IF @DuplicaTributacaoIEC = 1 
				BEGIN	
-- remove o detalhe de tributação IEC já criado por algum automatismo da nova adição
					DELETE FROM PRO_DUIT
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao
-- insere o detalhe de tributação IEC na nova adição
					INSERT INTO PRO_DUIT(DUC_EANO, DUC_PNUM, DUA_CODI, DMI_CODI, DIT_CODI, UME_CODI, UME_COD2, UME_NOME, DIT_QTDE, RRE_CODI, RRE_NOME, DIT_IMPO, DIT_TAXA, 
						DIT_TXVL, DIT_IDST)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, DMI_CODI, DIT_CODI, UME_CODI, UME_COD2, UME_NOME, DIT_QTDE, RRE_CODI, RRE_NOME, DIT_IMPO, DIT_TAXA, 
						DIT_TXVL, REPLACE(CONVERT(numeric(38, 10), DATEADD(MS, (DIT_CODI * 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())), '.', ',')
					FROM PRO_DUIT WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @NumAdicao 
					ORDER BY DMI_CODI, DIT_CODI
				END
-- gere o detalhe de elementos p/ tributação na nova adição
				IF @DuplicaElementosTributacao = 1 
				BEGIN
-- remove o detalhe de elementos p/ tributação já criado por algum automatismo da nova adição
					DELETE FROM PRO_DUET
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao
-- insere o detalhe de elementos p/ tributação na nova adição
					INSERT INTO PRO_DUET(DUC_EANO, DUC_PNUM, DUA_CODI, DET_CODI, DET_TIPO, DET_CIEC, UME_CODI, UME_COD2, DET_QTDE, DET_AUTO, DIT_IDST, RRE_CODI, RRE_NOME, 
						DET_IMPO, DET_TAXA, DET_TXVL, DET_IDST)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, det.DET_CODI, det.DET_TIPO, det.DET_CIEC, det.UME_CODI, det.UME_COD2, det.DET_QTDE, det.DET_AUTO, nit.DIT_IDST, det.RRE_CODI, det.RRE_NOME, 
						det.DET_IMPO, det.DET_TAXA, det.DET_TXVL, REPLACE(CONVERT(numeric(38, 10), DATEADD(MS, (det.DET_CODI * 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())), '.', ',')
					FROM PRO_DUET AS det WITH(NOLOCK)
						LEFT OUTER JOIN PRO_DUIT AS dit WITH(NOLOCK) ON det.DUC_EANO = dit.DUC_EANO AND det.DUC_PNUM = dit.DUC_PNUM AND det.DUA_CODI = dit.DUA_CODI AND det.DET_AUTO = 1 AND det.DIT_IDST = dit.DIT_IDST
						LEFT OUTER JOIN PRO_DUIT AS nit WITH(NOLOCK) ON nit.DUC_EANO = @NovoAno AND nit.DUC_PNUM = @NovoNumero AND dit.DUA_CODI = nit.DUA_CODI AND dit.DMI_CODI = nit.DMI_CODI AND dit.DIT_CODI = nit.DIT_CODI
					WHERE det.DUC_EANO = @Ano AND det.DUC_PNUM = @Numero AND det.DUA_CODI = @NumAdicao
					ORDER BY det.DET_CODI
				END
-- gere o detalhe de outras imposições na nova adição
				IF @DuplicaImposicoes = 1
				BEGIN				
-- remove o detalhe de outras imposições já criado por algum automatismo da nova adição
					ALTER TABLE PRO_DUOI DISABLE TRIGGER TAD_PRO_DUOI_IMPCAU
					DELETE FROM PRO_DUOI
					WHERE DUC_EANO = @NovoAno AND DUC_PNUM = @NovoNumero AND DUA_CODI = @NumAdicao
					ALTER TABLE PRO_DUOI ENABLE TRIGGER TAD_PRO_DUOI_IMPCAU
-- insere o detalhe de outras imposições na nova adição							
					INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_AGRO, RRE_LIVA, 
						DUO_IMPO, DUO_AUTO, DUO_BMAN, DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT, DET_IDST, DUO_DEST, DUO_MTAG, ALF_CODI, DUO_CCAC, DUO_CORF, DUO_CNRD, DUO_QTDE)
					SELECT @NovoAno, @NovoNumero, @NumAdicao, doi.DUO_CODI, doi.RRE_CODI, doi.RRE_NOME, doi.DUO_TIPO, doi.UME_CODI, doi.DUO_BTRI, doi.DUO_TXVL, doi.DUO_MONT, doi.RRE_AGRO, doi.RRE_LIVA, 
						doi.DUO_IMPO, doi.DUO_AUTO, doi.DUO_BMAN, doi.DUO_CAUC, doi.DUO_CANO, doi.DUO_CTIP, doi.DUO_CENT, net.DET_IDST, doi.DUO_DEST, doi.DUO_MTAG, doi.ALF_CODI, doi.DUO_CCAC, doi.DUO_CORF, doi.DUO_CNRD, doi.DUO_QTDE
					FROM PRO_DUOI AS doi WITH(NOLOCK)
						LEFT OUTER JOIN PRO_DUET AS det WITH(NOLOCK) ON doi.DUC_EANO = det.DUC_EANO AND doi.DUC_PNUM = det.DUC_PNUM AND doi.DUA_CODI = det.DUA_CODI AND doi.DUO_AUTO = 3 AND doi.DET_IDST = det.DET_IDST
						LEFT OUTER JOIN PRO_DUET AS net WITH(NOLOCK) ON net.DUC_EANO = @NovoAno AND net.DUC_PNUM = @NovoNumero AND det.DUA_CODI = net.DUA_CODI AND det.DET_CODI = net.DET_CODI
					WHERE doi.DUC_EANO = @Ano AND doi.DUC_PNUM = @Numero AND doi.DUA_CODI = @NumAdicao
					ORDER BY doi.DUO_CODI
				END
				FETCH NEXT FROM Adicoes INTO @NumAdicao, @IdAdicao
			END
			CLOSE Adicoes
			DEALLOCATE Adicoes
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPDuplicacao
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPDuplicacao
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_Duplica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_Duplica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ExportaFicheiroOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_IMP_Declaracoes_ExportaFicheiroOGMA] @NomeFicheiroXML varchar(100), @IdUtilizador int, @FicheiroXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @IdDeclaracao bigint, @NumAdicao int, @Regime varchar(4), @Ficheiro varbinary(MAX), @ComandoSQL varchar(1500)
	DECLARE @TmpFicheiroOGMA TABLE(
		ID int NOT NULL IDENTITY(1, 1), 	
		DUC_IDTY bigint NOT NULL, 
		DUA_CODI int NOT NULL, 
		DUC_REGI varchar(4) NOT NULL, 
		FICHEIRO xml NOT NULL)
-- inicia processo de geração da declaração	IMP-CAU
	BEGIN TRY	
		SET @NumErro = 0		
-- obtem as declarações DUI2 e respetivos ficheiros XML associados ao nome do ficheiro OGMA recebido
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT duc.DUC_IDTY, dua.DUA_CODI, duc.DUC_REGI, dfm.DUF_FICH
			FROM PRO_DUCG AS duc WITH(NOLOCK) 			
				INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM 
				INNER JOIN PRO_DUFI AS dfm WITH(NOLOCK) ON duc.DUC_EANO = dfm.DUC_EANO AND duc.DUC_PNUM = dfm.DUC_PNUM AND duc.DUC_FUPS = dfm.DUF_NOMF AND dfm.DUF_ORIG = 3 AND dfm.DUF_ENVI = 0								
			WHERE duc.DUC_FUPS = @NomeFicheiroXML
			ORDER BY duc.DUC_IDTY, dua.DUA_CODI
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumAdicao, @Regime, @Ficheiro
		WHILE @@FETCH_STATUS = 0
		BEGIN					
-- obtem o xml do ficheiro importado
			SET @FicheiroXML = CAST(@Ficheiro AS varchar(MAX))
-- insere na tabela tmp o ficheiro XML associado à declaração
			INSERT INTO @TmpFicheiroOGMA(DUC_IDTY, DUA_CODI, DUC_REGI, FICHEIRO)
			VALUES(@IdDeclaracao, @NumAdicao, @Regime, @FicheiroXML.query('(FICH_DESPCHANTE/FICH_DESPCHANTE_LINE[NOTAS=sql:variable("@Regime")])[sql:variable("@NumAdicao")]'))
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumAdicao, @Regime, @Ficheiro
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- constroi XML para ficheiro XML no formato OGMA a partir da declaração IMP-CAU e respetivo ficheiro original
		SET @FicheiroXML = 
			(SELECT
				(SELECT 
					f.x.value('DT_PROCESSO[1]', 'varchar(10)') AS "DT_PROCESSO", 
					f.x.value('PROCESSO[1]', 'varchar(100)') AS "PROCESSO", 
					f.x.value('TIPO[1]', 'varchar(1)') AS "TIPO", 
					f.x.value('BI_LI_ID[1]', 'varchar(45)') AS "BI_LI_ID", 
					f.x.value('AWB[1]', 'varchar(25)') AS "AWB", 
					f.x.value('RO_ID[1]', 'varchar(45)') AS "RO_ID", 
					f.x.value('PO[1]', 'varchar(20)') AS "PO", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('ARTIGO[1]', 'varchar(40)')) AS "ARTIGO", 
					f.x.value('QTD_REC[1]', 'varchar(45)') AS "QTD_REC", 
					f.x.value('UOM_REC[1]', 'varchar(3)') AS "UOM_REC", 
					f.x.value('VALOR_UNIT_REC[1]', 'varchar(45)') AS "VALOR_UNIT_REC", 
					f.x.value('RRM[1]', 'varchar(30)') AS "RRM", 
					f.x.value('LOTE[1]', 'varchar(80)') AS "LOTE", 
					f.x.value('SERIAL_NUM[1]', 'varchar(250)') AS "SERIAL_NUM", 
					f.x.value('PP_OGMA[1]', 'varchar(22)') AS "PP_OGMA", 
					f.x.value('NOTAS[1]', 'varchar(100)') AS "NOTAS", 
					ISNULL(duc.DUC_NORD, '') AS "DAU", 
					duc.DUC_REVI AS "REVISAO", 
					ISNULL(CONVERT(varchar(10), duc.DUC_NDAT, 105), '') AS "DAU_DATE", 
					ISNULL(duc.DUC_REGI, '') AS "REGIME", 
					dua.DUA_CODI AS "NUM_ADIC", 
					ISNULL(dua.APA_CP33, '') AS "PP_ALF", 
					f.x.value('QTD_REC[1]', 'varchar(45)') AS "QTD_ALF", 
					f.x.value('UOM_REC[1]', 'varchar(3)') AS "UOM_ALF", 
					CAST(dua.DUA_MB35 AS decimal(28, 6)) AS "PESO_GROSS_ALF", 
					CAST(dua.DUA_ML38 AS decimal(28, 6)) AS "PESO_NET_TOTAL_ALF", 
					CAST(ROUND((dua.DUA_ML38 / ISNULL(CAST(NULLIF(f.x.value('QTD_REC[1]', 'varchar(45)'), '') AS decimal(28, 6)), 1)), 6) AS decimal(28, 6)) AS "PESO_NET_UNIT_ALF", 
					CAST(dua.DUA_VEST AS decimal(28, 6)) AS "VALOR_ALF", 
					(LTRIM(STR(duc.DUC_PNUM, 7, 0)) + '/' + RIGHT(STR(duc.DUC_EANO, 4, 0), 2)) AS "N_PROC_DESPACHANTE", 
					FLOOR(ISNULL(duc.DUC_TVL6, 0)) AS "N_VOLUMES", 
					f.x.value('CLASSIFICACAO[1]', 'varchar(50)') AS "CLASSIFICACAO", 
					f.x.value('LICENCA[1]', 'varchar(50)') AS "LICENCA", 
					f.x.value('END_USER[1]', 'varchar(50)') AS "END_USER", 
					f.x.value('GUIA[1]', 'varchar(20)') AS "GUIA", 
					f.x.value('QTD_EXP[1]', 'varchar(45)') AS "QTD_EXP", 
					f.x.value('UOM_EXP[1]', 'varchar(3)') AS "UOM_EXP", 
					f.x.value('VALOR_UNIT_EXP[1]', 'varchar(45)') AS "VALOR_UNIT_EXP", 
					f.x.value('DAU[1]', 'varchar(20)') AS "DAU_PREC", 
					f.x.value('REVISAO[1]', 'varchar(45)') AS "REVISAO_PREC", 
					f.x.value('DAU_DATE[1]', 'varchar(10)') AS "DAU_DATE_PREC", 
					f.x.value('REGIME[1]', 'varchar(4)') AS "REGIME_PREC", 
					f.x.value('NUM_ADIC_PREC[1]', 'varchar(45)') AS "NUM_ADIC_PREC", 
					f.x.value('PP_ALF[1]', 'varchar(22)') AS "PP_PREC", 
					f.x.value('PESO_GROSS[1]', 'varchar(45)') AS "PESO_GROSS", 
					f.x.value('PESO_NET_TOTAL[1]', 'varchar(45)') AS "PESO_NET_TOTAL", 
					f.x.value('KEY_ADIC_PREC[1]', 'varchar(45)') AS "KEY_ADIC_PREC", 
					f.x.value('N_PROC_DESPACHANTE_PREC[1]', 'varchar(10)') AS "N_PROC_DESPACHANTE_PREC", 
					f.x.value('BEM[1]', 'varchar(1)') AS "BEM", 
					f.x.value('DESIGN_REC[1]', 'varchar(100)') AS "DESIGN_REC", 
					f.x.value('DESIGN_EXP[1]', 'varchar(100)') AS "DESIGN_EXP", 
					f.x.value('WEIGHT_UNIT[1]', 'varchar(45)') AS "WEIGHT_UNIT", 
					f.x.value('UOM_WEIGHT[1]', 'varchar(12)') AS "UOM_WEIGHT", 
					f.x.value('PESO_NET_REMAINING[1]', 'varchar(45)') AS "PESO_NET_REMAINING", 
					f.x.value('COUNTRY_EXP[1]', 'varchar(50)') AS "COUNTRY_EXP", 
					f.x.value('TIPO_EXP[1]', 'varchar(15)') AS "TIPO_EXP", 
					f.x.value('PROCESS_TYPE[1]', 'varchar(2)') AS "PROCESS_TYPE", 
					f.x.value('FACTURA[1]', 'varchar(100)') AS "FACTURA", 
					f.x.value('PROJECTO[1]', 'varchar(25)') AS "PROJECTO", 
					f.x.value('PAIS_EXP_MERCADORIA[1]', 'varchar(3)') AS "PAIS_EXP_MERCADORIA", 
					f.x.value('TIPO_CERTIFICADO[1]', 'varchar(100)') AS "TIPO_CERTIFICADO", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('EXPEDIDOR[1]', 'varchar(200)')) AS "EXPEDIDOR", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('DESTINATARIO[1]', 'varchar(200)')) AS "DESTINATARIO", 
					f.x.value('DATA_FATURA[1]', 'varchar(10)') AS "DATA_FATURA", 
					f.x.value('PACKING_SLIP[1]', 'varchar(25)') AS "PACKING_SLIP", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(f.x.value('DESIGNACAO_MERCADORIA[1]', 'varchar(100)')) AS "DESIGNACAO_MERCADORIA", 
					f.x.value('PAIS_ORIGEM_MERCADORIA[1]', 'varchar(3)') AS "PAIS_ORIGEM_MERCADORIA", 
					f.x.value('AUTORIZ_REGIME_EVOLUCAO[1]', 'varchar(35)') AS "AUTORIZ_REGIME_EVOLUCAO", 
					f.x.value('DT_AUTORIZ_REGIME_EVOLUCAO[1]', 'varchar(10)') AS "DT_AUTORIZ_REGIME_EVOLUCAO", 
					f.x.value('AUTORIZACAO_PREC[1]', 'varchar(35)') AS "AUTORIZACAO_PREC", 
					f.x.value('GARANTIA[1]', 'varchar(10)') AS "GARANTIA", 
					f.x.value('VALOR_FRETE_LOTE[1]', 'varchar(45)') AS "VALOR_FRETE_LOTE", 
					f.x.value('TAXA_CAMBIO[1]', 'varchar(45)') AS "TAXA_CAMBIO", 
					f.x.value('CODIGO_MOEDA_FATURACAO[1]', 'varchar(3)') AS "CODIGO_MOEDA_FATURACAO", 
					f.x.value('TAXA_CAMBIO_PREC[1]', 'varchar(45)') AS "TAXA_CAMBIO_PREC", 
					f.x.value('NUMERO_CERTIFICADO[1]', 'varchar(100)') AS "NUMERO_CERTIFICADO", 
					f.x.value('DATA_CERTIFICADO[1]', 'varchar(10)') AS "DATA_CERTIFICADO", 
					f.x.value('COD_OPERACAO[1]', 'varchar(10)') AS "COD_OPERACAO", 
					f.x.value('TIPO_PROCEDIMENTO[1]', 'varchar(20)') AS "TIPO_PROCEDIMENTO", 
					f.x.value('DOCS_USAR_DESP_EXP[1]', 'varchar(10)') AS "DOCS_USAR_DESP_EXP" 
				FROM @TmpFicheiroOGMA AS fch	
					CROSS APPLY fch.FICHEIRO.nodes('FICH_DESPCHANTE_LINE') AS f(x)
					INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON fch.DUC_IDTY = duc.DUC_IDTY	
					INNER JOIN PRO_DUAD AS dua WITH(NOLOCK) ON duc.DUC_EANO = dua.DUC_EANO AND duc.DUC_PNUM = dua.DUC_PNUM AND fch.DUA_CODI = dua.DUA_CODI
				ORDER BY fch.ID
				FOR XML PATH('FICH_DESPCHANTE_LINE'), TYPE)				
			FOR XML PATH('FICH_DESPCHANTE'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH				
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ExportaFicheiroOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ExportaFicheiroOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaDeclaracoesTNT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaDeclaracoesTNT] @DirectoriaErros varchar(500), @IdUtilizador int AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int,  @Erro varchar(MAX), @DataAtual datetime, @DataAtualCambio datetime, @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin), @i int, @Erros varchar(MAX), 
		@PathFicheiroErro varchar(500), @Linha varchar(MAX)
-- inicia variaveis
	SET @NumErro = 0
	SET @Erro = ''
-- inicia processo de importação da declaração IMP-CAU
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem data atual p/ câmbios
		SET @DataAtualCambio = CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)	
-- constroi XML para declaração IMP-CAU a partir da tabela interna no formato TNT
		SET @XMLDeclaracao = 
			(SELECT	
				(SELECT 'I' AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
					CAST(0 AS bit) AS "despachoCentralizado", 
					'H1' AS "anexoB", 
					'99' AS "natureza", 
					NULLIF(RTRIM(LTRIM(tnt.DU2_CPRT)), '') AS "documentoTransporte", 
					(SELECT 
						(SELECT 							
							NULLIF(RTRIM(LTRIM(tnt.DU2_ENOM)), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_EMOR)), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_ELOC)), '') AS "localidade", 
							ISNULL(NULLIF(RTRIM(LTRIM(tnt.DU2_ECPO)), ''), '0') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_ELPO)), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_PA15)), '') AS "pais"
						HAVING NULLIF(RTRIM(LTRIM(tnt.DU2_ENOM)), '') <> ''
						FOR XML PATH('exportador'), TYPE), 
						NULLIF(RTRIM(LTRIM(tnt.DU2_PA15)), '') AS "paisExpedicao", 
						(SELECT 
							ISNULL(NULLIF(RTRIM(LTRIM(tnt.DU2_DNIF)), ''), '999999990') AS "nif", 
							1 AS "tipoNIF", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_DNOM)), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_DMOR)), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_DLOC)), '') AS "localidade", 
							ISNULL(NULLIF(RTRIM(LTRIM(tnt.DU2_DCPO)), ''), '0') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_DLPO)), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_PA17)), '') AS "pais"
						FOR XML PATH('importador'), TYPE),
						NULLIF(RTRIM(LTRIM(tnt.DU2_PA17)), '') AS "paisDestino",						
						(SELECT
							'0693I8' AS "codigoDeclarante"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE), 
					NULLIF(RTRIM(LTRIM(tnt.DU2_NVRF)), '') AS "vossaReferencia", 
					NULLIF(RTRIM(LTRIM(tnt.DU2_ALFA)), '') AS "estancia", 
					(CASE 
						WHEN RTRIM(LTRIM(tnt.DU2_PA15)) IN ('CH', 'NO', 'GB', 'TR', 'LI', 'SM', 'AD', 'GI', 'UA') THEN 'EUA' 
						ELSE 'IMA' 
					END) AS "tipoDeclaracao", 
					NULLIF(RTRIM(LTRIM(tnt.DU2_CO24)), '') AS "naturezaTransacao", 
					NULLIF(RTRIM(LTRIM(tnt.DU2_CO20)), '') AS "condicaoEntrega", 
					(SELECT
						ISNULL((CASE 
									WHEN CEN_LOCT = 1 AND CEN_LOCD = 0 THEN NULLIF(RTRIM(LTRIM(tnt.DU2_ELOC)), '')
									WHEN CEN_LOCT = 1 AND CEN_LOCD <> 0 THEN NULLIF(RTRIM(LTRIM(tnt.DU2_DLOC)), '')
									ELSE NULL
								END), '*****N/A*****') AS "localidadeCE", 
						ISNULL((CASE 
									WHEN CEN_LOCT = 1 AND CEN_LOCD = 0 THEN NULLIF(RTRIM(LTRIM(tnt.DU2_PA15)), '')
									WHEN CEN_LOCT = 1 AND CEN_LOCD <> 0 THEN NULLIF(RTRIM(LTRIM(tnt.DU2_PA17)), '')
									ELSE NULL
								END), '--') AS "paisCE"
					FOR XML PATH('localizacao'), TYPE), 			
					(SELECT 
						(SELECT
							ISNULL(NULLIF(SUBSTRING(RTRIM(LTRIM(tnt.DU2_PR22)), 1, 2), ''), 'EU') AS "pais", 	
							CAST(tnt.DU2_MT22 AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							0 AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							0 AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT
							CAST(tnt.DU2_MLQT AS decimal(18, 6)) AS "massaLiquida", 							
							CAST(tnt.DU2_MBRT AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT
						NULLIF(RTRIM(LTRIM(tnt.DU2_CPRT)), '') AS "numeroNRUR", 
						(SELECT 
							(CASE WHEN NULLIF(RTRIM(LTRIM(tnt.DU2_NVSR)), '') IN (9, 10, 12, 15) THEN '40' ELSE '30' END) AS "meioTransporte", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_PA21)), '') AS "pais"						
						FOR XML PATH('fronteira'), TYPE), 
						(CASE WHEN NULLIF(RTRIM(LTRIM(tnt.DU2_NVSR)), '') IN (9, 10, 12, 15) THEN '40' ELSE '30' END) AS "meioTransporteChegada", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_MT18)), '') AS "identificacao", 
						0 AS "contentorizada"
					FOR XML PATH('transporte'), TYPE), 
					(SELECT
						'B' AS "tipoLocalizacao", 
						'Y' AS "qualificador", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_CO30)), '') AS "armazemDTP"
					FOR XML PATH('localizacaoMercadorias'), TYPE), 
					(SELECT 
						NULLIF(RTRIM(LTRIM(tnt.DU2_DELG)), '') AS "locID", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_GTWY)), '') AS "gateway", 
						tnt.DU2_NVSR AS "serviceLevel", 		
						NULLIF(RTRIM(LTRIM(tnt.DU2_CIDE)), '') AS "portesAcc", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_AERP)), '') AS "portes", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_REF1)), '') AS "despachoAcc", 	
						NULLIF(RTRIM(LTRIM(tnt.DU2_PPFC)), '') AS "condEntrega", 												
						NULLIF(RTRIM(LTRIM(tnt.DU2_AERD)), '') AS "nomeFicheiro"				
					FOR XML PATH('dadosEspecificos'), TYPE), 
					(SELECT 
						NULLIF(RTRIM(LTRIM(tnt.DU2_MCPA)), '') AS "miniCPA", 	
						(CONVERT(varchar(10), tnt.DU2_DTVO, 127) + 'Z') AS "dataVoo", 							
						NULLIF(RTRIM(LTRIM(tnt.DU2_AERO)), '') AS "aeroportoOrigem", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_NVOO)), '') AS "numeroVoo", 						
						NULLIF(RTRIM(LTRIM(tnt.DU2_TRAC)), '') AS "tracking", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_TPCG)), '') AS "tipoCarga"
					FOR XML PATH('dadosAWB'), TYPE), 
					(SELECT 
						NULLIF(RTRIM(LTRIM(tnt.DU2_CIEX)), '') AS "numeroContaExpedidor", 						
						NULLIF(RTRIM(LTRIM(tnt.DU2_DNOM)), '') AS "nomeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_DMOR)), '') AS "moradaOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_DLOC)), '') AS "localidadeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_DCPO)), '') AS "codigoPostalOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_DLPO)), '') AS "localidadePostalOriginalDestinatario", 						
						NULLIF(RTRIM(LTRIM(tnt.DU2_REF2)), '') AS "referenciaExterna2", 
						NULLIF(RTRIM(LTRIM(tnt.DU2_SHIP)), '') AS "shipID"
					FOR XML PATH('dadosEntidades'), TYPE), 
					(SELECT
						NULLIF(RTRIM(LTRIM(tnt.DU2_DTYP)), '') AS "dutyType", 
						tnt.DU2_PAYM AS "payment", 
						(CONVERT(varchar(10), tnt.DU2_DTIN, 127) + 'Z') AS "dataDocumentoTransporte"
					FOR XML PATH('outrosDados'), TYPE), 
					(SELECT
						6 AS "codigoFollowUp"					
					FOR XML PATH('followUp'), TYPE), 										
					(SELECT
						(SELECT 
							1 AS "numeroAdicao", 
							ISNULL(NULLIF(RTRIM(LTRIM(tnt.DU2_CO33)), ''), '9999999999') AS "codigoPautal", 							
							ISNULL(NULLIF(RTRIM(LTRIM(tnt.DU2_DESG)), ''), 'NÃO CLASSIFICADO') AS "designacao", 								
							NULLIF(RTRIM(LTRIM(tnt.DU2_PA16)), '') AS "paisOrigem",		
							1 AS "metodoAvaliacao", 
							CAST(tnt.DU2_MLQT AS decimal(18, 6)) AS "massaLiquida", 					
							CAST(tnt.DU2_MBRT AS decimal(18, 6)) AS "massaBruta",	
							CAST(tnt.DU2_US41 AS decimal(18, 6)) AS "unidades", 																				
							CAST(tnt.DU2_MT22 AS decimal(18, 3)) AS "montanteAd", 
							(SELECT TOP 1
								(SELECT 
									'CT' AS "unidadeMedida", 
									tnt.DU2_TVL6 AS "volumes", 
									'S/M' AS "marcas", 									
									CAST(0 AS bit) AS "parte"																		
								FOR XML PATH('marcaEVolume'), TYPE)																
							FOR XML PATH('marcasEVolumes'), TYPE)											
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE), 
					(SELECT
						(SELECT 
							'PAC' AS "codigoIncidencia", 
							(CONVERT(varchar(23), @DataAtual, 127) + 'Z') AS "dataInicio", 
							(CONVERT(varchar(23), @DataAtual, 127) + 'Z') AS "dataFim"
						FOR XML PATH('incidencia'), TYPE)
					FOR XML PATH('incidencias'), TYPE), 
					(SELECT TOP 1
						(SELECT 
							0 AS "tipoManifesto", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_PA16)), '') AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(tnt.DU2_DESG)), '') AS "descricao", 
							CAST(0 AS decimal(18, 3)) AS "valor", 
							ISNULL(NULLIF(SUBSTRING(RTRIM(LTRIM(tnt.DU2_PR22)), 1, 2), ''), 'EU') AS "paisMoeda", 
							CAST(tnt.DU2_MT22 AS decimal(18, 3)) AS "totalFatura", 
							(NULLIF(RTRIM(LTRIM(tnt.DU2_CPRT)), '') 
							+ (CASE number 
								WHEN 1 THEN '' 
								ELSE ('_' + CAST((number - 1) AS varchar(10))) 
							END)) AS "numeroCPA", 
							CAST(tnt.DU2_MBRT AS numeric(18, 3)) AS "pesoBruto"	
						FROM master.dbo.spt_values 
						WHERE number >= 1 AND number <= tnt.DU2_TVL6
						GROUP BY number
						FOR XML PATH('manifesto'), TYPE)		
					FROM master.dbo.spt_values 
					WHERE number >= 1 AND number <= tnt.DU2_TVL6
					GROUP BY number		
					FOR XML PATH('manifestos'), TYPE)
				FROM IMP_DUI2 AS tnt WITH(NOLOCK)
					INNER JOIN TAB_CENT AS cen WITH(NOLOCK) ON tnt.DU2_CO20 = cen.CEN_CODI
				WHERE tnt.DU2_SINT = 0 AND ROUND((tnt.DU2_MT22 / dbo.FNT_Geral_ObtemCambio(0, SUBSTRING(tnt.DU2_PR22, 1, 2), @DataAtualCambio)), 2) > 150
				FOR XML PATH('declaracao'), TYPE)		
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da(s) declaração(ões) IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT	
-- actualiza as declarações IMP-CAU TNT processadas
		UPDATE IMP_DUI2 SET 
			DU2_SINT = 1, 
			DU2_DTEX = @DataAtual
		FROM PRO_DUCG WITH(NOLOCK)
		WHERE IMP_DUI2.DU2_SINT = 0 AND ROUND((IMP_DUI2.DU2_MT22 / dbo.FNT_Geral_ObtemCambio(0, SUBSTRING(IMP_DUI2.DU2_PR22, 1, 2), @DataAtualCambio)), 2) > 150
			AND RTRIM(LTRIM(IMP_DUI2.DU2_CPRT)) = PRO_DUCG.DUC_CPRT AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_AERP)), '') = PRO_DUCG.DUC_POSA 
			AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_AERD)), '') = PRO_DUCG.DUC_FUPS AND NULLIF(RTRIM(LTRIM(IMP_DUI2.DU2_TMAN)), '') = 'D' AND IMP_DUI2.DU2_DTVO = PRO_DUCG.DUC_DTVO								
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ISNULL(@Erro, '') +
					'Detalhes do Erro: ' + CHAR(12) + 
					' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(12) + 
					' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + CHAR(12) + 
					' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(12) + 
					' » Objeto: ' + ERROR_PROCEDURE() + CHAR(12) + 
					' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + CHAR(12) + 
					' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH		
-- se ocorreram erros no tratamento das declarações ou processamento das declarações, gera ficheiro de erros
	IF ISNULL(@Erro, '') <> ''
	BEGIN		
		SET @Erro = @Erro + CHAR(12)
		SET @PathFicheiroErro = @DirectoriaErros + '\' + REPLACE(CAST(CAST(@DataAtual AS numeric(38,6)) AS varchar(20)), '.', '_') + '.txt'															
		SET @i = CHARINDEX(CHAR(12), @Erro, 0)
		WHILE @i > 0
		BEGIN
			SET @Linha = SUBSTRING(@Erro, 1, @i - 1)
			EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
			SET @Erro = STUFF(@Erro, 1, @i, '')
			SET @i = CHARINDEX(CHAR(12), @Erro, 0)
		END					
	END			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaDeclaracoesTNT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaDeclaracoesTNT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaDeXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaDeXML] @XMLDeclaracoes xml(XMLSC_DeclaracoesIMPCAUToGIDWin), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL, NUMERO int NOT NULL)	
	DECLARE @NumErro int, @CodUtilizador varchar(30), @CamposAdicionais int, @InterfaceDUContas bit, @CodigoTipoDocContas varchar(4), @ValidaAWB bit, @NumDigitosAWB int, @DataAtual datetime, 
		@Ano smallint, @TotalAdicoes int, @TotalVolumes int, @TotalVolumesDirty int, @TotalVolumesClean int, @TotalVolumesScan int, @TotalValorAduaneiro numeric(38, 6), @GarantiaGlobal bit, 
		@NumeroNRG varchar(24), @TipoEntidadeCaucao int, @AnoCaucao varchar(4), @TipoCaucao varchar(1), @AlfandegaCaucao varchar(8), @CodAcessoCaucao varchar(4), @OutrasRefCaucao varchar(35), 
		@NIFResponsavelCaucao varchar(17), @IdDeclaracao bigint, @Numero int, @NRL varchar(22), @ValorTrafegoCTT numeric(38, 6), @NumMascaras int, @TipoMascara int, @CodMascara int, 
		@ExtraFieldUPDATEValue varchar(20), @IdRegisto bigint, @UltCodTabela int, @UltCodTabela1 int, @OperacaoManifesto int, @Resultado int, @MsgErro varchar(MAX)
	DECLARE @acao varchar(1), @data datetime, @despachoCentralizado bit, @anexoB varchar(2), @natureza varchar(3), @documentoTransporte varchar(18), @descricaoGenerica varchar(40), 
		@nifExportador varchar(17), @nomeExportador varchar(70), @moradaExportador varchar(70), @localidadeExportador varchar(35), @codigoPostalExportador varchar(12), 
		@localidadePostalExportador varchar(35), @paisExportador varchar(2), @paisExpedicao varchar(2), @nifImportador varchar(17), @tipoNIFImportador int, @nomeImportador varchar(70), 
		@moradaImportador varchar(70), @localidadeImportador varchar(35), @codigoPostalImportador varchar(12), @localidadePostalImportador varchar(35), @paisImportador varchar(2), 
		@telefoneImportador varchar(14), @emailImportador varchar(200), @paisDestino varchar(2), @regiao int, @declarante varchar(6), @estatutoDeclarante int, @vossaReferencia varchar(50), 
		@estancia varchar(8), @tipoDeclaracao varchar(4), @naturezaTransacao varchar(2), @condicaoEntrega varchar(3), @localidadeCE varchar(30), @paisCE varchar(2), @portoAeroporto varchar(3), 
		@paisFatura varchar(2), @valorTotalFatura decimal(18, 3), @paisFrete varchar(2), @valorTotalFrete decimal(18, 3), @paisSeguro varchar(2), @valorTotalSeguro decimal(18, 3), 
		@totalMassaLiquida decimal(18, 6), @totalMassaBruta decimal(18, 6), @numeroNRUR varchar(30), @meioTransporteFronteira varchar(2), @paisFronteira varchar(2), 
		@meioTransporteInterior varchar(2), @meioTransporteChegada varchar(2), @identificacaoTransporte varchar(30), @contentorizada int, @numeroContentor varchar(17), 
		@tipoLocalizacao varchar(1), @qualificador varchar(1), @armazemDTP varchar(17), @estanciaLM varchar(8), @nifOperadorEconomico varchar(17), @moradaLM varchar(70), @localidadeLM varchar(35), 
		@codigoPostalLM varchar(12), @armazem varchar(17), @locID varchar(6), @gateway varchar(6), @serviceLevel int, @portesAcc varchar(10), @portes varchar(13), @despachoAcc varchar(50), 
		@freteOriginal decimal(18, 2), @moedafreteOriginal varchar(3), @despesas decimal(18, 3), @condEntrega varchar(2), @nomeFicheiro varchar(100), @numeroPDDT int, @dataEntrada datetime, 
		@numeroPDDTDEV int, @numeroTD int, @numeroACTM int, @numeroSequencia int, @posicaoArmazem varchar(4), @miniCPA varchar(20), @dataVoo datetime, @aeroportoOrigem varchar(80), 
		@numeroVoo varchar(20), @posicaoAviao varchar(13), @tracking varchar(35), @tipoCarga varchar(5), @numeroContaExpedidor varchar(10), @numeroContaDestinatario varchar(10), 
		@nomeOriginalDestinatario varchar(70), @moradaOriginalDestinatario varchar(70), @localidadeOriginalDestinatario varchar(35), @codigoPostalOriginalDestinatario varchar(12), 
		@localidadePostalOriginalDestinatario varchar(35), @referenciaExterna1 varchar(50), @referenciaExterna2 varchar(50), @shipID varchar(11), @dutyType varchar(2), @payment int, 
		@dataDocumentoTransporte datetime, @numeroRequerimento varchar(30), @numeroDURetorno varchar(30), @numeroT1Retorno varchar(30), @anotacoes varchar(MAX), @followUp int, 
		@utilizadorNomeado varchar(30), @XMLCamposExtra xml, @XMLDocumentos xml, @XMLPrecedentes xml, @XMLPedidos xml, @XMLAdicoes xml, @XMLIncidencias xml, @XMLFollowUps xml, 
		@XMLContactos xml, @XMLManifestos xml, @XMLArquivos xml	
	DECLARE @CodigoNatureza varchar(3), @NomeNatureza varchar(35), @NaturezaRetorno bit, @CodigoFollowUp int, @CodigoUtilizadorNomeado varchar(30)
	DECLARE @CodigoAlfandegaSujeicao varchar(8), @NomeAlfandegaSujeicao varchar(70), @CodigoAlfandegaApresentacao varchar(8), @CodigoLocalizacaoMercadoriasEstanciaSujeicao varchar(17)
	DECLARE @CodigoTipoDeclaracao varchar(4), @NomeTipoDeclaracao varchar(35), @NaturezaTipoDeclaracao int, @1CasaTipoDeclaracao varchar(5), @2CasaTipoDeclaracao varchar(4), 
		@Regime varchar(4) 			
	DECLARE @CodigoExportador varchar(18), @CodigoPaisExportador varchar(2), @NomePaisExportador varchar(35)
	DECLARE @CodigoPaisExpedicao varchar(2), @NomePaisExpedicao varchar(35)			
	DECLARE @CodigoPaisImportador varchar(2)			
	DECLARE @CodigoCliente varchar(18), @CodigoClienteCC varchar(18), @NIFResponsavelCaucaoCliente varchar(17), @CodigoClienteServico varchar(18), @NomeClienteServico varchar(70), 
		@BeneficiarioIVACliente bit, @CaucaoCliente varchar(24), @AnoCaucaoCliente varchar(4), @TipoCaucaoCliente varchar(1), @AlfandegaCaucaoCliente varchar(8), 
		@CodAcessoCaucaoCliente varchar(4), @OutrasRefCaucaoCliente varchar(35)
	DECLARE @CodigoPaisDestino varchar(2), @NomePaisDestino varchar(35)			
	DECLARE @CodigoRegiao int			
	DECLARE @CodigoDeclarante varchar(6), @NomeDeclarante varchar(70), @NIFDeclarante varchar(18), @CedulaDeclarante varchar(18), @CaucaoDeclarante varchar(24), @AnoCaucaoDeclarante varchar(4), 
		@TipoCaucaoDeclarante varchar(1), @AlfandegaCaucaoDeclarante varchar(8), @CodAcessoCaucaoDeclarante varchar(4), @OutrasRefCaucaoDeclarante varchar(35)
	DECLARE @CodigoMeioTransporteFronteira varchar(2), @NomeMeioTransporteFronteira varchar(35)
	DECLARE @CodigoPaisMeioTransporteFronteira varchar(2)			
	DECLARE @CodigoMeioTransporteInterior varchar(2)					
	DECLARE @CodigoMeioTransporteChegada varchar(2), @NomeMeioTransporteChegada varchar(35), @TipoIdentificacaoMeioTransporte int, @TotalOptativas numeric(38, 6), @MeioTransportePorVolume bit
	DECLARE @CodigoCondicaoEntrega varchar(3), @CodigoFormula int, @TipoLocCondicaoEntrega int, @OpcaoLocCondicaoEntrega int
	DECLARE @DescricaoFormula varchar(70), @FormulaFOB bit, @FormulaPositiva bit
	DECLARE @CodigoNaturezaTransacao varchar(2), @NomeNaturezaTransacao varchar(70)			
	DECLARE @CodigoPaisCondicaoEntrega varchar(2)
	DECLARE @CodigoPortoAeroporto varchar(8)
	DECLARE @CodigoLocalizacaoMercadorias varchar(17), @NomeLocalizacaoMercadorias varchar(70)
	DECLARE @CodigoAlfandegaLM varchar(8), @NomeAlfandegaLM varchar(70)
	DECLARE @CodigoPaisMontante varchar(2), @MoedaMontante varchar(3), @CambioMontante numeric(38, 6), @ValorTotalEUR numeric(38, 6)
	DECLARE @CodigoPaisFrete varchar(2), @MoedaFrete varchar(3), @CambioFrete numeric(38, 6)
	DECLARE @CodigoPaisSeguro varchar(2), @MoedaSeguro varchar(3), @CambioSeguro numeric(38, 6)
	DECLARE @CodigoArmazem varchar(17), @NomeArmazem varchar(70), @CodigoTipoArmazem varchar(1), @NomeTipoArmazem varchar(35), @CodigoDocumentoArmazem varchar(5), 
		@NumReferenciaArmazem varchar(35), @EORIArmazem varchar(17)
	DECLARE @CodigoPaisVerbaTransitario varchar(2), @MoedaVerbaTransitario varchar(35), @CambioVerbaTransitario numeric(38, 6)
	DECLARE @tipoDocumento int, @codigoDocumento varchar(5), @numeroDocumento varchar(70), @qualificadorDC varchar(2), @dataValidade datetime, @pais varchar(2), @montante decimal(18, 2), 
		@entidadeEmissora varchar(70), @unidadeMedida varchar(3), @quantidade decimal(18, 6)
	DECLARE @IdDocumento int, @NomeDocumento varchar(70), @IdPais int, @IdUnidadeMedida int
	DECLARE @codigoPedido varchar(5), @numeroPedido varchar(512)
	DECLARE @IdPedido int
	DECLARE @codigoIncidencia varchar(8), @dataInicio datetime, @dataFim datetime, @observacoes varchar(MAX), @tipoIncidencia varchar(1)
	DECLARE @IdIncidencia int, @NomeIncidencia varchar(60), @ReleaseHold int
	DECLARE @utilizador varchar(30), @dataHora datetime
	DECLARE @IdUtilizadorValido int
	DECLARE @descricaoContacto varchar(200)
	DECLARE @tipoManifesto int, @paisManifesto varchar(2), @descricao varchar(104), @valor decimal(18, 3), @paisMoedaManifesto varchar(2), @totalFatura decimal(18, 3), @numeroCPA varchar(35), 
		@pesoBruto decimal(18, 3)
	DECLARE @CodigoPaisManifesto varchar(2), @IdPaisMoedaManifesto int, @MoedaManifesto varchar(3)
	DECLARE @nomeArquivo varchar(100), @descricaoArquivo varchar(150), @tipoArquivo varchar(8), @origemArquivo int, @ficheiroBase64 varchar(MAX)
	DECLARE @FicheiroBinario varbinary(MAX)
	DECLARE @acaoAdicao varchar(1), @numeroAdicao int, @codigoPautal varchar(22), @designacao varchar(150), @regimeAdicional varchar(6), @paisOrigem varchar(2), @preferencia varchar(3), 
		@metodoAvaliacao int, @massaLiquida decimal(18, 6), @massaBruta decimal(18, 6), @unidades decimal(18, 6), @montanteAd decimal(18, 3), @valorFrete decimal(18, 3), 
		@valorSeguro decimal(18, 3), @taxaIVA decimal(18, 2), @XMLMarcasEVolumes xml, @XMLContentores xml, @XMLVeiculos xml
	DECLARE @CodigoArtigo varchar(22), @IdDesdobramento int, @CodigoPaisOrigem varchar(2), @IdAdicao int, @CodigoPreferencia varchar(3), @DireitosDDP numeric(38, 6)
	DECLARE @volumes int, @marcas varchar(512), @numeroObjeto varchar(20), @codigoBarras varchar(30), @parte bit
	DECLARE @CodigoUnidadeMedida varchar(3), @NomeUnidadeMedida varchar(35), @VolumesAZero bit
	DECLARE @IdUnidadeMedidaVolumes int, @VolumesPrecedente int, @IdUnidadeMedidaQualificador int
	DECLARE @tipoContentor varchar(10)
	DECLARE @homologacaoTecnica varchar(20), @adicionalISV varchar(4), @tabela varchar(1), @marca varchar(20), @modelo varchar(20), @qualificadorV varchar(1), @categoria varchar(2), 
		@tipoVeiculo varchar(3), @combustivel varchar(2), @cilindrada decimal(18, 3), @co2 int, @tipoCO2 varchar(4), @particulas varchar(10), @autonomia int, @documentoIMT varchar(5), 
		@valorISV decimal(18, 2), @XMLChassis xml
	DECLARE @CodigoCategoria varchar(2), @CodigoTipoVeiculo varchar(3), @CodigoTipoCombustivel varchar(2)
	DECLARE @matricula varchar(10), @dataMatricula datetime, @numeroChassi varchar(22), @dataChassi datetime
	DECLARE @ValorEstatistico numeric(38, 6), @Ajustamento numeric(38, 6), @ValorEUR numeric(38, 6), @SomaMontantesAdicoes numeric(38, 6), @SomaFretesAdicoes numeric(38, 6), 
		@SomaSegurosAdicoes numeric(38, 6), @TaxaFDA numeric(38, 6), @Direitos numeric(38, 6), @Acrescimos numeric(38, 6), @Deducoes numeric(38, 6)
-- inicia variaveis
	SET @NumErro = 0
-- obtem utilizador
	SELECT @CodUtilizador = UTI_UTIL
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_IDTY = @IdUtilizador
-- obtem nos campos adicionais qual o tipo de empresa configurada
	SELECT TOP 1 @CamposAdicionais = ISNULL(PDE_CADI, 0), @InterfaceDUContas = PDE_IDCV, @CodigoTipoDocContas = PDE_TDOC, @ValidaAWB = PDE_VCPI, @NumDigitosAWB = PDE_DCPI
	FROM TAB_PDES WITH(NOLOCK)
-- carrega declaracoes IMP-CAU do XML p/ INSERT
	DECLARE DeclaracoesIMP CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT t.c.value('@acao[1]', 'varchar(1)'), 
			t.c.value('data[1]', 'datetime'), 
			t.c.value('despachoCentralizado[1]', 'bit'), 			
			t.c.value('anexoB[1]', 'varchar(2)'), 			
			t.c.value('natureza[1]', 'varchar(3)'), 
			NULLIF(t.c.value('documentoTransporte[1]', 'varchar(18)'), ''), 
			NULLIF(t.c.value('descricaoGenerica[1]', 'varchar(40)'), ''), 
			NULLIF(t.c.value('(operadores/exportador/nif)[1]', 'varchar(17)'), ''), 
			t.c.value('(operadores/exportador/nome)[1]', 'varchar(70)'), 
			t.c.value('(operadores/exportador/morada)[1]', 'varchar(70)'), 
			t.c.value('(operadores/exportador/localidade)[1]', 'varchar(35)'), 
			t.c.value('(operadores/exportador/codigoPostal)[1]', 'varchar(12)'), 
			t.c.value('(operadores/exportador/localidadePostal)[1]', 'varchar(35)'), 
			t.c.value('(operadores/exportador/pais)[1]', 'varchar(2)'), 
			NULLIF(t.c.value('(operadores/paisExpedicao)[1]', 'varchar(2)'), ''), 
			t.c.value('(operadores/importador/nif)[1]', 'varchar(17)'), 
			t.c.value('(operadores/importador/tipoNIF)[1]', 'int'), 
			t.c.value('(operadores/importador/nome)[1]', 'varchar(70)'), 
			t.c.value('(operadores/importador/morada)[1]', 'varchar(70)'), 
			t.c.value('(operadores/importador/localidade)[1]', 'varchar(35)'), 
			t.c.value('(operadores/importador/codigoPostal)[1]', 'varchar(12)'), 
			t.c.value('(operadores/importador/localidadePostal)[1]', 'varchar(35)'), 
			t.c.value('(operadores/importador/pais)[1]', 'varchar(2)'), 
			NULLIF(t.c.value('(operadores/importador/telefone)[1]', 'varchar(14)'), ''), 
			NULLIF(t.c.value('(operadores/importador/email)[1]', 'varchar(200)'), ''), 
			t.c.value('(operadores/paisDestino)[1]', 'varchar(2)'),
			t.c.value('(operadores/regiao)[1]', 'int'),
			t.c.value('(operadores/declarante/codigoDeclarante)[1]', 'varchar(6)'), 
			t.c.value('(operadores/declarante/estatuto)[1]', 'int'), 
			NULLIF(t.c.value('vossaReferencia[1]', 'varchar(50)'), ''), 
			t.c.value('estancia[1]', 'varchar(8)'), 
			t.c.value('tipoDeclaracao[1]', 'varchar(4)'), 			
			NULLIF(t.c.value('naturezaTransacao[1]', 'varchar(2)'), ''), 
			t.c.value('condicaoEntrega[1]', 'varchar(3)'),
			NULLIF(t.c.value('(localizacao/localidadeCE)[1]', 'varchar(30)'), ''),
			NULLIF(t.c.value('(localizacao/paisCE)[1]', 'varchar(2)'), ''),
			NULLIF(t.c.value('portoAeroporto[1]', 'varchar(3)'), ''), 
			t.c.value('(totais/fatura/pais)[1]', 'varchar(2)'),
			t.c.value('(totais/fatura/valorTotal)[1]', 'decimal(18, 3)'), 
			t.c.value('(totais/frete/pais)[1]', 'varchar(2)'),
			t.c.value('(totais/frete/valorTotal)[1]', 'decimal(18, 3)'), 
			t.c.value('(totais/seguro/pais)[1]', 'varchar(2)'),
			t.c.value('(totais/seguro/valorTotal)[1]', 'decimal(18, 3)'), 
			t.c.value('(totais/pesos/massaLiquida)[1]', 'decimal(18, 6)'), 
			t.c.value('(totais/pesos/massaBruta)[1]', 'decimal(18, 6)'), 
			NULLIF(t.c.value('(transporte/numeroNRUR)[1]', 'varchar(30)'), ''),
			NULLIF(t.c.value('(transporte/fronteira/meioTransporte)[1]', 'varchar(2)'), ''),
			NULLIF(t.c.value('(transporte/fronteira/pais)[1]', 'varchar(2)'), ''),
			NULLIF(t.c.value('(transporte/meioTransporteInterior)[1]', 'varchar(2)'), ''), 
			t.c.value('(transporte/meioTransporteChegada)[1]', 'varchar(2)'),
			NULLIF(t.c.value('(transporte/identificacao)[1]', 'varchar(30)'), ''),
			t.c.value('(transporte/contentorizada)[1]', 'int'),
			NULLIF(t.c.value('(transporte/numeroContentor)[1]', 'varchar(17)'), ''),
			NULLIF(t.c.value('(localizacaoMercadorias/tipoLocalizacao)[1]', 'varchar(1)'), ''),
			NULLIF(t.c.value('(localizacaoMercadorias/qualificador)[1]', 'varchar(1)'), ''),
			NULLIF(t.c.value('(localizacaoMercadorias/armazemDTP)[1]', 'varchar(17)'), ''), 
			NULLIF(t.c.value('(localizacaoMercadorias/estancia)[1]', 'varchar(8)'), ''), 
			NULLIF(t.c.value('(localizacaoMercadorias/nifOperadorEconomico)[1]', 'varchar(17)'), ''), 
			NULLIF(t.c.value('(localizacaoMercadorias/endereco/morada)[1]', 'varchar(70)'), ''), 
			NULLIF(t.c.value('(localizacaoMercadorias/endereco/localidade)[1]', 'varchar(35)'), ''), 
			NULLIF(t.c.value('(localizacaoMercadorias/endereco/codigoPostal)[1]', 'varchar(12)'), ''), 
			NULLIF(t.c.value('armazem[1]', 'varchar(17)'), ''),
			NULLIF(t.c.value('(dadosEspecificos/locID)[1]', 'varchar(6)'), ''), 
			NULLIF(t.c.value('(dadosEspecificos/gateway)[1]', 'varchar(6)'), ''), 
			t.c.value('(dadosEspecificos/serviceLevel)[1]', 'int'), 
			NULLIF(t.c.value('(dadosEspecificos/portesAcc)[1]', 'varchar(10)'), ''), 
			NULLIF(t.c.value('(dadosEspecificos/portes)[1]', 'varchar(13)'), ''), 
			NULLIF(t.c.value('(dadosEspecificos/despachoAcc)[1]', 'varchar(50)'), ''), 
			ISNULL(t.c.value('(dadosEspecificos/freteOriginal)[1]', 'decimal(18, 2)'), 0), 
			NULLIF(t.c.value('(dadosEspecificos/moedafreteOriginal)[1]', 'varchar(3)'), ''), 
			ISNULL(t.c.value('(dadosEspecificos/despesas)[1]', 'decimal(18, 3)'), 0), 
			NULLIF(t.c.value('(dadosEspecificos/condEntrega)[1]', 'varchar(2)'), ''), 
			NULLIF(t.c.value('(dadosEspecificos/nomeFicheiro)[1]', 'varchar(100)'), ''), 
			t.c.value('(depositoTemporario/numeroPDDT)[1]', 'int'), 
			t.c.value('(depositoTemporario/dataEntrada)[1]', 'datetime'), 
			t.c.value('(depositoTemporario/numeroPDDTDEV)[1]', 'int'), 
			t.c.value('(depositoTemporario/numeroTD)[1]', 'int'), 
			t.c.value('(depositoTemporario/numeroACTM)[1]', 'int'), 
			t.c.value('(depositoTemporario/numeroSequencia)[1]', 'int'), 
			NULLIF(t.c.value('(depositoTemporario/posicaoArmazem)[1]', 'varchar(4)'), ''), 
			NULLIF(t.c.value('(dadosAWB/miniCPA)[1]', 'varchar(20)'), ''), 
			t.c.value('(dadosAWB/dataVoo)[1]', 'datetime'),  
			NULLIF(t.c.value('(dadosAWB/aeroportoOrigem)[1]', 'varchar(80)'), ''), 
			NULLIF(t.c.value('(dadosAWB/numeroVoo)[1]', 'varchar(20)'), ''), 
			NULLIF(t.c.value('(dadosAWB/posicaoAviao)[1]', 'varchar(13)'), ''), 
			NULLIF(t.c.value('(dadosAWB/tracking)[1]', 'varchar(35)'), ''), 
			NULLIF(t.c.value('(dadosAWB/tipoCarga)[1]', 'varchar(5)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/numeroContaExpedidor)[1]', 'varchar(10)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/numeroContaDestinatario)[1]', 'varchar(10)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/nomeOriginalDestinatario)[1]', 'varchar(70)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/moradaOriginalDestinatario)[1]', 'varchar(70)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/localidadeOriginalDestinatario)[1]', 'varchar(35)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/codigoPostalOriginalDestinatario)[1]', 'varchar(12)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/localidadePostalOriginalDestinatario)[1]', 'varchar(35)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/referenciaExterna1)[1]', 'varchar(50)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/referenciaExterna2)[1]', 'varchar(50)'), ''), 
			NULLIF(t.c.value('(dadosEntidades/shipID)[1]', 'varchar(11)'), ''), 
			NULLIF(t.c.value('(outrosDados/dutyType)[1]', 'varchar(2)'), ''), 
			t.c.value('(outrosDados/payment)[1]', 'int'), 
			t.c.value('(outrosDados/dataDocumentoTransporte)[1]', 'datetime'),
			t.c.value('(outrosDados/numeroRequerimento)[1]', 'varchar(30)'), 
			t.c.value('(outrosDados/numeroDURetorno)[1]', 'varchar(30)'), 
			t.c.value('(outrosDados/numeroT1Retorno)[1]', 'varchar(30)'), 			
			NULLIF(t.c.value('anotacoes[1]', 'varchar(MAX)'), ''), 
			t.c.value('(followUp/codigoFollowUp)[1]', 'int'),
			NULLIF(t.c.value('(followUp/utilizadorNomeado)[1]', 'varchar(30)'), ''), 
			t.c.query('camposExtra'), 											
			t.c.query('documentosECertificados'), 
			t.c.query('documentosPrecedentes'),			
			t.c.query('pedidos'),
			t.c.query('adicoes'), 
			t.c.query('incidencias'), 
			t.c.query('followUps'),
			t.c.query('contactos'), 
			t.c.query('manifestos'), 
			t.c.query('arquivos')
		FROM @XMLDeclaracoes.nodes('declaracoesIMPToGIDWin/declaracao') AS t(c)			
	OPEN DeclaracoesIMP
	FETCH NEXT FROM DeclaracoesIMP INTO @acao, @data, @despachoCentralizado, @anexoB, @natureza, @documentoTransporte, @descricaoGenerica, @nifExportador, @nomeExportador, @moradaExportador, 
		@localidadeExportador, @codigoPostalExportador, @localidadePostalExportador, @paisExportador, @paisExpedicao, @nifImportador, @tipoNIFImportador, @nomeImportador, @moradaImportador, 
		@localidadeImportador, @codigoPostalImportador, @localidadePostalImportador, @paisImportador, @telefoneImportador, @emailImportador, @paisDestino, @regiao, @declarante, 
		@estatutoDeclarante, @vossaReferencia, @estancia, @tipoDeclaracao, @naturezaTransacao, @condicaoEntrega, @localidadeCE, @paisCE, @portoAeroporto, @paisFatura, @valorTotalFatura, 
		@paisFrete, @valorTotalFrete, @paisSeguro, @valorTotalSeguro, @totalMassaLiquida, @totalMassaBruta, @numeroNRUR, @meioTransporteFronteira, @paisFronteira, @meioTransporteInterior, 
		@meioTransporteChegada, @identificacaoTransporte, @contentorizada, @numeroContentor, @tipoLocalizacao, @qualificador, @armazemDTP, @estanciaLM, @nifOperadorEconomico, @moradaLM, 
		@localidadeLM, @codigoPostalLM, @armazem, @locID, @gateway, @serviceLevel, @portesAcc, @portes, @despachoAcc, @freteOriginal, @moedafreteOriginal, @despesas, @condEntrega, @nomeFicheiro, 
		@numeroPDDT, @dataEntrada, @numeroPDDTDEV, @numeroTD, @numeroACTM, @numeroSequencia, @posicaoArmazem, @miniCPA, @dataVoo, @aeroportoOrigem, @numeroVoo, @posicaoAviao, @tracking, 
		@tipoCarga, @numeroContaExpedidor, @numeroContaDestinatario, @nomeOriginalDestinatario, @moradaOriginalDestinatario, @localidadeOriginalDestinatario, @codigoPostalOriginalDestinatario, 
		@localidadePostalOriginalDestinatario, @referenciaExterna1, @referenciaExterna2, @shipID, @dutyType, @payment, @dataDocumentoTransporte, @numeroRequerimento, @numeroDURetorno, 
		@numeroT1Retorno, @anotacoes, @followUp, @utilizadorNomeado, @XMLCamposExtra, @XMLDocumentos, @XMLPrecedentes, @XMLPedidos, @XMLAdicoes, @XMLIncidencias, @XMLFollowUps, @XMLContactos, 
		@XMLManifestos, @XMLArquivos
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- inicia transacção para importação da declaração IMP-CAU
		BEGIN TRANSACTION TspIMPImportacao
		BEGIN TRY	
-- inicia variáveis
			SET @Ano = YEAR(@data)	
			SET @Numero = NULL
			SET @IdDeclaracao = NULL
			SET @TotalAdicoes = 0
			SET @TotalVolumes = 0
			SET @TotalVolumesDirty = 0
			SET @TotalVolumesClean = 0
			SET @TotalVolumesScan = 0
			SET @TotalValorAduaneiro = 0
			SET @CodigoNatureza = NULL 
			SET @NomeNatureza = NULL
			SET @NaturezaRetorno = 0
			SET @CodigoFollowUp = NULL
			SET @CodigoUtilizadorNomeado = NULL
			SET @CodigoAlfandegaSujeicao = NULL
			SET @NomeAlfandegaSujeicao = NULL
			SET @CodigoAlfandegaApresentacao = NULL
			SET @CodigoLocalizacaoMercadoriasEstanciaSujeicao = NULL
			SET @CodigoTipoDeclaracao = NULL 
			SET @NomeTipoDeclaracao = NULL 
			SET @NaturezaTipoDeclaracao = NULL
			SET @1CasaTipoDeclaracao = NULL 
			SET @2CasaTipoDeclaracao = NULL 			
			SET @Regime = NULL
			SET @CodigoExportador = NULL 
			SET @CodigoPaisExportador = NULL
			SET @NomePaisExportador = NULL
			SET @CodigoPaisExpedicao = NULL
			SET @NomePaisExpedicao = NULL
			SET @CodigoPaisImportador = NULL
			SET @CodigoCliente = NULL
			SET @CodigoClienteCC = NULL
			SET @NIFResponsavelCaucaoCliente = NULL 
			SET @CodigoClienteServico = NULL 
			SET @NomeClienteServico = NULL
			SET @BeneficiarioIVACliente = 0
			SET @CaucaoCliente = NULL
			SET @AnoCaucaoCliente = NULL
			SET @TipoCaucaoCliente = NULL
			SET @AlfandegaCaucaoCliente = NULL
			SET @CodAcessoCaucaoCliente = NULL
			SET @OutrasRefCaucaoCliente = NULL
			SET @CodigoPaisDestino = NULL
			SET @NomePaisDestino = NULL
			SET @CodigoRegiao = NULL
			SET @CodigoDeclarante = NULL 
			SET @NomeDeclarante = NULL 
			SET @NIFDeclarante = NULL 
			SET @CedulaDeclarante = NULL 
			SET @CaucaoDeclarante = NULL
			SET @AnoCaucaoDeclarante = NULL
			SET @TipoCaucaoDeclarante = NULL
			SET @AlfandegaCaucaoDeclarante = NULL
			SET @CodAcessoCaucaoDeclarante = NULL
			SET @OutrasRefCaucaoDeclarante = NULL
			SET @CodigoMeioTransporteFronteira = NULL 
			SET @NomeMeioTransporteFronteira = NULL
			SET @CodigoPaisMeioTransporteFronteira = NULL
			SET @CodigoMeioTransporteInterior = NULL 			
			SET @CodigoMeioTransporteChegada = NULL
			SET @NomeMeioTransporteChegada = NULL
			SET @TipoIdentificacaoMeioTransporte = NULL 
			SET @TotalOptativas = 0
			SET @MeioTransportePorVolume = 0
			SET @CodigoCondicaoEntrega = NULL
			SET @CodigoFormula = NULL
			SET @TipoLocCondicaoEntrega = NULL
			SET @OpcaoLocCondicaoEntrega = NULL			
			SET @DescricaoFormula = NULL
			SET @FormulaFOB = 0
			SET @FormulaPositiva = 0
			SET @CodigoNaturezaTransacao = NULL
			SET @NomeNaturezaTransacao = NULL
			SET @CodigoPaisCondicaoEntrega = NULL
			SET @CodigoPortoAeroporto = NULL
			SET @CodigoLocalizacaoMercadorias = NULL
			SET @NomeLocalizacaoMercadorias = NULL
			SET @CodigoAlfandegaLM = NULL 
			SET @NomeAlfandegaLM = NULL
			SET @CodigoPaisMontante = NULL
			SET @MoedaMontante = NULL 
			SET @CambioMontante = 0
			SET @ValorTotalEUR = 0
			SET @CodigoPaisFrete = NULL
			SET @MoedaFrete = NULL 
			SET @CambioFrete = 0
			SET @CodigoPaisSeguro = NULL
			SET @MoedaSeguro = NULL 
			SET @CambioSeguro = 0
			SET @CodigoArmazem = NULL
			SET @NomeArmazem = NULL
			SET @CodigoTipoArmazem = NULL
			SET @NomeTipoArmazem = NULL
			SET @CodigoDocumentoArmazem = NULL
			SET @NumReferenciaArmazem = NULL
			SET @EORIArmazem = NULL
			SET @CodigoPaisVerbaTransitario = NULL 
			SET @MoedaVerbaTransitario = NULL
			SET @CambioVerbaTransitario = 0
			SET @SomaMontantesAdicoes = 0
			SET @SomaFretesAdicoes = 0
			SET @SomaSegurosAdicoes = 0
			SET @OperacaoManifesto = NULL
			SET @ExtraFieldUPDATEValue = NULL
-- obtem data atual GMT
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- verifica se documento transporte é válido
			IF (@ValidaAWB = 1) AND (@NumDigitosAWB > 0) AND (LEN(ISNULL(@documentoTransporte, '')) <> @NumDigitosAWB)
				RAISERROR('Documento de transporte "%s" inválido porque não cumpre o número de caracteres configurado.', 16, 1, @documentoTransporte)
-- obtem dados do follow-up
			SELECT @CodigoFollowUp = FUP_CODI
			FROM GIDWIN.dbo.FAP_FWUP WITH(NOLOCK)
			WHERE FUP_EXPO = 0 AND FUP_CODI = @followUp
-- verifica se o follow-up é válido
			IF (@followUp IS NOT NULL) AND (@CodigoFollowUp IS NULL)
				RAISERROR('Follow-up "%d" inválido.', 16, 2, @followUp)
-- obtem dados do utilizador nomeado
			SELECT @CodigoUtilizadorNomeado = UTI_UTIL
			FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
			WHERE UTI_UTIL = @utilizadorNomeado
-- verifica se o utilizador nomeado é válido
			IF (ISNULL(@utilizadorNomeado, '') <> '') AND (ISNULL(@CodigoUtilizadorNomeado, '') = '')
				RAISERROR('Utilizador nomeado "%s" inválido.', 16, 3, @utilizadorNomeado)
-- obtem dados da natureza de despacho			
			SELECT @CodigoNatureza = NDE_CODI, @NomeNatureza = NDE_NOME, @NaturezaRetorno = NDE_RETO, 
				@CodigoFollowUp = (CASE WHEN (@CodigoFollowUp IS NULL) AND (FUP_CODI IS NOT NULL) THEN FUP_CODI ELSE @CodigoFollowUp END),
				@CodigoTipoDocContas = (CASE WHEN (@CamposAdicionais <> 3) AND (@InterfaceDUContas = 1) AND (@CodigoTipoDocContas <> '') AND (NDE_TLCV IS NOT NULL) AND (NDE_TLCV = 0) THEN @CodigoTipoDocContas ELSE NULL END)		
			FROM TAB_NDES WITH(NOLOCK)
			WHERE NDE_PART = 0 AND NDE_VDAR = 0 AND NDE_VEXI = 0 AND NDE_CODI = @natureza
-- verifica se a natureza é válida
			IF ISNULL(@CodigoNatureza, '') = ''
				RAISERROR('Natureza "%s" inválida.', 16, 4, @natureza)
-- obtem dados do Tipo de Declaração
			SELECT @CodigoTipoDeclaracao = TDE_CODI, @NomeTipoDeclaracao = TDE_NOME, @NaturezaTipoDeclaracao = ISNULL(TDE_NATU, 1), @1CasaTipoDeclaracao = TDE_1CAS, 
				@2CasaTipoDeclaracao = TDE_2CAS, @Regime = TDE_REGI
			FROM TAB_TDEC WITH(NOLOCK)
			WHERE ISNULL(TDE_1CAS, '') <> 'EU' AND ISNULL(TDE_2CAS, '') <> '' AND ISNULL(TDE_NATU, 0) = 1 AND TDE_CODI = @tipoDeclaracao	
-- verifica se o tipo de declaração é válido
			IF ISNULL(@CodigoTipoDeclaracao, '') = ''
				RAISERROR('Tipo de declaração "%s" inválido.', 16, 5, @tipoDeclaracao)
			ELSE
				IF ISNULL(@Regime, '') = ''
					RAISERROR('Tipo de declaração "%s" sem regime definido.', 16, 6, @tipoDeclaracao)
				ELSE
					IF ((@anexoB = 'H1') AND (LEFT(@Regime, 2) NOT IN ('01', '07', '40', '42', '43', '44', '45', '46', '48', '61', '63', '68')))
					OR ((@anexoB = 'H2') AND (LEFT(@Regime, 2) <> '71'))
					OR ((@anexoB = 'H3') AND (LEFT(@Regime, 2) <> '53'))
					OR ((@anexoB = 'H4') AND (LEFT(@Regime, 2) <> '51'))
					OR ((@anexoB = 'H5') AND (LEFT(@Regime, 2) NOT IN ('40', '42', '61', '63', '95', '96')))
					OR ((@anexoB = 'H6') AND (LEFT(@Regime, 2) NOT IN ('01', '07', '40')))
					OR ((@anexoB = 'I1') AND (LEFT(@Regime, 2) NOT IN ('01', '07', '40', '42', '43', '44', '45', '46', '48', '51', '53', '61', '63', '68')))
						RAISERROR('Regime "%s" não se enquadra no anexo "%s" da declaração.', 16, 7, @Regime, @anexoB)
					ELSE
						IF ISNULL(@2CasaTipoDeclaracao, '') NOT IN ('A', 'B', 'C', 'D', 'E', 'F')
							RAISERROR('Tipo de declaração adicional "%s" inválido.', 16, 8, @2CasaTipoDeclaracao)
-- obtem dados do país do fornecedor (exportador)
			SELECT @CodigoPaisExportador = PAI_CODI, @NomePaisExportador = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisExportador
-- verifica se o país do fornecedor (exportador) é válido
			IF (ISNULL(@paisExportador, '') <> '') AND (ISNULL(@CodigoPaisExportador, '') = '')
				RAISERROR('País "%s" do exportador inválido.', 16, 9, @paisExportador)
-- obtem dados do fornecedor (exportador)
			SELECT TOP 1 @CodigoExportador = frn.FOR_CODI, @nomeExportador = ISNULL(frn.FOR_NOME, @nomeExportador), @CodigoPaisExportador = ISNULL(pai.PAI_CODI, @CodigoPaisExportador), 
				@NomePaisExportador = ISNULL(pai.PAI_NOME, @NomePaisExportador), @moradaExportador = ISNULL(frn.FOR_MORA, @moradaExportador), 
				@localidadeExportador = ISNULL(frn.FOR_LOCA, @localidadeExportador), @codigoPostalExportador = ISNULL(frn.FOR_CPOS, @codigoPostalExportador), 
				@localidadePostalExportador = ISNULL(frn.FOR_LPOS, @localidadePostalExportador)
			FROM TAB_FORN AS frn WITH(NOLOCK) 
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON frn.PAI_CODI = pai.PAI_CODI
			WHERE frn.FOR_INAC = 0 AND frn.FOR_DESP = 1 AND frn.FOR_NIF = @nifExportador
-- obtem dados do país de expedição
			SELECT @CodigoPaisExpedicao = PAI_CODI, @NomePaisExpedicao = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisExpedicao
-- verifica se o país de expedição é válido
			IF (ISNULL(@paisExpedicao, '') <> '') AND (ISNULL(@CodigoPaisExpedicao, '') = '')
				RAISERROR('País de expedição "%s" inválido.', 16, 10, @paisExpedicao)				
			ELSE
				IF (@anexoB IN ('H6', 'I2')) AND (ISNULL(@CodigoPaisExpedicao, '') <> '')
					RAISERROR('País de expedição "%s" inválido para o anexo B "%s".', 16, 11, @CodigoPaisExpedicao, @anexoB)	
				ELSE
					IF (@anexoB NOT IN ('H6', 'I2')) AND (ISNULL(@CodigoPaisExpedicao, '') = '')
						RAISERROR('O anexo B "%s" obriga ao preenchimento do país de expedição.', 16, 12, @anexoB)	
-- obtem dados da região
			SELECT @CodigoRegiao = (CASE WHEN RES_DONO IS NOT NULL THEN RES_DONO ELSE RES_CODI END)
			FROM TAB_REST WITH(NOLOCK)
			WHERE RES_CODI = @regiao
-- verifica se o país de expedição é válido
			IF (@regiao IS NOT NULL) AND (@CodigoRegiao IS NULL)
				RAISERROR('Região "%d" inválida.', 16, 13, @regiao)
			ELSE
				IF (@anexoB IN ('H6', 'I1', 'I2')) AND (@CodigoRegiao IS NOT NULL)
					RAISERROR('Região "%d" inválida para o anexo B "%s".', 16, 14, @CodigoRegiao, @anexoB)					
-- obtem dados do país do cliente (importador)
			SELECT @CodigoPaisImportador = PAI_CODI
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisImportador
-- verifica se o país do cliente (importador) é válido
			IF ISNULL(@CodigoPaisImportador, '') = '' 
				RAISERROR('País "%s" do importador inválido.', 16, 15, @paisImportador)				
-- obtem dados do cliente (importador)
			SELECT TOP 1 @CodigoCliente = cli.CLI_CODI, @CodigoClienteCC = ISNULL(NULLIF(cli.CLI_CCOR, ''), cli.CLI_CODI), @NIFResponsavelCaucaoCliente = cli.CLI_CNIF, 
				@CodigoClienteServico = cli.CLI_SENT, @NomeClienteServico = cse.CLI_NOME, 
				@nomeImportador = (CASE 
										WHEN cli.CLI_NIF = '999999990' THEN @nomeImportador 
										ELSE ISNULL(cli.CLI_NOME, @nomeImportador) 
									END), 
				@CodigoPaisImportador = (CASE 
										WHEN cli.CLI_NIF = '999999990' THEN @CodigoPaisImportador 
										ELSE ISNULL(pai.PAI_CODI, @CodigoPaisImportador)
									END), 				
				@moradaImportador = (CASE 
										WHEN cli.CLI_NIF = '999999990' THEN @moradaImportador 
										ELSE ISNULL(cli.CLI_MORA, @moradaImportador) 
									END), 
				@localidadeImportador = (CASE 
											WHEN cli.CLI_NIF = '999999990' THEN @localidadeImportador 
											ELSE ISNULL(cli.CLI_LOCA, @localidadeImportador) 
										END), 
				@codigoPostalImportador = (CASE 
											WHEN cli.CLI_NIF = '999999990' THEN @codigoPostalImportador 
											ELSE ISNULL(cli.CLI_CPOS, @codigoPostalImportador)
										END), 
				@localidadePostalImportador = (CASE 
												WHEN cli.CLI_NIF = '999999990' THEN @localidadePostalImportador 
												ELSE ISNULL(cli.CLI_LPOS, @localidadePostalImportador) 
										END), 
				@telefoneImportador = (CASE 
										WHEN cli.CLI_NIF = '999999990' THEN @telefoneImportador 
										ELSE ISNULL(cli.CLI_TELF, @telefoneImportador)
									END), 
				@emailImportador = (CASE 
										WHEN cli.CLI_NIF = '999999990' THEN @emailImportador 
										ELSE ISNULL(cli.CLI_EMAI, @emailImportador) 
									END), 
				@tipoNIFImportador = (CASE 
										WHEN cli.CLI_NIF = '999999990' THEN @tipoNIFImportador
										ELSE ISNULL(cli.CLI_TNIF, @tipoNIFImportador) 
									END), 						
				@BeneficiarioIVACliente = (CASE
					WHEN  (cli.CLI_BIVA = 1) AND (cli.CLI_DIBI <= @data) THEN 1 
					ELSE 0
				END), 
				@CaucaoCliente = (CASE 
					WHEN (ISNULL(cli.CLI_NCA1, '') <> '') AND (cli.CLI_INA1 = 0) THEN (ISNULL(RIGHT(cli.CLI_ANO1, 2), '') + ISNULL(cli.ALF_CODI1, '') + REPLICATE('0', (7 - LEN(cli.CLI_NCA1))) + cli.CLI_NCA1)
					WHEN (ISNULL(cli.CLI_NCA2, '') <> '') AND (cli.CLI_INA2 = 0) THEN (ISNULL(RIGHT(cli.CLI_ANO2, 2), '') + ISNULL(cli.ALF_CODI2, '') + REPLICATE('0', (7 - LEN(cli.CLI_NCA2))) + cli.CLI_NCA2)
					WHEN (ISNULL(cli.CLI_NCA3, '') <> '') AND (cli.CLI_INA3 = 0) THEN (ISNULL(RIGHT(cli.CLI_ANO3, 2), '') + ISNULL(cli.ALF_CODI3, '') + REPLICATE('0', (7 - LEN(cli.CLI_NCA3))) + cli.CLI_NCA3)
					WHEN (ISNULL(cli.CLI_NCA4, '') <> '') AND (cli.CLI_INA4 = 0) THEN (ISNULL(RIGHT(cli.CLI_ANO4, 2), '') + ISNULL(cli.ALF_CODI4, '') + REPLICATE('0', (7 - LEN(cli.CLI_NCA4))) + cli.CLI_NCA4)
					WHEN (ISNULL(cli.CLI_NCA5, '') <> '') AND (cli.CLI_INA5 = 0) THEN (ISNULL(RIGHT(cli.CLI_ANO5, 2), '') + ISNULL(cli.ALF_CODI5, '') + REPLICATE('0', (7 - LEN(cli.CLI_NCA5))) + cli.CLI_NCA5)
					ELSE NULL 
				END),
				@AnoCaucaoCliente = (CASE 
					WHEN (ISNULL(cli.CLI_NCA1, '') <> '') AND (cli.CLI_INA1 = 0) THEN cli.CLI_ANO1
					WHEN (ISNULL(cli.CLI_NCA2, '') <> '') AND (cli.CLI_INA2 = 0) THEN cli.CLI_ANO2
					WHEN (ISNULL(cli.CLI_NCA3, '') <> '') AND (cli.CLI_INA3 = 0) THEN cli.CLI_ANO3
					WHEN (ISNULL(cli.CLI_NCA4, '') <> '') AND (cli.CLI_INA4 = 0) THEN cli.CLI_ANO4
					WHEN (ISNULL(cli.CLI_NCA5, '') <> '') AND (cli.CLI_INA5 = 0) THEN cli.CLI_ANO5
					ELSE NULL 
				END),
				@TipoCaucaoCliente = (CASE 
					WHEN (ISNULL(cli.CLI_NCA1, '') <> '') AND (cli.CLI_INA1 = 0) THEN cli.CLI_TCA1
					WHEN (ISNULL(cli.CLI_NCA2, '') <> '') AND (cli.CLI_INA2 = 0) THEN cli.CLI_TCA2
					WHEN (ISNULL(cli.CLI_NCA3, '') <> '') AND (cli.CLI_INA3 = 0) THEN cli.CLI_TCA3
					WHEN (ISNULL(cli.CLI_NCA4, '') <> '') AND (cli.CLI_INA4 = 0) THEN cli.CLI_TCA4
					WHEN (ISNULL(cli.CLI_NCA5, '') <> '') AND (cli.CLI_INA5 = 0) THEN cli.CLI_TCA5
					ELSE NULL 
				END),
				@AlfandegaCaucaoCliente = (CASE 
					WHEN (ISNULL(cli.CLI_NCA1, '') <> '') AND (cli.CLI_INA1 = 0) THEN cli.ALF_CODI1
					WHEN (ISNULL(cli.CLI_NCA2, '') <> '') AND (cli.CLI_INA2 = 0) THEN cli.ALF_CODI2
					WHEN (ISNULL(cli.CLI_NCA3, '') <> '') AND (cli.CLI_INA3 = 0) THEN cli.ALF_CODI3
					WHEN (ISNULL(cli.CLI_NCA4, '') <> '') AND (cli.CLI_INA4 = 0) THEN cli.ALF_CODI4
					WHEN (ISNULL(cli.CLI_NCA5, '') <> '') AND (cli.CLI_INA5 = 0) THEN cli.ALF_CODI5
					ELSE NULL 
				END),
				@CodAcessoCaucaoCliente = (CASE 
					WHEN (ISNULL(cli.CLI_NCA1, '') <> '') AND (cli.CLI_INA1 = 0) THEN cli.CLI_CCA1
					WHEN (ISNULL(cli.CLI_NCA2, '') <> '') AND (cli.CLI_INA2 = 0) THEN cli.CLI_CCA2
					WHEN (ISNULL(cli.CLI_NCA3, '') <> '') AND (cli.CLI_INA3 = 0) THEN cli.CLI_CCA3
					WHEN (ISNULL(cli.CLI_NCA4, '') <> '') AND (cli.CLI_INA4 = 0) THEN cli.CLI_CCA4
					WHEN (ISNULL(cli.CLI_NCA5, '') <> '') AND (cli.CLI_INA5 = 0) THEN cli.CLI_CCA5
					ELSE NULL 
				END),
				@OutrasRefCaucaoCliente = (CASE 
					WHEN (ISNULL(cli.CLI_NCA1, '') <> '') AND (cli.CLI_INA1 = 0) THEN cli.CLI_OCA1
					WHEN (ISNULL(cli.CLI_NCA2, '') <> '') AND (cli.CLI_INA2 = 0) THEN cli.CLI_OCA2
					WHEN (ISNULL(cli.CLI_NCA3, '') <> '') AND (cli.CLI_INA3 = 0) THEN cli.CLI_OCA3
					WHEN (ISNULL(cli.CLI_NCA4, '') <> '') AND (cli.CLI_INA4 = 0) THEN cli.CLI_OCA4
					WHEN (ISNULL(cli.CLI_NCA5, '') <> '') AND (cli.CLI_INA5 = 0) THEN cli.CLI_OCA5
					ELSE NULL 
				END), 
				@CodigoRegiao = (CASE WHEN (@CodigoRegiao IS NULL) AND (@anexoB NOT IN ('H6', 'I1', 'I2')) THEN cli.RES_CODI ELSE @CodigoRegiao END)
			FROM TAB_CLIE AS cli WITH(NOLOCK) 
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON cli.PAI_CODI = pai.PAI_CODI
				LEFT OUTER JOIN TAB_CLIE AS cse WITH(NOLOCK) ON cli.CLI_SENT = cse.CLI_CODI
			WHERE cli.CLI_INAC = 0 AND cli.CLI_DESP = 1 AND cli.CLI_NIF = @nifImportador
-- se cliente (importador) não existir, assume como cliente "Consumidor Final"
			IF ISNULL(@CodigoCliente, '') = ''
			BEGIN
				SELECT TOP 1 @CodigoCliente = CLI_CODI, @CodigoClienteCC = ISNULL(NULLIF(CLI_CCOR, ''), CLI_CODI), @NIFResponsavelCaucaoCliente = CLI_CNIF, 						
					@BeneficiarioIVACliente = (CASE
						WHEN  (CLI_BIVA = 1) AND (CLI_DIBI <= @data) THEN 1 
						ELSE 0
					END), 
					@CaucaoCliente = (CASE 
						WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN (ISNULL(RIGHT(CLI_ANO1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(CLI_NCA1))) + CLI_NCA1)
						WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN (ISNULL(RIGHT(CLI_ANO2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(CLI_NCA2))) + CLI_NCA2)
						WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN (ISNULL(RIGHT(CLI_ANO3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(CLI_NCA3))) + CLI_NCA3)
						WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN (ISNULL(RIGHT(CLI_ANO4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(CLI_NCA4))) + CLI_NCA4)
						WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN (ISNULL(RIGHT(CLI_ANO5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(CLI_NCA5))) + CLI_NCA5)
						ELSE NULL 
					END),
					@AnoCaucaoCliente = (CASE 
						WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN CLI_ANO1
						WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN CLI_ANO2
						WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN CLI_ANO3
						WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN CLI_ANO4
						WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN CLI_ANO5
						ELSE NULL 
					END),
					@TipoCaucaoCliente = (CASE 
						WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN CLI_TCA1
						WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN CLI_TCA2
						WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN CLI_TCA3
						WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN CLI_TCA4
						WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN CLI_TCA5
						ELSE NULL 
					END),
					@AlfandegaCaucaoCliente = (CASE 
						WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN ALF_CODI1
						WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN ALF_CODI2
						WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN ALF_CODI3
						WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN ALF_CODI4
						WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN ALF_CODI5
						ELSE NULL 
					END),
					@CodAcessoCaucaoCliente = (CASE 
						WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN CLI_CCA1
						WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN CLI_CCA2
						WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN CLI_CCA3
						WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN CLI_CCA4
						WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN CLI_CCA5
						ELSE NULL 
					END),
					@OutrasRefCaucaoCliente = (CASE 
						WHEN (ISNULL(CLI_NCA1, '') <> '') AND (CLI_INA1 = 0) THEN CLI_OCA1
						WHEN (ISNULL(CLI_NCA2, '') <> '') AND (CLI_INA2 = 0) THEN CLI_OCA2
						WHEN (ISNULL(CLI_NCA3, '') <> '') AND (CLI_INA3 = 0) THEN CLI_OCA3
						WHEN (ISNULL(CLI_NCA4, '') <> '') AND (CLI_INA4 = 0) THEN CLI_OCA4
						WHEN (ISNULL(CLI_NCA5, '') <> '') AND (CLI_INA5 = 0) THEN CLI_OCA5
						ELSE NULL 
					END), 
					@CodigoRegiao = (CASE WHEN (@CodigoRegiao IS NULL) AND (@anexoB NOT IN ('H6', 'I1', 'I2')) THEN RES_CODI ELSE @CodigoRegiao END)
				FROM TAB_CLIE WITH(NOLOCK) 
				WHERE CLI_INAC = 0 AND CLI_DESP = 1 AND CLI_NIF = '999999990'
			END
-- verifica se o cliente (importador) é válido
			IF ISNULL(@CodigoCliente, '') = ''
				RAISERROR('Cliente importador "%s" inválido.', 16, 16, @nifImportador)							
-- obtem dados do país de destino
			SELECT @CodigoPaisDestino = PAI_CODI, @NomePaisDestino = PAI_NOME
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisDestino
-- verifica se o país de expedição é válido
			IF ISNULL(@CodigoPaisDestino, '') = ''
				RAISERROR('País de destino "%s" inválido.', 16, 17, @paisDestino)
			ELSE
				IF (ISNULL(@CodigoPaisDestino, '') = 'PT') AND (LEFT(@Regime, 2) IN ('42', '63'))
					RAISERROR('País "%s" de destino inválido para o regime "%s".', 16, 18, @paisImportador, @Regime)	
-- obtem dados do declarante
			SELECT @CodigoDeclarante = DEC_CODI, @NomeDeclarante = DEC_NOME, @CedulaDeclarante = DEC_CEDU, @NIFDeclarante = DEC_NIF, 				
				@CaucaoDeclarante = (CASE 
					WHEN (ISNULL(DEC_NCA1, '') <> '') AND (DEC_INA1 = 0) THEN (ISNULL(RIGHT(DEC_ACA1, 2), '') + ISNULL(ALF_CODI1, '') + REPLICATE('0', (7 - LEN(DEC_NCA1))) + DEC_NCA1)
					WHEN (ISNULL(DEC_NCA2, '') <> '') AND (DEC_INA2 = 0) THEN (ISNULL(RIGHT(DEC_ACA2, 2), '') + ISNULL(ALF_CODI2, '') + REPLICATE('0', (7 - LEN(DEC_NCA2))) + DEC_NCA2)
					WHEN (ISNULL(DEC_NCA3, '') <> '') AND (DEC_INA3 = 0) THEN (ISNULL(RIGHT(DEC_ACA3, 2), '') + ISNULL(ALF_CODI3, '') + REPLICATE('0', (7 - LEN(DEC_NCA3))) + DEC_NCA3)
					WHEN (ISNULL(DEC_NCA4, '') <> '') AND (DEC_INA4 = 0) THEN (ISNULL(RIGHT(DEC_ACA4, 2), '') + ISNULL(ALF_CODI4, '') + REPLICATE('0', (7 - LEN(DEC_NCA4))) + DEC_NCA4)
					WHEN (ISNULL(DEC_NCA5, '') <> '') AND (DEC_INA5 = 0) THEN (ISNULL(RIGHT(DEC_ACA5, 2), '') + ISNULL(ALF_CODI5, '') + REPLICATE('0', (7 - LEN(DEC_NCA5))) + DEC_NCA5)
					ELSE NULL 
				END),
				@AnoCaucaoDeclarante = (CASE 
					WHEN (ISNULL(DEC_NCA1, '') <> '') AND (DEC_INA1 = 0) THEN DEC_ACA1
					WHEN (ISNULL(DEC_NCA2, '') <> '') AND (DEC_INA2 = 0) THEN DEC_ACA2
					WHEN (ISNULL(DEC_NCA3, '') <> '') AND (DEC_INA3 = 0) THEN DEC_ACA3
					WHEN (ISNULL(DEC_NCA4, '') <> '') AND (DEC_INA4 = 0) THEN DEC_ACA4
					WHEN (ISNULL(DEC_NCA5, '') <> '') AND (DEC_INA5 = 0) THEN DEC_ACA5
					ELSE NULL 
				END),
				@TipoCaucaoDeclarante = (CASE 
					WHEN (ISNULL(DEC_NCA1, '') <> '') AND (DEC_INA1 = 0) THEN DEC_TCA1
					WHEN (ISNULL(DEC_NCA2, '') <> '') AND (DEC_INA2 = 0) THEN DEC_TCA2
					WHEN (ISNULL(DEC_NCA3, '') <> '') AND (DEC_INA3 = 0) THEN DEC_TCA3
					WHEN (ISNULL(DEC_NCA4, '') <> '') AND (DEC_INA4 = 0) THEN DEC_TCA4
					WHEN (ISNULL(DEC_NCA5, '') <> '') AND (DEC_INA5 = 0) THEN DEC_TCA5
					ELSE NULL 
				END),
				@AlfandegaCaucaoDeclarante = (CASE 
					WHEN (ISNULL(DEC_NCA1, '') <> '') AND (DEC_INA1 = 0) THEN ALF_CODI1
					WHEN (ISNULL(DEC_NCA2, '') <> '') AND (DEC_INA2 = 0) THEN ALF_CODI2
					WHEN (ISNULL(DEC_NCA3, '') <> '') AND (DEC_INA3 = 0) THEN ALF_CODI3
					WHEN (ISNULL(DEC_NCA4, '') <> '') AND (DEC_INA4 = 0) THEN ALF_CODI4
					WHEN (ISNULL(DEC_NCA5, '') <> '') AND (DEC_INA5 = 0) THEN ALF_CODI5
					ELSE NULL 
				END),
				@CodAcessoCaucaoDeclarante = (CASE 
					WHEN (ISNULL(DEC_NCA1, '') <> '') AND (DEC_INA1 = 0) THEN DEC_CCA1
					WHEN (ISNULL(DEC_NCA2, '') <> '') AND (DEC_INA2 = 0) THEN DEC_CCA2
					WHEN (ISNULL(DEC_NCA3, '') <> '') AND (DEC_INA3 = 0) THEN DEC_CCA3
					WHEN (ISNULL(DEC_NCA4, '') <> '') AND (DEC_INA4 = 0) THEN DEC_CCA4
					WHEN (ISNULL(DEC_NCA5, '') <> '') AND (DEC_INA5 = 0) THEN DEC_CCA5
					ELSE NULL 
				END),
				@OutrasRefCaucaoDeclarante = (CASE 
					WHEN (ISNULL(DEC_NCA1, '') <> '') AND (DEC_INA1 = 0) THEN DEC_OCA1
					WHEN (ISNULL(DEC_NCA2, '') <> '') AND (DEC_INA2 = 0) THEN DEC_OCA2
					WHEN (ISNULL(DEC_NCA3, '') <> '') AND (DEC_INA3 = 0) THEN DEC_OCA3
					WHEN (ISNULL(DEC_NCA4, '') <> '') AND (DEC_INA4 = 0) THEN DEC_OCA4
					WHEN (ISNULL(DEC_NCA5, '') <> '') AND (DEC_INA5 = 0) THEN DEC_OCA5
					ELSE NULL 
				END)
			FROM TAB_DECL WITH(NOLOCK) 
			WHERE DEC_INAC = 0 AND DEC_CODI = @declarante
-- verifica se o declarante é válido
			IF ISNULL(@CodigoDeclarante, '') = ''
				RAISERROR('Declarante "%s" inválido.', 16, 19, @declarante)						
-- obtem dados da condição de entrega 
			SELECT @CodigoCondicaoEntrega = CEN_CODI, @TipoLocCondicaoEntrega = CEN_LOCT, @OpcaoLocCondicaoEntrega = CEN_LOCD, 
				@CodigoFormula = (CASE 
									WHEN CEN_FOR1 = 1 THEN FIN_CODI1 
									WHEN CEN_FOR2 = 1 THEN FIN_CODI2 
									WHEN CEN_FOR3 = 1 THEN FIN_CODI3 
									WHEN CEN_FOR4 = 1 THEN FIN_CODI4 
									WHEN CEN_FOR5 = 1 THEN FIN_CODI5 
									ELSE NULL 
								END)
			FROM TAB_CENT WITH(NOLOCK)
			WHERE CEN_CODI = @condicaoEntrega
-- verifica se a condição de entrega é válida
			IF ISNULL(@CodigoCondicaoEntrega, '') = '' 
				RAISERROR('Condição de entrega "%s" inválida.', 16, 20, @condicaoEntrega)	
-- obtem dados da formula obtida	
			SELECT @DescricaoFormula = NULLIF(FIN_DESC, ''), 
				@FormulaFOB = FIN_VFOB, 
				@FormulaPositiva = (CASE 
										WHEN ISNULL(NULLIF(CHARINDEX('+', ISNULL(FIN_DESC, '')), 0), 999999999) < ISNULL(NULLIF(CHARINDEX('-', ISNULL(FIN_DESC, '')), 0), 999999999) THEN 1 
										ELSE 0 
									END)			
			FROM TAB_FINC WITH(NOLOCK)
			WHERE FIN_CODI = @CodigoFormula
-- obtem dados do país da condição de entrega
			SELECT @CodigoPaisCondicaoEntrega = PAI_CODI
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisCE
-- verifica se o país da condição de entrega é válido
			IF (ISNULL(@paisCE, '') <> '') AND (ISNULL(@CodigoPaisCondicaoEntrega, '') = '')
				RAISERROR('País da condição de entrega "%s" inválido.', 16, 21, @paisCE)	
-- obtem dados do porto/aeroporto
			SELECT @CodigoPortoAeroporto = PAE_CODI
			FROM TAB_PAER WITH(NOLOCK)
			WHERE PAE_CODI = @portoAeroporto AND ((@FormulaPositiva = 0 AND PAI_CODI = 'PT') OR (@FormulaPositiva = 1 AND PAI_CODI = ISNULL(NULLIF(@CodigoPaisExportador, ''), PAI_CODI)))
-- verifica se o porto/aeroporto é válido
			IF (ISNULL(@portoAeroporto, '') <> '') AND (ISNULL(@CodigoPortoAeroporto, '') = '')
				RAISERROR('Porto/Aeroporto "%s" inválido.', 16, 22, @portoAeroporto)	
-- obtem dados da alfândega de sujeição
			SELECT @CodigoAlfandegaSujeicao = ALF_CODI, @NomeAlfandegaSujeicao = ALF_NOME, @CodigoLocalizacaoMercadoriasEstanciaSujeicao = LME_CODI, 
				@CodigoPortoAeroporto = (CASE WHEN (ISNULL(@CodigoPortoAeroporto, '') = '') AND (ISNULL(@localidadeCE, '') = '') AND (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (@FormulaPositiva = 0) AND (ISNULL(PAE_CODI, '') <> '') THEN PAE_CODI ELSE @CodigoPortoAeroporto END), 				
				@tipoLocalizacao = (CASE WHEN (ISNULL(@tipoLocalizacao, '') = '') AND (@anexoB <> 'H6') THEN (CASE ALF_TLOC WHEN 'EA' THEN 'A' WHEN 'LA' THEN 'B' WHEN 'OL' THEN 'D' ELSE 'B' END) ELSE @tipoLocalizacao END), 
				@qualificador = (CASE WHEN (ISNULL(@qualificador, '') = '') AND (@anexoB <> 'H6') THEN (CASE ALF_TLOC WHEN 'EA' THEN 'V' WHEN 'LA' THEN 'Y' WHEN 'OL' THEN 'Z' ELSE NULL END) ELSE @qualificador END)
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE LEN(ALF_CODI) = 8 AND ALF_CODI = @estancia
-- verifica se a alfândega é válida
			IF ISNULL(@CodigoAlfandegaSujeicao, '') = ''
				RAISERROR('Alfândega "%s" inválida.', 16, 23, @estancia)
			ELSE
				IF (@anexoB = 'H6') AND (ISNULL(@CodigoAlfandegaSujeicao, '') <> 'PT000236')
					RAISERROR('Alfândega "%s" inválida para o anexo B "%s".', 16, 24, @CodigoAlfandegaSujeicao, @anexoB)
				ELSE
					IF (@anexoB <> 'H6') AND (@despachoCentralizado = 1)
						SET @CodigoAlfandegaApresentacao = @CodigoAlfandegaSujeicao			
-- obtem dados da natureza de transação
			SELECT @CodigoNaturezaTransacao = NTR_CODI, @NomeNaturezaTransacao = NTR_NOME
			FROM TAB_NTRA WITH(NOLOCK)
			WHERE NTR_CODI = @naturezaTransacao	
-- verifica se a natureza de transação é válida
			IF (ISNULL(@naturezaTransacao, '') <> '') AND (ISNULL(@CodigoNaturezaTransacao, '') = '')
				RAISERROR('Natureza de transação "%s" inválida.', 16, 25, @naturezaTransacao)							
-- obtem dados do país da moeda do montante
			SELECT @CodigoPaisMontante = PAI_CODI, @MoedaMontante = PAI_PREF, @CambioMontante = dbo.FNT_Geral_ObtemCambio(0, PAI_CODI, @data)
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisFatura
-- verifica se o país da moeda do montante é válido
			IF ISNULL(@CodigoPaisMontante, '') = ''				
				RAISERROR('País "%s" da moeda da fatura inválido.', 16, 26, @paisFatura)	
			ELSE
				SET @ValorTotalEUR = ROUND(@valorTotalFatura / ISNULL(NULLIF(@CambioMontante, 0), 1), 2)
-- obtem dados do país da moeda do frete
			SELECT @CodigoPaisFrete = PAI_CODI, @MoedaFrete = PAI_PREF, @CambioFrete = dbo.FNT_Geral_ObtemCambio(0, PAI_CODI, @data)
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisFrete
-- verifica se o país da moeda do frete é válido
			IF ISNULL(@CodigoPaisFrete, '') = ''	
				RAISERROR('País "%s" da moeda do frete inválido.', 16, 27, @paisFrete)
-- obtem dados do país da moeda do seguro
			SELECT @CodigoPaisSeguro = PAI_CODI, @MoedaSeguro = PAI_PREF, @CambioSeguro = dbo.FNT_Geral_ObtemCambio(0, PAI_CODI, @data)
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisSeguro
-- verifica se o país da moeda do seguro é válido
			IF ISNULL(@CodigoPaisSeguro, '') = ''	
				RAISERROR('País "%s" da moeda do seguro inválido.', 16, 28, @paisSeguro)						
-- verifica se a massa líquida/massa bruta são válidas
			IF @totalMassaLiquida > @totalMassaBruta
				RAISERROR('Massa líquida superior à massa bruta.', 16, 29)															
-- obtem dados do meio de transporte fronteira
			SELECT @CodigoMeioTransporteFronteira = MTR_CODI, @NomeMeioTransporteFronteira = MTR_NOME				
			FROM TAB_MTRA WITH(NOLOCK)
			WHERE MTR_CODI = @meioTransporteFronteira
-- verifica se o meio de transporte fronteira é válido
			IF (ISNULL(@meioTransporteFronteira, '') <> '') AND (ISNULL(@CodigoMeioTransporteFronteira, '') = '')
				RAISERROR('Meio de transporte fronteira "%s" inválido.', 16, 30, @meioTransporteFronteira)	
-- obtem dados do país do meio de transporte fronteira
			SELECT @CodigoPaisMeioTransporteFronteira = PAI_CODI	
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = @paisFronteira
-- verifica se o país do meio de transporte fronteira é válido
			IF (ISNULL(@paisFronteira, '') <> '') AND (ISNULL(@CodigoPaisMeioTransporteFronteira, '') = '')
				RAISERROR('País do meio de transporte fronteira "%s" inválido.', 16, 31, @paisFronteira)
-- obtem dados do meio de transporte interior
			SELECT @CodigoMeioTransporteInterior = MTR_CODI
			FROM TAB_MTRA WITH(NOLOCK)
			WHERE MTR_CODI = @meioTransporteInterior
-- verifica se o meio de transporte interior é válido
			IF (ISNULL(@meioTransporteInterior, '') <> '') AND (ISNULL(@CodigoMeioTransporteInterior, '') = '')
				RAISERROR('Meio de transporte interior "%s" inválido.', 16, 32, @meioTransporteInterior)	
-- obtem dados do meio de transporte chegada
			SELECT @CodigoMeioTransporteChegada = mtr.MTR_CODI, @NomeMeioTransporteChegada = mtr.MTR_NOME, 
				@TotalOptativas = (CASE mtr.MTR_OPAU 
												WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
																	FROM TAB_MTRO WITH(NOLOCK) 
																	WHERE MTR_IDTY = mtr.MTR_IDTY 
																		AND @totalMassaBruta BETWEEN MTO_LMNP AND MTO_LMXP 
																		AND @ValorTotalEUR BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
												ELSE ISNULL(mtr.MTR_VOP1, 0) 
											END), 
				@TipoIdentificacaoMeioTransporte = (CASE WHEN @anexoB NOT IN ('H2', 'H6', 'I1', 'I2') THEN mtr.MTR_TIPO ELSE NULL END), 
				@MeioTransportePorVolume = (CASE ISNULL(mtr.MTR_VPVL, 0) WHEN 2 THEN 1 ELSE 0 END), 
				@CodigoMeioTransporteFronteira = (CASE WHEN (ISNULL(@CodigoMeioTransporteFronteira, '') = '') AND (@anexoB NOT IN ('H6', 'I1', 'I2')) THEN mtr.MTR_CODI ELSE @CodigoMeioTransporteFronteira END)
			FROM TAB_MTRA AS mtr WITH(NOLOCK)
			WHERE mtr.MTR_CODI = @meioTransporteChegada
-- verifica se o meio de transporte é válido
			IF ISNULL(@CodigoMeioTransporteChegada, '') = ''
				RAISERROR('Meio de transporte chegada "%s" inválido.', 16, 33, @meioTransporteChegada)	
-- obtem dados da localização de mercadorias
			SELECT @CodigoLocalizacaoMercadorias = LME_CODI, @NomeLocalizacaoMercadorias = LME_NOME
			FROM TAB_LMER WITH(NOLOCK)
			WHERE LME_CODI = @armazemDTP AND LME_FLUX = 1 AND LEFT(RIGHT(LME_CODI, 5), 3) = (CASE @qualificador WHEN 'U' THEN LEFT(RIGHT(LME_CODI, 5), 3) ELSE RIGHT(@CodigoAlfandegaSujeicao, 3) END)
-- verifica se a localização das mercadorias é válida
			IF (ISNULL(@armazemDTP, '') <> '') AND (ISNULL(@CodigoLocalizacaoMercadorias, '') = '')
				RAISERROR('Armazém DTP "%s" da localização das mercadorias inválido.', 16, 34, @armazemDTP)
			ELSE
				IF (ISNULL(@CodigoLocalizacaoMercadorias, '') = '') AND (ISNULL(@qualificador, '') = 'Y') 
					SET @CodigoLocalizacaoMercadorias = @CodigoLocalizacaoMercadoriasEstanciaSujeicao
-- obtem dados da estância da localização das mercadorias
			SELECT @CodigoAlfandegaLM = ALF_CODI, @NomeAlfandegaLM = ALF_NOME
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE LEFT(ALF_CODI, 2) = 'PT' AND LEN(ALF_CODI) = 8 AND ALF_CODI = @estanciaLM
-- verifica se a estância da localização das mercadorias é válida
			IF (ISNULL(@estanciaLM, '') <> '') AND (ISNULL(@CodigoAlfandegaLM, '') = '')
				RAISERROR('Alfândega "%s" da localização das mercadorias inválida.', 16, 35, @estanciaLM)
			ELSE
				IF (ISNULL(@CodigoAlfandegaLM, '') = '') AND (ISNULL(@qualificador, '') = 'V') 
					SET @CodigoAlfandegaLM = @CodigoAlfandegaSujeicao
-- obtem dados do armazém
			SELECT @CodigoArmazem = arm.ARM_CODI, @NomeArmazem = arm.ARM_NOME, @CodigoDocumentoArmazem = arm.DOC_CODI, @NumReferenciaArmazem = arm.ARM_NAUT, @EORIArmazem = arm.ARM_EORI, 
				@CodigoTipoArmazem = tar.TAR_CODI, @NomeTipoArmazem = tar.TAR_DESC
			FROM TAB_ARMZ AS arm WITH(NOLOCK)
				LEFT OUTER JOIN TAB_TARM AS tar WITH(NOLOCK) ON arm.TAR_CODI = tar.TAR_CODI
			WHERE arm.ARM_CODI = @armazem
-- verifica se o armazém é válido
			IF (ISNULL(@armazem, '') <> '') AND (ISNULL(@CodigoArmazem, '') = '')
				RAISERROR('Armazém "%s" inválido.', 16, 36, @armazem)
-- obtem dados do país da moeda da verba transitário
			SELECT @CodigoPaisVerbaTransitario = PAI_CODI, @MoedaVerbaTransitario = PAI_PREF, @CambioVerbaTransitario = dbo.FNT_Geral_ObtemCambio(0, PAI_CODI, @data)
			FROM TAB_PAIS WITH(NOLOCK)
			WHERE PAI_CODI = 'EU'
-- verifica se o país da moeda da verba transitário é válido
			IF ISNULL(@CodigoPaisVerbaTransitario, '') = ''	
				RAISERROR('País "EU" da moeda da verba transitário inválido.', 16, 37)	
-- calcula a localidade e pais da condição de entrega
			IF (ISNULL(@CodigoPortoAeroporto, '') = '') AND (ISNULL(@localidadeCE, '') = '') AND (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (@TipoLocCondicaoEntrega = 1)
			BEGIN
				IF @OpcaoLocCondicaoEntrega = 0 
					SET @localidadeCE = @localidadeExportador 
				ELSE 
					SET @localidadeCE = @localidadeImportador 
			END 
			IF (ISNULL(@CodigoPortoAeroporto, '') = '') AND (ISNULL(@paisCE, '') = '') AND (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (@TipoLocCondicaoEntrega = 1)
			BEGIN
				IF @OpcaoLocCondicaoEntrega = 0 
					SET @CodigoPaisCondicaoEntrega = @CodigoPaisExportador 
				ELSE 
					SET @CodigoPaisCondicaoEntrega = @CodigoPaisImportador 
			END
-- calcula todos os dados da garantia		
			IF @anexoB IN ('H2', 'I1', 'I2')
			BEGIN
				SET @GarantiaGlobal = 0
				SET @TipoEntidadeCaucao = NULL
				SET @NumeroNRG = NULL
				SET @AnoCaucao = NULL
				SET @TipoCaucao = NULL
				SET @AlfandegaCaucao = NULL
				SET @CodAcessoCaucao = NULL
				SET @OutrasRefCaucao = NULL
				SET @NIFResponsavelCaucao = NULL
			END
			ELSE
			BEGIN
				SET  @GarantiaGlobal = 1
				IF ISNULL(@CaucaoCliente, '') <> ''
				BEGIN
					SET @TipoEntidadeCaucao = 1
					SET @NumeroNRG = @CaucaoCliente
					SET @AnoCaucao = @AnoCaucaoCliente
					SET @TipoCaucao = @TipoCaucaoCliente
					SET @AlfandegaCaucao = @AlfandegaCaucaoCliente
					SET @CodAcessoCaucao = @CodAcessoCaucaoCliente
					SET @OutrasRefCaucao = @OutrasRefCaucaoCliente
					IF @anexoB IN ('H1', 'H3', 'H4', 'H5', 'H6')
						SET @NIFResponsavelCaucao = @NIFResponsavelCaucaoCliente
					ELSE
						SET @NIFResponsavelCaucao = NULL
				END
				ELSE
					IF ISNULL(@CaucaoDeclarante, '') <> ''
					BEGIN
						SET @TipoEntidadeCaucao = 0
						SET @NumeroNRG = @CaucaoDeclarante
						SET @AnoCaucao = @AnoCaucaoDeclarante
						SET @TipoCaucao = @TipoCaucaoDeclarante
						SET @AlfandegaCaucao = @AlfandegaCaucaoDeclarante
						SET @CodAcessoCaucao = @CodAcessoCaucaoDeclarante
						SET @OutrasRefCaucao = @OutrasRefCaucaoDeclarante
						SET @NIFResponsavelCaucao = NULL
					END
					ELSE
					BEGIN
						SET @TipoEntidadeCaucao = NULL
						SET @NumeroNRG = NULL
						SET @AnoCaucao = NULL
						SET @TipoCaucao = NULL
						SET @AlfandegaCaucao = NULL
						SET @CodAcessoCaucao = NULL
						SET @OutrasRefCaucao = NULL
						SET @NIFResponsavelCaucao = NULL
					END	
			END		
-- calcula os dados do endereço das mercadorias
			IF (ISNULL(@moradaLM, '') = '') AND (ISNULL(@qualificador, '') = 'Z')
				SET @moradaLM = @moradaImportador
			IF (ISNULL(@codigoPostalLM, '') = '') AND (ISNULL(@qualificador, '') = 'Z')
				SET @codigoPostalLM = @codigoPostalImportador
			IF (ISNULL(@localidadeLM, '') = '') AND (ISNULL(@qualificador, '') = 'Z')
				SET @localidadeLM = @localidadePostalImportador
-- verifica as regras da estância de apresentação
			IF (@anexoB = 'H6') AND (ISNULL(@CodigoAlfandegaApresentacao, '') <> '')
				RAISERROR('Estância de apresentação "%s" inválida para o anexo B "%s".', 16, 38, @CodigoAlfandegaApresentacao, @anexoB)
			ELSE
				IF (@despachoCentralizado = 0) AND (ISNULL(@CodigoAlfandegaApresentacao, '') <> '')
					RAISERROR('Estância de apresentação "%s" inválida para despacho centralizado.', 16, 39, @CodigoAlfandegaApresentacao)
				ELSE
					IF (@anexoB <> 'H6') AND (@despachoCentralizado = 1) AND (ISNULL(@CodigoAlfandegaApresentacao, '') = '')
						RAISERROR('O anexo B "%s" com despacho centralizado obriga ao preenchimento da estância de apresentação.', 16, 40, @anexoB)
-- verifica as regras da massa líquida
			IF (@anexoB IN ('H2', 'H3', 'I2')) AND (@totalMassaLiquida > 0)
				RAISERROR('O anexo B "%s" não permite a definição de massa líquida.', 16, 41, @anexoB)
			ELSE
				IF (@anexoB NOT IN ('H2', 'H3', 'I2')) AND (@totalMassaLiquida = 0)
					RAISERROR('O anexo B "%s" obriga ao preenchimento da massa líquida.', 16, 42, @anexoB)	
-- verifica as regras do número NRUR
			IF (@anexoB = 'I2') AND (ISNULL(@numeroNRUR, '') <> '')
				RAISERROR('Número NRUR "%s" inválido para o anexo B "%s".', 16, 43, @numeroNRUR, @anexoB)	
-- verifica as regras da natureza de transação
			IF (@anexoB IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoNaturezaTransacao, '') <> '') 
				RAISERROR('Natureza de transação "%s" inválida para o anexo B "%s".', 16, 44, @CodigoNaturezaTransacao, @anexoB)
			ELSE
				IF (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoNaturezaTransacao, '') = '') 
					RAISERROR('O anexo B "%s" obriga ao preenchimento da natureza de transação.', 16, 45, @anexoB)
-- verifica as regras do meio de transporte fronteira
			IF (@anexoB IN ('H6', 'I1', 'I2')) AND (ISNULL(@CodigoMeioTransporteFronteira, '') <> '') 
				RAISERROR('Meio de transporte fronteira "%s" inválido para o anexo B "%s".', 16, 46, @CodigoMeioTransporteFronteira, @anexoB)
			ELSE
				IF (@anexoB NOT IN ('H6', 'I1', 'I2')) AND (ISNULL(@CodigoMeioTransporteFronteira, '') = '') 
					RAISERROR('O anexo B "%s" obriga ao preenchimento do meio de transporte fronteira.', 16, 47, @anexoB)
-- verifica as regras do país do meio de transporte fronteira
			IF (@anexoB IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoPaisMeioTransporteFronteira, '') <> '')
				RAISERROR('País do meio de transporte fronteira "%s" inválido para o anexo B "%s".', 16, 48, @CodigoPaisMeioTransporteFronteira, @anexoB)
			ELSE
				IF (ISNULL(@CodigoMeioTransporteFronteira, '') = '') AND (ISNULL(@CodigoPaisMeioTransporteFronteira, '') <> '')
					RAISERROR('País do meio de transporte fronteira "%s" inválido quando o meio de transporte fronteira não está definido.', 16, 49, @CodigoPaisMeioTransporteFronteira)
-- verifica as regras do meio de transporte interior
			IF (@anexoB IN ('H6', 'I1', 'I2')) AND (ISNULL(@CodigoMeioTransporteInterior, '') <> '')
				RAISERROR('Meio de transporte interior "%s" inválido para o anexo B "%s".', 16, 50, @CodigoMeioTransporteInterior, @anexoB)						
			ELSE
				IF (@anexoB IN ('H2', 'H5')) AND (ISNULL(@CodigoMeioTransporteInterior, '') = '')
					RAISERROR('O anexo B "%s" obriga ao preenchimento do meio de transporte interior.', 16, 51, @anexoB)
-- verifica as regras da localização da condição de entrega
			IF (@anexoB IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@localidadeCE, '') <> '')
				RAISERROR('Localização da condição de entrega "%s" inválida para o anexo B "%s".', 16, 52, @localidadeCE, @anexoB)
			ELSE
				IF (ISNULL(@CodigoPortoAeroporto, '') <> '') AND (ISNULL(@localidadeCE, '') <> '')
					RAISERROR('Localização da condição de entrega "%s" inválida quando o porto/aeroporto está definido.', 16, 53, @localidadeCE)
				ELSE
					IF (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoPortoAeroporto, '') = '') AND (ISNULL(@localidadeCE, '') = '')
						RAISERROR('O anexo B "%s" sem porto/aeroporto definido obriga ao preenchimento da localização da condição de entrega.', 16, 54, @anexoB)	
-- verifica as regras do país da condição de entrega
			IF (@anexoB IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoPaisCondicaoEntrega, '') <> '')
				RAISERROR('País "%s" da condição de entrega inválido para o anexo B "%s".', 16, 55, @CodigoPaisCondicaoEntrega, @anexoB)
			ELSE				
				IF (ISNULL(@CodigoPortoAeroporto, '') <> '') AND (ISNULL(@CodigoPaisCondicaoEntrega, '') <> '')
					RAISERROR('País "%s" da condição de entrega inválido quando o porto/aeroporto está definido.', 16, 56, @CodigoPaisCondicaoEntrega)
				ELSE
					IF (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoPortoAeroporto, '') = '') AND (ISNULL(@CodigoPaisCondicaoEntrega, '') = '')
						RAISERROR('O anexo B "%s" sem porto/aeroporto definido obriga ao preenchimento do país da condição de entrega.', 16, 57, @anexoB)
-- verifica as regras do porto/aeroporto da condição de entrega
			IF (@anexoB IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoPortoAeroporto, '') <> '')
				RAISERROR('Porto/Aeroporto "%s" da condição de entrega inválido para o anexo B "%s".', 16, 58, @CodigoPortoAeroporto, @anexoB)
			ELSE
				IF (ISNULL(@localidadeCE, '') <> '') AND (ISNULL(@CodigoPortoAeroporto, '') <> '')
					RAISERROR('Porto/Aeroporto "%s" da condição de entrega inválida quando a localização da condição de entrega está definida.', 16, 59, @CodigoPortoAeroporto)
				ELSE
					IF (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@localidadeCE, '') = '') AND (ISNULL(@CodigoPortoAeroporto, '') = '')
						RAISERROR('O anexo B "%s" sem localização da condição de entrega definida obriga ao preenchimento do porto/aeroporto da condição de entrega.', 16, 60, @anexoB)	
-- verifica as regras do tipo de identificação do meio de transporte
			IF (@anexoB IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@TipoIdentificacaoMeioTransporte, '') <> '')
				RAISERROR('Tipo de identificação do meio de transporte "%s" inválido para o anexo B "%s".', 16, 61, @TipoIdentificacaoMeioTransporte, @anexoB)
			ELSE
				IF (LEFT(ISNULL(@CodigoMeioTransporteChegada, '0'), 1) IN ('0', '5', '6', '7', '9')) AND (ISNULL(@TipoIdentificacaoMeioTransporte, '') <> '')
					RAISERROR('Tipo de identificação do meio de transporte "%s" inválido quando o meio de transporte chegada não está definido ou é "5", "6", "7" ou "9".', 16, 62, @TipoIdentificacaoMeioTransporte)
				ELSE
					IF (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (LEFT(ISNULL(@CodigoMeioTransporteChegada, '0'), 1) IN ('1', '2', '3', '4', '8')) AND (ISNULL(@TipoIdentificacaoMeioTransporte, '') = '')
						RAISERROR('O anexo B "%s" com meio de transporte chegada de "1", "2", "3", "4" ou "8" obriga ao preenchimento do tipo de identificação.', 16, 63, @anexoB)	
-- verifica as regras da identificação do meio de transporte
			IF (@anexoB IN ('H2', 'H6', 'I1', 'I2')) AND (ISNULL(@identificacaoTransporte, '') <> '')
				RAISERROR('Identificação do meio de transporte "%s" inválida para o anexo B "%s".', 16, 64, @identificacaoTransporte, @anexoB)
			ELSE
				IF (LEFT(ISNULL(@CodigoMeioTransporteChegada, '0'), 1) IN ('0', '5', '7')) AND (ISNULL(@identificacaoTransporte, '') <> '')
					RAISERROR('Identificação do meio de transporte "%s" inválida quando o meio de transporte chegada não está definido ou é "5" ou "7".', 16, 65, @identificacaoTransporte)
				ELSE
					IF (@anexoB NOT IN ('H2', 'H6', 'I1', 'I2')) AND (LEFT(ISNULL(@CodigoMeioTransporteChegada, '0'), 1) IN ('1', '2', '3', '4', '6', '8', '9')) AND (ISNULL(@identificacaoTransporte, '') = '')
						RAISERROR('O anexo B "%s" com meio de transporte chegada de "1", "2", "3", "4", "6", "8" ou "9" obriga ao preenchimento da identificação do meio de transporte.', 16, 66, @anexoB)	
-- verifica as regras da mercadoria contentorizada							
			IF (@anexoB = 'H6') AND (@contentorizada = 1)
				RAISERROR('Mercadoria não pode ser contentorizada para o anexo B "%s".', 16, 67, @anexoB)
			ELSE
				IF (@contentorizada = 0) AND (ISNULL(@numeroContentor, '') <> '')
					RAISERROR('Número do contentor "%s" inválido quando a mercadoria não é contentorizada.', 16, 68, @numeroContentor)
-- verifica as regras do tipo de localização
			IF (@anexoB = 'H6') AND (ISNULL(@tipoLocalizacao, '') <> '')
				RAISERROR('Tipo de localização "%s" inválida para o anexo B "%s".', 16, 69, @tipoLocalizacao, @anexoB)
			ELSE
				IF (@anexoB <> 'H6') AND (ISNULL(@tipoLocalizacao, '') = '')
					RAISERROR('O anexo B "%s" obriga ao preenchimento do tipo de localização.', 16, 70, @anexoB)
-- verifica as regras do armazém
			IF (@anexoB IN ('H5', 'H6', 'I1', 'I2')) AND (ISNULL(@CodigoArmazem, '') <> '')
				RAISERROR('Armazém "%s" inválido para o anexo B "%s".', 16, 71, @CodigoArmazem, @anexoB)
			ELSE
				IF (@anexoB = 'H2') AND (ISNULL(@CodigoArmazem, '') = '')
					RAISERROR('O anexo B "%s" obriga ao preenchimento do armazém.', 16, 72, @anexoB)
				ELSE
					IF (@anexoB IN ('H1', 'H3', 'H4')) AND (LEFT(@Regime, 2) = '07') AND (ISNULL(@CodigoArmazem, '') = '')
						RAISERROR('O anexo B "%s" com o regime "%s" obrigam ao preenchimento do armazém.', 16, 73, @anexoB, @Regime)
-- verifica as regras do NIF responsável da garantia
			IF (@anexoB IN ('H2', 'I1', 'I2')) AND (ISNULL(@NIFResponsavelCaucao, '') <> '')
				RAISERROR('NIF responsável da garantia "%s" inválido para o anexo B "%s".', 16, 74, @NIFResponsavelCaucao, @anexoB)
			ELSE
				IF (ISNULL(@TipoEntidadeCaucao, -1) = 0) AND (ISNULL(@NIFResponsavelCaucao, '') <> '')
					RAISERROR('NIF responsável da garantia "%s" inválido quando a garantia é do declarante.', 16, 75, @NIFResponsavelCaucao)
				ELSE
					IF (@anexoB IN ('H1', 'H3', 'H4', 'H5', 'H6')) AND (ISNULL(@TipoEntidadeCaucao, -1) = 1) AND (ISNULL(@NIFResponsavelCaucao, '') = '')
						RAISERROR('O anexo B "%s" com a garantia do cliente obriga ao preenchimento do NIF responsável da garantia.', 16, 76, @anexoB)
-- verifica as regras do qualificador
			IF (@qualificador NOT IN ('U', 'Y')) AND (ISNULL(@CodigoLocalizacaoMercadorias, '') <> '')
				RAISERROR('Localização das mercadorias "%s" inválida para o qualificador "%s".', 16, 77, @CodigoLocalizacaoMercadorias, @qualificador)
			ELSE
				IF (@qualificador IN ('U', 'Y')) AND (ISNULL(@CodigoLocalizacaoMercadorias, '') = '')
					RAISERROR('O qualificador "%s" obriga ao preenchimento da localização das mercadorias.', 16, 78, @qualificador)
				ELSE
					IF (@qualificador <> 'V') AND (ISNULL(@CodigoAlfandegaLM, '') <> '')
						RAISERROR('Estância das mercadorias "%s" inválida para o qualificador "%s".', 16, 79, @CodigoAlfandegaLM, @qualificador)
					ELSE
						IF (@qualificador = 'V') AND (ISNULL(@CodigoAlfandegaLM, '') = '')
							RAISERROR('O qualificador "%s" obriga ao preenchimento da estância das mercadorias.', 16, 80, @qualificador)
						ELSE
							IF (@qualificador <> 'X') AND (ISNULL(@nifOperadorEconomico, '') <> '')
								RAISERROR('NIF do operador económico das mercadorias "%s" inválido para o qualificador "%s".', 16, 81, @nifOperadorEconomico, @qualificador)
							ELSE
								IF (@qualificador = 'X') AND (ISNULL(@nifOperadorEconomico, '') = '')
									RAISERROR('O qualificador "%s" obriga ao preenchimento do NIF do operador económico das mercadorias.', 16, 82, @qualificador)
								ELSE
									IF (@qualificador <> 'Z') AND ((ISNULL(@moradaLM, '') <> '') OR (ISNULL(@localidadeLM, '') <> '') OR (ISNULL(@codigoPostalLM, '') <> ''))
										RAISERROR('Dados de endereço das mercadorias "%s", "%s", "%s" inválidos para o qualificador "%s".', 16, 83, @moradaLM, @localidadeLM, @codigoPostalLM, @qualificador)
									ELSE
										IF (@qualificador = 'Z') AND ((ISNULL(@moradaLM, '') = '') OR (ISNULL(@localidadeLM, '') = '') OR (ISNULL(@codigoPostalLM, '') = ''))
											RAISERROR('O qualificador "%s" obriga ao preenchimento dos dados de endereço das mercadorias.', 16, 84, @qualificador)
-- verifica as regras do armazém
			IF (ISNULL(@CodigoArmazem, '') <> '') AND (ISNULL(@CodigoTipoArmazem, '') = '')
				RAISERROR('O armazém "%s" obriga ao preenchimento do tipo de armazém.', 16, 85, @CodigoArmazem)
			ELSE
				IF (ISNULL(@CodigoArmazem, '') <> '') AND (ISNULL(@CodigoDocumentoArmazem, '') = '')
					RAISERROR('O armazém "%s" obriga ao preenchimento do documento do armazém.', 16, 86, @CodigoArmazem)
				ELSE
					IF (ISNULL(@CodigoArmazem, '') <> '') AND (ISNULL(@NumReferenciaArmazem, '') = '')
						RAISERROR('O armazém "%s" obriga ao preenchimento do número de referência do armazém.', 16, 87, @CodigoArmazem)
					ELSE
						IF (ISNULL(@CodigoArmazem, '') <> '') AND (ISNULL(@EORIArmazem, '') = '')
							RAISERROR('O armazém "%s" obriga ao preenchimento do EORI titular autorização do armazém.', 16, 88, @CodigoArmazem)		
-- obtém a máscara de faturação do cliente/natureza
			SET @NumMascaras = 1
			SET @TipoMascara = 0
			SET @CodMascara = 0
			EXEC SP_ObtemMascaraFacturacao @CodigoClienteCC, @CodigoNatureza, @NumMascaras OUTPUT, @TipoMascara OUTPUT, @CodMascara OUTPUT
-- processa a inserção ou edição da declaração IMP-CAU conforme a ação
			IF @acao = 'I'
			BEGIN
-- se posição no armazém não definida, preenche com valor por defeito
				IF (ISNULL(@documentoTransporte, '') <> '') AND (ISNULL(@posicaoArmazem, '') = '')
					SET @posicaoArmazem = 'C' + RIGHT(@documentoTransporte, 1)
-- se numero NRUR não definido, preenche com valor por defeito (excepto em "I2")
				IF (ISNULL(@documentoTransporte, '') <> '') AND (@anexoB <> 'I2') AND (ISNULL(@numeroNRUR, '') = '')
					SET @numeroNRUR = @documentoTransporte
-- obtem valores totais da declaração existentes apenas nas adições
				DECLARE Totais CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						CAST(ISNULL(t.c.value('sum(marcasEVolumes/marcaEVolume/volumes)', 'float'), 0) AS int), 
						t.c.value('massaBruta[1]', 'decimal(18, 6)'), 
						t.c.value('montanteAd[1]', 'decimal(18, 3)'), 						
						t.c.value('valorFrete[1]', 'decimal(18, 3)'), 
						t.c.value('valorSeguro[1]', 'decimal(18, 3)')					
					FROM @XMLAdicoes.nodes('adicoes/adicao') AS t(c)
				OPEN Totais
				FETCH NEXT FROM Totais INTO @volumes, @massaBruta, @montanteAd, @valorFrete, @valorSeguro
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @TotalAdicoes = @TotalAdicoes + 1
					SET @TotalVolumes = @TotalVolumes + @volumes
					SET @valorFrete = ISNULL(@valorFrete, ROUND((CASE (@valorTotalFatura - @SomaMontantesAdicoes - @montanteAd) 
																	WHEN 0 THEN (@valorTotalFrete - @SomaFretesAdicoes) 
																	ELSE (@massaBruta * @valorTotalFrete / @totalMassaBruta) 
																END), 3))
					SET @valorSeguro = ISNULL(@valorSeguro, ROUND((CASE (@valorTotalFatura - @SomaMontantesAdicoes - @montanteAd) 
																	WHEN 0 THEN (@valorTotalSeguro - @SomaSegurosAdicoes) 
																	ELSE (@montanteAd * @valorTotalSeguro / @valorTotalFatura) 
																END), 3))					
					SET @ValorEUR = ROUND(@montanteAd / @CambioMontante, 2)
					SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@DescricaoFormula, 0, @CambioFrete, @CambioSeguro, @valorFrete, @valorSeguro, 0, 0, 0)
					SET @ValorEstatistico = dbo.fn_IMP_CalculaValorEstatistico(@ValorEUR, @Ajustamento)
					SET @TotalValorAduaneiro = @TotalValorAduaneiro + @ValorEstatistico
					SET @SomaMontantesAdicoes = @SomaMontantesAdicoes + @montanteAd
					SET @SomaFretesAdicoes = @SomaFretesAdicoes + @valorFrete
					SET @SomaSegurosAdicoes = @SomaSegurosAdicoes + @valorSeguro
					FETCH NEXT FROM Totais INTO @volumes, @massaBruta, @montanteAd, @valorFrete, @valorSeguro
				END
				CLOSE Totais
				DEALLOCATE Totais
-- obtem valores totais de volumes dirty, clean e scan da declaração existentes apenas nos manifestos
				DECLARE Totais CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('tipoManifesto[1]', 'int')				
					FROM @XMLManifestos.nodes('manifestos/manifesto') AS t(c)
					WHERE ISNULL(t.c.value('numeroCPA[1]', 'varchar(35)'), '') <> ''
				OPEN Totais
				FETCH NEXT FROM Totais INTO @tipoManifesto
				WHILE @@FETCH_STATUS = 0
				BEGIN				
					IF @tipoManifesto = 0 
						SET @TotalVolumesDirty = @TotalVolumesDirty + 1
					ELSE
						IF @tipoManifesto = 1
							SET @TotalVolumesClean = @TotalVolumesClean + 1
						ELSE
							IF @tipoManifesto = 2 
								SET @TotalVolumesScan = @TotalVolumesScan + 1											
					FETCH NEXT FROM Totais INTO @tipoManifesto
				END
				CLOSE Totais
				DEALLOCATE Totais	
-- obtem o número para a nova declaração
				SELECT TOP 1 @Numero = PDE_NPRO, @ValorTrafegoCTT = (CASE @MeioTransportePorVolume WHEN 1 THEN ISNULL(PDE_TPOS1, 0) ELSE 0 END)
				FROM TAB_PDES				
-- verifica se o número é válido
				IF @Numero = 0
					RAISERROR('Número da declaração não foi especificado.', 16, 89)			
-- constroi NRL
				SET @NRL = RIGHT(STR(@Ano, 4), 2) + 'PT' + REPLICATE('0', 9 - LEN(@NIFDeclarante)) + @NIFDeclarante + REPLICATE('0', 9 - LEN(LTRIM(STR(@Numero, 9)))) + LTRIM(STR(@Numero, 9))
-- insere os dados gerais da nova declaração IMP-CAU
				INSERT INTO PRO_DUCG(DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, TDE_CODI, DUC_TIPO, ALF_CODI, DUC_ADI5, DUC_TVL6, DUC_REF7, DUC_EXP2, DUC_DST8, DEC_CO14, PAI_PA15, PAI_P15A, 
					PAI_PA16, PAI_PA17, PAI_P17A, PAI_P17B, MTR_PT18, DUC_MT18, DUC_OP18, DUC_CT18, MTR_FT21, PAI_PA21, DUC_CT19, CEN_CO20, DUC_FR20, DUC_DE20, NTR_CO24, LME_CO30, DUC_LC30, 
					PAI_PR22, DUC_MT22, DUC_TX23, DUC_FRET, PAI_FRET, DUC_TXFR, DUC_SEGU, PAI_SEGU, DUC_TXSE, DUC_MLQT, DUC_MBRT, DUC_VTRN, PAI_VTRN, DUC_TXVT, DUC_VEUR, DUC_UFOB, DUC_VFOB, 
					DUC_DIRT, DUC_TFDA, DUC_ENOM, DUC_EMOR, DUC_ELOC, DUC_ECPO, DUC_ELPO, DUC_ENIF, PAI_ELIV, DUC_DNOM, DUC_DMOR, DUC_DLOC, DUC_DCPO, DUC_DLPO, DUC_DNIF, PAI_DLIV, DUC_HIST, 
					DUC_VLRC, DUC_VLRE, DUC_VATT, DUC_UCRI, DUC_DTCR, DUC_UALT, DUC_DTAL, NDE_NOME, TDE_NOME, ALF_NOME, PAI_NO15, PAI_NO16, PAI_NO17, PAI_MO22, PAI_MOFT, PAI_MOSG, PAI_MOVT, 
					DEC_NOME, DEC_CENI, MTR_NO18, MTR_NO21, DUC_MASC, DUC_NREQ, DUC_NDUR, DUC_T1RE, DUC_DDTE, DUC_DTVO, DUC_PAYM, DUC_NPDT, DUC_NPDD, DUC_NTDP, DUC_PARM, DUC_NVRF, DUC_TREM, 
					DUC_CIEX, DUC_CIDE, DUC_AERO, DUC_PPFC, DUC_NVOO, DUC_MCPA, DUC_NSEQ, DUC_REF1, DUC_REF2, DUC_SHIP, DUC_TRAC, DUC_DTYP, DUC_POSA, DUC_TPCG, DUC_FUPS, DUC_VDIR, DUC_VCLE, 
					DUC_D2NO, DUC_D2MO, DUC_D2LO, DUC_D2CP, DUC_D2LP, FIN_CODI, DUC_TPDS, DUC_TPDC, TDE_1CAS, TDE_2CAS, DUC_GTWY, DUC_DELG, DUC_TMSF, TDO_DOCU, CLI_CODI, CLI_NOME, DUC_CGLB, 
					DUC_CAUC, DUC_CANO, DUC_CTIP, DUC_TLOC, ALF_CODI1, ALF_NOME1, DUC_LAMO, DUC_LALO, DUC_LACP, ARM_CODI, ARM_NOME, TAR_CODI, TAR_DESC, DUC_NRLO, DUC_DUNO, DUC_CENT, NTR_NOME, 
					DUC_VBAT, DUC_VSCA, DUC_VFRC, DUC_MFRC, DUC_NVSR, FUP_CODI, DUC_DDDT, DUC_UNMD, DUC_NACT, DUC_BIVA, DUC_VDES, DUC_DTEL, DUC_DEMA, DUC_DCEN, DUC_ANXB, DUC_DGEN,  DEC_NIF, 
					DUC_CNIR, ALF_CODI2, DUC_CCAC, DUC_CORF, ALF_CODI3, PAI_CODI2, PAE_CODI, MTR_CODI, MTR_TIPO, DUC_CONT, DUC_QUAL, DUC_ONIF, DOC_CODI, DUC_NRAU, DUC_EORI, DUC_REGI)	
				OUTPUT inserted.DUC_IDTY, inserted.DUC_PNUM INTO @TblID
				VALUES (@Numero, --DUC_PNUM, 
					@Ano, --DUC_EANO, 
					@data, --DUC_DATA, 
					@CodigoNatureza, --NDE_CODI, 
					@documentoTransporte, --DUC_CPRT, 
					@CodigoTipoDeclaracao, --TDE_CODI, 
					@NaturezaTipoDeclaracao, --DUC_TIPO, 
					@CodigoAlfandegaSujeicao, --ALF_CODI, 
					@TotalAdicoes, --DUC_ADI5, 
					@TotalVolumes, --DUC_TVL6, 
					@numeroNRUR, --DUC_REF7, 
					@CodigoExportador, --DUC_EXP2, 
					@CodigoCliente, --DUC_DST8, 
					@CodigoDeclarante, --DEC_CO14, 
					@CodigoPaisExpedicao, --PAI_PA15, 
					@CodigoPaisExpedicao, --PAI_P15A, 
					@CodigoPaisExportador, --PAI_PA16, 
					@CodigoPaisDestino, --PAI_PA17, 
					@CodigoPaisDestino, --PAI_P17A, 
					@CodigoRegiao, --PAI_P17B, 
					@CodigoMeioTransporteChegada, --MTR_PT18, 
					@identificacaoTransporte, --DUC_MT18, 
					@TotalOptativas, --DUC_OP18, 
					@ValorTrafegoCTT, --DUC_CT18, 
					@CodigoMeioTransporteFronteira, --MTR_FT21, 
					@CodigoPaisMeioTransporteFronteira, --PAI_PA21, 
					@contentorizada, --DUC_CT19, 
					@CodigoCondicaoEntrega, --CEN_CO20, 
					@DescricaoFormula, --DUC_FR20, 
					@localidadeCE, --DUC_DE20, 
					@CodigoNaturezaTransacao, --NTR_CO24, 
					@CodigoLocalizacaoMercadorias, --LME_CO30, 
					@NomeLocalizacaoMercadorias, --DUC_LC30, 
					@CodigoPaisMontante, --PAI_PR22, 
					@valorTotalFatura, --DUC_MT22, 
					@CambioMontante, --DUC_TX23, 
					@valorTotalFrete, --DUC_FRET, 
					@CodigoPaisFrete, --PAI_FRET, 
					@CambioFrete, --DUC_TXFR, 
					@valorTotalSeguro, --DUC_SEGU, 
					@CodigoPaisSeguro, --PAI_SEGU, 
					@CambioSeguro, --DUC_TXSE, 
					@totalMassaLiquida, --DUC_MLQT, 
					@totalMassaBruta, --DUC_MBRT, 
					0, --DUC_VTRN, 
					@CodigoPaisVerbaTransitario, --PAI_VTRN, 
					@CambioVerbaTransitario, --DUC_TXVT, 
					@ValorTotalEUR, --DUC_VEUR, 
					@FormulaFOB, --DUC_UFOB, 
					0, --DUC_VFOB, 
					0, --DUC_DIRT, 
					0, --DUC_TFDA, 
					@nomeExportador, --DUC_ENOM, 
					@moradaExportador, --DUC_EMOR, 
					@localidadeExportador, --DUC_ELOC, 
					@codigoPostalExportador, --DUC_ECPO, 
					@localidadePostalExportador, --DUC_ELPO, 
					@nifExportador, --DUC_ENIF, 
					@CodigoPaisExportador, --PAI_ELIV, 
					@nomeImportador, --DUC_DNOM, 
					@moradaImportador, --DUC_DMOR, 
					@localidadeImportador, --DUC_DLOC, 
					@codigoPostalImportador, --DUC_DCPO, 
					@localidadePostalImportador, --DUC_DLPO, 
					@nifImportador, --DUC_DNIF, 
					@CodigoPaisImportador, --PAI_DLIV, 
					@anotacoes, --DUC_HIST, 
					0, --DUC_VLRC, 
					'Zero euros', --DUC_VLRE, 
					@TotalValorAduaneiro, --DUC_VATT, 
					@CodUtilizador, --DUC_UCRI, 
					@DataAtual, --DUC_DTCR, 
					@CodUtilizador, --DUC_UALT, 
					@DataAtual, --DUC_DTAL, 
					@NomeNatureza, --NDE_NOME, 
					@NomeTipoDeclaracao, --TDE_NOME, 
					@NomeAlfandegaSujeicao, --ALF_NOME, 
					@NomePaisExpedicao, --PAI_NO15, 
					@NomePaisExportador, --PAI_NO16, 
					@NomePaisDestino, --PAI_NO17, 
					@MoedaMontante, --PAI_MO22, 
					@MoedaFrete, --PAI_MOFT, 
					@MoedaSeguro, --PAI_MOSG, 
					@MoedaVerbaTransitario, --PAI_MOVT, 
					@NomeDeclarante, --DEC_NOME, 
					@CedulaDeclarante, --DEC_CENI, 
					@NomeMeioTransporteChegada, --MTR_NO18, 
					@NomeMeioTransporteFronteira, --MTR_NO21, 
					@CodMascara, --DUC_MASC, 
					@numeroRequerimento, --DUC_NREQ, 
					@numeroDURetorno, --DUC_NDUR, 
					@numeroT1Retorno, --DUC_T1RE, 
					@dataEntrada, --DUC_DDTE, 
					@dataVoo, --DUC_DTVO, 
					@payment, --DUC_PAYM, 
					@numeroPDDT, --DUC_NPDT, 
					@numeroPDDTDEV, --DUC_NPDD, 
					@numeroTD, --DUC_NTDP, 
					@posicaoArmazem, --DUC_PARM, 
					@vossaReferencia, --DUC_NVRF, 
					@totalMassaBruta, --DUC_TREM, 
					@numeroContaExpedidor, --DUC_CIEX, 
					ISNULL(@portesAcc, @numeroContaDestinatario), --DUC_CIDE, 
					@aeroportoOrigem, --DUC_AERO, 
					@condEntrega, --DUC_PPFC, 
					@numeroVoo, --DUC_NVOO, 
					@miniCPA, --DUC_MCPA, 
					@numeroSequencia, --DUC_NSEQ, 
					ISNULL(@despachoAcc, @referenciaExterna1), --DUC_REF1, 
					@referenciaExterna2, --DUC_REF2, 
					@shipID, --DUC_SHIP, 
					@tracking, --DUC_TRAC, 
					@dutyType, --DUC_DTYP, 
					ISNULL(@portes, @posicaoAviao), --DUC_POSA, 
					@tipoCarga, --DUC_TPCG, 
					@nomeFicheiro, --DUC_FUPS, 
					@TotalVolumesDirty, --DUC_VDIR, 
					@TotalVolumesClean, --DUC_VCLE, 
					@nomeOriginalDestinatario, --DUC_D2NO, 
					@moradaOriginalDestinatario, --DUC_D2MO, 
					@localidadeOriginalDestinatario, --DUC_D2LO, 
					@codigoPostalOriginalDestinatario, --DUC_D2CP, 
					@localidadePostalOriginalDestinatario, --DUC_D2LP, 
					@CodigoFormula, --FIN_CODI, 
					@tipoNIFImportador, --DUC_TPDS, 
					@estatutoDeclarante, --DUC_TPDC, 
					@1CasaTipoDeclaracao, --TDE_1CAS, 
					@2CasaTipoDeclaracao, --TDE_2CAS, 
					@gateway, --DUC_GTWY, 
					@locID, --DUC_DELG, 
					@TipoMascara, --DUC_TMSF, 
					@CodigoTipoDocContas, --TDO_DOCU, 
					@CodigoClienteServico, --CLI_CODI, 
					@NomeClienteServico, --CLI_NOME, 
					@GarantiaGlobal, --DUC_CGLB, 
					@NumeroNRG, --DUC_CAUC, 
					@AnoCaucao, --DUC_CANO, 
					@TipoCaucao, --DUC_CTIP, 
					@tipoLocalizacao, --DUC_TLOC, 
					@CodigoAlfandegaLM, --ALF_CODI1, 
					@NomeAlfandegaLM, --ALF_NOME1, 
					@moradaLM, --DUC_LAMO, 
					@localidadeLM, --DUC_LALO, 
					@codigoPostalLM, --DUC_LACP, 
					@CodigoArmazem, --ARM_CODI, 
					@NomeArmazem, --ARM_NOME, 
					@CodigoTipoArmazem, --TAR_CODI, 
					@NomeTipoArmazem, --TAR_DESC, 
					@NRL, --DUC_NRLO, 
					2, --DUC_DUNO, 
					@TipoEntidadeCaucao, --DUC_CENT, 
					@NomeNaturezaTransacao, --NTR_NOME, 
					1, --DUC_VBAT, 
					@TotalVolumesScan, --DUC_VSCA, 
					@freteOriginal, --DUC_VFRC, 
					@moedafreteOriginal, --DUC_MFRC, 
					@serviceLevel, --DUC_NVSR, 
					@CodigoFollowUp, --FUP_CODI,
					@dataDocumentoTransporte, --DUC_DDDT, 
					@CodigoUtilizadorNomeado, --DUC_UNMD, 
					@numeroACTM, --DUC_NACT, 
					@BeneficiarioIVACliente, --DUC_BIVA, 
					@despesas, --DUC_VDES, 
					@telefoneImportador, --DUC_DTEL, 
					@emailImportador, --DUC_DEMA, 
					@despachoCentralizado, --DUC_DCEN, 
					@anexoB, --DUC_ANXB, 
					@descricaoGenerica, --DUC_DGEN,  
					@NIFDeclarante, --DEC_NIF, 
					@NIFResponsavelCaucao, --DUC_CNIR, 
					@AlfandegaCaucao, --ALF_CODI2, 
					@CodAcessoCaucao, --DUC_CCAC, 
					@OutrasRefCaucao, --DUC_CORF, 
					@CodigoAlfandegaApresentacao, --ALF_CODI3, 
					@CodigoPaisCondicaoEntrega, --PAI_CODI2, 
					@CodigoPortoAeroporto, --PAE_CODI, 
					@CodigoMeioTransporteInterior, --MTR_CODI, 
					@TipoIdentificacaoMeioTransporte, --MTR_TIPO, 
					@numeroContentor, --DUC_CONT, 
					@qualificador, --DUC_QUAL, 
					@nifOperadorEconomico, --DUC_ONIF, 
					@CodigoDocumentoArmazem, --DOC_CODI, 
					@NumReferenciaArmazem, --DUC_NRAU, 
					@EORIArmazem, --DUC_EORI, 
					@Regime /*DUC_REGI*/)		
-- obtem o ID da nova declaração IMP-CAU
				SELECT @IdDeclaracao = ID, @Numero = NUMERO
				FROM @TblID
			END
			ELSE
			BEGIN
-- obtem o tipo de update especifico a realizar
				SELECT TOP 1 @ExtraFieldUPDATEValue = t.c.value('valorCampoExtra[1]', 'varchar(20)')
				FROM @XMLCamposExtra.nodes('camposExtra/campoExtra') AS t(c) 
				WHERE t.c.value('codigoCampoExtra[1]', 'varchar(100)') = 'UPDATE' AND @CamposAdicionais = 3 --DHL				
-- obtem o tipo de dados de manifesto				
				SELECT TOP 1 @OperacaoManifesto = t.c.value('tipoManifesto[1]', 'int') 
				FROM @XMLManifestos.nodes('manifestos/manifesto') AS t(c)
-- obtem o número da declaração a atualizar	
				IF @CamposAdicionais = 8 --ENTREPOSTO
				BEGIN
					SELECT @Numero = DUC_PNUM
					FROM PRO_DUCG WITH(NOLOCK)
					WHERE DUC_DUNO = 2 AND DUC_EANO = @Ano AND DUC_PNUM = ISNULL((SELECT t.c.value('valorCampoExtra[1]', 'varchar(20)')
																				FROM @XMLCamposExtra.nodes('camposExtra/campoExtra') AS t(c)
																				WHERE t.c.value('codigoCampoExtra[1]', 'varchar(100)') = 'DUC_PNUM'), -1)
				END	
				ELSE
				BEGIN
					SELECT TOP 1 @Numero = DUC_PNUM								
					FROM PRO_DUCG WITH(NOLOCK)						
					WHERE DUC_DUNO = 2 AND DUC_EANO = @Ano AND DUC_CPRT = @documentoTransporte 
					ORDER BY DUC_IDTY DESC
				END
-- verifica se o número é válido
				IF @Numero IS NULL
					RAISERROR('Documento de transporte "%s" não existe em nenhuma declaraçao IMP-CAU.', 16, 90, @documentoTransporte)	
-- obtem dados da declaração a atualizar
				SELECT @IdDeclaracao = duc.DUC_IDTY, @TaxaFDA = ISNULL(duc.DUC_TFDA, 0), @valorTotalSeguro = ISNULL(duc.DUC_SEGU, 0), @CambioSeguro = ISNULL(duc.DUC_TXSE, 0), 
					@TotalVolumesDirty = ISNULL(duc.DUC_VDIR, 0), @TotalVolumesClean = ISNULL(duc.DUC_VCLE, 0), @TotalVolumesScan = duc.DUC_VSCA, 
					@DescricaoFormula = (CASE ISNULL(@ExtraFieldUPDATEValue, '') WHEN 'DHL-PORTAL' THEN @DescricaoFormula ELSE duc.DUC_FR20 END), 
					@valorTotalFrete = (CASE ISNULL(@ExtraFieldUPDATEValue, '') WHEN 'DHL-PORTAL' THEN @valorTotalFrete ELSE ISNULL(duc.DUC_FRET, 0) END), 
					@CambioFrete = (CASE ISNULL(@ExtraFieldUPDATEValue, '') WHEN 'DHL-PORTAL' THEN @CambioFrete ELSE ISNULL(duc.DUC_TXFR, 0) END), 
					@valorTotalFatura = (CASE WHEN (@CamposAdicionais = 2) OR (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') THEN @valorTotalFatura ELSE ISNULL(duc.DUC_MT22, 0) END), 
					@CambioMontante = (CASE WHEN (@CamposAdicionais = 2) OR (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') THEN @CambioMontante ELSE ISNULL(duc.DUC_TX23, 0) END), 
					@MeioTransportePorVolume = (CASE ISNULL(mtr.MTR_VPVL, 0) WHEN 2 THEN 1 ELSE 0 END), 
					@TotalOptativas = (CASE mtr.MTR_OPAU 
											WHEN 1 THEN ISNULL((SELECT TOP 1 MTO_VOPT 
																FROM TAB_MTRO WITH(NOLOCK) 
																WHERE MTR_IDTY = mtr.MTR_IDTY 
																	AND (CASE WHEN ((@CamposAdicionais IN (1, 4) AND @OperacaoManifesto <> 2) OR (@CamposAdicionais = 2 AND @OperacaoManifesto = 0) OR (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') OR (@CamposAdicionais = 3 AND (CASE WHEN @NaturezaRetorno = 1 THEN 1 WHEN (@NaturezaRetorno = 0 AND duc.DUC_ADI5 = 1 AND (ABS(duc.DUC_MBRT) - @totalMassaBruta) < 0.500) THEN 1 ELSE 0 END) = 1)) THEN @totalMassaBruta ELSE ISNULL(duc.DUC_MBRT, 0) END) BETWEEN MTO_LMNP AND MTO_LMXP 
																	AND (CASE WHEN (@CamposAdicionais = 2 AND @OperacaoManifesto = 0) OR (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') THEN @ValorTotalEUR ELSE ISNULL(duc.DUC_VEUR, 0) END) BETWEEN MTO_LMNV AND MTO_LMXV), 0) 
											ELSE ISNULL(mtr.MTR_VOP1, 0) 
										END) 											
				FROM PRO_DUCG AS duc WITH(NOLOCK)
					LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON (CASE WHEN @CamposAdicionais IN (1, 4) THEN @CodigoMeioTransporteChegada ELSE duc.MTR_PT18 END) = mtr.MTR_CODI
				WHERE duc.DUC_EANO = @Ano AND duc.DUC_PNUM = @Numero 				
-- obtem valores totais da declaração existentes apenas nas adições
				DECLARE Totais CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT CAST(ISNULL(t.c.value('sum(marcasEVolumes/marcaEVolume/volumes)', 'float'), 0) AS int), 
						t.c.value('massaBruta[1]', 'decimal(18, 6)'), 
						t.c.value('montanteAd[1]', 'decimal(18, 3)'), 						
						t.c.value('valorFrete[1]', 'decimal(18, 3)'), 
						t.c.value('valorSeguro[1]', 'decimal(18, 3)'),
						ISNULL(adi.DUA_CODI, 0), ISNULL(adi.DUA_VDIR, 0), ISNULL(adi.DUA_ACRE, 0), ISNULL(adi.DUA_DEDU, 0)
					FROM @XMLAdicoes.nodes('adicoes/adicao') AS t(c)
						LEFT OUTER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON adi.DUC_EANO = @Ano AND adi.DUC_PNUM = @Numero AND t.c.value('numeroAdicao[1]', 'int') = adi.DUA_CODI
				OPEN Totais
				FETCH NEXT FROM Totais INTO @volumes, @massaBruta, @montanteAd, @valorFrete, @valorSeguro, @numeroAdicao, @Direitos, @Acrescimos, @Deducoes
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @TotalAdicoes = @TotalAdicoes + 1					
					SET @TotalVolumes = @TotalVolumes + @volumes
					SELECT @SomaMontantesAdicoes = ISNULL(SUM(DUA_VA42), 0), @SomaFretesAdicoes = ISNULL(SUM(ISNULL(DUA_VFRE, 0)), 0), @SomaSegurosAdicoes = ISNULL(SUM(ISNULL(DUA_VSEG, 0)), 0)			
					FROM PRO_DUAD WITH(NOLOCK)
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI <> @numeroAdicao
					SET @valorFrete = ISNULL(@valorFrete, ROUND((CASE (@valorTotalFatura - @SomaMontantesAdicoes - @montanteAd) 
																	WHEN 0 THEN (@valorTotalFrete - @SomaFretesAdicoes) 
																	ELSE (@massaBruta * @valorTotalFrete / @totalMassaBruta) 
																END), 3))
					SET @valorSeguro = ISNULL(@valorSeguro, ROUND((CASE (@valorTotalFatura - @SomaMontantesAdicoes - @montanteAd) 
																	WHEN 0 THEN (@valorTotalSeguro - @SomaSegurosAdicoes) 
																	ELSE (@montanteAd * @valorTotalSeguro / @valorTotalFatura) 
																END), 3))					
					SET @ValorEUR = ROUND(@montanteAd / @CambioMontante, 2)
					SET @Ajustamento = dbo.fn_IMP_CalculaAjustamento(@DescricaoFormula, @TaxaFDA, @CambioFrete, @CambioSeguro, @valorFrete, @valorSeguro, @Direitos, @Acrescimos, @Deducoes)
					SET @ValorEstatistico = dbo.fn_IMP_CalculaValorEstatistico(@ValorEUR, @Ajustamento)
					SET @TotalValorAduaneiro = @TotalValorAduaneiro + @ValorEstatistico
					SET @SomaMontantesAdicoes = @SomaMontantesAdicoes + @montanteAd
					SET @SomaFretesAdicoes = @SomaFretesAdicoes + @valorFrete
					SET @SomaSegurosAdicoes = @SomaSegurosAdicoes + @valorSeguro
					FETCH NEXT FROM Totais INTO @volumes, @massaBruta, @montanteAd, @valorFrete, @valorSeguro, @numeroAdicao, @Direitos, @Acrescimos, @Deducoes
				END
				CLOSE Totais
				DEALLOCATE Totais
-- -- inicia total de volumes dirty, clean e scan em função do tipo de manifesto (se "Clean" [1] remove também as linhas "Scan")
				IF @OperacaoManifesto = 1
				BEGIN				
					SET @TotalVolumesClean = 0
					SET @TotalVolumesScan = 0
				END
				ELSE				
					IF @OperacaoManifesto = 0
						SET @TotalVolumesDirty = 0 
					ELSE
						IF @OperacaoManifesto = 2
							SET @TotalVolumesScan = 0		
-- obtem valores totais de volumes dirty, clean e scan da declaração existentes apenas nos manifestos
				DECLARE Totais CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('tipoManifesto[1]', 'int')				
					FROM @XMLManifestos.nodes('manifestos/manifesto') AS t(c)
					WHERE ISNULL(t.c.value('numeroCPA[1]', 'varchar(35)'), '') <> ''
				OPEN Totais
				FETCH NEXT FROM Totais INTO @tipoManifesto
				WHILE @@FETCH_STATUS = 0
				BEGIN				
					IF @tipoManifesto = 0 
						SET @TotalVolumesDirty = @TotalVolumesDirty + 1
					ELSE
						IF @tipoManifesto = 1
							SET @TotalVolumesClean = @TotalVolumesClean + 1
						ELSE
							IF @tipoManifesto = 2 
								SET @TotalVolumesScan = @TotalVolumesScan + 1											
					FETCH NEXT FROM Totais INTO @tipoManifesto
				END
				CLOSE Totais
				DEALLOCATE Totais										
-- atualiza os dados gerais da nova declaração IMP-CAU		
				IF @CamposAdicionais IN (1, 4) --FEDEX/TNT | TNT
				BEGIN
					UPDATE PRO_DUCG SET 
						NDE_CODI = @CodigoNatureza, 
						NDE_NOME = @NomeNatureza, 
						ALF_CODI = @CodigoAlfandegaSujeicao,  
						ALF_NOME = @NomeAlfandegaSujeicao, 						
						DUC_TVL6 = @TotalVolumes, 
						DUC_VATT = @TotalValorAduaneiro, 
						DUC_VDIR = @TotalVolumesDirty, 
						DUC_VCLE = @TotalVolumesClean, 
						DUC_VSCA = @TotalVolumesScan, 
						LME_CO30 = @CodigoLocalizacaoMercadorias, 
						DUC_LC30 = @NomeLocalizacaoMercadorias, 
						DUC_DTVO = @dataVoo, 
						DUC_MBRT = (CASE @OperacaoManifesto 
										WHEN 2 THEN DUC_MBRT 
										ELSE @totalMassaBruta 
									END), 
						DUC_MLQT = (CASE @OperacaoManifesto 
										WHEN 2 THEN DUC_MLQT 
										ELSE @totalMassaLiquida 
									END), 
						DUC_TREM = (CASE @OperacaoManifesto 
										WHEN 2 THEN DUC_TREM 
										ELSE @totalMassaBruta 
									END), 
						MTR_PT18 = @CodigoMeioTransporteChegada, 
						MTR_NO18 = @NomeMeioTransporteChegada, 
						DUC_MT18 = @identificacaoTransporte, 
						DUC_OP18 = @TotalOptativas, 							
						MTR_FT21 = @CodigoMeioTransporteFronteira,
						MTR_NO21 = @NomeMeioTransporteFronteira, 
						PAI_PA21 = @CodigoPaisMeioTransporteFronteira, 
						DUC_UALT = @CodUtilizador, 
						DUC_DTAL = @DataAtual
					WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
				END
				ELSE				
				IF @CamposAdicionais = 2 --UPS
				BEGIN
					IF @OperacaoManifesto = 0 --Dirty
					BEGIN
						UPDATE PRO_DUCG SET 							
							DUC_TVL6 = @TotalVolumes, 
							DUC_VATT = @TotalValorAduaneiro, 
							DUC_VDIR = @TotalVolumesDirty, 
							DUC_VCLE = @TotalVolumesClean, 
							DUC_VSCA = @TotalVolumesScan, 
							PAI_PR22 = @CodigoPaisMontante, 
							DUC_MT22 = @valorTotalFatura, 
							DUC_TX23 = @CambioMontante, 
							DUC_MLQT = @totalMassaLiquida, 
							DUC_MBRT = @totalMassaBruta, 
							DUC_VEUR = @ValorTotalEUR, 					
							PAI_MO22 = @MoedaMontante, 
							DUC_TREM = @totalMassaBruta, 
							DUC_OP18 = @TotalOptativas, 
							DUC_FUPS = @nomeFicheiro, 					
							DUC_VFRC = @freteOriginal, 
							DUC_MFRC = @moedafreteOriginal, 
							DUC_NVSR = @serviceLevel, 					 							
							DUC_UALT = @CodUtilizador, 
							DUC_DTAL = @DataAtual
						WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
					END
					ELSE
					BEGIN
						UPDATE PRO_DUCG SET 														
							DUC_VDIR = @TotalVolumesDirty, 
							DUC_VCLE = @TotalVolumesClean, 
							DUC_VSCA = @TotalVolumesScan, 											 
							DUC_DTVO = @dataVoo, 
							DUC_UALT = @CodUtilizador, 
							DUC_DTAL = @DataAtual
						WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
					END
				END
				ELSE				
				IF @CamposAdicionais = 3 --DHL
				BEGIN
					IF ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL'
					BEGIN
						SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de UPDATE (das Adições) não ser processado					
						UPDATE PRO_DUCG SET 
							NDE_CODI = @CodigoNatureza, 
							NDE_NOME = @NomeNatureza, 	
							FUP_CODI = ISNULL(@CodigoFollowUp, FUP_CODI), 	
							DUC_UNMD = (CASE WHEN @CodigoFollowUp IS NOT NULL THEN NULL ELSE DUC_UNMD END),  
							DUC_TMSF = @TipoMascara,
							DUC_MASC = @CodMascara,
							CEN_CO20 = @CodigoCondicaoEntrega, 
							DUC_DE20 = @localidadeCE, 
							PAI_CODI2 = @CodigoPaisCondicaoEntrega, 
							PAE_CODI = @CodigoPortoAeroporto, 
							FIN_CODI = @CodigoFormula, 
							DUC_FR20 = @DescricaoFormula, 
							DUC_UFOB = @FormulaFOB, 
							DUC_VFOB = (CASE @FormulaFOB WHEN 0 THEN 0 ELSE DUC_VFOB END), 
							PAI_PR22 = @CodigoPaisMontante,
							PAI_MO22 = @MoedaMontante, 
							DUC_TX23 = @CambioMontante, 
							DUC_MT22 = @valorTotalFatura, 
							DUC_VEUR = @ValorTotalEUR, 
							DUC_VATT = @TotalValorAduaneiro, 							
							DUC_OP18 = @TotalOptativas, 
							DUC_VTRN = (CASE @TotalOptativas WHEN 0 THEN DUC_VTRN ELSE 0 END), 
							PAI_FRET = @CodigoPaisFrete,
							PAI_MOFT = @MoedaFrete, 
							DUC_TXFR = @CambioFrete,
							DUC_FRET = @valorTotalFrete,
							DUC_DST8 = @CodigoCliente, 
							DUC_DNOM = @nomeImportador,
							DUC_DMOR = @moradaImportador, 
							DUC_DLOC = @localidadeImportador, 
							DUC_DCPO = @codigoPostalImportador,
							DUC_DLPO = @localidadePostalImportador,
							DUC_DNIF = @nifImportador, 
							PAI_DLIV = @CodigoPaisImportador, 
							DUC_TPDS = @tipoNIFImportador, 
							CLI_CODI = @CodigoClienteServico,  
							CLI_NOME = @NomeClienteServico,  
							DUC_BIVA = @BeneficiarioIVACliente, 
							DUC_DTEL = @telefoneImportador,
							DUC_DEMA = @emailImportador,
							PAI_P17B = @CodigoRegiao, 
							DUC_CAUC = @NumeroNRG, 
							DUC_CANO = @AnoCaucao, 
							DUC_CTIP = @TipoCaucao, 
							DUC_CENT = @TipoEntidadeCaucao, 
							ALF_CODI2 = @AlfandegaCaucao, 
							DUC_CCAC = @CodAcessoCaucao, 
							DUC_CORF = @OutrasRefCaucao, 														 														
							DUC_UALT = @CodUtilizador, 
							DUC_DTAL = @DataAtual
						WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano	
						SET CONTEXT_INFO 0x0 --reset à variavel global de sessão				
					END
					ELSE
					BEGIN
						UPDATE PRO_DUCG SET 
							NDE_CODI = @CodigoNatureza, 
							NDE_NOME = @NomeNatureza, 						
							DUC_TVL6 = @TotalVolumes, 
							DUC_VATT = @TotalValorAduaneiro, 
							DUC_VDIR = @TotalVolumesDirty, 
							DUC_VCLE = @TotalVolumesClean, 
							DUC_VSCA = @TotalVolumesScan, 						
							DUC_DTVO = @dataVoo, 
							DUC_MBRT = (CASE 
											WHEN @NaturezaRetorno = 1 THEN @totalMassaBruta 
											WHEN (@NaturezaRetorno = 0 AND DUC_ADI5 = 1 AND (ABS(DUC_MBRT) - @totalMassaBruta) < 0.500) THEN @totalMassaBruta 
											ELSE DUC_MBRT
										END), 						
							DUC_TREM = (CASE 
											WHEN @NaturezaRetorno = 1 THEN @totalMassaBruta 
											WHEN (@NaturezaRetorno = 0 AND DUC_ADI5 = 1 AND (ABS(DUC_MBRT) - @totalMassaBruta) < 0.500) THEN @totalMassaBruta 
											ELSE DUC_TREM
										END), 
							DUC_OP18 = (CASE 
											WHEN @NaturezaRetorno = 1 THEN @TotalOptativas 
											WHEN (@NaturezaRetorno = 0 AND DUC_ADI5 = 1 AND (ABS(DUC_MBRT) - @totalMassaBruta) < 0.500) THEN @TotalOptativas 
											ELSE DUC_OP18
										END), 
							DUC_CIDE = ISNULL(@portesAcc, @numeroContaDestinatario), 
							DUC_NVOO = @numeroVoo, 
							DUC_SHIP = @shipID, 
							DUC_DTYP = @dutyType, 						
							DUC_DTEL = @telefoneImportador,
							DUC_DEMA = @emailImportador,
							DUC_UALT = @CodUtilizador, 
							DUC_DTAL = @DataAtual
						WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano					
					END
				END				
				ELSE
				BEGIN
					UPDATE PRO_DUCG SET 
						DUC_ADI5 = @TotalAdicoes, 							
						DUC_TVL6 = @TotalVolumes, 
						DUC_VATT = @TotalValorAduaneiro, 
						DUC_VDIR = @TotalVolumesDirty, 
						DUC_VCLE = @TotalVolumesClean, 
						DUC_VSCA = @TotalVolumesScan, 
						DUC_UALT = @CodUtilizador, 
						DUC_DTAL = @DataAtual
					WHERE DUC_PNUM = @Numero AND DUC_EANO = @Ano
				END				
-- remove o detalhe de adições da declaração
				IF @CamposAdicionais = 8 --ENTREPOSTO
				BEGIN
					SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de DELETE não ser processado
					DELETE FROM PRO_DUAD
					WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero
					SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
				END
				ELSE
-- remove o detalhe de Marcas e Volumes das adições da declaração
					IF ((@CamposAdicionais <> 2) OR ((@CamposAdicionais = 2) AND (@OperacaoManifesto = 0))) AND (ISNULL(@ExtraFieldUPDATEValue, '') = '')
					BEGIN
						SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de DELETE não ser processado
						DELETE FROM PRO_DU31
						WHERE DUC_EANO = @Ano and DUC_PNUM = @Numero
						SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
					END
-- remove dados de manifesto do tipo dirty, clean ou scan quando em edição (se "Clean" [1] remove também as linhas "Scan")
				IF @OperacaoManifesto = 1
				BEGIN					
					SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de DELETE não ser processado
					DELETE FROM PRO_DUOD
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUO_TIPO >= 1
					SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
				END
				ELSE
				BEGIN
					SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de DELETE não ser processado			
					DELETE FROM PRO_DUOD
					WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUO_TIPO = @tipoManifesto		
					SET CONTEXT_INFO 0x0 --reset à variavel global de sessão		
				END	
			END
-- processa a inserção ou edição dos documentos e certificados da declaração IMP-CAU conforme a ação
			IF @acao = 'I'
			BEGIN			
-- obtem os documentos e certificados 
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('tipoDocumento[1]', 'int'), 
						t.c.value('codigoDocumento[1]', 'varchar(5)'), 
						NULLIF(t.c.value('numeroDocumento[1]', 'varchar(70)'), ''),
						NULLIF(t.c.value('qualificadorDC[1]', 'varchar(2)'), ''),
						t.c.value('dataValidade[1]', 'datetime'), 
						NULLIF(t.c.value('pais[1]', 'varchar(2)'), ''),
						ISNULL(t.c.value('montante[1]', 'decimal(18, 2)'), 0),
						NULLIF(t.c.value('entidadeEmissora[1]', 'varchar(70)'), ''),
						NULLIF(t.c.value('unidadeMedida[1]', 'varchar(3)'), ''),
						ISNULL(t.c.value('quantidade[1]', 'decimal(18, 6)'), 0)
					FROM @XMLDocumentos.nodes('documentosECertificados/documento') AS t(c)
				OPEN Documentos
				FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento, @qualificadorDC, @dataValidade, @pais, @montante, @entidadeEmissora, @unidadeMedida, 
					@quantidade
				WHILE @@FETCH_STATUS = 0
				BEGIN		
-- inicia variáveis
					SET @IdDocumento = NULL
					SET @IdPais = NULL
					SET @IdUnidadeMedida = NULL
-- obtem dados do documento
					SELECT @IdDocumento = DOC_IDTY
					FROM TAB_DOCU WITH(NOLOCK)
					WHERE LEN(DOC_CODI) = 4 AND DOC_DESP = 1 AND DOC_DTRA = (CASE @tipoDocumento WHEN 1 THEN 1 ELSE 0 END) AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
					IF @IdDocumento IS NULL
						RAISERROR('Documento "%s" inválido.', 16, 91, @codigoDocumento)		
-- obtem dados do país
					SELECT @IdPais = PAI_IDTY
					FROM TAB_PAIS WITH(NOLOCK)
					WHERE PAI_CODI = @pais
-- verifica se o país é válido
					IF (ISNULL(@pais, '') <> '') AND (@IdPais IS NULL)
						RAISERROR('País "%s" inválido.', 16, 92, @pais)
					ELSE
						IF (@IdPais IS NULL) AND (@montante > 0) 
							RAISERROR('Montante inválido quando não se especifica país.', 16, 93)
						ELSE
							IF (@IdPais IS NOT NULL) AND (@montante = 0) 
								RAISERROR('O país "%s" obriga ao preenchimento do montante.', 16, 94, @pais)
-- obtem dados da unidade de medida
					SELECT @IdUnidadeMedida = UME_IDTY
					FROM TAB_UMED WITH(NOLOCK)
					WHERE UME_IMPT = 1 AND UME_CODI = @unidadeMedida
-- verifica se a unidade de medida é válida
					IF (ISNULL(@unidadeMedida, '') <> '') AND (@IdUnidadeMedida IS NULL)
						RAISERROR('Unidade de medida "%s" inválida.', 16, 95, @unidadeMedida)										
-- insere o documento no detalhe de documentos e certificados na nova declaracao IMP-CAU
					INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, qualificador, dataValidade, id_paisMoeda, montante, entidadeEmissora, id_unidadeMedida, 
						quantidade, id_utilizadorControlo, dataControlo)
					VALUES (@IdDeclaracao, 
						@tipoDocumento, 
						@IdDocumento, 
						@numeroDocumento, 
						@qualificadorDC,
						@dataValidade, 
						@IdPais, 
						@montante,
						@entidadeEmissora, 
						@IdUnidadeMedida, 
						@quantidade, 						
						@IdUtilizador, 
						@DataAtual)		
					FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento, @qualificadorDC, @dataValidade, @pais, @montante, @entidadeEmissora, @unidadeMedida, 
						@quantidade
				END
				CLOSE Documentos
				DEALLOCATE Documentos
			END
			ELSE
			BEGIN
-- obtem os documentos e certicados
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('tipoDocumento[1]', 'int'), 
						t.c.value('codigoDocumento[1]', 'varchar(5)'), 
						NULLIF(t.c.value('numeroDocumento[1]', 'varchar(70)'), ''),
						NULLIF(t.c.value('qualificadorDC[1]', 'varchar(2)'), ''),
						t.c.value('dataValidade[1]', 'datetime'), 
						NULLIF(t.c.value('pais[1]', 'varchar(2)'), ''),
						ISNULL(t.c.value('montante[1]', 'decimal(18, 2)'), 0),
						NULLIF(t.c.value('entidadeEmissora[1]', 'varchar(70)'), ''),
						NULLIF(t.c.value('unidadeMedida[1]', 'varchar(3)'), ''),
						ISNULL(t.c.value('quantidade[1]', 'decimal(18, 6)'), 0)
					FROM @XMLDocumentos.nodes('documentosECertificados/documento') AS t(c)
				OPEN Documentos
				FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento, @qualificadorDC, @dataValidade, @pais, @montante, @entidadeEmissora, @unidadeMedida, 
					@quantidade
				WHILE @@FETCH_STATUS = 0
				BEGIN		
-- inicia variáveis
					SET @IdRegisto = NULL
					SET @IdPais = NULL
					SET @IdUnidadeMedida = NULL
					SET @IdDocumento = NULL
-- obtem dados do país
					SELECT @IdPais = PAI_IDTY
					FROM TAB_PAIS WITH(NOLOCK)
					WHERE PAI_CODI = @pais
-- verifica se o país é válido
					IF (ISNULL(@pais, '') <> '') AND (@IdPais IS NULL)
						RAISERROR('País "%s" inválido.', 16, 96, @pais)
					ELSE
						IF (@IdPais IS NULL) AND (@montante > 0) 
							RAISERROR('Montante inválido quando não se especifica país.', 16, 97)
						ELSE
							IF (@IdPais IS NOT NULL) AND (@montante = 0) 
								RAISERROR('O país "%s" obriga ao preenchimento do montante.', 16, 98, @pais)
-- obtem dados da unidade de medida
					SELECT @IdUnidadeMedida = UME_IDTY
					FROM TAB_UMED WITH(NOLOCK)
					WHERE UME_IMPT = 1 AND UME_CODI = @unidadeMedida
-- verifica se a unidade de medida é válida
					IF (ISNULL(@unidadeMedida, '') <> '') AND (@IdUnidadeMedida IS NULL)
						RAISERROR('Unidade de medida "%s" inválida.', 16, 99, @unidadeMedida)
-- obtem id do detalhe de documento
					SELECT @IdRegisto = ddo.id
					FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoIMP = @IdDeclaracao AND doc.DOC_CODI = @codigoDocumento AND ddo.tipo = @tipoDocumento 
-- altera o documento na declaracao se este já existir
					IF @IdRegisto IS NOT NULL
					BEGIN
-- edita o documento no detalhe de documentos e certificados na nova declaracao IMP-CAU
						UPDATE tb_IMP_DeclaracoesDocumentos SET 
							numero = @numeroDocumento, 
							qualificador = @qualificadorDC, 
							dataValidade = @dataValidade, 
							id_paisMoeda = @IdPais, 
							montante = @montante, 
							entidadeEmissora = @entidadeEmissora, 
							id_unidadeMedida = @IdUnidadeMedida, 
							quantidade = @quantidade, 
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual
						WHERE id = @IdRegisto	
					END
					ELSE
-- insere o documento na declaração se não existir e apenas quando é DHL e atualização do portal
						IF ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL'
						BEGIN					
-- obtem dados do documento
							SELECT @IdDocumento = DOC_IDTY
							FROM TAB_DOCU WITH(NOLOCK)
							WHERE LEN(DOC_CODI) = 4 AND DOC_DESP = 1 AND DOC_DTRA = (CASE @tipoDocumento WHEN 1 THEN 1 ELSE 0 END) AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
							IF @IdDocumento IS NULL
								RAISERROR('Documento "%s" inválido.', 16, 100, @codigoDocumento)											
-- insere o documento no detalhe de documentos e certificados na nova declaracao IMP-CAU
							INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, qualificador, dataValidade, id_paisMoeda, montante, entidadeEmissora, 
								id_unidadeMedida, quantidade, id_utilizadorControlo, dataControlo)
							VALUES (@IdDeclaracao, 
								@tipoDocumento, 
								@IdDocumento, 
								@numeroDocumento, 
								@qualificadorDC,
								@dataValidade, 
								@IdPais, 
								@montante,
								@entidadeEmissora, 
								@IdUnidadeMedida, 
								@quantidade, 						
								@IdUtilizador, 
								@DataAtual)							
						END
					FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento, @qualificadorDC, @dataValidade, @pais, @montante, @entidadeEmissora, @unidadeMedida, 
						@quantidade
				END
				CLOSE Documentos
				DEALLOCATE Documentos
			END
-- processa a inserção dos restantes detalhes da declaração IMP-CAU apenas quando a ação for INSERT
			IF @acao = 'I'
			BEGIN
-- obtem os documentos precedentes
				DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('codigoDocumento[1]', 'varchar(5)'), 
						t.c.value('numeroDocumento[1]', 'varchar(70)'), 
						NULLIF(t.c.value('qualificadorDC[1]', 'varchar(2)'), '')
					FROM @XMLPrecedentes.nodes('documentosPrecedentes/documentoPrecedente') AS t(c)
				OPEN Documentos
				FETCH NEXT FROM Documentos INTO @codigoDocumento, @numeroDocumento, @qualificadorDC
				WHILE @@FETCH_STATUS = 0
				BEGIN		
-- inicia variáveis
					SET @IdDocumento = NULL
					SET @IdRegisto = NULL
-- obtem dados do documento
					SELECT @IdDocumento = DOC_IDTY
					FROM TAB_DOCU WITH(NOLOCK)
					WHERE DOC_CA40 = 1 AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
					IF @IdDocumento IS NULL
						RAISERROR('Documento precedente "%s" inválido.', 16, 101, @codigoDocumento)		
-- obtem id do detalhe de documento precedente
					SELECT @IdRegisto = id
					FROM tb_IMP_DeclaracoesPrecedentes WITH(NOLOCK) 						
					WHERE id_declaracaoIMP = @IdDeclaracao AND id_documento = @IdDocumento	
-- verifica se vai proceder à inserção ou edição (no caso do documento já ter sido criado porum processo automático)
					IF @IdRegisto IS NULL
					BEGIN												
-- insere o documento no detalhe de documentos precedentes na nova declaracao IMP-CAU
						INSERT INTO tb_IMP_DeclaracoesPrecedentes(id_declaracaoIMP, id_documento, numero, qualificador, id_utilizadorControlo, dataControlo)
						VALUES (@IdDeclaracao, 
							@IdDocumento, 
							@numeroDocumento, 
							@qualificadorDC, 										
							@IdUtilizador, 
							@DataAtual)		
					END
					ELSE
					BEGIN												
-- edita o documento no detalhe de documentos precedentes na nova declaracao IMP-CAU
						UPDATE tb_IMP_DeclaracoesPrecedentes SET 
							numero = @numeroDocumento, 
							qualificador = @qualificadorDC, 
							id_utilizadorControlo = @IdUtilizador, 
							dataControlo = @DataAtual
						WHERE id = @IdRegisto
					END
					FETCH NEXT FROM Documentos INTO @codigoDocumento, @numeroDocumento, @qualificadorDC
				END
				CLOSE Documentos
				DEALLOCATE Documentos
-- inicia variavel
				SET @UltCodTabela = ISNULL((SELECT MAX(DPD_CODI) FROM PRO_DUPD WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero), 0)
-- obtem os pedidos
				DECLARE Pedidos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('codigoPedido[1]', 'varchar(5)'), 
						NULLIF(t.c.value('numeroPedido[1]', 'varchar(512)'), ''), 
						NULLIF(t.c.value('qualificadorDC[1]', 'varchar(2)'), '')
					FROM @XMLPedidos.nodes('pedidos/pedido') AS t(c)
				OPEN Pedidos
				FETCH NEXT FROM Pedidos INTO @codigoPedido, @numeroPedido, @qualificadorDC
				WHILE @@FETCH_STATUS = 0
				BEGIN		
-- inicia variáveis
					SET @IdPedido = NULL
					SET @UltCodTabela = @UltCodTabela + 1
-- obtem dados do pedido
					SELECT @IdPedido = TXM_IDTY
					FROM TAB_TXML WITH(NOLOCK)
					WHERE LEN(TXM_CODI) = 5 AND TXM_CODI = @codigoPedido
-- verifica se o pedido é válido
					IF @IdPedido IS NULL
						RAISERROR('Pedido "%s" inválido.', 16, 102, @codigoPedido)		
-- insere o pedido no detalhe de pedidos na nova declaracao IMP-CAU
					INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC, DPD_QUAL)
					VALUES (@Ano,
						@Numero, 
						@UltCodTabela,  
						@codigoPedido, 
						@numeroPedido, 
						@qualificadorDC)		
					FETCH NEXT FROM Pedidos INTO @codigoPedido, @numeroPedido, @qualificadorDC
				END
				CLOSE Pedidos
				DEALLOCATE Pedidos
-- inicia variavel
				SET @UltCodTabela = ISNULL((SELECT MAX(DUI_CODI) FROM PRO_DUIN WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero), 0)
-- obtem as incidências
				DECLARE Incidencias CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('codigoIncidencia[1]', 'varchar(8)'), 
						t.c.value('dataInicio[1]', 'datetime'), 
						t.c.value('dataFim[1]', 'datetime'), 
						NULLIF(t.c.value('observacoes[1]', 'varchar(MAX)'), ''),
						NULLIF(t.c.value('tipoIncidencia[1]', 'varchar(1)'), '')
					FROM @XMLIncidencias.nodes('incidencias/incidencia') AS t(c)
				OPEN Incidencias
				FETCH NEXT FROM Incidencias INTO @codigoIncidencia, @dataInicio, @dataFim, @observacoes, @tipoIncidencia
				WHILE @@FETCH_STATUS = 0
				BEGIN	
-- inicia variáveis					
					SET @IdIncidencia = NULL
					SET @UltCodTabela = @UltCodTabela + 1
-- obtem dados da incidência
					SELECT @IdIncidencia = t.SIN_IDTY, @NomeIncidencia = t.SIN_DESP, @ReleaseHold = ISNULL((CASE @tipoIncidencia WHEN 'R' THEN 0 WHEN 'H' THEN 1 ELSE NULL END), t.SIN_REHO)
					FROM (SELECT SIN_CODI, SIN_DESP, SIN_IDTY, NULL AS SIN_REHO
						FROM TAB_SINC WITH(NOLOCK)
						UNION ALL
						SELECT COS_CODE, COS_POST, COS_IDTY, (CASE WHEN COS_RELI = 1 THEN 0 WHEN COS_HOLD = 1 THEN 1 ELSE NULL END)
						FROM TAB_COSM WITH(NOLOCK)
					) AS t
					WHERE t.SIN_CODI = @codigoIncidencia
-- verifica se a incidência é válida
					IF @IdIncidencia IS NULL
						RAISERROR('Status de incidência "%s" inválido.', 16, 103, @codigoIncidencia)		
					ELSE
						IF @dataFim < @dataInicio
							RAISERROR('Data de fim inferior à data de início.', 16, 104)		
-- insere a incidência no detalhe de incidências na nova declaracao IMP-CAU
					INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM, DUI_OBSR, DUI_REHO)
					VALUES (@Ano, @Numero, @UltCodTabela, @codigoIncidencia, @NomeIncidencia, CAST(CONVERT(varchar(10), @dataInicio, 105) AS datetime), CAST(CONVERT(varchar(12), @dataInicio, 114) AS datetime), CAST(CONVERT(varchar(10), @dataFim, 105) AS datetime), CAST(CONVERT(varchar(12), @dataFim, 114) AS datetime), @observacoes, @ReleaseHold)
					FETCH NEXT FROM Incidencias INTO @codigoIncidencia, @dataInicio, @dataFim, @observacoes, @tipoIncidencia
				END
				CLOSE Incidencias
				DEALLOCATE Incidencias		
-- inicia variavel
				SET @UltCodTabela = ISNULL((SELECT MAX(DFW_CODI) FROM PRO_DUFW WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero), 0)
-- obtem os follow-ups
				DECLARE FollowUps CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('codigoFollowUp[1]', 'int'), 
						t.c.value('utilizador[1]', 'varchar(30)'), 
						t.c.value('dataHora[1]', 'datetime')						
					FROM @XMLFollowUps.nodes('followUps/followUpData') AS t(c)
				OPEN FollowUps
				FETCH NEXT FROM FollowUps INTO @followUp, @utilizador, @dataHora
				WHILE @@FETCH_STATUS = 0
				BEGIN		
-- inicia variáveis	
					SET @CodigoFollowUp = NULL
					SET @IdUtilizadorValido = NULL
					SET @UltCodTabela = @UltCodTabela + 1
-- obtem dados do follow-up
					SELECT @CodigoFollowUp = FUP_CODI
					FROM GIDWIN.dbo.FAP_FWUP WITH(NOLOCK)
					WHERE FUP_EXPO = 0 AND FUP_CODI = @followUp
-- verifica se o follow-up é válido
					IF @CodigoFollowUp IS NULL
						RAISERROR('Follow-up "%d" inválido.', 16, 105, @followUp)	
-- obtem dados do utilizador
					SELECT @IdUtilizadorValido = UTI_IDTY
					FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
					WHERE UTI_UTIL = @utilizador
-- verifica se o utilizador é válido
					IF @IdUtilizadorValido IS NULL
						RAISERROR('Utilizador "%s" inválido.', 16, 106, @utilizador)											
-- insere o follow-up no detalhe de follow-ups na nova declaracao IMP-CAU
					INSERT INTO PRO_DUFW(DUC_EANO, DUC_PNUM, DFW_CODI, DFW_DATA, FUP_CODI, UTI_UTIL)
					VALUES (@Ano, 
						@Numero, 
						@UltCodTabela, 
						@dataHora,						
						@CodigoFollowUp, 
						@utilizador)		
					FETCH NEXT FROM FollowUps INTO @followUp, @utilizador, @dataHora
				END
				CLOSE FollowUps
				DEALLOCATE FollowUps										
-- obtem os contactos
				DECLARE Contactos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('descricaoContacto[1]', 'varchar(200)'), 
						t.c.value('utilizador[1]', 'varchar(30)'), 
						t.c.value('dataHora[1]', 'datetime')						
					FROM @XMLContactos.nodes('contactos/contacto') AS t(c)
				OPEN Contactos
				FETCH NEXT FROM Contactos INTO @descricaoContacto, @utilizador, @dataHora
				WHILE @@FETCH_STATUS = 0
				BEGIN				
-- inicia variáveis	
					SET @IdUtilizadorValido = NULL
-- obtem dados do utilizador
					SELECT @IdUtilizadorValido = UTI_IDTY
					FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
					WHERE UTI_UTIL = @utilizador
-- verifica se o utilizador é válido
					IF @IdUtilizadorValido IS NULL
						RAISERROR('Utilizador "%s" inválido.', 16, 107, @utilizador)								
-- insere o contacto no detalhe de contactos na nova declaracao IMP-CAU
					INSERT INTO PRO_DUCN(DUC_PNUM, DUC_EANO, DCN_TEXT, DCN_UCRI, DCN_DTCR)
					VALUES (@Numero, 
						@Ano, 
						@descricaoContacto, 
						@utilizador,												
						@dataHora)		
					FETCH NEXT FROM Contactos INTO @descricaoContacto, @utilizador, @dataHora
				END
				CLOSE Contactos
				DEALLOCATE Contactos	
-- obtem os arquivos
				DECLARE Arquivos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						t.c.value('nomeArquivo[1]', 'varchar(100)'), 
						t.c.value('descricaoArquivo[1]', 'varchar(150)'), 
						t.c.value('tipoArquivo[1]', 'varchar(8)'), 
						t.c.value('origemArquivo[1]', 'int'),
						t.c.value('ficheiroBase64[1]', 'varchar(MAX)')					
					FROM @XMLArquivos.nodes('arquivos/arquivo') AS t(c)
				OPEN Arquivos
				FETCH NEXT FROM Arquivos INTO @nomeArquivo, @descricaoArquivo, @tipoArquivo, @origemArquivo, @ficheiroBase64
				WHILE @@FETCH_STATUS = 0
				BEGIN				
-- converte o base64 para varbinary 
					SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@ficheiroBase64"))', 'varbinary(MAX)')									
-- insere o arquivo no detalhe de arquivo documental na nova declaracao IMP-CAU
					INSERT INTO PRO_DUFI(DUC_PNUM, DUC_EANO, DUF_DESC, DUF_DATA, DUF_NOMF, DUF_UTIL, DUF_TMSG, DUF_ORIG, DUF_FICH)
					VALUES (@Numero, 
						@Ano, 
						@descricaoArquivo, 																		
						@DataAtual, 
						@nomeArquivo, 
						@CodUtilizador,
						@tipoArquivo, 
						@origemArquivo, 
						@FicheiroBinario)		
					FETCH NEXT FROM Arquivos INTO @nomeArquivo, @descricaoArquivo, @tipoArquivo, @origemArquivo, @ficheiroBase64
				END
				CLOSE Arquivos
				DEALLOCATE Arquivos	
			END
-- inicia variavel
			SET @UltCodTabela = ISNULL((SELECT MAX(DUO_CODI) FROM PRO_DUOD WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero), 0)
-- obtem os manifestos
			DECLARE Manifestos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT 
					t.c.value('tipoManifesto[1]', 'int'), 
					NULLIF(t.c.value('paisManifesto[1]', 'varchar(2)'), ''), 
					NULLIF(t.c.value('descricao[1]', 'varchar(104)'), ''), 
					t.c.value('valor[1]', 'decimal(18, 3)'), 
					NULLIF(t.c.value('paisMoeda[1]', 'varchar(2)'), ''), 
					t.c.value('totalFatura[1]', 'decimal(18, 3)'), 
					NULLIF(t.c.value('numeroCPA[1]', 'varchar(35)'), ''), 
					t.c.value('pesoBruto[1]', 'decimal(18, 3)')					
				FROM @XMLManifestos.nodes('manifestos/manifesto') AS t(c)
			OPEN Manifestos
			FETCH NEXT FROM Manifestos INTO @tipoManifesto, @paisManifesto, @descricao, @valor, @paisMoedaManifesto, @totalFatura, @numeroCPA, @pesoBruto
			WHILE @@FETCH_STATUS = 0
			BEGIN			
-- inicia variáveis										
				SET @CodigoPaisManifesto = NULL
				SET @IdPaisMoedaManifesto = NULL
				SET @MoedaManifesto = NULL
				SET @UltCodTabela = @UltCodTabela + 1
-- obtem dados do país do manifesto
				SELECT @CodigoPaisManifesto = PAI_CODI
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisManifesto
-- verifica se o país do manifesto é válido
				IF (ISNULL(@paisManifesto, '') <> '') AND (ISNULL(@CodigoPaisManifesto, '') = '')
					RAISERROR('País "%s" do manifesto inválido.', 16, 108, @paisManifesto)
-- obtem dados do país da moeda do manifesto
				SELECT @IdPaisMoedaManifesto = PAI_IDTY, @MoedaManifesto = PAI_PREF
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisMoedaManifesto	
-- verifica se o país da moeda do manifesto é válido
				IF (ISNULL(@paisMoedaManifesto, '') <> '') AND (@IdPaisMoedaManifesto IS NULL)
					RAISERROR('País "%s" da moeda do manifesto inválido.', 16, 109, @paisMoedaManifesto)												
-- insere o manifesto no detalhe de manifestos na nova declaracao IMP-CAU
				SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de INSERT não ser processado
				INSERT INTO PRO_DUOD(DUC_EANO, DUC_PNUM, DUO_CODI, PAI_CODI, DUO_DESC, DUO_VALO, DUO_MOED, DUO_TFAC, DUO_CPA2, DUO_PES2, DUO_TIPO, PAI_IDTY)				
				VALUES (@Ano,
					@Numero, 
					@UltCodTabela, 
					@CodigoPaisManifesto, 
					@descricao,
					@valor, 
					@MoedaManifesto, 
					@totalFatura,
					@numeroCPA, 	
					@pesoBruto,
					@tipoManifesto, 												
					@IdPaisMoedaManifesto)	
				SET CONTEXT_INFO 0x0 --reset à variavel global de sessão											
				FETCH NEXT FROM Manifestos INTO @tipoManifesto, @paisManifesto, @descricao, @valor, @paisMoedaManifesto, @totalFatura, @numeroCPA, @pesoBruto
			END
			CLOSE Manifestos
			DEALLOCATE Manifestos		
-- altera ação da declaração de modo a ignorar a leitura das adições
			IF (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') AND (EXISTS(SELECT 1 FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_ADI5 > 1 AND DUC_IDTY = @IdDeclaracao))			
				SET @acao = ''							
-- obtem as adições do XML
			DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
				SELECT ISNULL(NULLIF(t.c.value('@acao[1]', 'varchar(1)'), ''), @acao), 
					t.c.value('numeroAdicao[1]', 'int'), 
					t.c.value('codigoPautal[1]', 'varchar(22)'), 
					t.c.value('designacao[1]', 'varchar(150)'), 
					NULLIF(t.c.value('regimeAdicional[1]', 'varchar(6)'), ''), 
					NULLIF(t.c.value('paisOrigem[1]', 'varchar(2)'), ''), 
					NULLIF(t.c.value('preferencia[1]', 'varchar(3)'), ''), 
					t.c.value('metodoAvaliacao[1]', 'int'), 
					t.c.value('massaLiquida[1]', 'decimal(18, 6)'), 
					t.c.value('massaBruta[1]', 'decimal(18, 6)'), 
					ISNULL(t.c.value('unidades[1]', 'decimal(18, 6)'), 0), 
					t.c.value('montanteAd[1]', 'decimal(18, 3)'), 						
					t.c.value('valorFrete[1]', 'decimal(18, 3)'), 
					t.c.value('valorSeguro[1]', 'decimal(18, 3)'), 
					t.c.value('taxaIVA[1]', 'decimal(18, 2)'),  						
					t.c.query('documentosECertificados'),
					t.c.query('documentosPrecedentes'), 					
					t.c.query('pedidos'), 
					t.c.query('marcasEVolumes'), 
					t.c.query('contentores'), 
					t.c.query('veiculos')
				FROM @XMLAdicoes.nodes('adicoes/adicao') AS t(c)
				WHERE (@acao = 'I') OR ((@acao = 'U') AND ((@CamposAdicionais <> 2) OR ((@CamposAdicionais = 2) AND (@OperacaoManifesto = 0))))					
			OPEN Adicoes			
			FETCH NEXT FROM Adicoes INTO @acaoAdicao, @numeroAdicao, @codigoPautal, @designacao, @regimeAdicional, @paisOrigem, @preferencia, @metodoAvaliacao, @massaLiquida, @massaBruta, 
				@unidades, @montanteAd, @valorFrete, @valorSeguro, @taxaIVA, @XMLDocumentos, @XMLPrecedentes, @XMLPedidos, @XMLMarcasEVolumes, @XMLContentores, @XMLVeiculos
			WHILE @@FETCH_STATUS = 0
			BEGIN	
-- inicia variáveis
				SET @CodigoArtigo = NULL	
				SET @IdDesdobramento = NULL				
				SET @CodigoPaisOrigem = NULL
				SET @CodigoPreferencia = NULL
				SET @IdAdicao = NULL
				SET @Resultado = 0
				SET @MsgErro = NULL
-- obtem dados do artigo
				SELECT TOP 1 @CodigoArtigo = APA_CODI, 
						@designacao = (CASE 											
											WHEN APA_CPAU IN ('9999999999', '9999999998', '9999999997', '9999999996') THEN @designacao --cóodigo de artigo genérico/códigos de artigo restritos e dumping
											ELSE ISNULL(NULLIF(APA_DESG, ''), @designacao) 
									END)
				FROM TAB_APAU WITH(NOLOCK)
				WHERE APA_INAC = 0 AND APA_FLUX IN (0, 1) AND APA_EDAR = 0 AND LEN(APA_CPAU) >= 10 AND APA_CPAU = @codigoPautal
-- se artigo não existir, assume como artigo "Artigo Genérico"
				IF ISNULL(@CodigoArtigo, '') = ''
				BEGIN
					SELECT TOP 1 @CodigoArtigo = APA_CODI
					FROM TAB_APAU WITH(NOLOCK) 
					WHERE APA_INAC = 0 AND APA_FLUX IN (0, 1) AND APA_EDAR = 0 AND LEN(APA_CPAU) >= 10 AND APA_CPAU = '9999999999'
				END
-- verifica se o artigo é válido
				IF ISNULL(@CodigoArtigo, '') = ''
					RAISERROR('Artigo "%s" inválido.', 16, 110, @codigoPautal)	
-- obtem dados do desdobramento do regime
				SELECT TOP 1 @IdDesdobramento = id					
				FROM tb_TBL_Desdobramentos WITH(NOLOCK)
				WHERE tipoDeclaracao = @1CasaTipoDeclaracao AND regime = @Regime AND desdobramento1 = @regimeAdicional
-- verifica se o desdobramento é válido
				IF (ISNULL(@regimeAdicional, '') <> '') AND (@IdDesdobramento IS NULL) 					
					RAISERROR('Regime adicional "%s" inválido.', 16, 111, @regimeAdicional)					
-- obtem dados do país de origem
				SELECT @CodigoPaisOrigem = PAI_CODI
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @paisOrigem	
-- verifica se o país de origem é válido
				IF (ISNULL(@paisOrigem, '') <> '') AND (ISNULL(@CodigoPaisOrigem, '') = '')
					RAISERROR('País de origem "%s" inválido.', 16, 112, @paisOrigem)	
-- obtem dados da preferência
				SELECT @CodigoPreferencia = PRE_CODI
				FROM TAB_PREF WITH(NOLOCK)
				WHERE PRE_CODI = @preferencia
-- verifica se a preferência é válida
				IF (ISNULL(@preferencia, '') <> '') AND (ISNULL(@CodigoPreferencia, '') = '')
					RAISERROR('Preferência "%s" inválida.', 16, 113, @preferencia)
-- processa a inserção ou edição da adição conforme a ação da adição 
				IF @acaoAdicao = 'I'
				BEGIN
-- insere a adição no detalhe de adições na nova declaracao IMP-CAU
					SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de DELETE não ser processado
					EXEC @Resultado = sp_IMP_Declaracoes_AdicoesInsere @Ano, @Numero, @numeroAdicao, @CodigoArtigo, @massaLiquida, @massaBruta, @montanteAd, @unidades, @CodigoPreferencia, @CodigoPaisOrigem, @designacao, @regimeAdicional, @metodoAvaliacao, @valorFrete, @valorSeguro, @taxaIVA, @IdAdicao OUTPUT, @MsgErro OUTPUT
					SET CONTEXT_INFO 0x0 --reset à variavel global de sessão	
					IF @Resultado > 0
						RAISERROR('Erro na inserção da adição n.º "%d"! ERRO: "%s".', 16, 114, @numeroAdicao, @MsgErro)		
				END	
				ELSE
				BEGIN	
-- obtem dados da adição
					SELECT @IdAdicao = adi.DUA_IDEN, @unidades = ISNULL(adi.DUA_US41, 0), @CodigoPreferencia = adi.PRE_CO36, @CodigoPaisOrigem = adi.PAI_CO34, @DireitosDDP = ISNULL(adi.DUA_VDIR, 0), 
						@montanteAd = (CASE  
											WHEN (@CamposAdicionais = 2) OR (ISNULL(@ExtraFieldUPDATEValue, '') = 'DHL-PORTAL') THEN @montanteAd
											ELSE adi.DUA_VA42 
										END), 
						@massaLiquida = (CASE 
											WHEN (@CamposAdicionais IN (1, 2, 4)) AND (@OperacaoManifesto <> 2) THEN @massaLiquida 
											ELSE adi.DUA_ML38 
										END), 
						@massaBruta = (CASE 										
										WHEN @CamposAdicionais = 3 THEN (CASE 
																			WHEN @NaturezaRetorno = 1 THEN @massaBruta 
																			WHEN (@NaturezaRetorno = 0 AND duc.DUC_ADI5 = 1 AND (ABS(adi.DUA_MB35) - @massaBruta) < 0.500) THEN @massaBruta 
																			ELSE adi.DUA_MB35 
																		END)
										WHEN (@CamposAdicionais IN (1, 4)) AND (@OperacaoManifesto = 2) THEN adi.DUA_MB35 
										ELSE @massaBruta 
									END)
					FROM PRO_DUAD AS adi WITH(NOLOCK) 	
						INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM						
					WHERE adi.DUC_EANO = @Ano AND adi.DUC_PNUM = @Numero AND adi.DUA_CODI = @numeroAdicao					 								
-- verifica se a adição é válida
					IF @IdAdicao IS NULL
						RAISERROR('Adição n.º "%d" não existe na declaraçao IMP-CAU.', 16, 115, @numeroAdicao)	
-- edita a adição no detalhe de adições na nova declaracao IMP-CAU
					SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de DELETE não ser processado
					EXEC @Resultado = sp_IMP_Declaracoes_AdicoesEdita @IdAdicao, @Ano, @Numero, @numeroAdicao, @CodigoArtigo, @massaLiquida, @massaBruta, @montanteAd, @unidades, @CodigoPreferencia, @CodigoPaisOrigem, @DireitosDDP, @MsgErro OUTPUT
					SET CONTEXT_INFO 0x0 --reset à variavel global de sessão	
					IF @Resultado > 0
						RAISERROR('Erro na edição da adição n.º "%d"! ERRO: "%s".', 16, 116, @numeroAdicao, @MsgErro)														
				END
-- inicia variavel
				SET @UltCodTabela = ISNULL((SELECT MAX(D31_CODI) FROM PRO_DU31 WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @numeroAdicao), 0)
-- obtem as marcas e volumes da adição
				DECLARE MarcasVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
					SELECT 
						NULLIF(t.c.value('unidadeMedida[1]', 'varchar(3)'), ''),
						t.c.value('volumes[1]', 'int'), 							
						NULLIF(t.c.value('marcas[1]', 'varchar(512)'), ''), 														
						NULLIF(t.c.value('numeroObjeto[1]', 'varchar(20)'), ''),							
						NULLIF(t.c.value('codigoBarras[1]', 'varchar(30)'), ''),							
						t.c.value('parte[1]', 'bit')
					FROM @XMLMarcasEVolumes.nodes('marcasEVolumes/marcaEVolume') as t(c)
				OPEN MarcasVolumes
				FETCH NEXT FROM MarcasVolumes INTO @unidadeMedida, @volumes, @marcas, @numeroObjeto, @codigoBarras, @parte
				WHILE @@FETCH_STATUS = 0
				BEGIN		
-- inicia variáveis						
					SET @CodigoUnidadeMedida = NULL
					SET @NomeUnidadeMedida = NULL
					SET @VolumesAZero = 0
					SET @UltCodTabela = @UltCodTabela + 1	
-- obtem dados da unidade de medida
					SELECT @CodigoUnidadeMedida = UME_CODI, @NomeUnidadeMedida = UME_NOME, @VolumesAZero = UME_TVOL
					FROM TAB_UMED WITH(NOLOCK)
					WHERE UME_IMPT = 1 AND LEN(UME_CODI) <= 2 AND UME_CODI = @unidadeMedida
-- verifica se a unidade de medida é válida
					IF (ISNULL(@unidadeMedida, '') <> '') AND (ISNULL(@CodigoUnidadeMedida, '') = '')
						RAISERROR('Unidade de medida "%s" inválida.', 16, 117, @unidadeMedida)
					ELSE
						IF (@anexoB = 'H6') AND (ISNULL(@CodigoUnidadeMedida, '') <> '')
							RAISERROR('Unidade de medida "%s" inválida para o anexo B "%s".', 16, 118, @CodigoUnidadeMedida, @anexoB)
						ELSE
							IF (@anexoB <> 'H6') AND (ISNULL(@CodigoUnidadeMedida, '') = '')
								RAISERROR('O anexo B "%s" obriga ao preenchimento da unidade de medida.', 16, 119, @anexoB)							
							ELSE
								IF (ISNULL(@CodigoUnidadeMedida, '') NOT IN ('NE', 'NF', 'NG')) AND (@volumes = 0)
									RAISERROR('Unidade de medida "%s" obriga ao preenchimento dos volumes.', 16, 120, @unidadeMedida)
								ELSE
									IF (ISNULL(@CodigoUnidadeMedida, '') <> '') AND (@VolumesAZero = 1) AND (@volumes > 0)
										RAISERROR('Volumes inválidos para a Unidade de medida "%s".', 16, 121, @unidadeMedida)
-- verifica se as marcas é válida
					IF (@anexoB = 'H6') AND (ISNULL(@marcas, '') <> '')
						RAISERROR('Marcas "%s" inválida para o anexo B "%s".', 16, 122, @marcas, @anexoB)
					ELSE
						IF (@anexoB NOT IN ('H6', 'I1')) AND (ISNULL(@marcas, '') = '')
							RAISERROR('O anexo B "%s" obriga ao preenchimento das marcas.', 16, 123, @anexoB)
-- verifica restantes regras														
					IF (@numeroAdicao > 1) AND (@parte = 1)
						RAISERROR('"Parte" apenas é válido na 1ª adição.', 16, 124)
					IF (@CamposAdicionais <> 5) AND (ISNULL(@numeroObjeto, '') <> '')
						RAISERROR('Número do objeto "%s" inválido neste contexto.', 16, 125, @numeroObjeto)
					IF (@CamposAdicionais <> 5) AND (ISNULL(@codigoBarras, '') <> '')
						RAISERROR('Código de barras "%s" inválido neste contexto.', 16, 126, @codigoBarras)						
-- insere a marca e volume no sub-detalhe de marcas e volumes da adição na nova declaracao IMP-CAU
					SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de INSERT não ser processado
					INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_TTVL, D31_LOPT)
					VALUES (@Ano, 
						@Numero, 
						@numeroAdicao, 
						@UltCodTabela, 
						@marcas, 
						@numeroObjeto, 
						@volumes, 
						@CodigoUnidadeMedida, 
						@NomeUnidadeMedida, 
						@parte, 
						@VolumesAZero, 
						@codigoBarras)	
					SET CONTEXT_INFO 0x0 --reset à variavel global de sessão	
					FETCH NEXT FROM MarcasVolumes INTO @unidadeMedida, @volumes, @marcas, @numeroObjeto, @codigoBarras, @parte
				END
				CLOSE MarcasVolumes
				DEALLOCATE MarcasVolumes																
-- processa a inserção dos restantes detalhes da adição apenas quando a ação for INSERT
				IF @acaoAdicao = 'I'
				BEGIN
-- inicia variavel
					SET @UltCodTabela = ISNULL((SELECT MAX(DDO_CODI) FROM PRO_DDOC WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @numeroAdicao), 0)
-- obtem os documentos e certicados da adição
					DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
						SELECT 
							t.c.value('tipoDocumento[1]', 'int'), 
							t.c.value('codigoDocumento[1]', 'varchar(5)'), 
							NULLIF(t.c.value('numeroDocumento[1]', 'varchar(70)'), ''), 							
							t.c.value('dataValidade[1]', 'datetime'), 
							NULLIF(t.c.value('pais[1]', 'varchar(2)'), ''),
							ISNULL(t.c.value('montante[1]', 'decimal(18, 2)'), 0),
							NULLIF(t.c.value('entidadeEmissora[1]', 'varchar(70)'), ''),
							NULLIF(t.c.value('unidadeMedida[1]', 'varchar(3)'), ''),
							ISNULL(t.c.value('quantidade[1]', 'decimal(18, 6)'), 0)
						FROM @XMLDocumentos.nodes('documentosECertificados/documento') as t(c)
					OPEN Documentos
					FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento, @dataValidade, @pais, @montante, @entidadeEmissora, @unidadeMedida, @quantidade
					WHILE @@FETCH_STATUS = 0
					BEGIN		
-- inicia variáveis
						SET @IdDocumento = NULL
						SET @NomeDocumento = NULL
						SET @IdPais = NULL
						SET @CodigoUnidadeMedida = NULL
						SET @UltCodTabela = @UltCodTabela + 1
-- obtem dados do documento
						SELECT @IdDocumento = DOC_IDTY, @NomeDocumento = DOC_NOME, 
							@numeroDocumento = ISNULL(@numeroDocumento, (CASE DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END))							
						FROM TAB_DOCU WITH(NOLOCK)
						WHERE LEN(DOC_CODI) = 4 AND DOC_DESP = 1 AND DOC_DTRA = (CASE @tipoDocumento WHEN 1 THEN 1 ELSE 0 END) AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
						IF @IdDocumento IS NULL
							RAISERROR('Documento "%s" inválido.', 16, 127, @codigoDocumento)		
-- obtem dados do país
						SELECT @IdPais = PAI_IDTY
						FROM TAB_PAIS WITH(NOLOCK)
						WHERE PAI_CODI = @pais
-- verifica se o país é válido
						IF (ISNULL(@pais, '') <> '') AND (@IdPais IS NULL)
							RAISERROR('País "%s" inválido.', 16, 128, @pais)
						ELSE
							IF (@IdPais IS NULL) AND (@montante > 0) 
								RAISERROR('Montante inválido quando não se especifica país.', 16, 129)
							ELSE
								IF (@IdPais IS NOT NULL) AND (@montante = 0) 
									RAISERROR('O país "%s" obriga ao preenchimento do montante.', 16, 130, @pais)
-- obtem dados da unidade de medida
						SELECT @CodigoUnidadeMedida = UME_CODI
						FROM TAB_UMED WITH(NOLOCK)
						WHERE UME_IMPT = 1 AND UME_CODI = @unidadeMedida
-- verifica se a unidade de medida é válida
						IF (ISNULL(@unidadeMedida, '') <> '') AND (ISNULL(@CodigoUnidadeMedida, '') = '')
							RAISERROR('Unidade de medida "%s" inválida.', 16, 131, @unidadeMedida)				
-- insere o documento no sub-detalhe de documentos da adição na nova declaracao IMP-CAU
						INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_TIPO, DDO_EEMI, UME_CODI, DDO_QTDE)
						VALUES (@Ano, 
							@Numero, 
							@numeroAdicao, 
							@UltCodTabela, 
							@codigoDocumento, 
							@NomeDocumento, 
							@numeroDocumento, 
							@dataValidade, 
							@pais, 
							@montante, 
							0, 
							@tipoDocumento, 
							@entidadeEmissora, 
							@CodigoUnidadeMedida, 
							@quantidade)		
						FETCH NEXT FROM Documentos INTO @tipoDocumento, @codigoDocumento, @numeroDocumento, @dataValidade, @pais, @montante, @entidadeEmissora, @unidadeMedida, @quantidade
					END
					CLOSE Documentos
					DEALLOCATE Documentos	
-- obtem os documentos precedentes
					DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
						SELECT 
							t.c.value('codigoDocumento[1]', 'varchar(5)'), 
							t.c.value('numeroDocumento[1]', 'varchar(70)'), 
							NULLIF(t.c.value('qualificadorDC[1]', 'varchar(2)'), '')
						FROM @XMLPrecedentes.nodes('documentosPrecedentes/documentoPrecedente') AS t(c)
					OPEN Documentos
					FETCH NEXT FROM Documentos INTO @codigoDocumento, @numeroDocumento, @qualificadorDC
					WHILE @@FETCH_STATUS = 0
					BEGIN		
-- inicia variáveis
						SET @IdDocumento = NULL					
						SET @IdUnidadeMedidaVolumes = NULL
						SET @VolumesPrecedente = NULL
						SET @IdUnidadeMedidaQualificador = NULL
-- obtem dados do documento
						SELECT @IdDocumento = DOC_IDTY
						FROM TAB_DOCU WITH(NOLOCK)
						WHERE DOC_CA40 = 1 AND DOC_CODI = @codigoDocumento
-- verifica se o documento é válido
						IF @IdDocumento IS NULL
							RAISERROR('Documento precedente "%s" inválido.', 16, 132, @codigoDocumento)		
-- obtem dados da unidade de medida de volumes no detalhe de Marcas&Volumes da adição
						SELECT TOP 1 @VolumesPrecedente = NULLIF(dam.D31_QNTD, 0), @IdUnidadeMedidaVolumes = ume.UME_IDTY
						FROM PRO_DU31 AS dam WITH(NOLOCK)
							LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON dam.UME_CODI = ume.UME_CODI
						WHERE dam.DUC_EANO = @Ano AND dam.DUC_PNUM = @Numero AND dam.DUA_CODI = @numeroAdicao
						ORDER BY dam.D31_CODI
-- obtem dados da unidade de medida do qualificador
						SELECT @IdUnidadeMedidaQualificador = UME_IDTY
						FROM TAB_UMED WITH(NOLOCK)
						WHERE UME_IMPT = 1 AND UME_CODI = 'KGM'
-- insere o documento no sub-detalhe de documentos precedentes da adição na nova declaracao IMP-CAU																	
						INSERT INTO tb_IMP_DeclaracoesAdicoesPrecedentes(id_adicao, id_documento, numero, id_unidadeMedidaVolumes, volumes, id_unidadeMedidaQualificador, quantidade, numeroAdicao, 
							id_utilizadorControlo, dataControlo)
						VALUES (@IdAdicao, 
							@IdDocumento, 
							@numeroDocumento, 						
							@IdUnidadeMedidaVolumes, 
							@VolumesPrecedente, 
							@IdUnidadeMedidaQualificador, 
							@massaBruta, 
							@numeroAdicao, 
							@IdUtilizador, 
							@DataAtual)							
						FETCH NEXT FROM Documentos INTO @codigoDocumento, @numeroDocumento, @qualificadorDC
					END
					CLOSE Documentos
					DEALLOCATE Documentos							
-- obtem os pedidos da adição
					DECLARE Pedidos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
						SELECT 
							t.c.value('codigoPedido[1]', 'varchar(5)'), 
							NULLIF(t.c.value('numeroPedido[1]', 'varchar(512)'), '')
						FROM @XMLPedidos.nodes('pedidos/pedido') AS t(c)
					OPEN Pedidos
					FETCH NEXT FROM Pedidos INTO @codigoPedido, @numeroPedido
					WHILE @@FETCH_STATUS = 0
					BEGIN		
-- inicia variáveis
						SET @IdPedido = NULL
-- obtem dados do pedido
						SELECT @IdPedido = TXM_IDTY
						FROM TAB_TXML WITH(NOLOCK)
						WHERE LEN(TXM_CODI) = 5 AND TXM_CODI = @codigoPedido
-- verifica se o pedido é válido
						IF @IdPedido IS NULL
							RAISERROR('Pedido "%s" inválido.', 16, 133, @codigoPedido)		
-- insere o pedido no sub-detalhe de pedidos da adição na nova declaracao IMP-CAU
						INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, id_utilizadorControlo, dataControlo)
						VALUES (@IdAdicao,			
							@IdPedido, 
							@numeroPedido,  							
							@IdUtilizador, 
							@DataAtual)		
						FETCH NEXT FROM Pedidos INTO @codigoPedido, @numeroPedido
					END
					CLOSE Pedidos
					DEALLOCATE Pedidos		
-- inicia variavel
					SET @UltCodTabela = ISNULL((SELECT MAX(DCO_CODI) FROM PRO_DCON WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @numeroAdicao), 0)
-- obtem os contentores da adição
					DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
						SELECT 
							t.c.value('numeroContentor[1]', 'varchar(17)'), 													
							NULLIF(t.c.value('tipoContentor[1]', 'varchar(10)'), '')
						FROM @XMLContentores.nodes('contentores/contentor') as t(c)
					OPEN Contentores
					FETCH NEXT FROM Contentores INTO @numeroContentor, @tipoContentor
					WHILE @@FETCH_STATUS = 0
					BEGIN		
-- inicia variáveis						
						SET @UltCodTabela = @UltCodTabela + 1	
-- verifica regra													
						IF (@contentorizada = 0) AND (ISNULL(@numeroContentor, '') <> '')
							RAISERROR('Número de contentor "%s" inválido quando declaração não é contentorizada.', 16, 134, @numeroContentor)
-- insere o contentor no sub-detalhe de contentores da adição na nova declaracao IMP-CAU
						INSERT INTO PRO_DCON(DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO)
						VALUES (@Ano, 
							@Numero, 
							@numeroAdicao, 
							@UltCodTabela, 
							@numeroContentor, 
							@tipoContentor)		
						FETCH NEXT FROM Contentores INTO @numeroContentor, @tipoContentor
					END
					CLOSE Contentores
					DEALLOCATE Contentores	
-- inicia variavel
					SET @UltCodTabela = ISNULL((SELECT MAX(DBT_CODI) FROM PRO_DUBT WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @numeroAdicao), 0)
-- obtem os veículos da adição
					DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
						SELECT 
							NULLIF(t.c.value('homologacaoTecnica[1]', 'varchar(20)'), ''), 
							NULLIF(t.c.value('adicionalISV[1]', 'varchar(4)'), ''), 
							NULLIF(t.c.value('tabela[1]', 'varchar(1)'), ''), 
							t.c.value('marca[1]', 'varchar(20)'), 
							t.c.value('modelo[1]', 'varchar(20)'), 
							NULLIF(t.c.value('qualificadorV[1]', 'varchar(1)'), ''), 
							NULLIF(t.c.value('categoria[1]', 'varchar(2)'), ''), 
							NULLIF(t.c.value('tipoVeiculo[1]', 'varchar(3)'), ''), 
							NULLIF(t.c.value('combustivel[1]', 'varchar(2)'), ''), 
							ISNULL(t.c.value('cilindrada[1]', 'decimal(18, 3)'), 0), 
							ISNULL(t.c.value('co2[1]', 'int'), 0), 
							NULLIF(t.c.value('tipoCO2[1]', 'varchar(4)'), ''), 
							NULLIF(t.c.value('particulas[1]', 'varchar(6)'), ''), 
							t.c.value('autonomia[1]', 'int'), 
							NULLIF(t.c.value('documentoIMT[1]', 'varchar(5)'), ''), 
							ISNULL(t.c.value('valorISV[1]', 'decimal(18, 2)'), 0), 
							t.c.query('chassis')
						FROM @XMLVeiculos.nodes('veiculos/veiculo') AS t(c)
					OPEN Veiculos
					FETCH NEXT FROM Veiculos INTO @homologacaoTecnica, @adicionalISV, @tabela, @marca, @modelo, @qualificadorV, @categoria, @tipoVeiculo, @combustivel, @cilindrada, @co2, 
						@tipoCO2, @particulas, @autonomia, @documentoIMT, @valorISV, @XMLChassis
					WHILE @@FETCH_STATUS = 0
					BEGIN		
-- inicia variáveis						
						SET @CodigoCategoria = NULL
						SET @CodigoTipoVeiculo = NULL
						SET @CodigoTipoCombustivel = NULL
						SET @UltCodTabela = @UltCodTabela + 1	
-- obtem dados da categoria
						SELECT @CodigoCategoria = CAT_CODI
						FROM TAB_CATG WITH(NOLOCK)
						WHERE CAT_CODI = @categoria
-- verifica se a categoria é válida
						IF (ISNULL(@categoria, '') <> '') AND (ISNULL(@CodigoCategoria, '') = '')
							RAISERROR('Categoria "%s" inválida.', 16, 135, @categoria)
-- obtem dados do tipo veículo
						SELECT @CodigoTipoVeiculo = TVE_CODI
						FROM TAB_TVEI WITH(NOLOCK)
						WHERE TVE_CODI = @tipoVeiculo
-- verifica se o tipo veículo é válido
						IF (ISNULL(@tipoVeiculo, '') <> '') AND (ISNULL(@CodigoTipoVeiculo, '') = '')
							RAISERROR('Tipo de veículo "%s" inválido.', 16, 136, @tipoVeiculo)
-- obtem dados do tipo combústivel
						SELECT @CodigoTipoCombustivel = TCO_CODI
						FROM TAB_TCOM WITH(NOLOCK)
						WHERE TCO_CODI = @combustivel
-- verifica se o tipo combústivel é válido
						IF (ISNULL(@combustivel, '') <> '') AND (ISNULL(@CodigoTipoCombustivel, '') = '')
							RAISERROR('Tipo de combustível "%s" inválido.', 16, 137, @combustivel)
-- verifica restantes regras																		
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@tabela, '') IN ('A', 'B', 'C')) AND (ISNULL(@homologacaoTecnica, '') = '') 
							RAISERROR('A tabela "%s" sem adicional ISV obriga ao preenchimento da homologação técnica.', 16, 138, @tabela)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@qualificadorV, '') = '') 
							RAISERROR('Sem adicional ISV obriga ao preenchimento do qualificador.', 16, 139)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@CodigoTipoVeiculo, '') = '') 
							RAISERROR('Sem adicional ISV obriga ao preenchimento do tipo de veículo.', 16, 140)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@tabela, '') = '') AND (ISNULL(@CodigoCategoria, '') = '') 
							RAISERROR('Sem adicional ISV e sem tabela obriga ao preenchimento da categoria.', 16, 141)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@tabela, '') = '') AND (ISNULL(@CodigoTipoCombustivel, '') = '') 
							RAISERROR('Sem adicional ISV e sem tabela obriga ao preenchimento do tipo de combustível.', 16, 142)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@tabela, '') = '') AND (@cilindrada = 0) 
							RAISERROR('Sem adicional ISV e sem tabela obriga ao preenchimento da cilindrada.', 16, 143)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@tabela, '') = '') AND (ISNULL(@particulas, '') = '') 
							RAISERROR('Sem adicional ISV e sem tabela obriga ao preenchimento das partículas.', 16, 144)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@tabela, '') = 'A') AND (@co2 = 0) 
							RAISERROR('A tabela "%s" sem adicional ISV obriga ao preenchimento do co2.', 16, 145, @tabela)
						IF (ISNULL(@adicionalISV, '') = '') AND (ISNULL(@tabela, '') = 'A') AND (ISNULL(@tipoCO2, '') = '') 
							RAISERROR('A tabela "%s" sem adicional ISV obriga ao preenchimento do tipo co2.', 16, 146, @tabela)
						IF (LEFT(@Regime, 2) IN ('40', '61')) AND (ISNULL(@documentoIMT, '') = '')
							RAISERROR('O regime "%s" obriga ao preenchimento do documento IMT.', 16, 147, @Regime)
-- insere o veículo no sub-detalhe de veículos da adição na nova declaracao IMP-CAU
						INSERT INTO PRO_DUBT(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, DBT_VLIA, DBT_MARC, 
							DBT_MODE, DBT_IDCR, DBT_HOMO, DBT_TABE, DBT_TCO2, DBT_AUTN, DBT_DIMT)
						VALUES (@Ano, 
							@Numero, 
							@numeroAdicao, 
							@UltCodTabela, 
							@cilindrada, 
							0, 
							@CodigoTipoVeiculo, 
							@qualificadorV, 
							@adicionalISV, 
							@co2, 
							@CodigoCategoria, 
							@CodigoTipoCombustivel, 
							@particulas, 
							@valorISV, 
							@marca, 
							@modelo, 
							REPLACE(CONVERT(numeric(38, 10), DATEADD(MILLISECOND, (@UltCodTabela * 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())), '.', ','), 
							@homologacaoTecnica, 
							@tabela, 
							@tipoCO2, 
							@autonomia, 
							@documentoIMT)		
-- inicia variavel
						SET @UltCodTabela1 = ISNULL((SELECT MAX(DVC_CODI) FROM PRO_DUVE WHERE DUC_EANO = @Ano AND DUC_PNUM = @Numero AND DUA_CODI = @numeroAdicao AND DBT_CODI = @UltCodTabela), 0)
-- obtem os chassis do veículo
						DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
							SELECT 
								NULLIF(t.c.value('matricula[1]', 'varchar(10)'), ''), 
								t.c.value('dataMatricula[1]', 'datetime'), 																				
								NULLIF(t.c.value('numeroChassi[1]', 'varchar(22)'), ''),
								t.c.value('dataChassi[1]', 'datetime') 
							FROM @XMLChassis.nodes('chassis/chassi') AS t(c)
						OPEN Chassis
						FETCH NEXT FROM Chassis INTO @matricula, @dataMatricula, @numeroChassi, @dataChassi
						WHILE @@FETCH_STATUS = 0
						BEGIN		
-- inicia variáveis						
							SET @UltCodTabela1 = @UltCodTabela1 + 1	
-- verifica regras												
							IF (ISNULL(@qualificadorV, '') IN ('', 'A')) AND (ISNULL(@matricula, '') = '')
								RAISERROR('O qualificador "%s" obriga ao preenchimento da matrícula.', 16, 148, @qualificadorV)
							ELSE
								IF (ISNULL(@qualificadorV, '') IN ('', 'A')) AND (@dataMatricula IS NULL)
									RAISERROR('O qualificador "%s" obriga ao preenchimento da data da matrícula.', 16, 149, @qualificadorV)
								ELSE
									IF (ISNULL(@qualificadorV, '') IN ('N', 'U')) AND (ISNULL(@numeroChassi, '') = '')
										RAISERROR('O qualificador "%s" obriga ao preenchimento do chassi.', 16, 150, @qualificadorV)
									ELSE
										IF (ISNULL(@qualificadorV, '') IN ('N', 'U')) AND (@dataChassi IS NULL)
											RAISERROR('O qualificador "%s" obriga ao preenchimento da data do chassi.', 16, 151, @qualificadorV)
							IF (ISNULL(@matricula, '') = '') AND (@dataMatricula IS NOT NULL)
								RAISERROR('Data da matrícula inválida.', 16, 152)
							IF (ISNULL(@numeroChassi, '') = '') AND (@dataChassi IS NOT NULL)
								RAISERROR('Data do chassi inválida.', 16, 153)
-- insere o chassi no sub-detalhe de chassis do veículo da adição na nova declaracao IMP-CAU
							INSERT INTO PRO_DUVE(DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, DVC_CODI, DVC_MATR, DVC_CHAS, DVC_DMAT, DVC_DCHA)
							VALUES (@Ano, 
								@Numero, 
								@numeroAdicao, 
								@UltCodTabela, 
								@UltCodTabela1,
								@matricula, 
								@numeroChassi, 
								@dataMatricula, 
								@dataChassi)		
							FETCH NEXT FROM Chassis INTO @matricula, @dataMatricula, @numeroChassi, @dataChassi
						END
						CLOSE Chassis
						DEALLOCATE Chassis
						FETCH NEXT FROM Veiculos INTO @homologacaoTecnica, @adicionalISV, @tabela, @marca, @modelo, @qualificadorV, @categoria, @tipoVeiculo, @combustivel, @cilindrada, @co2, 
							@tipoCO2, @particulas, @autonomia, @documentoIMT, @valorISV, @XMLChassis
					END
					CLOSE Veiculos
					DEALLOCATE Veiculos
				END									
				FETCH NEXT FROM Adicoes INTO @acaoAdicao, @numeroAdicao, @codigoPautal, @designacao, @regimeAdicional, @paisOrigem, @preferencia, @metodoAvaliacao, @massaLiquida, @massaBruta, 
					@unidades, @montanteAd, @valorFrete, @valorSeguro, @taxaIVA, @XMLDocumentos, @XMLPrecedentes, @XMLPedidos, @XMLMarcasEVolumes, @XMLContentores, @XMLVeiculos
			END
			CLOSE Adicoes
			DEALLOCATE Adicoes																
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @NumErro = 1 
			SET @Erro = ISNULL(@Erro, '') + 
						'Detalhes do Erro: ' + CHAR(13) + 
						' » Data: ' + CONVERT(varchar(23), @DataAtual, 126) + CHAR(13) +
						' » Doc. Transporte: ' + ISNULL(@documentoTransporte, '') + CHAR(13) +
						' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + 
						' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + CHAR(13) + 
						' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + 
						' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + 
						' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + CHAR(13) + 
						' » Mensagem: ' + ERROR_MESSAGE() + CHAR(13) 
-- em caso de erro faz rollback da transacção iniciada						           
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION TspIMPImportacao
		END CATCH			
-- se sucesso faz commit da transacção iniciada
		IF @@TRANCOUNT > 0
			COMMIT TRANSACTION TspIMPImportacao
		FETCH NEXT FROM DeclaracoesIMP INTO @acao, @data, @despachoCentralizado, @anexoB, @natureza, @documentoTransporte, @descricaoGenerica, @nifExportador, @nomeExportador, @moradaExportador, 
			@localidadeExportador, @codigoPostalExportador, @localidadePostalExportador, @paisExportador, @paisExpedicao, @nifImportador, @tipoNIFImportador, @nomeImportador, @moradaImportador, 
			@localidadeImportador, @codigoPostalImportador, @localidadePostalImportador, @paisImportador, @telefoneImportador, @emailImportador, @paisDestino, @regiao, @declarante, 
			@estatutoDeclarante, @vossaReferencia, @estancia, @tipoDeclaracao, @naturezaTransacao, @condicaoEntrega, @localidadeCE, @paisCE, @portoAeroporto, @paisFatura, @valorTotalFatura, 
			@paisFrete, @valorTotalFrete, @paisSeguro, @valorTotalSeguro, @totalMassaLiquida, @totalMassaBruta, @numeroNRUR, @meioTransporteFronteira, @paisFronteira, @meioTransporteInterior, 
			@meioTransporteChegada, @identificacaoTransporte, @contentorizada, @numeroContentor, @tipoLocalizacao, @qualificador, @armazemDTP, @estanciaLM, @nifOperadorEconomico, @moradaLM, 
			@localidadeLM, @codigoPostalLM, @armazem, @locID, @gateway, @serviceLevel, @portesAcc, @portes, @despachoAcc, @freteOriginal, @moedafreteOriginal, @despesas, @condEntrega, @nomeFicheiro, 
			@numeroPDDT, @dataEntrada, @numeroPDDTDEV, @numeroTD, @numeroACTM, @numeroSequencia, @posicaoArmazem, @miniCPA, @dataVoo, @aeroportoOrigem, @numeroVoo, @posicaoAviao, @tracking, 
			@tipoCarga, @numeroContaExpedidor, @numeroContaDestinatario, @nomeOriginalDestinatario, @moradaOriginalDestinatario, @localidadeOriginalDestinatario, @codigoPostalOriginalDestinatario, 
			@localidadePostalOriginalDestinatario, @referenciaExterna1, @referenciaExterna2, @shipID, @dutyType, @payment, @dataDocumentoTransporte, @numeroRequerimento, @numeroDURetorno, 
			@numeroT1Retorno, @anotacoes, @followUp, @utilizadorNomeado, @XMLCamposExtra, @XMLDocumentos, @XMLPrecedentes, @XMLPedidos, @XMLAdicoes, @XMLIncidencias, @XMLFollowUps, @XMLContactos, 
			@XMLManifestos, @XMLArquivos
	END
	CLOSE DeclaracoesIMP
	DEALLOCATE DeclaracoesIMP	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaDeXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaDeXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaFicheiroCTT]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaFicheiroCTT] @FicheiroXML xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin)
-- inicia variaveis
	SET @NumErro = 0
-- inicia processo de importação da declaração IMP-CAU
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para declaração IMP-CAU a partir do ficheiro XML no formato CTT
		SET @XMLDeclaracao = 
			(SELECT	
				(SELECT t.c.value('@Acao[1]', 'varchar(1)') AS "@acao", 
					(CONVERT(varchar(10), t.c.value('Data[1]', 'datetime'), 127) + 'Z') AS "data", 
					CAST(0 AS bit) AS "despachoCentralizado", 
					'H6' AS "anexoB", 
					NULLIF(t.c.value('CodNatureza[1]', 'varchar(3)'), '') AS "natureza", 
					NULLIF(t.c.value('NumDocTransporte[1]', 'varchar(18)'), '') AS "documentoTransporte", 
					(SELECT 
						(SELECT 
							NULLIF(t.c.value('NIFExpedidor[1]', 'varchar(17)'), '') AS "nif", 
							NULLIF(t.c.value('NomeExpedidor[1]', 'varchar(70)'), '') AS "nome", 
							NULLIF(t.c.value('MoradaExpedidor[1]', 'varchar(70)'), '') AS "morada", 
							NULLIF(t.c.value('LocalidadeExpedidor[1]', 'varchar(35)'), '') AS "localidade", 
							NULLIF(t.c.value('CodPostalExpedidor[1]', 'varchar(12)'), '') AS "codigoPostal", 
							NULLIF(t.c.value('LocPostalExpedidor[1]', 'varchar(35)'), '') AS "localidadePostal", 
							NULLIF(t.c.value('CodPaisExpedidor[1]', 'varchar(2)'), '') AS "pais"
						HAVING ISNULL(t.c.value('NomeExpedidor[1]', 'varchar(70)'), '') <> ''
						FOR XML PATH('exportador'), TYPE), 
						(SELECT 
							ISNULL(NULLIF(t.c.value('NIFDestinatario[1]', 'varchar(17)'), ''), '999999990') AS "nif", 
							t.c.value('TipoDestinatario[1]', 'int') AS "tipoNIF", 
							NULLIF(t.c.value('NomeDestinatario[1]', 'varchar(70)'), '') AS "nome", 
							NULLIF(t.c.value('MoradaDestinatario[1]', 'varchar(70)'), '') AS "morada", 
							NULLIF(t.c.value('LocalidadeDestinatario[1]', 'varchar(35)'), '') AS "localidade", 
							NULLIF(t.c.value('CodPostalDestinatario[1]', 'varchar(12)'), '') AS "codigoPostal", 
							NULLIF(t.c.value('LocalidadeDestinatario[1]', 'varchar(35)'), '') AS "localidadePostal", 
							NULLIF(t.c.value('CodPaisDestinatario[1]', 'varchar(2)'), '') AS "pais" 			
						FOR XML PATH('importador'), TYPE),
						NULLIF(t.c.value('CodPais17[1]', 'varchar(2)'), '') AS "paisDestino",
						(SELECT
							NULLIF(t.c.value('CodDeclarante[1]', 'varchar(6)'), '') AS "codigoDeclarante"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE), 
					NULLIF(t.c.value('CodEstancia[1]', 'varchar(8)'), '') AS "estancia", 
					(CASE 
						WHEN (ISNULL(t.c.value('CodNatureza[1]', 'varchar(3)'), '') = '40') AND (ISNULL(t.c.value('CodTipoDeclaracao[1]', 'varchar(4)'), '') IN ('FREU', 'FRIM')) THEN 
							(CASE 
								WHEN ISNULL(t.c.value('CodPais15A[1]', 'varchar(2)'), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'GB') THEN 'FREU' 
								ELSE 'FRIM' 
							END) 						
						ELSE 'RPIM' 
					END) AS "tipoDeclaracao", 
					NULLIF(t.c.value('CodCondEntrega[1]', 'varchar(3)'), '') AS "condicaoEntrega", 
					(SELECT 
						(SELECT
							NULLIF(t.c.value('CodPais22[1]', 'varchar(2)'), '') AS "pais", 							
							CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/PrecoAdicao)', 'float'), 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							ISNULL(NULLIF(t.c.value('MoedaFrete[1]', 'varchar(2)'), ''), 'EU') AS "pais", 							
							CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/ValorFrete)', 'float'), 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							ISNULL(NULLIF(t.c.value('MoedaSeguro[1]', 'varchar(2)'), ''), 'EU') AS "pais", 							
							CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/ValorSeguro)', 'float'), 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT
							CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/MassaLiquida)', 'float'), 0) AS decimal(18, 6)) AS "massaLiquida", 							
							CAST(ISNULL(t.c.value('sum(Adicoes/Adicao/MassaBruta)', 'float'), 0) AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT
						NULLIF(t.c.value('NumDocTransporte[1]', 'varchar(18)'), '') AS "numeroNRUR", 
						NULLIF(t.c.value('CodMeioTransporte18[1]', 'varchar(2)'), '') AS "meioTransporteChegada", 
						0 AS "contentorizada"
					FOR XML PATH('transporte'), TYPE), 
					(SELECT
						t.c.value('CodFollowUp[1]', 'int') AS "codigoFollowUp"
					HAVING ISNULL(t.c.value('CodFollowUp[1]', 'int'), -1) <> -1
					FOR XML PATH('followUp'), TYPE), 					
					(SELECT 
						0 AS "tipoDocumento", 
						NULLIF(d.c.value('CodDocumento[1]', 'varchar(5)'), '') AS "codigoDocumento",
						NULLIF(d.c.value('NumeroReferencia[1]', 'varchar(70)'), '') AS "numeroDocumento", 
						(CONVERT(varchar(10), d.c.value('DataEmissao[1]', 'datetime'), 127) + 'Z') AS "dataValidade"					
					FROM t.c.nodes('Adicoes/Adicao/Documentos/Documento') AS d(c)
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON d.c.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI																	
					WHERE d.c.value('(../../NumAdicao)[1]', 'int') = 1 AND doc.DOC_DTRA = 0						
					FOR XML PATH('documento'), ROOT('documentosECertificados'), TYPE),	
					(SELECT 
						doc.DOC_CODI AS "codigoDocumento", 
						NULLIF(d.c.value('NumeroReferencia[1]', 'varchar(70)'), '') AS "numeroDocumento"			
					FROM t.c.nodes('Adicoes/Adicao/Documentos/Documento') AS d(c) 
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON d.c.value('CodDocumento[1]', 'varchar(5)') = doc.DOC_CODI												
					WHERE d.c.value('(../../NumAdicao)[1]', 'int') = 1 AND doc.DOC_CODI = 'N337' AND ISNULL(d.c.value('NumeroReferencia[1]', 'varchar(70)'), '') <> ''								
					FOR XML PATH('documentoPrecedente'), ROOT('documentosPrecedentes'), TYPE),																											
					(SELECT
						(SELECT 
							a.c.value('NumAdicao[1]', 'int') AS "numeroAdicao", 
							ISNULL((SELECT TOP 1 NULLIF(APA_CPAU, '') FROM TAB_APAU WITH(NOLOCK) WHERE APA_CODI = NULLIF(a.c.value('CodArtigoPautal[1]', 'varchar(22)'), '')), '9999999999') AS "codigoPautal", 							
							ISNULL(NULLIF(a.c.value('Designacao[1]', 'varchar(150)'), ''), 'NÃO CLASSIFICADO') AS "designacao", 	
							NULLIF(a.c.value('C37B[1]', 'varchar(6)'), '') AS "regimeAdicional", 						
							NULLIF(a.c.value('CodPaisOrigem[1]', 'varchar(2)'), '') AS "paisOrigem",		
							a.c.value('MassaLiquida[1]', 'decimal(18, 6)') AS "massaLiquida", 					
							a.c.value('MassaBruta[1]', 'decimal(18, 6)') AS "massaBruta",																					
							a.c.value('PrecoAdicao[1]', 'decimal(18, 3)') AS "montanteAd", 						
							(SELECT 
								m.c.value('QtdVolumes[1]', 'int') AS "volumes", 
								NULLIF(m.c.value('Numero[1]', 'varchar(20)'), '') AS "numeroObjeto", 
								NULLIF(m.c.value('Loptica[1]', 'varchar(30)'), '') AS "codigoBarras", 
								m.c.value('P[1]', 'bit') AS "parte"		
							FROM a.c.nodes('MarcasEVolumes/MarcaEVolume') AS m(c)	
							WHERE (a.c.value('NumAdicao[1]', 'int') = 1) OR ((a.c.value('NumAdicao[1]', 'int') > 1) AND (m.c.value('P[1]', 'bit') = 0) AND (m.c.value('R[1]', 'bit') = 0))															
							FOR XML PATH('marcaEVolume'), ROOT('marcasEVolumes'), TYPE)
						FROM t.c.nodes('Adicoes/Adicao') as a(c) 			
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE)
				FROM @FicheiroXML.nodes('DeclaracoesImpToGIDWin/Declaracao') AS t(c)
				WHERE NOT EXISTS(SELECT 1 FROM PRO_DUCG WITH(NOLOCK) WHERE (DUC_EANO = YEAR(@DataAtual) OR DUC_EANO = (YEAR(@DataAtual) - 1)) AND DUC_CPRT = NULLIF(t.c.value('NumDocTransporte[1]', 'varchar(18)'), ''))
				FOR XML PATH('declaracao'), TYPE)		
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da(s) declaração(ões) IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT								
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaFicheiroCTT] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaFicheiroCTT] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaFicheiroDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaFicheiroDHL] @FicheiroXML xml, @Gateway varchar(3), @MsgDate datetime, @XMLDadosRestricao xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin)
	DECLARE @TblAdicoes TABLE(
		id int NOT NULL IDENTITY(1, 1), 	
		documentoTransporte varchar(18) NOT NULL, 	
		totalAdicoes int NOT NULL,
		totalMassaBruta decimal(18, 6) NOT NULL,		
		numeroAdicao int NOT NULL, 
		codigoPautal varchar(22) NULL, 
		designacao varchar(260) NULL, 
		codPaisOrigem varchar(2) NULL, 
		regimeAdicional varchar(6) NULL, 
		unidades decimal(18, 6) NOT NULL,
		massaBruta decimal(18, 6) NOT NULL, 
		montante decimal(18, 2) NOT NULL)
-- inicia variaveis
	SET @NumErro = 0
-- inicia processo de importação da declaração IMP-CAU
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem as adições agrupadas por código pautal do ficheiro XML
		INSERT INTO @TblAdicoes(	
			documentoTransporte, 	
			totalAdicoes, 
			totalMassaBruta, 			
			numeroAdicao, 
			codigoPautal, 
			designacao, 
			codPaisOrigem, 
			regimeAdicional, 
			unidades,
			massaBruta, 
			montante)
		SELECT 			
			t.documentoTransporte, 
			COUNT(*) OVER(PARTITION BY t.documentoTransporte), 
			ISNULL(t.totalMassaBruta, 0), 			
			ROW_NUMBER() OVER(PARTITION BY t.documentoTransporte ORDER BY t.codigoPautal, t.designacao, t.codPaisOrigem, t.regimeAdicional), 
			NULLIF(t.codigoPautal, ''), 
			NULLIF(t.designacao, ''), 
			NULLIF(t.codPaisOrigem, ''), 
			NULLIF(t.regimeAdicional, ''), 
			SUM(ISNULL(t.unidades, 0)), 
			0, 
			SUM(ABS(ISNULL(t.montante, 0)))
		FROM (SELECT 
				l.c.value('(../../HAWB)[1]', 'varchar(18)') AS documentoTransporte, 
				l.c.value('(../../GrossWgt)[1]', 'numeric(28, 6)') AS totalMassaBruta, 								
				(CASE 
					WHEN r.c.value('numero[1]', 'int') IS NOT NULL THEN r.c.value('../artigoPautal[1]', 'varchar(22)')
					ELSE ISNULL(NULLIF(art.APA_CPAU, ''), '9999999999') 
				END) AS codigoPautal, 
				(CASE 
					WHEN r.c.value('numero[1]', 'int') IS NOT NULL THEN (NULLIF(r.c.value('../designacaoPautal[1]', 'varchar(150)'), '') + ' - ' + ISNULL(NULLIF(l.c.value('TariffCdNo[1]', 'varchar(22)'), ''), '9999999999'))
					ELSE ISNULL(ISNULL(NULLIF(art.APA_DESG, ''), NULLIF(l.c.value('DescOfGoods[1]', 'varchar(150)'), '')), 'NÃO CLASSIFICADO') 
				END) AS designacao, 
				(CASE 
					WHEN EXISTS(SELECT 1 FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = NULLIF(ISNULL(NULLIF(l.c.value('CtryMfctrerOrgn[1]', 'varchar(2)'), ''), l.c.value('CtryOrgnCd[1]', 'varchar(2)')), '') AND PAI_ZEUR = 1) THEN 'EU' 
					ELSE NULLIF(ISNULL(NULLIF(l.c.value('CtryMfctrerOrgn[1]', 'varchar(2)'), ''), l.c.value('CtryOrgnCd[1]', 'varchar(2)')), '') 
				END) AS codPaisOrigem, 
				l.c.value('(LineItemCustom/CustomAtt[Name_Eng="Special Code"]/Val)[1]', 'varchar(6)') AS regimeAdicional, 
				CAST(NULLIF(l.c.value('TariffQnty[1]', 'varchar(20)'), '') AS decimal(18, 6)) AS unidades, 
				l.c.value('InvLineVal[1]', 'decimal(18, 3)') AS montante				
			FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp/LineItems/LineItem') AS l(c)					
				LEFT OUTER JOIN @XMLDadosRestricao.nodes('DadosRestricao/AdicaoRestrita') AS r(c) ON l.c.value('GoodsItemNo[1]', 'int') = r.c.value('numero[1]', 'int')
				OUTER APPLY (SELECT TOP 1 APA_CPAU, APA_DESG FROM TAB_APAU WITH(NOLOCK) WHERE APA_CPAU = NULLIF(l.c.value('TariffCdNo[1]', 'varchar(22)'), '')) AS art
			) AS t								
		GROUP BY t.documentoTransporte, t.totalMassaBruta, t.codigoPautal, t.designacao, t.codPaisOrigem, t.regimeAdicional
-- processa calculos para o campo de massa bruta de cada adição em função do total de adições apurado
		UPDATE @TblAdicoes SET 			
			massaBruta = (ROUND((ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) / totalAdicoes), 3, 1) + (CASE 
																													WHEN (totalAdicoes > 1) AND (numeroAdicao = totalAdicoes) THEN (ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) - ROUND((ISNULL(NULLIF(ROUND(totalMassaBruta, 1, 1), 0), 0.1) / totalAdicoes), 3, 1) * numeroAdicao)
																													ELSE 0
																												END))
-- constroi XML para declaração IMP-CAU a partir do ficheiro XML no formato DHL
		SET @XMLDeclaracao = 
			(SELECT	
				(SELECT 'I' AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
					CAST(0 AS bit) AS "despachoCentralizado", 
					'H1' AS "anexoB", 
					(CASE 
						WHEN ISNULL(r.c.value('natureza[1]', 'varchar(3)'), '') <> '' THEN r.c.value('natureza[1]', 'varchar(3)') 
						WHEN NULLIF(t.c.value('(FlexFields[Name_Eng="MSC - Manifest Split Code"]/Val)[1]', 'varchar(255)'), '') IN ('ACH5', 'CASH', 'DDP5', 'FRQ', 'FRQP','DECLA','DECLC','DECLD') THEN 'PRE' 
						ELSE 'CDS' 
					END) AS "natureza", 
					NULLIF(t.c.value('HAWB[1]', 'varchar(18)'), '') AS "documentoTransporte", 
					(SELECT 
						(SELECT 							
							ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/CoName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCntctDtls/PreferredName)[1]', 'varchar(70)'), ''), '.')) AS "nome", 
							ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''), '.') AS "morada", 
							ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.') AS "localidade", 
							ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0') AS "codigoPostal", 
							ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.') AS "localidadePostal", 
							(CASE ISNULL(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') 
								WHEN 'IC' THEN 'ES' 
								WHEN 'RS' THEN 'XS' 
								WHEN 'XM' THEN 'SX' 
								WHEN 'XB' THEN 'BQ' 
								ELSE NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') 
							END) AS "pais"
						HAVING NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/CoName)[1]', 'varchar(70)'), '') <> ''
						FOR XML PATH('exportador'), TYPE), 
						(CASE ISNULL(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') 
							WHEN 'IC' THEN 'ES' 
							WHEN 'RS' THEN 'XS' 
							WHEN 'XM' THEN 'SX' 
							WHEN 'XB' THEN 'BQ' 
							ELSE NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') 
						END) AS "paisExpedicao", 
						(SELECT 
							ISNULL(NULLIF(t.c.value('(ShpCnsgne/VATNo)[1]', 'varchar(17)'), ''), '999999990') AS "nif", 
							1 AS "tipoNIF", 
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCntctDtls/PreferredName)[1]', 'varchar(70)'), ''), '.'))) AS "nome", 
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(70)'), ''),  ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''), '.')))) AS "morada", 				   
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.')) AS "localidade", 
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0')) AS "codigoPostal", 
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '.')) AS "localidadePostal", 
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '')) AS "pais", 
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="TEL"]/DeviceDtls)[1]', 'varchar(14)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="TEL"]/DeviceDtls)[1]', 'varchar(14)'), '')) AS "telefone", 
							ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="EML"]/DeviceDtls)[1]', 'varchar(200)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/Cntct/CntctDevices[DeviceType="EML"]/DeviceDtls)[1]', 'varchar(200)'), '')) AS "email"
						FOR XML PATH('importador'), TYPE),
						ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '')) AS "paisDestino",
						dbo.fn_Geral_ObtemRegiaoEstatisiticaDeCodPostal(NULLIF(SUBSTRING(ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), '0')), 1, 4), '.')) AS "regiao", 
						(SELECT
							'00' AS "codigoDeclarante"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE), 					
					(CASE @Gateway WHEN 'LIS' THEN 'PT000015' ELSE 'PT000020' END) AS "estancia", 
					'IMD' AS "tipoDeclaracao", 
					(CASE 
						WHEN (ISNULL(t.c.value('(ShpCnsgne/VATNo)[1]', 'varchar(18)'), '') = '514365455') THEN '41' 
						WHEN (ISNULL(t.c.value('(DatElGrp[@Cd="ShpClss"]/DatEl[Cd="Clss"]/Val)[1]', 'varchar(255)'), '') IN ('C2C', 'C2B', 'B2C')) THEN '12' 
						WHEN (ISNULL(t.c.value('ReasonForExpt[1]', 'varchar(1)'), '') = 'U') THEN '21' 
						WHEN (ISNULL(t.c.value('ReasonForExpt[1]', 'varchar(1)'), '') = 'G') THEN '34' 
						ELSE '11' 
					END) AS "naturezaTransacao", 
					t.c.value('Incoterms[1]', 'varchar(3)') AS "condicaoEntrega", 
					(SELECT
						ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), '*****N/A*****') AS "localidadeCE", 
						(CASE ISNULL(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') 
							WHEN 'IC' THEN 'ES' 
							WHEN 'RS' THEN 'XS' 
							WHEN 'XM' THEN 'SX' 
							WHEN 'XB' THEN 'BQ' 
							ELSE ISNULL(NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), ''), '--')
						END) AS "paisCE"
					FOR XML PATH('localizacao'), TYPE), 					
					(SELECT 
						(SELECT
							ISNULL(NULLIF(t.c.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') AS "pais", 	
							CAST(ISNULL(t.c.value('(TxAndDty/CstmsVal)[1]', 'decimal(18, 3)'), 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							ISNULL(NULLIF(t.c.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHGCurCd"]/Val)[1]', 'varchar(2)'), ''), 'EU') AS "pais", 							
							0 AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							0 AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT
							CAST(ROUND((ISNULL(NULLIF(ROUND(t.c.value('GrossWgt[1]', 'decimal(18, 6)'), 1, 1), 0), 0.1) * 0.95), 3) AS decimal(18, 6)) AS "massaLiquida", 							
							CAST(ISNULL(NULLIF(ROUND(t.c.value('GrossWgt[1]', 'decimal(18, 6)'), 1, 1), 0), 0.1) AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT
						NULLIF(t.c.value('HAWB[1]', 'varchar(30)'), '') AS "numeroNRUR", 
						(SELECT 
							'40' AS "meioTransporte"							
						FOR XML PATH('fronteira'), TYPE), 
						'40' AS "meioTransporteChegada", 
						0 AS "contentorizada"
					FOR XML PATH('transporte'), TYPE), 
					(SELECT
						'B' AS "tipoLocalizacao", 
						'Y' AS "qualificador", 
						(CASE @Gateway WHEN 'LIS' THEN 'DTP00000487015PT' ELSE 'DTP00000473020PT' END) AS "armazemDTP"
					FOR XML PATH('localizacaoMercadorias'), TYPE), 
					(SELECT 
						NULLIF(t.c.value('(DatElGrp[@Cd="ShpClss"]/DatEl[Cd="Clss"]/Val)[1]', 'varchar(6)'), '') AS "locID", 
						@Gateway AS "gateway", 			
						CAST(NULLIF(t.c.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHG"]/Val)[1]', 'varchar(255)'), '') AS decimal(18, 2)) AS "freteOriginal", 
						NULLIF(t.c.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtMFCHGCurCd"]/Val)[1]', 'varchar(3)'), '') AS "moedafreteOriginal"						
					FOR XML PATH('dadosEspecificos'), TYPE), 
					(SELECT 
						NULLIF(t.c.value('HAWB[1]', 'varchar(20)'), '') AS "miniCPA", 								
						NULLIF(t.c.value('ShpOrgn[1]', 'varchar(80)'), '') AS "aeroportoOrigem"
					FOR XML PATH('dadosAWB'), TYPE), 
					(SELECT 
						NULLIF(t.c.value('(ShpCnsgnr/DHLAcctNo)[1]', 'varchar(10)'), '') AS "numeroContaExpedidor", 
						NULLIF(t.c.value('(ShpCnsgne/DutyAcct)[1]', 'varchar(10)'), '') AS "numeroContaDestinatario", 
						ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(70)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(70)'), '')) AS "nomeOriginalDestinatario", 
						ISNULL(ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(70)'), ''), NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), '')), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(70)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(70)'), ''))) AS "moradaOriginalDestinatario", 
						ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) AS "localidadeOriginalDestinatario", 
						ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/PostalCd)[1]', 'varchar(12)'), '')) AS "codigoPostalOriginalDestinatario", 
						ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/City)[1]', 'varchar(35)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/City)[1]', 'varchar(35)'), '')) AS "localidadePostalOriginalDestinatario", 
						ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/CoName)[1]', 'varchar(50)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/CoName)[1]', 'varchar(50)'), '')) AS "referenciaExterna1", 
						ISNULL(ISNULL(NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/StreetName)[1]', 'varchar(50)'), ''), NULLIF(t.c.value('(ShpImpter/ImpterCoDtls/AddrEng/AddrLn1)[1]', 'varchar(50)'), '')), ISNULL(NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/StreetName)[1]', 'varchar(50)'), ''), NULLIF(t.c.value('(ShpCnsgne/CnsgneCoDtls/AddrEng/AddrLn1)[1]', 'varchar(50)'), ''))) AS "referenciaExterna2", 
						NULLIF(t.c.value('ProdContentCd[1]', 'varchar(11)'), '') AS "shipID"
					FOR XML PATH('dadosEntidades'), TYPE), 
					(SELECT
						(CONVERT(varchar(10), @MsgDate, 127) + 'Z') AS "dataDocumentoTransporte"
					FOR XML PATH('outrosDados'), TYPE), 
					(SELECT
						0 AS "codigoFollowUp"					
					FOR XML PATH('followUp'), TYPE), 
					(SELECT TOP 1
						(SELECT 
							xdo.DocContext AS "tipoDocumento", 
							xdo.DocType AS "codigoDocumento",
							xdo.DocRefNo AS "numeroDocumento", 							
							(CONVERT(varchar(10), xdo.DocDate, 127) + 'Z') AS "dataValidade"					
						FROM (
							SELECT (CASE WHEN NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') IN ('INV', 'PFI') THEN 0 ELSE 2 END) AS DocContext,
								(CASE NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') WHEN 'INV' THEN 'N380' WHEN 'PFI' THEN 'N325' WHEN 'ATA' THEN 'N955' WHEN 'ATR' THEN 'N041' WHEN 'EU1' THEN 'N954' WHEN 'FMA' THEN 'N865' WHEN 'PHY' THEN 'N851' WHEN 'VET' THEN 'N853' ELSE NULL END) AS DocType, 
								ISNULL(NULLIF(d.c.value('DocRefNo[1]', 'varchar(70)'), ''), 'SN') AS DocRefNo, 
								d.c.value('DocIssueDt[1]', 'datetime') AS DocDate
							FROM t.c.nodes('LineItems/LineItem/AddDocInfo') AS d(c)
							WHERE d.c.value('(../GoodsItemNo)[1]', 'int') = 1 AND NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') IN ('INV', 'PFI', 'ATA', 'ATR', 'EU1', 'FMA', 'PHY', 'VET')							
							) AS xdo INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON xdo.DocType = doc.DOC_CODI																	
						WHERE doc.DOC_DTRA = 0	
						FOR XML PATH('documento'), TYPE)
					FROM (
						SELECT (CASE NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') WHEN 'INV' THEN 'N380' WHEN 'PFI' THEN 'N325' WHEN 'ATA' THEN 'N955' WHEN 'ATR' THEN 'N041' WHEN 'EU1' THEN 'N954' WHEN 'FMA' THEN 'N865' WHEN 'PHY' THEN 'N851' WHEN 'VET' THEN 'N853' ELSE NULL END) AS DocType
						FROM t.c.nodes('LineItems/LineItem/AddDocInfo') AS d(c)
						WHERE d.c.value('(../GoodsItemNo)[1]', 'int') = 1 AND NULLIF(d.c.value('DocType[1]', 'varchar(20)'), '') IN ('INV', 'PFI', 'ATA', 'ATR', 'EU1', 'FMA', 'PHY', 'VET')												
						) AS xdo INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON xdo.DocType = doc.DOC_CODI																	
					WHERE doc.DOC_DTRA = 0	
					FOR XML PATH('documentosECertificados'), TYPE), 					
					(SELECT
						(SELECT 
							adi.numeroAdicao AS "numeroAdicao", 
							adi.codigoPautal AS "codigoPautal", 							
							adi.designacao AS "designacao", 	
							adi.regimeAdicional AS "regimeAdicional", 						
							(CASE ISNULL(adi.codPaisOrigem, '') 
								WHEN 'IC' THEN 'ES' 
								WHEN 'RS' THEN 'XS' 
								WHEN 'XM' THEN 'SX' 
								WHEN 'XB' THEN 'BQ' 
								ELSE adi.codPaisOrigem
							END) AS "paisOrigem",		
							1 AS "metodoAvaliacao", 
							CAST(ROUND((adi.massaBruta * 0.95), 3) AS decimal(18, 6)) AS "massaLiquida", 					
							CAST(adi.massaBruta AS decimal(18, 6)) AS "massaBruta",	
							CAST(adi.unidades AS decimal(18, 6)) AS "unidades", 																				
							CAST(adi.montante AS decimal(18, 3)) AS "montanteAd", 
							(SELECT TOP 1
								(SELECT 
									'CT' AS "unidadeMedida", 
									t.c.value('SDPieces[1]', 'int') AS "volumes", 
									'LETREIRO' AS "marcas", 									
									(CASE 
										WHEN adi.totalAdicoes > 1 THEN CAST(1 AS bit) 
										ELSE CAST(0 AS bit) 
									END) AS "parte"		
								HAVING adi.numeroAdicao = 1																
								FOR XML PATH('marcaEVolume'), TYPE)	
							HAVING adi.numeroAdicao = 1															
							FOR XML PATH('marcasEVolumes'), TYPE)					
						FROM @TblAdicoes AS adi							
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE), 
					(SELECT TOP 1
						(SELECT 
							0 AS "tipoManifesto", 
							NULLIF(t.c.value('(ShpCnsgnr/CnsgnrCoDtls/AddrEng/CtryCd)[1]', 'varchar(2)'), '') AS "paisManifesto", 
							NULLIF(t.c.value('(LineItems/LineItem/DescOfGoods)[1]', 'varchar(104)'), '') AS "descricao", 
							CAST(0 AS decimal(18, 3)) AS "valor", 
							ISNULL(NULLIF(t.c.value('(TxAndDty/CstmsValCrncyCd)[1]', 'varchar(2)'), ''), 'EU') AS "paisMoeda", 
							CAST(ISNULL(NULLIF(t.c.value('(CustomAtts/CustomAtt[Name_Eng="MonAmtTINVA"]/Val)[1]', 'varchar(255)'), ''), 0) AS decimal(18, 3)) AS "totalFatura", 
							(NULLIF(t.c.value('HAWB[1]', 'varchar(18)'), '') 
							+ (CASE number 
								WHEN 1 THEN '' 
								ELSE ('_' + CAST((number - 1) AS varchar(10))) 
							END)) AS "numeroCPA", 
							CAST(ISNULL(NULLIF(ROUND(t.c.value('GrossWgt[1]', 'numeric(18, 3)'), 1, 1), 0), 0.1) as numeric(18, 3)) AS "pesoBruto"	
						FROM master.dbo.spt_values 
						WHERE number >= 1 AND number <= t.c.value('SDPieces[1]', 'int')
						GROUP BY number
						FOR XML PATH('manifesto'), TYPE)		
					FROM master.dbo.spt_values 
					WHERE number >= 1 AND number <= t.c.value('SDPieces[1]', 'int')
					GROUP BY number		
					FOR XML PATH('manifestos'), TYPE)
				FROM @FicheiroXML.nodes('CstmsInterface/Dtls/Entries/Entry/Mvmts/Mvmt/TDOCs/TDOC/Shps/Shp') AS t(c)
					OUTER APPLY @XMLDadosRestricao.nodes('DadosRestricao') AS r(c)
				WHERE NOT EXISTS(SELECT 1 FROM PRO_DUCG WITH(NOLOCK) WHERE (DUC_EANO = YEAR(@DataAtual) OR DUC_EANO = (YEAR(@DataAtual) - 1)) AND DUC_CPRT = NULLIF(t.c.value('HAWB[1]', 'varchar(18)'), ''))
				FOR XML PATH('declaracao'), TYPE)		
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da(s) declaração(ões) IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT								
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ISNULL(@Erro, '') +
					'Detalhes do Erro: ' + CHAR(13) + 
					' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + 
					' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + CHAR(13) + 
					' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + 
					' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + 
					' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + CHAR(13) + 
					' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaFicheiroDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaFicheiroDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaFicheiroDHLPortal]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaFicheiroDHLPortal] @FicheiroXML xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @XMLNIFCliente varchar(18), @XMLNomeCliente varchar(70), @XMLMoradaCliente varchar(70), 
		@XMLLocalidadeCliente varchar(35), @XMLCodPostalCliente varchar(12), @XMLLocPostalCliente varchar(35), @XMLCodPaisCliente varchar(2), @XMLCodEANCliente varchar(13), 
		@XMLTelefoneCliente varchar(14), @XMLEmailCliente varchar(200), @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin)
-- inicia processo de geração da declaração	DAR
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- verifica se NIF de cliente não existe para inserir
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT 
				NULLIF(t.c.value('(importador/nif)[1]', 'varchar(18)'), ''), 
				NULLIF(t.c.value('(importador/nome)[1]', 'varchar(70)'), ''), 
				NULLIF(t.c.value('(importador/morada)[1]', 'varchar(70)'), ''), 
				NULLIF(t.c.value('(importador/localidade)[1]', 'varchar(35)'), ''), 
				NULLIF(t.c.value('(importador/codPostal)[1]', 'varchar(12)'), ''), 
				NULLIF(t.c.value('(importador/locPostal)[1]', 'varchar(35)'), ''), 
				NULLIF(t.c.value('(importador/pais)[1]', 'varchar(2)'), ''), 
				NULLIF(t.c.value('(importador/codigoEAN)[1]', 'varchar(13)'), ''), 
				NULLIF(t.c.value('(importador/telefone)[1]', 'varchar(14)'), ''), 
				NULLIF(t.c.value('(importador/email)[1]', 'varchar(200)'), '')
			FROM @FicheiroXML.nodes('DeclaracoesIMPPortalDHLToGIDWin/declaracao') AS t(c)
				INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON ddg.DUC_DUNO = 2 AND ddg.DUC_EANO = YEAR(@DataAtual) AND ddg.DUC_CPRT = NULLIF(t.c.value('documentoTransporte[1]', 'varchar(18)'), '')					
				LEFT OUTER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON NULLIF(t.c.value('(importador/nif)[1]', 'varchar(18)'), '') = cli.CLI_NIF									
			WHERE t.c.value('(importador/nif)[1]', 'varchar(18)') <> '' AND ddg.DUC_DENV IS NULL AND cli.CLI_IDTY IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLLocalidadeCliente, @XMLCodPostalCliente, @XMLLocPostalCliente, @XMLCodPaisCliente, 
			@XMLCodEANCliente, @XMLTelefoneCliente, @XMLEmailCliente
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			EXEC @NumErro = SP_Clientes_InsereOuEdita 0, @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLNIFCliente, NULL, NULL, @XMLLocalidadeCliente, @XMLCodPostalCliente, @XMLLocPostalCliente, @XMLCodPaisCliente, @XMLEmailCliente, @XMLTelefoneCliente, @XMLCodEANCliente, @CodUtilizador, @Erro OUTPUT					
			IF @NumErro <> 0
				RAISERROR('Erro na inserção do cliente "%s": "%s".', 16, 1, @XMLNIFCliente, @Erro)
			FETCH NEXT FROM Declaracoes INTO @XMLNIFCliente, @XMLNomeCliente, @XMLMoradaCliente, @XMLLocalidadeCliente, @XMLCodPostalCliente, @XMLLocPostalCliente, @XMLCodPaisCliente, 
				@XMLCodEANCliente, @XMLTelefoneCliente, @XMLEmailCliente
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- constroi XML para declaração IMP-CAU a partir do ficheiro XML no formato portal DHL
		SET @XMLDeclaracao = 
			(SELECT
				(SELECT 'U' AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data",	
					ddg.DUC_DCEN AS "despachoCentralizado", 
					ddg.DUC_ANXB AS "anexoB", 
					ISNULL(NULLIF(t.c.value('natureza[1]', 'varchar(3)'), ''), ddg.NDE_CODI) AS "natureza", 
					ISNULL(NULLIF(t.c.value('documentoTransporte[1]', 'varchar(18)'), ''), ddg.DUC_CPRT) AS "documentoTransporte",	
					ddg.DUC_DGEN AS "descricaoGenerica", 
					(SELECT 
						(SELECT 
							ddg.DUC_ENIF AS "nif", 
							ddg.DUC_ENOM AS "nome", 
							ddg.DUC_EMOR AS "morada", 
							ddg.DUC_ELOC AS "localidade", 
							ddg.DUC_ECPO AS "codigoPostal", 
							ddg.DUC_ELPO AS "localidadePostal", 
							ddg.PAI_ELIV AS "pais"
						HAVING ISNULL(ddg.DUC_ENOM, '') <> ''
						FOR XML PATH('exportador'), TYPE),
						ddg.PAI_PA15 AS "paisExpedicao", 
						(SELECT 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DNIF ELSE NULLIF(cli.CLI_NIF, '') END) AS "nif", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_TPDS ELSE cli.CLI_TNIF END) AS "tipoNIF", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DNOM ELSE NULLIF(cli.CLI_NOME, '') END) AS "nome", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DMOR ELSE NULLIF(cli.CLI_MORA, '') END) AS "morada", 				   
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DLOC ELSE NULLIF(cli.CLI_LOCA, '') END) AS "localidade", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DCPO ELSE NULLIF(cli.CLI_CPOS, '') END) AS "codigoPostal", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DLPO ELSE NULLIF(cli.CLI_LPOS, '') END) AS "localidadePostal", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.PAI_DLIV ELSE NULLIF(cli.PAI_CODI, '') END) AS "pais", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DTEL ELSE NULLIF(cli.CLI_TELF, '') END) AS "telefone", 
							(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.DUC_DEMA ELSE NULLIF(cli.CLI_EMAI, '') END) AS "email"
						FOR XML PATH('importador'), TYPE),
						NULLIF(ddg.PAI_PA17, '') AS "paisDestino",
						(CASE WHEN cli.CLI_IDTY IS NULL THEN ddg.PAI_P17B ELSE cli.RES_CODI END) AS "regiao", 
						(SELECT
							ddg.DEC_CO14 AS "codigoDeclarante",
							ddg.DUC_TPDC AS "estatuto"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE), 	
					ddg.DUC_NVRF AS "vossaReferencia", 				
					ddg.ALF_CODI AS "estancia", 
					ddg.TDE_CODI AS "tipoDeclaracao", 					
					ddg.NTR_CO24 AS "naturezaTransacao", 
					ISNULL(NULLIF(t.c.value('condicaoEntrega[1]', 'varchar(3)'), ''), ddg.CEN_CO20) AS "condicaoEntrega", 
					(SELECT 
						(SELECT
							ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN NULL ELSE NULLIF(t.c.value('paisMoedaFatura[1]', 'varchar(2)'), '') END), ddg.PAI_PR22) AS "pais", 	
							CAST(ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN NULL ELSE (SELECT SUM(a.c.value('montante[1]', 'decimal(18, 2)')) FROM t.c.nodes('adicoes/adicao') AS a(c) INNER JOIN PRO_DUAD AS dad WITH(NOLOCK) ON ddg.DUC_EANO = dad.DUC_EANO AND ddg.DUC_PNUM = dad.DUC_PNUM AND a.c.value('numeroAdicao[1]', 'int') = dad.DUA_CODI) END), ISNULL(ddg.DUC_MT22, 0)) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN NULL ELSE NULLIF(t.c.value('paisMoedaFrete[1]', 'varchar(2)'), '') END), ddg.PAI_FRET) AS "pais", 							
							CAST(ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN NULL ELSE (SELECT SUM(a.c.value('frete[1]', 'decimal(18, 2)')) FROM t.c.nodes('adicoes/adicao') AS a(c) INNER JOIN PRO_DUAD AS dad WITH(NOLOCK) ON ddg.DUC_EANO = dad.DUC_EANO AND ddg.DUC_PNUM = dad.DUC_PNUM AND a.c.value('numeroAdicao[1]', 'int') = dad.DUA_CODI) END), ISNULL(ddg.DUC_FRET, 0)) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							ddg.PAI_SEGU AS "pais", 							
							CAST(ISNULL(ddg.DUC_SEGU, 0) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT
							CAST(ISNULL(ddg.DUC_MLQT, 0) AS decimal(18, 6)) AS "massaLiquida", 							
							CAST(ISNULL(ddg.DUC_MBRT, 0) AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT						
						ddg.DUC_REF7 AS "numeroNRUR", 
						(SELECT
							ddg.MTR_FT21 AS "meioTransporte", 
							ddg.PAI_PA21 AS "pais"
						HAVING ISNULL(ddg.MTR_FT21, '') <> ''
						FOR XML PATH('fronteira'), TYPE),
						ddg.MTR_CODI AS "meioTransporteInterior", 
						ddg.MTR_PT18 AS "meioTransporteChegada", 
						ddg.DUC_MT18 AS "identificacao", 
						ddg.DUC_CT19 AS "contentorizada", 
						ddg.DUC_CONT AS "numeroContentor"
					FOR XML PATH('transporte'), TYPE), 		
					(SELECT
						ddg.DUC_TLOC AS "tipoLocalizacao", 
						ddg.DUC_QUAL AS "qualificador", 
						ddg.LME_CO30 AS "armazemDTP", 
						ddg.ALF_CODI1 AS "estancia", 
						ddg.DUC_ONIF AS "nifOperadorEconomico", 
						(SELECT
							ddg.DUC_LAMO AS "morada", 
							ddg.DUC_LALO AS "localidade", 
							ddg.DUC_LACP AS "codigoPostal"
						HAVING ISNULL(ddg.DUC_LAMO, '') <> ''
						FOR XML PATH('endereco'), TYPE)
					HAVING ISNULL(ddg.DUC_TLOC, '') <> ''
					FOR XML PATH('localizacaoMercadorias'), TYPE), 
					ddg.ARM_CODI AS "armazem", 
					(SELECT 						
						'UPDATE' AS "codigoCampoExtra",
						'DHL-PORTAL' AS "valorCampoExtra"				
					FOR XML PATH('campoExtra'), ROOT('camposExtra'), TYPE), 									
					(SELECT 						
						0 AS "tipoDocumento", 
						NULLIF(d.c.value('codigoDocumento[1]', 'varchar(5)'), '') AS "codigoDocumento",
						NULLIF(d.c.value('numeroDocumento[1]', 'varchar(70)'), '') AS "numeroDocumento", 							
						(CONVERT(varchar(10), d.c.value('dataDocumento[1]', 'datetime'), 127) + 'Z') AS "dataValidade"											
					FROM t.c.nodes('documentos/documento') AS d(c)	
					FOR XML PATH('documento'), ROOT('documentosECertificados'), TYPE), 											
					(SELECT 'U' AS "@acao", 
						a.c.value('numeroAdicao[1]', 'int') AS "numeroAdicao", 						
						ISNULL(NULLIF(apa.APA_CPAU, ''), ISNULL(NULLIF(dad.APA_CP33, ''), '9999999999')) AS "codigoPautal", 							
						ISNULL(NULLIF(apa.APA_DESG, ''), ISNULL(NULLIF(dad.DUA_DESG, ''), 'NÃO CLASSIFICADO')) AS "designacao", 															
						CAST(dad.DUA_ML38 AS decimal(18, 6)) AS "massaLiquida", 					
						CAST(dad.DUA_MB35 AS decimal(18, 6)) AS "massaBruta",	
						CAST(dad.DUA_US41 AS decimal(18, 6)) AS "unidades", 																				
						CAST(ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN dad.DUA_VA42 ELSE a.c.value('montante[1]', 'decimal(18, 2)') END), 0) AS decimal(18, 3)) AS "montanteAd", 
						CAST(ISNULL((CASE WHEN ddg.DUC_ADI5 > 1 THEN dad.DUA_VFRE ELSE a.c.value('frete[1]', 'decimal(18, 2)') END), 0) AS decimal(18, 3)) AS "valorFrete"									
					FROM t.c.nodes('adicoes/adicao') AS a(c) 		
						INNER JOIN PRO_DUAD AS dad WITH(NOLOCK) ON ddg.DUC_EANO = dad.DUC_EANO AND ddg.DUC_PNUM = dad.DUC_PNUM AND a.c.value('numeroAdicao[1]', 'int') = dad.DUA_CODI
						LEFT OUTER JOIN TAB_APAU AS apa WITH(NOLOCK) ON NULLIF(a.c.value('codigoArtigo[1]', 'varchar(22)'), '')	= apa.APA_CODI
					FOR XML PATH('adicao'), ROOT('adicoes'), TYPE)
				FROM @FicheiroXML.nodes('DeclaracoesIMPPortalDHLToGIDWin/declaracao') AS t(c)
					INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON ddg.DUC_DUNO = 2 AND ddg.DUC_EANO = YEAR(@DataAtual) AND ddg.DUC_CPRT = NULLIF(t.c.value('documentoTransporte[1]', 'varchar(18)'), '')					
					OUTER APPLY (SELECT TOP 1 CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_TELF, CLI_EMAI, CLI_NIF, CLI_TNIF, PAI_CODI, RES_CODI, CLI_IDTY
								FROM TAB_CLIE WITH(NOLOCK)
								WHERE CLI_INAC = 0 AND CLI_DESP = 1 AND CLI_NIF = NULLIF(t.c.value('(importador/nif)[1]', 'varchar(18)'), '')
								ORDER BY CLI_CACC DESC, CLI_IDTY DESC) AS cli
				WHERE ddg.DUC_DENV IS NULL
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da(s) declaração(ões) IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT	
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaFicheiroDHLPortal] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaFicheiroDHLPortal] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaFicheiroDHLScan]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaFicheiroDHLScan] @FicheiroASCII varchar(MAX), @TipoManifesto int, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON		
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @DataAtualCambio datetime, @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin), @Erro varchar(MAX)	
	DECLARE @tmpTbFicheiro TABLE(ID int IDENTITY NOT NULL,							
							TipoLinha varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
							DocTransporte varchar(35) COLLATE Latin1_General_CI_AI NOT NULL,
							Acao varchar(1) COLLATE Latin1_General_CI_AI NOT NULL,		
							CodNatureza varchar(3) COLLATE Latin1_General_CI_AI NOT NULL,					
							CodPaisMoeda varchar(2) COLLATE Latin1_General_CI_AI NOT NULL,						
							DadosLinha varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL,
							ValorEUR decimal(18, 2) NOT NULL,
							AnoDeclaracao int NULL,
							NumDeclaracao int NULL)	
	DECLARE @tmpTbManifesto TABLE(ID int IDENTITY NOT NULL,														
							DocTransporte varchar(35) COLLATE Latin1_General_CI_AI NOT NULL,
							Numero int NOT NULL)
	DECLARE @Delimiter CHAR(2), @NextPos int, @LastPos int, @Linha varchar(MAX), @TXTTipoLinha varchar(4), @TXTDocTransporte varchar(35), @TXTAcao varchar(1), @TXTCodNatureza varchar(3), 
		@TXTCodPaisMoeda varchar(2), @ValorEUR decimal(18, 4), @AnoDeclaracao int, @NumDeclaracao int, @TotalVolumes int, @i int
-- inicia variaveis
	SET @NumErro = 0
	SET @Erros = ''
-- inicia processo de geração das declarações IMP-CAU
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem data atual p/ câmbios
		SET @DataAtualCambio = CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
-- inicia variáveis
		SET @Delimiter = CHAR(13) + CHAR(10)
		SET @LastPos = 0
		SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, 1)
-- percorre as linhas do ficheiro e insere os respetivos dados na tabela tmp
		WHILE @NextPos > 0
		BEGIN
			SET @Linha = SUBSTRING(@FicheiroASCII, @LastPos, @NextPos - @LastPos)	
-- obtem o tipo de linha e número documento de transporte
			SET @TXTTipoLinha = LTRIM(RTRIM(SUBSTRING(@Linha, 1, 4)))	
-- se linha for "CGER", obtem número documento de transporte da nova declaração
			IF @TXTTipoLinha = 'CGER'
			BEGIN
				SET @TXTDocTransporte = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 8, 18))), '')
				IF NOT EXISTS(SELECT 1 FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_EANO = YEAR(@DataAtual) AND DUC_CPRT = @TXTDocTransporte)
					SET @TXTAcao = 'I'
				ELSE		
					IF EXISTS(SELECT 1 
							FROM (SELECT TOP 1 DUC_EANO, DUC_PNUM FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_EANO = YEAR(@DataAtual) AND DUC_CPRT = @TXTDocTransporte ORDER BY DUC_IDTY DESC) AS duc 
								INNER JOIN PRO_DUIN AS din WITH(NOLOCK) ON duc.DUC_EANO = din.DUC_EANO AND duc.DUC_PNUM = din.DUC_PNUM
							WHERE din.SIN_CODI IN ('A99', 'A00'))
						SET @TXTAcao = 'I'
					ELSE 
						SET @TXTAcao = 'U' 	
				IF @TXTAcao = 'I'
				BEGIN
					SET @AnoDeclaracao = NULL
					SET @NumDeclaracao = NULL
					SET @TXTCodNatureza = (CASE ISNULL(RTRIM(LTRIM(SUBSTRING(@Linha, 1383, 17))), '') 
											WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(@Linha, 5, 3))), '') 
											ELSE 'OSS' 
										END)
				END
				ELSE
				BEGIN
					SELECT TOP 1 @AnoDeclaracao = DUC_EANO, @NumDeclaracao = DUC_PNUM,  
						@TXTCodNatureza = (CASE ISNULL(RTRIM(LTRIM(SUBSTRING(@Linha, 1383, 17))), '') 
											WHEN '' THEN (CASE 
															WHEN NDE_CODI IN ('2', '2.1', '2.2', '2.6', '2.7', '40', '40F') THEN NDE_CODI
															ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(@Linha, 5, 3))), '') 
														END)
											ELSE 'OSS' 
										END)						
					FROM PRO_DUCG WITH(NOLOCK) 
					WHERE DUC_EANO = YEAR(@DataAtual) AND DUC_CPRT = @TXTDocTransporte 
					ORDER BY DUC_IDTY DESC
				END
				SET @TXTCodPaisMoeda = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 640, 2))), '')
				SET @ValorEUR = ROUND((CAST(STUFF(RTRIM(LTRIM(SUBSTRING(@Linha, 642, 14))), 11, 0, '.') AS decimal(18, 4)) / dbo.FNT_Geral_ObtemCambio(0, @TXTCodPaisMoeda, @DataAtualCambio)), 2)					
			END
			ELSE
-- se linha for "ADIC", obtem os volumes da nova declaração
				IF @TXTTipoLinha = 'ADIC'
				BEGIN
					SET @TotalVolumes = CAST(RTRIM(LTRIM(SUBSTRING(@Linha, 99, 10))) AS int)
					SET @i = 1
					WHILE @i <= @TotalVolumes
					BEGIN
						INSERT INTO @tmpTbManifesto(DocTransporte, Numero)
						VALUES (@TXTDocTransporte, @i) 
						SET @i = @i + 1
					END
				END	
-- insere dados da linha na tabela tmp
			INSERT INTO @tmpTbFicheiro (TipoLinha, DocTransporte, Acao, CodNatureza, CodPaisMoeda, DadosLinha, ValorEUR, AnoDeclaracao, NumDeclaracao)
			VALUES (@TXTTipoLinha, @TXTDocTransporte, @TXTAcao, @TXTCodNatureza, @TXTCodPaisMoeda, @Linha, @ValorEUR, @AnoDeclaracao, @NumDeclaracao)
-- incrementa variáveis
			SET @LastPos = @NextPos + 2
			SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, @NextPos + 1)			
		END	
-- obtem lista de declarações existentes dentro do ficheiro ASCII
		DECLARE DeclaracoesDHL CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
			SELECT DocTransporte
			FROM @tmpTbFicheiro
			WHERE TipoLinha = 'CGER'	
		OPEN DeclaracoesDHL
		FETCH NEXT FROM DeclaracoesDHL INTO @TXTDocTransporte
		WHILE @@FETCH_STATUS = 0
		BEGIN										
-- constroi XML para declaração IMP-CAU a partir do ficheiro ASCII no formato DHL
			SET @XMLDeclaracao = 
				(SELECT
					(SELECT cge.Acao AS "@acao", 
						(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
						CAST(0 AS bit) AS "despachoCentralizado", 
						'H1' AS "anexoB", 
						cge.CodNatureza AS "natureza", 
						cge.DocTransporte AS "documentoTransporte", 
						(SELECT 
							(SELECT 	
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 38, 18))), '') AS "nif", 						
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 56, 70))), '') AS "nome", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 126, 70))), '') AS "morada", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidade", 
								'0' AS "codigoPostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidadePostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') AS "pais"
							HAVING NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 56, 70))), '') <> ''
							FOR XML PATH('exportador'), TYPE), 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') AS "paisExpedicao", 
							(SELECT 
								ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 233, 18))), ''), '999999990') AS "nif", 
								0 AS "tipoNIF", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nome", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "morada", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidade", 
								ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), ''), '0') AS "codigoPostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') AS "pais", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1350, 14))), '') AS "telefone", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1290, 50))), '') AS "email"
							FOR XML PATH('importador'), TYPE),
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') AS "paisDestino",						
							(SELECT
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 547, 6))), '') AS "codigoDeclarante"
							FOR XML PATH('declarante'), TYPE)
						FOR XML PATH('operadores'), TYPE), 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 780, 2))), '') AS "vossaReferencia", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 30, 8))), '') AS "estancia", 
						'IMD' AS "tipoDeclaracao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 621, 2))), '') AS "naturezaTransacao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') AS "condicaoEntrega", 
						(SELECT
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 591, 30))), ''), '*****N/A*****') AS "localidadeCE", 
							'PT' AS "paisCE"
						FOR XML PATH('localizacao'), TYPE), 			
						(SELECT 
							(SELECT
								ISNULL(cge.CodPaisMoeda, 'EU') AS "pais", 	
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 642, 14))), 11, 0, '.') AS decimal(18, 3)) AS "valorTotal"
							FOR XML PATH('fatura'), TYPE), 
							(SELECT
								ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 669, 2))), ''), 'EU') AS "pais", 							
								0 AS "valorTotal"
							FOR XML PATH('frete'), TYPE), 
							(SELECT
								'EU' AS "pais", 							
								0 AS "valorTotal"
							FOR XML PATH('seguro'), TYPE), 
							(SELECT
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 42, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaLiquida", 							
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 29, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaBruta"
							FOR XML PATH('pesos'), TYPE)
						FOR XML PATH('totais'), TYPE), 
						(SELECT
							cge.DocTransporte AS "numeroNRUR", 
							(SELECT 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 553, 2))), '') AS "meioTransporte", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 585, 2))), '') AS "pais"						
							FOR XML PATH('fronteira'), TYPE), 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 553, 2))), '') AS "meioTransporteChegada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 555, 30))), '') AS "identificacao", 
							0 AS "contentorizada"
						FOR XML PATH('transporte'), TYPE), 
						(SELECT
							'B' AS "tipoLocalizacao", 
							'Y' AS "qualificador", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 623, 17))), '') AS "armazemDTP"
						FOR XML PATH('localizacaoMercadorias'), TYPE), 
						(SELECT  
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 805, 6))), '') AS "nomeFicheiro"
						FOR XML PATH('dadosEspecificos'), TYPE), 
						(SELECT 			
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 790, 11))), '') AS "miniCPA", 				
							(CONVERT(varchar(10), CONVERT(datetime, NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 671, 8))), ''), 112), 127) + 'Z') AS "dataVoo", 							
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 80))), '') AS "aeroportoOrigem", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 782, 8))), '') AS "numeroVoo", 						
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 916, 35))), '') AS "tracking", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 953, 5))), '') AS "tipoCarga"
						FOR XML PATH('dadosAWB'), TYPE), 
						(SELECT 				
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 10))), '') AS "numeroContaExpedidor",
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 233, 10))), '') AS "numeroContaDestinatario", 			
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nomeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "moradaOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidadeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), '') AS "codigoPostalOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostalOriginalDestinatario", 	
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 50))), '') AS "referenciaExterna1", 					
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 50))), '') AS "referenciaExterna2", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 905, 11))), '') AS "shipID"						
						FOR XML PATH('dadosEntidades'), TYPE), 
						(SELECT
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 951, 2))), '') AS "dutyType", 
							CAST(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 679, 1))), '') AS int) AS "payment", 
							(CONVERT(varchar(10), CONVERT(datetime, NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1271, 10))), ''), 127), 127) + 'Z') AS "dataDocumentoTransporte", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 973, 1))), '') AS "numeroRequerimento"
						FOR XML PATH('outrosDados'), TYPE), 							
						(SELECT TOP 1
							(SELECT 
								0 AS "tipoDocumento",
								NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 129, 5))), '') AS "codigoDocumento"
							HAVING ISNULL(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 129, 5))), '') <> '' AND cge.Acao = 'I'						
							FOR XML PATH('documento'), TYPE)
						HAVING ISNULL(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 129, 5))), '') <> '' AND cge.Acao = 'I'
						FOR XML PATH('documentosECertificados'), TYPE), 								
						(SELECT
							(SELECT 
								1 AS "numeroAdicao", 
								ISNULL((CASE cge.Acao WHEN 'U' THEN (SELECT NULLIF(APA_CP33, '') FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = cge.AnoDeclaracao AND DUC_PNUM = cge.NumDeclaracao AND DUA_CODI = 1) ELSE NULL END), '9999999999') AS "codigoPautal", 							
								ISNULL((SELECT TOP 1 NULLIF(RTRIM(LTRIM(SUBSTRING(DadosLinha, 7, 104))), '') FROM @tmpTbFicheiro WHERE TipoLinha = 'OUTD' AND DocTransporte = cge.DocTransporte), 'NÃO CLASSIFICADO') AS "designacao", 								
								NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 27, 2))), '') AS "paisOrigem",		
								1 AS "metodoAvaliacao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 42, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaLiquida", 					
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 29, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaBruta",	
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 65, 13))), 11, 0, '.') AS decimal(18, 3)) AS "montanteAd", 
								(SELECT TOP 1
									(SELECT 
										NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 109, 2))), '') AS "unidadeMedida", 
										CAST(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 99, 10))) AS int) AS "volumes", 
										NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 79, 20))), '') AS "marcas", 									
										CAST(0 AS bit) AS "parte"																		
									FOR XML PATH('marcaEVolume'), TYPE)																
								FOR XML PATH('marcasEVolumes'), TYPE)											
							FOR XML PATH('adicao'), TYPE)
						FOR XML PATH('adicoes'), TYPE), 						
						(SELECT TOP 1
							(SELECT 0 AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoeda", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "pesoBruto"
							FROM @tmpTbFicheiro AS otd
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte AND cge.Acao = 'I'						
							FOR XML PATH('manifesto'), TYPE),									
							(SELECT 1 AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoeda", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "pesoBruto"
							FROM @tmpTbManifesto AS man INNER JOIN (SELECT TOP 1 TipoLinha, DocTransporte, DadosLinha 
																	FROM @tmpTbFicheiro 
																	WHERE TipoLinha = 'OUTD' AND DocTransporte = cge.DocTransporte) AS otd ON man.DocTransporte = otd.DocTransporte 
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte AND @TipoManifesto = 0		
							FOR XML PATH('manifesto'), TYPE),	
							(SELECT 2 AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '') AS "paisMoeda", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS decimal(18, 3)) AS "pesoBruto"
							FROM @tmpTbManifesto AS man INNER JOIN (SELECT TOP 1 TipoLinha, DocTransporte, DadosLinha 
																	FROM @tmpTbFicheiro 
																	WHERE TipoLinha = 'OUTD' AND DocTransporte = cge.DocTransporte) AS otd ON man.DocTransporte = otd.DocTransporte 
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte							
							FOR XML PATH('manifesto'), TYPE)								
						FROM @tmpTbFicheiro AS otd
						WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte
						FOR XML PATH('manifestos'), TYPE)
					FROM @tmpTbFicheiro AS cge
						INNER JOIN @tmpTbFicheiro AS adi ON adi.TipoLinha = 'ADIC' AND cge.DocTransporte = adi.DocTransporte											
					WHERE cge.TipoLinha = 'CGER' AND cge.DocTransporte = @TXTDocTransporte
					FOR XML PATH('declaracao'), TYPE)		
				FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da declaração IMP-CAU
			SET @Erro = ''
			EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT									
			IF @NumErro <> 0
				SET @Erros = ISNULL(@Erros, '') + 'Erro na importação da declaração IMP-CAU "' + @TXTDocTransporte + '": ' + CHAR(13) + @Erro + CHAR(13)												
			FETCH NEXT FROM DeclaracoesDHL INTO @TXTDocTransporte
		END
		CLOSE DeclaracoesDHL
		DEALLOCATE DeclaracoesDHL	
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
		IF ISNULL(@Erros, '') <> ''
			RAISERROR ('%s', 16, 3, @Erros)		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erros = ISNULL(@Erros, '') +
			'Detalhes do Erro: ' + CHAR(13) + 
			' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + 
			' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + CHAR(13) + 
			' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + 
			' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + 
			' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + CHAR(13) + 
			' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaFicheiroDHLScan] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaFicheiroDHLScan] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaFicheiroFEDEX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_IMP_Declaracoes_ImportaFicheiroFEDEX] @FicheiroASCII varchar(MAX), @CodAlfandega varchar(8), @DataVoo datetime, @Matricula varchar(30), @CodPaisMeioTransporte varchar(2), 
	@TipoManifesto int, @CodNatureza varchar(3), @NumeroNRMMSTI varchar(70), @DataNRMMSTI datetime, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON		
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @DataAtualCambio datetime, @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin), @Erro varchar(MAX)	
	DECLARE @tmpTbFicheiro TABLE(ID int IDENTITY NOT NULL,							
							TipoLinha varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
							DocTransporte varchar(35) COLLATE Latin1_General_CI_AI NOT NULL,
							Acao varchar(1) COLLATE Latin1_General_CI_AI NOT NULL,
							CodNatureza varchar(3) COLLATE Latin1_General_CI_AI NOT NULL,
							CodPaisMoeda varchar(2) COLLATE Latin1_General_CI_AI NOT NULL,
							CodAlfandega varchar(8) COLLATE Latin1_General_CI_AI NOT NULL,
							DadosLinha varchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL,
							ValorEUR decimal(18, 2) NOT NULL)	
	DECLARE @Delimiter CHAR(2), @NextPos int, @LastPos int, @Linha varchar(MAX), @TXTTipoLinha varchar(4), @TXTDocTransporte varchar(35), @TXTAcao varchar(1), @TXTCodNatureza varchar(3), 
		@TXTCodPaisMoeda varchar(2), @TXTCodAlfandega varchar(8), @ValorEUR decimal(18, 3)
-- inicia variaveis
	SET @NumErro = 0
	SET @Erros = ''
-- inicia processo de geração das declarações DAR
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem data atual p/ câmbios
		SET @DataAtualCambio = CAST(CONVERT(varchar(10), @DataAtual, 105) + ' 23:58:58' AS datetime)
-- inicia variáveis
		SET @Delimiter = CHAR(13) + CHAR(10)
		SET @LastPos = 0
		SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, 1)
-- percorre as linhas do ficheiro e insere os respetivos dados na tabela tmp
		WHILE @NextPos > 0
		BEGIN
			SET @Linha = SUBSTRING(@FicheiroASCII, @LastPos, @NextPos - @LastPos)	
-- obtem o tipo de linha e número documento de transporte
			SET @TXTTipoLinha = LTRIM(RTRIM(SUBSTRING(@Linha, 1, 4)))	
-- se linha for "CGER", obtem número documento de transporte de nova declaração
			IF @TXTTipoLinha = 'CGER'
			BEGIN
				SET @TXTDocTransporte = NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 8, 18))), '')
				SET @TXTAcao = (CASE 
									WHEN (@TipoManifesto = 2) OR ((@TipoManifesto = 1) AND EXISTS(SELECT 1 FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_EANO = YEAR(@DataAtual) AND DUC_CPRT = @TXTDocTransporte AND DUC_DTVO >= @DataVoo)) THEN 'U'
									ELSE 'I'							
								END)
				IF @TXTAcao = 'I'
				BEGIN
					SET @TXTCodNatureza = (CASE 
											WHEN (ISNULL(RTRIM(LTRIM(SUBSTRING(@Linha, 473, 2))), '') = 'ES') THEN 'VGO' 
											WHEN (ISNULL(@CodNatureza, '') <> '') THEN @CodNatureza 
											WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(@Linha, 5, 3))), '') IN ('LAD', 'RAI', 'VGO') THEN NULLIF(RTRIM(LTRIM(SUBSTRING(@Linha, 5, 3))), '') 
											ELSE '99' 											
										END)
				END
				ELSE
				BEGIN
					SET @TXTCodNatureza = (SELECT TOP 1 (CASE duc.NDE_CODI
															WHEN '97' THEN '90' 
															WHEN '10' THEN (CASE tdo.TDO_TDSF 
																				WHEN 'FT' THEN '14' 
																				WHEN 'OR' THEN '13' 
																				ELSE duc.NDE_CODI 
																			END) 
															ELSE duc.NDE_CODI
														END)
											FROM PRO_DUCG AS duc WITH(NOLOCK)
												LEFT OUTER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON duc.TDO_DOCU = tdo.TDO_DOCU
											WHERE duc.DUC_EANO = YEAR(@DataAtual) AND duc.DUC_CPRT = @TXTDocTransporte AND duc.DUC_DTVO >= @DataVoo 
											ORDER BY duc.DUC_IDTY DESC)
				END
				SET @TXTCodPaisMoeda = (CASE ISNULL(LTRIM(RTRIM(SUBSTRING(@Linha, 640, 2))), '')
											WHEN 'DH' THEN 'AE' 
											WHEN 'SF' THEN 'CH' 
											WHEN 'UK' THEN 'GB' 
											WHEN 'JY' THEN 'JP' 
											WHEN 'SI' THEN 'SG' 
											WHEN 'NT' THEN 'TW' 
											ELSE NULLIF(LTRIM(RTRIM(SUBSTRING(@Linha, 640, 2))), '')
										END)
				SET @ValorEUR = ROUND((CAST(STUFF(RTRIM(LTRIM(SUBSTRING(@Linha, 642, 13))), 11, 0, '.') AS decimal(18, 3)) / dbo.FNT_Geral_ObtemCambio(0, @TXTCodPaisMoeda, @DataAtualCambio)), 2)	
				SET	@TXTCodAlfandega = (CASE @TipoManifesto 							
											WHEN 0 THEN (CASE 
															WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(@Linha, 1114, 3))), '') IN ('LIS', 'FNC', 'FAO', 'PXO') THEN 'PT000015' 
															ELSE 'PT000020' 
														END)
											ELSE @CodAlfandega 
										END)
			END
-- insere dados da linha na tabela tmp
			INSERT INTO @tmpTbFicheiro (TipoLinha, DocTransporte, Acao, CodNatureza, CodPaisMoeda, CodAlfandega, DadosLinha, ValorEUR)
			VALUES (@TXTTipoLinha, @TXTDocTransporte, @TXTAcao, @TXTCodNatureza, @TXTCodPaisMoeda, @TXTCodAlfandega, @Linha, @ValorEUR)
-- incrementa variáveis
			SET @LastPos = @NextPos + 2
			SET @NextPos = CHARINDEX(@Delimiter, @FicheiroASCII, @NextPos + 1)			
		END	
-- obtem lista de declarações existentes dentro do ficheiro ASCII
		DECLARE DeclaracoesFEDEX CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
			SELECT DocTransporte
			FROM @tmpTbFicheiro
			WHERE TipoLinha = 'CGER'	
		OPEN DeclaracoesFEDEX
		FETCH NEXT FROM DeclaracoesFEDEX INTO @TXTDocTransporte
		WHILE @@FETCH_STATUS = 0
		BEGIN										
-- constroi XML para declaração IMP-CAU a partir do ficheiro ASCII no formato FEDEX
			SET @XMLDeclaracao = 
				(SELECT
					(SELECT cge.Acao AS "@acao", 
						(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
						CAST(0 AS bit) AS "despachoCentralizado", 
						'H1' AS "anexoB", 
						cge.CodNatureza AS "natureza", 
						cge.DocTransporte AS "documentoTransporte", 
						(SELECT 
							(SELECT 							
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 56, 70))), '') AS "nome", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 126, 70))), '') AS "morada", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidade", 
								'0' AS "codigoPostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') AS "localidadePostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') AS "pais"
							HAVING NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 56, 70))), '') <> ''
							FOR XML PATH('exportador'), TYPE), 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') AS "paisExpedicao", 
							(SELECT 
								ISNULL((CASE 
											WHEN cge.CodNatureza IN ('LAD', 'RAI', 'VGO') THEN NULL 
											ELSE (CASE 
													WHEN EXISTS(SELECT 1 FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_BI = NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 801, 50))), '')) THEN (SELECT TOP 1 CLI_NIF FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_BI = NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 801, 50))), ''))
													ELSE (CASE 
															WHEN EXISTS(SELECT 1 FROM TAB_CLIE WITH(NOLOCK) WHERE SUBSTRING(CLI_NOME, 1, 12) LIKE '%' + SUBSTRING(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), ''), 1, 12) + '%' AND ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') <> '') THEN (SELECT TOP 1 CLI_NIF FROM TAB_CLIE WITH(NOLOCK) WHERE SUBSTRING(CLI_NOME, 1, 12) LIKE '%' + SUBSTRING(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), ''), 1, 12) + '%')
															ELSE NULL
														END) 
												 END) 
										END), '999999990') AS "nif", 
								0 AS "tipoNIF", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nome", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "morada", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidade", 
								ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), ''), '0') AS "codigoPostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostal", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') AS "pais"								
							FOR XML PATH('importador'), TYPE),
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '') AS "paisDestino",						
							(SELECT
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 547, 6))), '') AS "codigoDeclarante"
							FOR XML PATH('declarante'), TYPE)
						FOR XML PATH('operadores'), TYPE), 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1037, 50))), '') AS "vossaReferencia", 
						cge.CodAlfandega AS "estancia", 
						'IMD' AS "tipoDeclaracao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 621, 2))), '') AS "naturezaTransacao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') AS "condicaoEntrega", 
						(SELECT
							ISNULL((CASE 
										WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') IN ('CIP', 'CPT', 'DAP', 'DDU', 'DDP') THEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '')  
										WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') IN ('FCA', 'FAS') THEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 196, 35))), '') 
										ELSE NULL 
									END), '*****N/A*****') AS "localidadeCE", 
							ISNULL((CASE 
										WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') IN ('CIP', 'CPT', 'DAP', 'DDU', 'DDP') THEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 473, 2))), '')  
										WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 588, 3))), '') IN ('FCA', 'FAS') THEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 231, 2))), '') 
										ELSE NULL 
									END), '--') AS "paisCE"
						FOR XML PATH('localizacao'), TYPE), 			
						(SELECT 
							(SELECT
								ISNULL(cge.CodPaisMoeda, 'EU') AS "pais", 	
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 65, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valorTotal"
							FOR XML PATH('fatura'), TYPE), 
							(SELECT
								'EU' AS "pais", 							
								0 AS "valorTotal"
							FOR XML PATH('frete'), TYPE), 
							(SELECT
								'EU' AS "pais", 							
								0 AS "valorTotal"
							FOR XML PATH('seguro'), TYPE), 
							(SELECT
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 42, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaLiquida", 							
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 29, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaBruta"
							FOR XML PATH('pesos'), TYPE)
						FOR XML PATH('totais'), TYPE), 
						(SELECT
							cge.DocTransporte AS "numeroNRUR", 
							(SELECT 
								NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 583, 2))), '') AS "meioTransporte", 
								(CASE ISNULL(@CodPaisMeioTransporte, '') 
									WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 585, 2))), '')
									ELSE @CodPaisMeioTransporte 
								END) AS "pais"						
							FOR XML PATH('fronteira'), TYPE), 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 553, 2))), '') AS "meioTransporteChegada", 
							(CASE ISNULL(@Matricula, '') 
									WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 555, 20))), '')
									ELSE @Matricula 
								END) AS "identificacao", 
							0 AS "contentorizada"
						FOR XML PATH('transporte'), TYPE), 
						(SELECT
							'B' AS "tipoLocalizacao", 
							'Y' AS "qualificador", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 623, 16))), '') AS "armazemDTP"
						FOR XML PATH('localizacaoMercadorias'), TYPE), 
						(SELECT 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1114, 3))), '') AS "locID", 
							(CASE 
								WHEN ISNULL(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1114, 3))), '') IN ('LIS', 'FNC', 'FAO', 'PXO') THEN 'LIS' 
								ELSE 'OPO' 
							END) AS "gateway", 
							CAST(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 1120, 2))), '') AS int) AS "serviceLevel", 		
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 690, 10))), '') AS "portesAcc", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 954, 13))), '') AS "portes", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 801, 50))), '') AS "despachoAcc"									
						FOR XML PATH('dadosEspecificos'), TYPE), 
						(SELECT 							
							(CONVERT(varchar(10), @DataVoo, 127) + 'Z') AS "dataVoo", 							
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 700, 80))), '') AS "aeroportoOrigem", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 782, 8))), '') AS "numeroVoo", 						
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 912, 35))), '') AS "tracking", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 949, 2))), '') AS "tipoCarga"
						FOR XML PATH('dadosAWB'), TYPE), 
						(SELECT 							
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 251, 70))), '') AS "nomeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 321, 70))), '') AS "moradaOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 391, 35))), '') AS "localidadeOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 426, 12))), '') AS "codigoPostalOriginalDestinatario", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 438, 35))), '') AS "localidadePostalOriginalDestinatario", 						
							NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 851, 50))), '') AS "referenciaExterna2"							
						FOR XML PATH('dadosEntidades'), TYPE), 
						(SELECT
							(CASE NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 947, 2))), '') 
									WHEN '03' THEN '03' 
									ELSE (CASE 
											WHEN ROUND((cge.ValorEUR * dbo.FNT_Geral_ObtemCambio(0, 'US', @DataAtualCambio)), 2) >= 750 THEN '01' 
											ELSE '02' 
										END) 
								END) AS "dutyType", 
							CAST(NULLIF(RTRIM(LTRIM(SUBSTRING(cge.DadosLinha, 679, 1))), '') AS int) AS "payment"
						FOR XML PATH('outrosDados'), TYPE), 
						(SELECT
							(CASE cge.CodNatureza
								WHEN '99'THEN 6
								ELSE NULL 									
							END) AS "codigoFollowUp"
						HAVING cge.CodNatureza = '99'					
						FOR XML PATH('followUp'), TYPE), 		
						(SELECT TOP 1
							(SELECT 0 AS "tipoDocumento",
								DOC_CODI AS "codigoDocumento", 
								@NumeroNRMMSTI AS "numeroDocumento", 
								(CONVERT(varchar(10), @DataNRMMSTI, 127) + 'Z') AS "dataValidade"
							FROM TAB_DOCU WITH(NOLOCK)
							WHERE DOC_DESP = 1 AND DOC_DTRA = 0 AND DOC_CODI = 'N821' AND ISNULL(@NumeroNRMMSTI, '') <> ''
							FOR XML PATH('documento'), TYPE)
						FROM TAB_DOCU WITH(NOLOCK)
						WHERE DOC_DESP = 1 AND DOC_DTRA = 0 AND DOC_CODI = 'N821' AND ISNULL(@NumeroNRMMSTI, '') <> ''
						FOR XML PATH('documentosECertificados'), TYPE), 								
						(SELECT
							(SELECT 
								1 AS "numeroAdicao", 
								'9999999999' AS "codigoPautal", 							
								ISNULL((SELECT TOP 1 NULLIF(RTRIM(LTRIM(SUBSTRING(DadosLinha, 7, 104))), '') FROM @tmpTbFicheiro WHERE TipoLinha = 'OUTD' AND DocTransporte = cge.DocTransporte), 'NÃO CLASSIFICADO') AS "designacao", 								
								NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 27, 2))), '') AS "paisOrigem",		
								1 AS "metodoAvaliacao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 42, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaLiquida", 					
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 29, 13))), 11, 0, '.') AS decimal(18, 6)) AS "massaBruta",									
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 65, 13))), 11, 0, '.') AS decimal(18, 3)) AS "montanteAd", 
								(SELECT TOP 1
									(SELECT 
										NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 109, 2))), '') AS "unidadeMedida", 
										CAST(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 99, 10))) AS int) AS "volumes", 
										NULLIF(RTRIM(LTRIM(SUBSTRING(adi.DadosLinha, 79, 20))), '') AS "marcas", 									
										CAST(0 AS bit) AS "parte"																		
									FOR XML PATH('marcaEVolume'), TYPE)																
								FOR XML PATH('marcasEVolumes'), TYPE)											
							FOR XML PATH('adicao'), TYPE)
						FOR XML PATH('adicoes'), TYPE), 						
						(SELECT TOP 1
							(SELECT 
								@TipoManifesto AS "tipoManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 5, 2))), '') AS "paisManifesto", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 7, 104))), '') AS "descricao", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 131, 13))), 11, 0, '.') AS decimal(18, 3)) AS "valor", 
								ISNULL((CASE NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '')
											WHEN 'DH' THEN 'AE' 
											WHEN 'SF' THEN 'CH' 
											WHEN 'UK' THEN 'GB' 
											WHEN 'JY' THEN 'JP' 
											WHEN 'SI' THEN 'SG' 
											WHEN 'NT' THEN 'TW' 
											ELSE NULLIF(LTRIM(RTRIM(SUBSTRING(otd.DadosLinha, 144, 2))), '')
										END), 'EU') AS "paisMoeda", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 147, 13))), 11, 0, '.') AS decimal(18, 3)) AS "totalFatura", 
								NULLIF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 160, 35))), '') AS "numeroCPA", 
								CAST(STUFF(RTRIM(LTRIM(SUBSTRING(otd.DadosLinha, 195, 13))), 11, 0, '.') AS numeric(18, 3)) AS "pesoBruto"	
							FROM @tmpTbFicheiro AS otd
							WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte
							FOR XML PATH('manifesto'), TYPE)		
						FROM @tmpTbFicheiro AS otd
						WHERE otd.TipoLinha = 'OUTD' AND otd.DocTransporte = cge.DocTransporte
						FOR XML PATH('manifestos'), TYPE)
					FROM @tmpTbFicheiro AS cge
						INNER JOIN @tmpTbFicheiro AS adi ON adi.TipoLinha = 'ADIC' AND cge.DocTransporte = adi.DocTransporte
					WHERE cge.TipoLinha = 'CGER' AND cge.DocTransporte = @TXTDocTransporte
					FOR XML PATH('declaracao'), TYPE)		
				FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da declaração IMP-CAU
			SET @Erro = ''
			EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT									
			IF @NumErro <> 0
				SET @Erros = ISNULL(@Erros, '') + 'Erro na importação da declaração IMP-CAU "' + @TXTDocTransporte + '": ' + CHAR(13) + @Erro + CHAR(13)												
			FETCH NEXT FROM DeclaracoesFEDEX INTO @TXTDocTransporte
		END
		CLOSE DeclaracoesFEDEX
		DEALLOCATE DeclaracoesFEDEX	
-- se houve erros na importação de alguma declaração, gera erro genérico para detalhar os erros ocorridos na importação
		IF ISNULL(@Erros, '') <> ''
			RAISERROR ('%s', 16, 3, @Erros)		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erros = ISNULL(@Erros, '') +
			'Detalhes do Erro: ' + CHAR(13) + 
			' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + 
			' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + CHAR(13) + 
			' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + 
			' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + 
			' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + CHAR(13) + 
			' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaFicheiroFEDEX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaFicheiroFEDEX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaFicheiroOGMA]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaFicheiroOGMA] @FicheiroXML xml, @NomeFicheiroXML varchar(100), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @FicheiroBinario varbinary(MAX), @FicheiroBase64 varchar(MAX), @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin)
	DECLARE @TmpFicheiroOGMA TABLE(
		ID int NOT NULL IDENTITY(1, 1), 	
		ADICAO int NOT NULL, 
		DT_PROCESSO datetime NULL, 
		PROCESSO varchar(100) NULL, 
		BI_LI_ID int NULL, 
		AWB varchar(25) NULL, 	
		ARTIGO varchar(40) NULL, 			
		QTD_REC numeric(28, 6) NOT NULL, 	
		UOM_REC varchar(3) NULL, 
		VALOR_UNIT_REC numeric(28, 6) NOT NULL,			
		SERIAL_NUM varchar(100) NULL, 
		NOTAS varchar(100) NULL, 
		DAU varchar(20) NULL, 
		DAU_DATE datetime NULL,
		N_VOLUMES int NOT NULL,
		GUIA varchar(20) NULL, 	 				
		WEIGHT_UNIT numeric(28, 6) NOT NULL, 
		UOM_WEIGHT varchar(12) NULL, 
		PROCESS_TYPE varchar(2) NULL, 
		PAIS_EXP_MERCADORIA varchar(3) NULL, 
		EXPEDIDOR varchar(200) NULL, 
		PACKING_SLIP varchar(25) NULL, 
		DESIGNACAO_MERCADORIA varchar(100) NULL, 		
		TIPO_PROCEDIMENTO varchar(20) NULL)
-- inicia processo de importação da declaração IMP-CAU
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- converte ficheiro XML para binário e depois para base64
		SET @FicheiroBinario = CAST(CAST(@FicheiroXML AS varchar(MAX)) AS varbinary(MAX))
		SET @FicheiroBase64 = CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@FicheiroBinario")))', 'varchar(MAX)')
-- obtem do ficheiro XML os valores de todos os elementos necessários para a importação
		INSERT INTO @TmpFicheiroOGMA(ADICAO, DT_PROCESSO, PROCESSO, BI_LI_ID, AWB, ARTIGO, QTD_REC, UOM_REC, VALOR_UNIT_REC, SERIAL_NUM, NOTAS, DAU, DAU_DATE, N_VOLUMES, GUIA, WEIGHT_UNIT, 
			UOM_WEIGHT, PROCESS_TYPE, PAIS_EXP_MERCADORIA, EXPEDIDOR, PACKING_SLIP, DESIGNACAO_MERCADORIA, TIPO_PROCEDIMENTO)
		SELECT 
			ROW_NUMBER() OVER(PARTITION BY t.c.value('NOTAS[1]', 'varchar(100)') ORDER BY t.c.value('NOTAS[1]', 'varchar(100)')), 
			CONVERT(varchar(10), NULLIF(t.c.value('DT_PROCESSO[1]', 'varchar(10)'), ''), 127), 
			t.c.value('PROCESSO[1]', 'varchar(100)'), 
			t.c.value('BI_LI_ID[1]', 'int'), 
			t.c.value('AWB[1]', 'varchar(25)'), 
			t.c.value('ARTIGO[1]', 'varchar(40)'), 			
			ISNULL(t.c.value('QTD_REC[1]', 'numeric(28, 6)'), 0), 
			t.c.value('UOM_REC[1]', 'varchar(3)'), 
			ISNULL(t.c.value('VALOR_UNIT_REC[1]', 'numeric(28, 6)'), 0),			
			t.c.value('SERIAL_NUM[1]', 'varchar(100)'), 
			t.c.value('NOTAS[1]', 'varchar(100)'), 
			t.c.value('DAU[1]', 'varchar(20)'), 
			CONVERT(varchar(10), NULLIF(t.c.value('DAU_DATE[1]', 'varchar(10)'), ''), 127), 	
			ISNULL(t.c.value('N_VOLUMES[1]', 'int'), 0), 
			t.c.value('GUIA[1]', 'varchar(20)'), 					
			ISNULL(t.c.value('WEIGHT_UNIT[1]', 'numeric(28, 6)'), 0), 
			t.c.value('UOM_WEIGHT[1]', 'varchar(12)'), 
			t.c.value('PROCESS_TYPE[1]', 'varchar(2)'), 
			t.c.value('PAIS_EXP_MERCADORIA[1]', 'varchar(3)'), 
			t.c.value('EXPEDIDOR[1]', 'varchar(200)'), 
			t.c.value('PACKING_SLIP[1]', 'varchar(25)'), 
			t.c.value('DESIGNACAO_MERCADORIA[1]', 'varchar(100)'), 			
			t.c.value('TIPO_PROCEDIMENTO[1]', 'varchar(20)')
		FROM @FicheiroXML.nodes('FICH_DESPCHANTE/FICH_DESPCHANTE_LINE') AS t(c)	
-- constroi XML para declaração IMP-CAU a partir do ficheiro XML no formato OGMA
		SET @XMLDeclaracao = 
			(SELECT	
				(SELECT 'I' AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
					CAST(0 AS bit) AS "despachoCentralizado", 
					(CASE ISNULL(LEFT(fch.NOTAS, 2), '') 
						WHEN '51' THEN 'H4'
						WHEN '53' THEN 'H3'
						ELSE 'H1' 
					END) AS "anexoB", 
					NULLIF(LEFT(fch.NOTAS, 3), '') AS "natureza", 
					NULLIF(LEFT(fch.AWB, 18), '') AS "documentoTransporte", 
					(SELECT TOP 1 NULLIF(LEFT(adi.DESIGNACAO_MERCADORIA, 40), '') FROM @TmpFicheiroOGMA AS adi WHERE adi.NOTAS = fch.NOTAS ORDER BY adi.ID) AS "descricaoGenerica",
					(SELECT 
						(SELECT 
							NULLIF(frn.FOR_NIF, '') AS "nif", 
							NULLIF(frn.FOR_NOME, '') AS "nome", 
							NULLIF(frn.FOR_MORA, '') AS "morada", 
							NULLIF(frn.FOR_LOCA, '') AS "localidade", 
							NULLIF(frn.FOR_CPOS, '') AS "codigoPostal", 
							NULLIF(frn.FOR_LPOS, '') AS "localidadePostal", 
							NULLIF(frn.PAI_CODI, '') AS "pais"	
						HAVING frn.FOR_IDTY IS NOT NULL
						FOR XML PATH('exportador'), TYPE), 
						NULLIF(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') AS "paisExpedicao", 
						(SELECT 
							NULLIF(cli.CLI_NIF, '') AS "nif", 
							cli.CLI_TNIF AS "tipoNIF", 
							NULLIF(cli.CLI_NOME, '') AS "nome", 
							NULLIF(cli.CLI_MORA, '') AS "morada", 
							NULLIF(cli.CLI_LOCA, '') AS "localidade", 
							NULLIF(cli.CLI_CPOS, '') AS "codigoPostal", 
							NULLIF(cli.CLI_LPOS, '') AS "localidadePostal", 
							NULLIF(cli.PAI_CODI, '') AS "pais" 
						FOR XML PATH('importador'), TYPE),
						NULLIF(cli.PAI_CODI, '') AS "paisDestino",
						(SELECT
							(SELECT TOP 1 DEC_CODI FROM TAB_DECL WITH(NOLOCK) WHERE DEC_INAC = 0) AS "codigoDeclarante"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE), 
					alf.ALF_CODI AS "estancia", 
					(CASE 						
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Incompleta' THEN 
							((CASE 
								WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'EU' 
								ELSE 'IM' 
							END) + 'B')
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Simplificada' THEN 
							((CASE 
								WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'EU' 
								ELSE 'IM' 
							END) + 'C')
						WHEN ISNULL(fch.TIPO_PROCEDIMENTO, '') = 'Complementar' THEN 
							((CASE 
								WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'EU' 
								ELSE 'IM' 
							END) + 'Y')
						ELSE (NULLIF(LEFT(fch.NOTAS, 3), '') + (CASE 
																	WHEN ISNULL(LEFT(fch.PAIS_EXP_MERCADORIA, 2), '') IN ('CH', 'NO', 'IS', 'LI', 'TR', 'MK', 'XS', 'RS', 'GB', 'UA') THEN 'E' 
																	ELSE 'I' 
																END))
					END) AS "tipoDeclaracao", 
					(CASE 
						WHEN ISNULL(LEFT(fch.NOTAS, 4), '') = '7171' THEN NULL
						WHEN ISNULL(LEFT(fch.NOTAS, 2), '') = '51' THEN '42'
						ELSE '11' 
					END) AS "naturezaTransacao", 
					ISNULL(NULLIF(frn.CEN_CODI, ''), 'XXX') AS "condicaoEntrega", 
					(SELECT 
						(SELECT
							ISNULL(NULLIF(frn.PAI_CODI1, ''), 'US') AS "pais", 							
							CAST(ISNULL(NULLIF(SUM(fch.VALOR_UNIT_REC), 0.00), 0.01) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							CAST(0 AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							CAST(0 AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT
							CAST(SUM(ROUND((fch.WEIGHT_UNIT * 0.95), 3)) AS decimal(18, 6)) AS "massaLiquida", 							
							CAST(SUM(fch.WEIGHT_UNIT) AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT
						(SELECT
							(CASE ISNULL(LEFT(fch.NOTAS, 4), '')
								WHEN '7171' THEN '10'
								WHEN '4000' THEN '40'
								ELSE '30'
							END) AS "meioTransporte",
							(CASE 
								WHEN ISNULL(LEFT(fch.NOTAS, 4), '') = '7171' THEN NULL
								WHEN frn.FOR_CODI IN ('83', '84', '85', '86', '87', '264', '266', '267', '268', '269', '470') THEN 'DE' 
								ELSE 'ES' 
							END) AS "pais"
						FOR XML PATH('fronteira'), TYPE), 
						(CASE ISNULL(LEFT(fch.NOTAS, 4), '')
							WHEN '7171' THEN '30'
							WHEN '4000' THEN '40'
							ELSE ISNULL(NULLIF(duc.MTR_FT21, ''), ISNULL(NULLIF(alf.MTR_CODI, ''), '30'))
						END) AS "meioTransporteChegada", 
						(CASE 
							WHEN ISNULL(LEFT(fch.NOTAS, 4), '') IN ('7171', '4000') THEN NULL
							ELSE 'CAMIAO' 
						END) AS "identificacao", 
						0 AS "contentorizada"
					FOR XML PATH('transporte'), TYPE), 					
					(SELECT
						(CASE alf.ALF_CODI
							WHEN 'PT000088' THEN 'B'
							ELSE (CASE alf.ALF_TLOC 
									WHEN 'EA' THEN 'A' 
									WHEN 'LA' THEN 'B' 
									WHEN 'OL' THEN 'D' 
									ELSE 'B' 
								END)
						END) AS "tipoLocalizacao", 
						(CASE alf.ALF_CODI
							WHEN 'PT000088' THEN 'Y'
							ELSE (CASE alf.ALF_TLOC 
									WHEN 'EA' THEN 'V' 
									WHEN 'LA' THEN 'Y' 
									WHEN 'OL' THEN 'Z' 
									ELSE NULL 
								END)
						END) AS "qualificador", 
						(CASE alf.ALF_CODI
							WHEN 'PT000088' THEN (CASE ISNULL(LEFT(fch.NOTAS, 4), '')
													WHEN '7171' THEN 'RENT00000442088PT'
													WHEN '4000' THEN 'DTP00000988015PT'
													ELSE 'UENT00000174088PT'
												END)
							ELSE (CASE alf.ALF_TLOC 
									WHEN 'LA' THEN alf.LME_CODI
									ELSE NULL 
								END) 
						END) AS "armazemDTP", 
						(CASE alf.ALF_CODI
							WHEN 'PT000088' THEN NULL
							ELSE (CASE alf.ALF_TLOC 
									WHEN 'EA' THEN alf.ALF_CODI
									ELSE NULL 
								END) 
						END) AS "estancia"
					FOR XML PATH('localizacaoMercadorias'), TYPE), 
					(CASE 
						WHEN (alf.ALF_CODI = 'PT000088') AND (ISNULL(LEFT(fch.NOTAS, 4), '') <> '4000') THEN 'ENT00000174088'										
						ELSE NULL 
					END) AS "armazem", 
					(SELECT
						@NomeFicheiroXML AS "nomeFicheiro"
					FOR XML PATH('dadosEspecificos'), TYPE), 
					(SELECT
						NULLIF(fch.DAU, '') AS "referenciaExterna1"
					HAVING ISNULL(fch.DAU, '') <> ''
					FOR XML PATH('dadosEntidades'), TYPE), 					
					(SELECT
						0 AS "codigoFollowUp"
					FOR XML PATH('followUp'), TYPE),
					(SELECT TOP 1
						(SELECT 
							0 AS "tipoDocumento", 
							tab.DOC_CODI AS "codigoDocumento",
							NULLIF(tab.DOC_NUME, '') AS "numeroDocumento", 
							(CONVERT(varchar(10), tab.DOC_DATA, 127) + 'Z') AS "dataValidade"											
						FROM (SELECT DOC_CODI, LEFT(fch.AWB, 18) AS DOC_NUME, (SELECT TOP 1 idd.dataValidade FROM tb_IMP_DeclaracoesDocumentos AS idd WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON idd.id_documento = doc.DOC_IDTY WHERE idd.id_declaracaoIMP = duc.DUC_IDTY AND doc.DOC_CODI = 'N741') AS DOC_DATA
							FROM TAB_DOCU WITH(NOLOCK) 
							WHERE DOC_CODI = 'N740' AND DOC_DESP = 1 AND DOC_DTRA = 1 AND duc.MTR_PT18 = '40'
							UNION ALL
							SELECT DOC_CODI, LEFT(fch.AWB, 18) AS DOC_NUME, (SELECT TOP 1 DDO_DINI FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1 AND DOC_CODI = 'N821') AS DOC_DATA
							FROM TAB_DOCU WITH(NOLOCK) 
							WHERE DOC_CODI = 'N821' AND DOC_DESP = 1 AND DOC_DTRA = 1 AND duc.MTR_PT18 = '30'
							UNION ALL
							SELECT DOC_CODI, 'ALF.CONTROLO088' AS DOC_NUME, NULL AS DOC_DATA						
							FROM TAB_DOCU WITH(NOLOCK) 
							WHERE DOC_CODI = '9Z13' AND DOC_DESP = 1 AND DOC_DTRA = 0 AND ISNULL(LEFT(fch.NOTAS, 2), '') = '71' 
							UNION ALL
							SELECT DOC_CODI, adi.PACKING_SLIP AS DOC_NUME, NULL AS DOC_DATA	
							FROM @TmpFicheiroOGMA AS adi
								INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N380' AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0
							WHERE adi.NOTAS = fch.NOTAS AND ISNULL(adi.PACKING_SLIP, '') <> ''							
						) AS tab
						FOR XML PATH('documento'), TYPE)	
					FROM (SELECT DOC_CODI, LEFT(fch.AWB, 18) AS DOC_NUME, (SELECT TOP 1 idd.dataValidade FROM tb_IMP_DeclaracoesDocumentos AS idd WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON idd.id_documento = doc.DOC_IDTY WHERE idd.id_declaracaoIMP = duc.DUC_IDTY AND doc.DOC_CODI = 'N741') AS DOC_DATA
						FROM TAB_DOCU WITH(NOLOCK) 
						WHERE DOC_CODI = 'N740' AND DOC_DESP = 1 AND DOC_DTRA = 1 AND duc.MTR_PT18 = '40'
						UNION ALL
						SELECT DOC_CODI, LEFT(fch.AWB, 18) AS DOC_NUME, (SELECT TOP 1 DDO_DINI FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUA_CODI = 1 AND DOC_CODI = 'N821') AS DOC_DATA
						FROM TAB_DOCU WITH(NOLOCK) 
						WHERE DOC_CODI = 'N821' AND DOC_DESP = 1 AND DOC_DTRA = 1 AND duc.MTR_PT18 = '30'
						UNION ALL
						SELECT DOC_CODI, 'ALF.CONTROLO088' AS DOC_NUME, NULL AS DOC_DATA						
						FROM TAB_DOCU WITH(NOLOCK) 
						WHERE DOC_CODI = '9Z13' AND DOC_DESP = 1 AND DOC_DTRA = 0 AND ISNULL(LEFT(fch.NOTAS, 2), '') = '71' 
						UNION ALL
						SELECT DOC_CODI, adi.PACKING_SLIP AS DOC_NUME, NULL AS DOC_DATA	
						FROM @TmpFicheiroOGMA AS adi
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N380' AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0
						WHERE adi.NOTAS = fch.NOTAS AND ISNULL(adi.PACKING_SLIP, '') <> ''																
					) AS tab
					FOR XML PATH('documentosECertificados'), TYPE), 
					(SELECT TOP 1
						(SELECT 
							DOC_CODI AS "codigoDocumento", 
							NULLIF(fch.DAU, '') AS "numeroDocumento"			
						FROM TAB_DOCU WITH(NOLOCK) 
						WHERE DOC_CODI = 'IM' AND NULLIF(RIGHT(fch.NOTAS, 2), '') <> '00' AND ISNULL(fch.DAU, '') <> ''
						FOR XML PATH('documentoPrecedente'), TYPE)		
					FROM TAB_DOCU WITH(NOLOCK) 
					WHERE DOC_CODI = 'IM' AND NULLIF(RIGHT(fch.NOTAS, 2), '') <> '00' AND ISNULL(fch.DAU, '') <> ''
					FOR XML PATH('documentosPrecedentes'), TYPE), 
					(SELECT
						(SELECT 
							1 AS "numeroAdicao", 
							'9999999999' AS "codigoPautal", 							
							ISNULL(NULLIF(MIN(fch.DESIGNACAO_MERCADORIA), ''), 'NÃO CLASSIFICADO') AS "designacao", 								
							CAST(SUM(ROUND((fch.WEIGHT_UNIT * 0.95), 3)) AS decimal(18, 6)) AS "massaLiquida", 					
							CAST(SUM(fch.WEIGHT_UNIT) AS decimal(18, 6)) AS "massaBruta",																					
							CAST(ISNULL(NULLIF(SUM(fch.VALOR_UNIT_REC), 0.00), 0.01) AS decimal(18, 3)) AS "montanteAd"										
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE), 
					(SELECT 
						(SELECT
							@NomeFicheiroXML AS "nomeArquivo", 
							'Ficheiro OGMA AWB/CMR' AS "descricaoArquivo", 
							'OUTRO' AS "tipoArquivo", 							
							3 AS "origemArquivo", 
							@FicheiroBase64 AS "ficheiroBase64" 
						FOR XML PATH('arquivo'), TYPE)
					FOR XML PATH('arquivos'), TYPE)
				FROM @TmpFicheiroOGMA AS fch				
					LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON NULLIF(fch.DAU, '') = duc.DUC_NORD
					LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON FOR_INAC = 0 AND FOR_DESP = 1 AND frn.FOR_CODI = (CASE ISNULL(LEFT(fch.NOTAS, 4), '')
																														WHEN '7171' THEN NULL
																														ELSE ISNULL((SELECT TOP 1 FOR_CODI
																																	FROM TAB_FORN WITH(NOLOCK) 
																																	WHERE FOR_NOME = NULLIF(fch.EXPEDIDOR, '')), '999999999')
																													END)
					INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON cli.CLI_CODI = ISNULL(NULLIF(frn.CLI_CODI, ''), '500792828') AND CLI_INAC = 0 AND CLI_DESP = 1
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON alf.ALF_CODI = ISNULL(NULLIF(frn.ALF_CODI, ''), 'PT000088')	
				GROUP BY fch.NOTAS, fch.AWB, fch.DAU, fch.TIPO_PROCEDIMENTO, fch.PAIS_EXP_MERCADORIA, duc.DUC_EANO, duc.DUC_PNUM, duc.MTR_PT18, duc.MTR_FT21, duc.DUC_IDTY, frn.FOR_CODI, 
					frn.FOR_NIF, frn.FOR_NOME, frn.FOR_MORA, frn.FOR_LOCA, frn.FOR_CPOS, frn.FOR_LPOS, frn.PAI_CODI, frn.CEN_CODI, frn.PAI_CODI1, frn.FOR_IDTY, cli.CLI_NIF, cli.CLI_TNIF, 
					cli.CLI_NOME, cli.CLI_MORA, cli.CLI_LOCA, cli.CLI_CPOS, cli.CLI_LPOS, cli.PAI_CODI, alf.ALF_CODI, alf.MTR_CODI, alf.ALF_TLOC, alf.LME_CODI
				FOR XML PATH('declaracao'), TYPE)		
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da(s) declaração(ões) IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT
-- senão houver erros na geração, insere as linhas constantes do ficheiro OGMA
		IF @NumErro = 0
		BEGIN
			INSERT INTO tb_TBL_LinhasOGMA(id_declaracaoIMP, numeroLinha, dataProcesso, numeroProcesso, idBILote, artigo, quantidade, unidadeMedidaQtd, valorUnitario, numeroSerie, observacoes, 
				numeroOrdem, dataOrdem, numeroVolumes, guia, pesoUnitario, unidadeMedidaPeso, tipoProcesso, expedidor, designacaoMercadoria, id_utilizadorControlo, dataControlo)
			SELECT duc.DUC_IDTY, fch.ADICAO, fch.DT_PROCESSO, fch.PROCESSO, fch.BI_LI_ID, fch.ARTIGO, fch.QTD_REC, fch.UOM_REC, fch.VALOR_UNIT_REC, fch.SERIAL_NUM, fch.NOTAS, 
				fch.DAU, fch.DAU_DATE, fch.N_VOLUMES, fch.GUIA, fch.WEIGHT_UNIT, fch.UOM_WEIGHT, fch.PROCESS_TYPE, fch.EXPEDIDOR, fch.DESIGNACAO_MERCADORIA, @IdUtilizador, @DataAtual
			FROM @TmpFicheiroOGMA AS fch	
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON YEAR(@DataAtual) = duc.DUC_EANO AND LEFT(fch.NOTAS, 3) = duc.NDE_CODI AND LEFT(fch.AWB, 18) = duc.DUC_CPRT AND @NomeFicheiroXML = duc.DUC_FUPS
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ISNULL(@Erro, '') +
					'Detalhes do Erro: ' + CHAR(13) + 
					' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + 
					' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + CHAR(13) + 
					' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + 
					' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + 
					' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + CHAR(13) + 
					' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaFicheiroOGMA] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaFicheiroOGMA] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ImportaFicheiroUPS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ImportaFicheiroUPS] @FicheiroXML xml, @TipoManifesto int, @DataVoo datetime, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON		
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @XMLDeclaracao xml(XMLSC_DeclaracoesIMPCAUToGIDWin)
-- inicia variaveis
	SET @NumErro = 0
-- inicia processo de importação da declaração IMP-CAU
	BEGIN TRY	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para declaração IMP-CAU a partir do ficheiro XML no formato UPS
		SET @XMLDeclaracao = 
			(SELECT	
				(SELECT (CASE 						
						WHEN @TipoManifesto = 0 THEN (CASE 
														WHEN EXISTS(SELECT 1 FROM PRO_DUCG WITH(NOLOCK) WHERE DUC_CPRT = NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AND CAST(CONVERT(varchar(10), DUC_DTVO, 127) AS datetime) = ISNULL(@DataVoo, CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 13, 6))) AS datetime))) THEN 'U' 
														ELSE 'I' 
													END) 
						WHEN EXISTS(SELECT 1 FROM PRO_DUCG AS duc WITH(NOLOCK) INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON duc.DUC_EANO = adi.DUC_EANO AND duc.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI = 1 WHERE duc.DUC_EANO = YEAR(@DataAtual) AND duc.DUC_CPRT = NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AND ISNULL(adi.DUA_DNUM, '') = '') THEN 'U'
						ELSE 'I'
					END) AS "@acao", 
					(CONVERT(varchar(10), @DataAtual, 127) + 'Z') AS "data", 
					CAST(0 AS bit) AS "despachoCentralizado", 
					'H1' AS "anexoB", 
					(CASE 
						WHEN EXISTS(SELECT 1 FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_DPRO = 1 AND CLI_NIF = NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9))), '')) AND SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '/', ''), 1, 2) <> 'FD' THEN '90' 
						ELSE '25' 
					END) AS "natureza", 
					NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AS "documentoTransporte", 
					(SELECT 
						(SELECT 							
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 104, 35))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') AS "localidade", 
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 9))), ''), '0') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), '') AS "localidadePostal", 
							(CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
								WHEN 'GB' THEN (CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 2))) 
													WHEN 'BT' THEN 'XI' 
													ELSE 'XU' 
												END) 
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '') 
							END) AS "pais"
						HAVING ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') <> ''
						FOR XML PATH('exportador'), TYPE), 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '') AS "paisExpedicao", 
						(SELECT 
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9))), ''), '999999990') AS "nif", 
							1 AS "tipoNIF", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "nome", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '') AS "morada", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidade", 
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), ''), '0') AS "codigoPostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidadePostal", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') AS "pais", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 268, 14))), '') AS "telefone" 							
						FOR XML PATH('importador'), TYPE),
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 265, 2))), '') AS "paisDestino",						
						(SELECT
							'0137I4' AS "codigoDeclarante"
						FOR XML PATH('declarante'), TYPE)
					FOR XML PATH('operadores'), TYPE), 
					'PT000020' AS "estancia", 
					'IMD' AS "tipoDeclaracao", 
					'11' AS "naturezaTransacao", 
					'FCA' AS "condicaoEntrega", 
					(SELECT
						ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 174, 35))), ''), '*****N/A*****') AS "localidadeCE", 
						(CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))) 
							WHEN 'GB' THEN (CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 231, 2))) 
												WHEN 'BT' THEN 'XI' 
												ELSE 'XU' 
											END) 
							ELSE ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), ''), '--')
						END) AS "paisCE"
					FOR XML PATH('localizacao'), TYPE), 					
					(SELECT 
						(SELECT
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 176, 2))), ''), 'EU') AS "pais", 	
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "valorTotal"
						FOR XML PATH('fatura'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							0 AS "valorTotal"
						FOR XML PATH('frete'), TYPE), 
						(SELECT
							'EU' AS "pais", 							
							0 AS "valorTotal"
						FOR XML PATH('seguro'), TYPE), 
						(SELECT							
							CAST(ROUND(((CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))) 
											WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) * 0.4536), 3) 
											ELSE (CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) / 10) 
										END) * 0.95), 3) AS decimal(18, 6)) AS "massaLiquida", 								 			
							CAST((CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))) 
									WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) * 0.4536), 3) 
									ELSE (CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) / 10) 
								END) AS decimal(18, 6)) AS "massaBruta"
						FOR XML PATH('pesos'), TYPE)
					FOR XML PATH('totais'), TYPE), 
					(SELECT
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AS "numeroNRUR", 
						(SELECT 
							(CASE 
								WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN '30' 
								ELSE '40' 
							END) AS "meioTransporte",
							(CASE 
								WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN 'PT' 
								ELSE 'DK' 
							END) AS "pais"						
						FOR XML PATH('fronteira'), TYPE), 
						(CASE 
							WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN '30' 
							ELSE '40' 
						END) AS "meioTransporteChegada", 
						(CASE 
							WHEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 1, 2))), '') IN ('GB', 'XU', 'XI') AND RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))) <> 'SRR6646' THEN 'CAMIAO' 
							ELSE 'OY-SRO' 
						END) AS "identificacao", 
						0 AS "contentorizada"
					FOR XML PATH('transporte'), TYPE), 
					(SELECT
						'B' AS "tipoLocalizacao", 
						'Y' AS "qualificador", 
						'DTP00000117020PT' AS "armazemDTP"
					FOR XML PATH('localizacaoMercadorias'), TYPE), 
					(SELECT 						
						CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 137, 2))) AS int) AS "serviceLevel", 
						(CASE @TipoManifesto 
							WHEN 1 THEN NULL 
							ELSE CAST(((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 207, 9))), ''), 0) AS decimal(18, 2)) / 100) - (CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 119, 13))), ''), 0) AS decimal(18, 2)) / 100)) AS decimal(18, 2)) 							     
						END) AS "freteOriginal", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 216, 3))), '') AS "moedafreteOriginal", 
						NULLIF(SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '/', ''), 1, 2), '') AS "condEntrega", 	
						NULLIF(t.c.value('nomeFicheiro[1]', 'varchar(100)'), '') AS "nomeFicheiro"					
					FOR XML PATH('dadosEspecificos'), TYPE), 
					(SELECT 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 34, 11))), '') AS "miniCPA", 
						(CONVERT(varchar(10), ISNULL(@DataVoo, CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 13, 6))) AS datetime)), 127) + 'Z') AS "dataVoo", 
						NULLIF(ISNULL((SELECT PAE_CODI FROM TAB_IATA WITH(NOLOCK) WHERE IAT_CODI = RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 3, 4)))), RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 3, 4)))), '') AS "aeroportoOrigem", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 353, 8))), '') AS "numeroVoo", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') AS "posicaoAviao", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 35))), '') AS "tracking", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 260, 5))), '') AS "tipoCarga"
					FOR XML PATH('dadosAWB'), TYPE), 
					(SELECT 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') AS "numeroContaExpedidor", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 59, 10))), '') AS "numeroContaDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 69, 35))), '') AS "nomeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 35))), '') AS "moradaOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidadeOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 256, 9))), '') AS "codigoPostalOriginalDestinatario", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 35))), '') AS "localidadePostalOriginalDestinatario", 						
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 296, 12))), '') AS "referenciaExterna2", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 51, 11))), '') AS "shipID"
					FOR XML PATH('dadosEntidades'), TYPE), 
					(SELECT
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 133, 2))), '') AS "dutyType", 						
						(CONVERT(varchar(10), CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 192, 9))) AS datetime), 127) + 'Z') AS "dataDocumentoTransporte", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 220, 1))), '') AS "numeroRequerimento", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 129, 20))), '') AS "numeroDURetorno", 
						NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b400000/linha)[1]', 'varchar(MAX)'), 199, 30))), '') AS "numeroT1Retorno"
					FOR XML PATH('outrosDados'), TYPE), 
					(SELECT
						(CASE 
							WHEN EXISTS(SELECT 1 FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_DPRO = 1 AND CLI_NIF = NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b701000/linha)[1]', 'varchar(MAX)'), 107, 9))), '')) AND SUBSTRING(REPLACE(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 319, 3))), '/', ''), 1, 2) <> 'FD' THEN 3 
							ELSE 0 
						END) AS "codigoFollowUp"					
					FOR XML PATH('followUp'), TYPE), 									
					(SELECT
						(SELECT 
							1 AS "numeroAdicao", 
							'9999999999' AS "codigoPautal", 							
							ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), ''), 'NÃO CLASSIFICADO') AS "designacao", 								
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 86, 2))), '') 
							END) AS "paisOrigem",		
							1 AS "metodoAvaliacao", 
							CAST(ROUND(((CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))) 
											WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) * 0.4536), 3) 
											ELSE (CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) / 10) 
										END) * 0.95), 3) AS decimal(18, 6)) AS "massaLiquida", 
							CAST((CASE RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 82, 3))) 
									WHEN 'LBS' THEN ROUND((CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) * 0.4536), 3) 
									ELSE (CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))) AS decimal(18, 6)) / 10) 
								END) AS decimal(18, 6)) AS "massaBruta",							
							CAST(ISNULL(NULLIF((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00), 0), 0.01) AS decimal(18, 3)) AS "montanteAd", 
							(SELECT TOP 1
								(SELECT 
									'CT' AS "unidadeMedida", 
									CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 100, 3))) AS int) AS "volumes", 
									'ADD' AS "marcas", 									
									CAST(0 AS bit) AS "parte"																		
								FOR XML PATH('marcaEVolume'), TYPE)																
							FOR XML PATH('marcasEVolumes'), TYPE)											
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE), 
					(SELECT 
						(SELECT 
							@TipoManifesto AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoeda", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(18, 3)) / 10.00) AS decimal(18, 3)) AS "pesoBruto"							
						FOR XML PATH('manifesto'), TYPE), 
						(SELECT 
							@TipoManifesto AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoeda", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(m.c.value('linha[1]', 'varchar(MAX)'), 167, 35))), '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(m.c.value('linha[1]', 'varchar(MAX)'), 66, 3))), ''), 0) AS decimal(18, 3)) / 10.00) AS decimal(18, 3)) AS "pesoBruto"
						FROM t.c.nodes('b600xxx') AS m(c)							
						FOR XML PATH('manifesto'), TYPE), 
						(SELECT 
							2 AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoeda", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 77, 5))), ''), 0) AS decimal(18, 3)) / 10.00) AS decimal(18, 3)) AS "pesoBruto"							
						HAVING @TipoManifesto = 1
						FOR XML PATH('manifesto'), TYPE), 
						(SELECT 
							2 AS "tipoManifesto", 
							(CASE ISNULL(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
								WHEN '' THEN NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b300000/linha)[1]', 'varchar(MAX)'), 240, 2))), '')
								ELSE NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 195, 2))), '') 
							END) AS "paisManifesto", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 58, 104))), '') AS "descricao", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 162, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "valor", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b500000/linha)[1]', 'varchar(MAX)'), 172, 2))), '') AS "paisMoeda", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b200000/linha)[1]', 'varchar(MAX)'), 166, 10))), ''), 0) AS decimal(18, 3)) / 100.00) AS decimal(18, 3)) AS "totalFatura", 
							NULLIF(RTRIM(LTRIM(SUBSTRING(m.c.value('linha[1]', 'varchar(MAX)'), 167, 35))), '') AS "numeroCPA", 
							CAST((CAST(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(m.c.value('linha[1]', 'varchar(MAX)'), 66, 3))), ''), 0) AS decimal(18, 3)) / 10.00) AS decimal(18, 3)) AS "pesoBruto"
						FROM t.c.nodes('b600xxx') AS m(c)	
						WHERE @TipoManifesto = 1						
						FOR XML PATH('manifesto'), TYPE)		
					FOR XML PATH('manifestos'), TYPE)
				FROM @FicheiroXML.nodes('declaracaoUPS') AS t(c)
				WHERE NOT EXISTS(SELECT 1 
								FROM PRO_DUCG WITH(NOLOCK) 
								WHERE DUC_CPRT = NULLIF(RTRIM(LTRIM(SUBSTRING(t.c.value('(b202000/linha)[1]', 'varchar(MAX)'), 51, 18))), '') 
									AND CAST(CONVERT(varchar(10), DUC_DTVO, 127) AS datetime) = ISNULL(@DataVoo, CAST(RTRIM(LTRIM(SUBSTRING(t.c.value('(b100000/linha)[1]', 'varchar(MAX)'), 13, 6))) AS datetime)) 
									AND NDE_CODI <> '25' AND @TipoManifesto = 0)
				FOR XML PATH('declaracao'), TYPE)		
			FOR XML PATH('declaracoesIMPToGIDWin'), ELEMENTS)
-- processa a geração da(s) declaração(ões) IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_ImportaDeXML @XMLDeclaracao, @IdUtilizador, @Erro OUTPUT								
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ISNULL(@Erro, '') +
					'Detalhes do Erro: ' + CHAR(13) + 
					' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + 
					' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) + CHAR(13) + 
					' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + 
					' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + 
					' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) + CHAR(13) + 
					' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ImportaFicheiroUPS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ImportaFicheiroUPS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_IntegracaoNSTI_AtribuiID]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_IntegracaoNSTI_AtribuiID] @XMLDeclaracoes xml, @IdDeclaracaoNSTI int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- atribui o ID da declaração NSTI gerada pela integração NSTI nas declarações IMP-CAU
		UPDATE PRO_DUCG SET DUC_INST = @IdDeclaracaoNSTI
		WHERE DUC_IDTY IN (SELECT x.d.value('id[1]', 'bigint')
							FROM @XMLDeclaracoes.nodes('DeclaracoesIMPCAU/Declaracao') AS x(d))
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_IntegracaoNSTI_AtribuiID] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_IntegracaoNSTI_AtribuiID] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard] @XMLDeclaracoes xml, @TipoDeclaracao tinyint, @Data datetime, @TipoIntegracao tinyint, @CodNatureza varchar(6), 
	@CodOperadorNSTI varchar(18), @NumOperadorTIR varchar(17), @NomeRepresentante varchar(70), @LocalidadeOperadorNSTI varchar(35), @NIFClienteExpedidor varchar(18), 
	@CodPaisExpedicao varchar(2), @CodClienteServico varchar(18), @CodFornecedorDestinatario varchar(18), @CodPaisDestino varchar(2), @CodLocalAutorizado varchar(17), 
	@CodEstanciaPartida varchar(8), @CodEstanciaDestino varchar(8), @MatriculaMeioTranspPartida varchar(27), @CodPaisMeioTranspPartida varchar(2), @FicheiroXML xml OUTPUT, 
	@Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- constroi XML para ficheiro NSTI formato STANDARD do GIDWin XE
		SET @FicheiroXML = 				
			(SELECT
				(SELECT 'I' AS "@acao",
					(CONVERT(varchar(10), @Data, 120) + 'Z') AS "data",
					@CodNatureza AS "natureza",					 
					(SELECT
						(SELECT
							@CodOperadorNSTI AS "operador",
							NULLIF(@NumOperadorTIR, '') AS "numeroOperadorTIR",
							@NomeRepresentante AS "nomeRepresentante",
							@LocalidadeOperadorNSTI AS "localDeclaracao"
						FOR XML PATH('operadorNSTI'), TYPE), 
						(SELECT
							@NIFClienteExpedidor AS "nif"			
						FOR XML PATH('expedidor'), TYPE),
						@CodPaisExpedicao AS "paisExpedicao",
						(SELECT
							@CodFornecedorDestinatario AS "fornecedor"			
						FOR XML PATH('destinatario'), TYPE),
						@CodPaisDestino AS "paisDestino",
						@CodClienteServico AS "clienteServico"											
					FOR XML PATH('operadores'), TYPE), 
					'T1' AS "tipoDeclaracao",
					(SELECT
						'LC' AS "tipo",
						@CodLocalAutorizado AS localAutorizado
					FOR XML PATH('localizacaoMercadorias'), TYPE), 
					(SELECT
						@CodEstanciaPartida AS "estanciaPartida",							
						@CodEstanciaDestino AS "estanciaDestino"
					FOR XML PATH('estancias'), TYPE),
					(SELECT
						(SELECT
							'3' AS "meioTransporte",
							NULLIF(@MatriculaMeioTranspPartida, '') AS "matricula",
							@CodPaisMeioTranspPartida AS "pais"
						FOR XML PATH('partida'), TYPE)						
					FOR XML PATH('transporte'), TYPE), 								
					(SELECT
						(SELECT 'I' AS "@acao", 
							ROW_NUMBER() OVER(ORDER BY duc.DUC_IDTY, adi.DUA_CODI) AS "numeroAdicao",
							adi.APA_CO33 AS "artigo",
							NULLIF(adi.DUA_DESG, '') AS "designacao",
							CAST(0 AS decimal(18, 3)) AS "massaLiquida",
							CAST(ISNULL(duc.DUC_MBRT, 0) AS decimal(18, 3)) AS "massaBruta",
							CAST((CASE @TipoDeclaracao 
								WHEN 1 THEN ISNULL(adi.DUA_US41, 0)
								ELSE NULL 
							END) AS decimal(18, 6)) AS "unidadesSupl", 
							'EU' AS paisMoeda,
							CAST(ISNULL(duc.DUC_VATT, 0) AS decimal(18, 3)) AS "valor",							
							(SELECT TOP 1									
								(SELECT
									NULLIF((CASE 
												WHEN (@TipoIntegracao = 1) AND (LEFT(@CodEstanciaDestino, 2) <> 'PT') THEN duc.DUC_CPRT 
												ELSE LEFT(amv.D31_MARC, 42)
											END), '') AS "marcas",
									tem.TEM_CODI AS "tipoEmbalagem",
									CAST(amv.D31_QNTD AS int) AS "volumes", 
									0 AS "unidades", 
									CAST(0 AS bit) AS "parte"									
								FOR XML PATH('marcaEVolume'), TYPE)
							FROM PRO_DU31 AS amv WITH(NOLOCK)
								INNER JOIN TAB_TEMB AS tem WITH(NOLOCK) ON amv.UME_CODI = tem.TEM_CODI
							WHERE amv.DUC_EANO = adi.DUC_EANO AND amv.DUC_PNUM = adi.DUC_PNUM AND amv.DUA_CODI = adi.DUA_CODI AND amv.D31_CODI = 1 AND tem.TEM_NSTI = 1
							FOR XML PATH('marcasEVolumes'), TYPE),
							(SELECT
								(SELECT
									t.RAA_CODI AS "documento",
									ISNULL(NULLIF((RIGHT(duc.ALF_CODI, 3) + LEFT(duc.MTR_PT18, 1) + STR(s.DRA_APAN, 4) + s.DRA_APC1), ''), 'S/N') AS "referencia",
									CONVERT(varchar(10), s.DRA_APDT, 105) AS "complemento"
								FOR XML PATH('referenciaAdministrativa'), TYPE)
							FROM (SELECT 'CM' AS RAA_CODI 
									HAVING @TipoDeclaracao = 0
									UNION
									SELECT DOC_CODI AS RAA_CODI
									FROM TAB_DOCU WITH(NOLOCK) 
									WHERE DOC_CODI = 'N337' AND @TipoDeclaracao = 1) AS t
								LEFT OUTER JOIN (SELECT TOP 1 DRA_APAN, DRA_APC1, DRA_APDT
												FROM PRO_DURA WITH(NOLOCK) 
												WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DRA_QUAL = 'X') AS s ON 1 = 1							 												
							FOR XML PATH('referenciasAdministrativas'), TYPE),
							(SELECT 								
								doc.DOC_CODI AS "documento",
								NULLIF(LEFT(s.DDO_NUME, 35), '') AS "referencia"																	
							FROM TAB_DOCU AS doc WITH(NOLOCK)
								INNER JOIN (SELECT (CASE @TipoDeclaracao WHEN 1 THEN 'N380' ELSE '380' END) AS DOC_CODI, ISNULL((SELECT SUBSTRING(DDO_NUME, 1, 35) FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 0 AND DOC_CODI = 'N380'), 'S/N') AS DDO_NUME
											HAVING @TipoIntegracao IN (0, 2)
											UNION ALL
											SELECT (CASE @TipoDeclaracao WHEN 1 THEN 'N740' ELSE '740' END) AS DOC_CODI, ISNULL((SELECT SUBSTRING(DDO_NUME, 1, 35) FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 0 AND DOC_CODI = 'N740'), 'S/N') AS DDO_NUME
											HAVING @TipoIntegracao IN (0, 1)
											UNION ALL
											SELECT (CASE @TipoDeclaracao WHEN 1 THEN 'N740' ELSE '740' END) AS DOC_CODI, 'ENTRADA' AS DDO_NUME
											HAVING @TipoIntegracao = 2
											UNION ALL
											SELECT (CASE @TipoDeclaracao WHEN 1 THEN 'N740' ELSE '740' END) AS DOC_CODI, 'SAÍDA' AS DDO_NUME
											HAVING @TipoIntegracao = 2
											UNION ALL
											SELECT (CASE @TipoDeclaracao WHEN 1 THEN '9Z07' ELSE 'ZZZ' END) AS DOC_CODI, ('TD ' + ISNULL(CAST(duc.DUC_NTDP AS varchar(20)), '')) AS DDO_NUME
											HAVING @TipoIntegracao = 2) AS s ON doc.DOC_CODI = s.DOC_CODI
							WHERE doc.DOC_TRAN = 1 AND ISNULL(LEFT(s.DDO_NUME, 35), '') <> ''							
							FOR XML PATH('dadosDocumento'), ROOT('documentos'), TYPE)
						FROM @XMLDeclaracoes.nodes('DeclaracoesIMPCAU/Declaracao') AS x(d)
							INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON x.d.value('id[1]', 'bigint') = duc.DUC_IDTY
							INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON duc.DUC_EANO = adi.DUC_EANO AND duc.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI = 1						
						FOR XML PATH('adicao'), TYPE)
					FOR XML PATH('adicoes'), TYPE)
				FOR XML PATH('declaracao'), TYPE)
			FOR XML PATH('TRACAUToGIDWin'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_IntegracaoNSTI_ExportaXMLStandard] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_IntegracaoNSTI_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_IntegracaoNSTI_ObtemDados] @Ano smallint, @CodEstanciaPartida varchar(8), @CodNaturezaDe varchar(6), @CodNaturezaA varchar(6), 
	@CodStatusIncidencia varchar(8), @DataVooDe datetime, @DataVooA datetime, @ExcluiRelease bit, @TipoManifesto tinyint, @TipoCarga varchar(5), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem as declarações IMP-CAU disponíveis para integração NSTI
		SELECT duc.DUC_IDTY AS id, duc.DUC_EANO AS ano, duc.DUC_PNUM AS numero, duc.DUC_CPRT AS documentoTransporte, duc.DUC_DST8 AS codigoCliente, 
			duc.DUC_DNOM AS nomeCliente, duc.NDE_CODI AS codigoNatureza, duc.NDE_NOME AS nomeNatureza,
			(SELECT TOP 1 SIN_CODI FROM PRO_DUIN WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUI_REHO = 1) AS codigoIncidencia,
			(SELECT TOP 1 SIN_DESC from PRO_DUIN where DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DUI_REHO = 1) AS nomeIncidencia,
			CAST(1 AS bit) AS "S."
		FROM PRO_DUCG AS duc WITH(NOLOCK)
		WHERE duc.NST_CODI IS NULL AND duc.DUC_INST IS NULL AND duc.DUC_EANO = @Ano 
			AND (ISNULL(@CodEstanciaPartida, '') = '' OR duc.ALF_CODI = @CodEstanciaPartida)
			AND (ISNULL(@CodNaturezaDe, '') = '' OR duc.NDE_CODI >= @CodNaturezaDe)
			AND (ISNULL(@CodNaturezaA, '') = '' OR duc.NDE_CODI <= @CodNaturezaA)
			AND (@DataVooDe IS NULL OR CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime) >= CAST(CONVERT(varchar(10), @DataVooDe, 105) AS datetime))
			AND (@DataVooA IS NULL OR CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime) <= CAST(CONVERT(varchar(10), @DataVooA, 105) AS datetime))
			AND (ISNULL(@CodStatusIncidencia, '') = '' OR EXISTS(SELECT 1 FROM PRO_DUIN WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND SIN_CODI = @CodStatusIncidencia))
			AND EXISTS(SELECT 1 FROM PRO_DUOD WITH(NOLOCK) WHERE DUC_PNUM = duc.DUC_PNUM AND DUC_EANO = duc.DUC_EANO AND DUO_TIPO = @TipoManifesto)
			AND (ISNULL(@TipoCarga, '') = '' OR DUC_TPCG = @TipoCarga)
			AND (@ExcluiRelease = 0 OR NOT EXISTS(SELECT 1 FROM PRO_DUIN WITH(NOLOCK) WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND (SIN_CODI = 'A00' OR DUI_REHO = 0) AND @ExcluiRelease = 1))
		ORDER BY duc.DUC_CPRT
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_IntegracaoNSTI_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_IntegracaoNSTI_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_Listagens]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_Listagens] @ModoMenu bit, @IDListagem tinyint, @Ano smallint, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @MesAtual tinyint
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
	SET @MesAtual = MONTH(@DataAtual)
	BEGIN TRY	
		SET @NumErro = 0
-- obtem as listagens a apresentar nas declarações IMP-CAU
		IF @ModoMenu = 1
		BEGIN
			SELECT 0 AS id, 'Reduzida (Mensal)' AS titulo, 'Vista Reduzida p/ Mês Atual' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 1 AS id, 'Reduzida (Global)' AS titulo, 'Vista Reduzida Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 2 AS id, 'Standard (Mensal)' AS titulo, 'Vista Standard p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 3 AS id, 'Standard (Global)' AS titulo, 'Vista Standard Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 4 AS id, 'Detalhada (Mensal)' AS titulo, 'Vista Detalhada p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo
			UNION
			SELECT 5 AS id, 'Detalhada (Global)' AS titulo, 'Vista Detalhada Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 6 AS id, 'Adições Reduzida (Mensal)' AS titulo, 'Vista Adições Reduzida p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION
			SELECT 7 AS id, 'Adições Reduzida (Global)' AS titulo, 'Vista Adições Reduzida Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo
			UNION
			SELECT 8 AS id, 'Adições Standard (Mensal)' AS titulo, 'Vista Adições Standard p/ Mês Atual' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION
			SELECT 9 AS id, 'Adições Standard (Global)' AS titulo, 'Vista Adições Standard Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			UNION
			SELECT 10 AS id, 'Documentos (Gerais)' AS titulo, 'Vista Documentos Gerais' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION
			SELECT 11 AS id, 'Documentos (Adições)' AS titulo, 'Vista Documentos das Adições' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			UNION			
			SELECT 12 AS id, 'Documentos Precedentes (Gerais)' AS titulo, 'Vista Documentos Precedentes Gerais' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo		
			UNION
			SELECT 13 AS id, 'Documentos Precedentes (Adições)' AS titulo, 'Vista Documentos Precedentes das Adições' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo		
			UNION
			SELECT 14 AS id, 'Chassis/Matriculas' AS titulo, 'Vista Chassis/Matriculas' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo	
			UNION
			SELECT 15 AS id, 'Contentores' AS titulo, 'Vista Contentores' AS hint, -1 AS imagem, CAST(1 AS bit) AS novoGrupo					
			ORDER BY id, titulo			
		END
		ELSE
		BEGIN
-- obtem as declarações IMP-CAU para as listagens "Reduzida (Mensal)" e "Reduzida (Global)"
			IF @IDListagem IN (0, 1)
			BEGIN
				SELECT DUC_IDTY AS id, DUC_PNUM AS "Processo", DUC_DATA AS "Data", DUC_DTVO AS "Data Voo", DUC_ANXB AS "Anexo", NDE_CODI AS "Natureza", TDE_1CAS AS "Tipo Declaração", 
					TDE_2CAS AS "TD Adicional", DUC_REGI AS "Regime", DUC_CPRT AS "Documento Transporte", DUC_NVRF AS "V/ Referência", DUC_NRLO AS "NRL", DUC_NORD AS "NRM", 
					(CASE DUC_STAT WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Anulado' WHEN 4 THEN 'Finalizado' ELSE 'Por Enviar' END) AS "Status", 
					(CASE DUC_ESTO WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'NR' THEN 'Notificação de Registo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
						WHEN 'CA' THEN 'Controlo Aduaneiro' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída não Autorizada' 
						WHEN 'LED' THEN 'Lembrete de Envio de Documentos' WHEN 'LDC' THEN 'Lembrete de Expiração Prazo DC' WHEN 'PDA' THEN 'Pedido Documentos Adicionais' ELSE NULL 
					END) AS "Estado Operação", 
					DUC_DTAS AS "Data AS", DUC_ENOM AS "Exportador", DUC_DNOM AS "Importador", DUC_ADI5 AS "Adições", DUC_TVL6 AS "Volumes", DUC_CNTN AS "Conta N.º", DUC_CRTA AS "CA", DUC_CRTD AS "CD", DUC_CRTF AS "CF", DUC_UCRI AS "Utilizador", 
					DUC_DTCR AS "Data Criação"
				FROM PRO_DUCG WITH(NOLOCK)
				WHERE DUC_DUNO = 2 AND DUC_EANO = @Ano AND (CASE @IDListagem WHEN 0 THEN MONTH(DUC_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY DUC_PNUM				
			END
			ELSE
-- obtem as declarações IMP-CAU para as listagens "Standard (Mensal)" e "Standard (Global)"
			IF @IDListagem IN (2, 3)
			BEGIN
				SELECT DUC_IDTY AS id, DUC_PNUM AS "Processo", DUC_DATA AS "Data", DUC_DTVO AS "Data Voo", DUC_ANXB AS "Anexo", NDE_CODI AS "Natureza", ALF_CODI AS "Estância", 
					TDE_1CAS AS "Tipo Declaração", TDE_2CAS AS "TD Adicional", DUC_REGI AS "Regime", DUC_CPRT AS "Documento Transporte", DUC_NVRF AS "V/ Referência", DUC_NRLO AS "NRL", DUC_NORD AS "NRM", 
					(CASE DUC_STAT WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Anulado' WHEN 4 THEN 'Finalizado' ELSE 'Por Enviar' END) AS "Status", 
					(CASE DUC_ESTO WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'NR' THEN 'Notificação de Registo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
						WHEN 'CA' THEN 'Controlo Aduaneiro' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída não Autorizada' 
						WHEN 'LED' THEN 'Lembrete de Envio de Documentos' WHEN 'LDC' THEN 'Lembrete de Expiração Prazo DC' WHEN 'PDA' THEN 'Pedido Documentos Adicionais' ELSE NULL 
					END) AS "Estado Operação", 
					DUC_DTAS AS "Data AS", DUC_ENOM AS "Exportador", PAI_PA15 AS "P.E.", DUC_DNOM AS "Importador", DUC_DNIF AS "NIF", DUC_BIVA AS "BIVA", CEN_CO20 AS "C.E.", 
					LME_CO30 AS "Armazém DTP", MTR_FT21 AS "MT Fronteira", MTR_PT18 AS "MT Chegada", DUC_CONT AS "Contentor", PAI_MO22 AS "Moeda", DUC_MT22 AS "Montante", 
					DUC_VATT AS "Valor Aduaneiro", DUC_VLRC AS "Dívida Aduaneira", DUC_ADI5 AS "Adições", DUC_TVL6 AS "Volumes", DUC_CNTN AS "Conta N.º", DUC_CRTA AS "CA", DUC_CRTD AS "CD", DUC_CRTF AS "CF", DUC_UCRI AS "Utilizador", 
					DUC_DTCR AS "Data Criação"
				FROM PRO_DUCG WITH(NOLOCK)
				WHERE DUC_DUNO = 2 AND DUC_EANO = @Ano AND (CASE @IDListagem WHEN 2 THEN MONTH(DUC_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY DUC_PNUM				
			END
			ELSE
-- obtem as declarações IMP-CAU para as listagens "Detalhada (Mensal)" e "Detalhada (Global)"
			IF @IDListagem IN (4, 5)
			BEGIN
				SELECT DUC_IDTY AS id, DUC_PNUM AS "Processo", DUC_DATA AS "Data", DUC_DTVO AS "Data Voo", DUC_ANXB AS "Anexo", NDE_CODI AS "Natureza", ALF_CODI AS "Estância", 
					TDE_1CAS AS "Tipo Declaração", TDE_2CAS AS "TD Adicional", DUC_REGI AS "Regime", DUC_CPRT AS "Documento Transporte", DUC_NVRF AS "V/ Referência", DUC_NPRO AS "N.º Provisório", DUC_NRLO AS "NRL", 
					DUC_NORD AS "NRM", DUC_NDAT AS "Data NRM", 
					(CASE DUC_STAT WHEN 1 THEN 'Enviado' WHEN 2 THEN 'Integrado' WHEN 3 THEN 'Anulado' WHEN 4 THEN 'Finalizado' ELSE 'Por Enviar' END) AS "Status", 
					(CASE DUC_ESTO WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'NR' THEN 'Notificação de Registo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
						WHEN 'CA' THEN 'Controlo Aduaneiro' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída não Autorizada' 
						WHEN 'LED' THEN 'Lembrete de Envio de Documentos' WHEN 'LDC' THEN 'Lembrete de Expiração Prazo DC' WHEN 'PDA' THEN 'Pedido Documentos Adicionais' ELSE NULL 
					END) AS "Estado Operação", 
					DUC_DTAS AS "Data AS", DUC_DTDC AS "Data Complementar", DUC_ENOM AS "Exportador", PAI_PA15 AS "P.E.", DUC_DNOM AS "Importador", PAI_PA17 AS "P.D.", DUC_DNIF AS "NIF", 
					DUC_BIVA AS "BIVA", DUC_CAUC AS "NRG", CEN_CO20 AS "C.E.", LME_CO30 AS "Armazém DTP", ARM_CODI AS "Armazém", MTR_FT21 AS "MT Fronteira", MTR_PT18 AS "MT Chegada", 
					DUC_MT18 AS "Matricula", DUC_CONT AS "Contentor", PAI_MO22 AS "Moeda", DUC_MT22 AS "Montante", DUC_VEUR AS "Total EUR", DUC_FRET AS "Frete", DUC_SEGU AS "Seguro", 
					DUC_VATT AS "Valor Aduaneiro", DUC_VLRC AS "Dívida Aduaneira", DUC_ADI5 AS "Adições", DUC_TVL6 AS "Volumes", DUC_MLQT AS "Massa Líquida", DUC_MBRT AS "Massa Bruta", 
					DUC_CNTN AS "Conta N.º", DUC_CRTA AS "CA", DUC_CRTD AS "CD", DUC_CRTF AS "CF", DUC_UCRI AS "Utilizador", DUC_DTCR AS "Data Criação"
				FROM PRO_DUCG WITH(NOLOCK)
				WHERE DUC_DUNO = 2 AND DUC_EANO = @Ano AND (CASE @IDListagem WHEN 4 THEN MONTH(DUC_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY DUC_PNUM									
			END
			ELSE
-- obtem as adições IMP-CAU para as listagens "Adições Reduzida (Mensal)" e "Adições Reduzida (Global)"
			IF @IDListagem IN (6, 7)
			BEGIN
				SELECT c.DUC_IDTY AS id, c.DUC_PNUM AS "Processo", c.DUC_DATA AS "Data", c.DUC_REGI AS "Regime", 
					(CASE c.DUC_ESTO WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'NR' THEN 'Notificação de Registo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
						WHEN 'CA' THEN 'Controlo Aduaneiro' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída não Autorizada' 
						WHEN 'LED' THEN 'Lembrete de Envio de Documentos' WHEN 'LDC' THEN 'Lembrete de Expiração Prazo DC' WHEN 'PDA' THEN 'Pedido Documentos Adicionais' ELSE NULL 
					END) AS "Estado Operação", c.DUC_DNOM AS "Importador", c.DUC_NVRF AS "V/ Referência", c.DUC_NORD as "NRM", c.DUC_CRTA AS "CA", c.DUC_CRTD AS "CD", c.DUC_CRTF AS "CF",
					a.DUA_CODI AS "N.º", SUBSTRING(a.APA_CP33, 1, 6) AS "Codigo Pautal", SUBSTRING(a.APA_CP33, 7, 2) AS "NC", SUBSTRING(a.APA_CP33, 9, 2) AS "TARIC", 
					SUBSTRING(a.APA_CP33, 11, 4) AS "AD TARIC1", SUBSTRING(a.APA_CP33, 15, 4) AS "AD TARIC2", SUBSTRING(a.APA_CP33, 19, 4) AS "IVA", a.DUA_AIVA AS "AD IVA", 
					a.DUA_DESG AS "Designação Mercadorias", a.PRE_CO36 AS "Preferência", a.DUA_VEST AS "Valor Estatistico", a.DUA_VATO AS "Valor Aduaneiro" 
				FROM PRO_DUCG AS c WITH(NOLOCK) 
					INNER JOIN PRO_DUAD AS a WITH(NOLOCK) ON c.DUC_EANO = a.DUC_EANO AND c.DUC_PNUM = a.DUC_PNUM
				WHERE c.DUC_DUNO = 2 AND c.DUC_EANO = @Ano AND (CASE @IDListagem WHEN 6 THEN MONTH(c.DUC_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY c.DUC_PNUM, a.DUA_CODI				
			END
			ELSE
-- obtem as adições IMP-CAU para as listagens "Adições Standard (Mensal)" e "Adições Standard (Global)"
			IF @IDListagem IN (8, 9)
			BEGIN
				SELECT c.DUC_IDTY AS id, c.DUC_PNUM AS "Processo", c.DUC_DATA AS "Data", c.DUC_REGI AS "Regime", 
					(CASE c.DUC_ESTO WHEN 'AP' THEN 'Operação Aceite' WHEN 'RE' THEN 'Operação Rejeitada' WHEN 'NR' THEN 'Notificação de Registo' WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
						WHEN 'CA' THEN 'Controlo Aduaneiro' WHEN 'AS' THEN 'Autorização de Saída' WHEN 'ND' THEN 'Notificação da Dívida' WHEN 'SNA' THEN 'Saída não Autorizada' 
						WHEN 'LED' THEN 'Lembrete de Envio de Documentos' WHEN 'LDC' THEN 'Lembrete de Expiração Prazo DC' WHEN 'PDA' THEN 'Pedido Documentos Adicionais' ELSE NULL 
					END) AS "Estado Operação", c.DUC_DNOM AS "Importador", c.DUC_NVRF AS "V/ Referência", c.DUC_NORD AS "NRM", c.DUC_CRTA AS "CA", c.DUC_CRTD AS "CD", c.DUC_CRTF AS "CF",
					a.DUA_CODI AS "N.º", SUBSTRING(a.APA_CP33, 1, 6) AS "Codigo Pautal", SUBSTRING(a.APA_CP33, 7, 2) AS "NC", SUBSTRING(a.APA_CP33, 9, 2) AS "TARIC", 
					SUBSTRING(a.APA_CP33, 11, 4) AS "AD TARIC1", SUBSTRING(a.APA_CP33, 15, 4) AS "AD TARIC2", SUBSTRING(a.APA_CP33, 19, 4) AS "IVA", a.DUA_AIVA AS "AD IVA", 
					a.DUA_DESG AS "Designação Mercadorias", a.DUA_R37B AS "Regime Adicional", a.DUA_1TAR AS "IC1", a.DUA_2TAR AS "IC2", a.DUA_3TAR AS "IC3", a.DUA_4TAR AS "IC4", 
					a.DUA_5TAR AS "IC5", a.PRE_CO36 AS "Preferência", a.DUA_ML38 AS "Massa Liquida", a.DUA_MB35 AS "Massa Bruta", a.DUA_US41 AS "Unidades", a.DUA_VA42 AS "Valor Adição", 
					a.DUA_VFRE AS "Frete", a.DUA_VSEG AS "Seguro", a.DUA_VTRA AS "Verba Transitário", a.DUA_AJUS AS "Ajustamento", a.DUA_VEST AS "Valor Estatistico", 
					a.DUA_VATO AS "Valor Aduaneiro", a.DUA_BTRI AS "BT Direitos", a.DUA_TXVL AS "Taxa Direitos", a.DUA_MTRI AS "MT Direitos", a.DUA_BTIV AS "BT IVA", a.DUA_TIVA AS "Taxa IVA", 
					a.DUA_VIVA AS "MT IVA"
				FROM PRO_DUCG AS c WITH(NOLOCK) 
					INNER JOIN PRO_DUAD AS a WITH(NOLOCK) ON c.DUC_EANO = a.DUC_EANO AND c.DUC_PNUM = a.DUC_PNUM
				WHERE c.DUC_DUNO = 2 AND c.DUC_EANO = @Ano AND (CASE @IDListagem WHEN 8 THEN MONTH(c.DUC_DATA) ELSE @MesAtual END) = @MesAtual
				ORDER BY c.DUC_PNUM, a.DUA_CODI								
			END
			ELSE
-- obtem os documentos gerais IMP-CAU para a listagem "Documentos (Gerais)"
			IF @IDListagem = 10
			BEGIN
				SELECT c.DUC_IDTY AS id, c.DUC_PNUM AS "Processo", c.DUC_DNOM AS "Importador", c.DUC_NVRF AS "V/ Referência", c.DUC_NORD as "NRM", doc.DOC_CODI AS "Documento", 
					(CASE ddo.tipo WHEN 1 THEN 'Transporte' WHEN 2 THEN 'Ref. Adicional' ELSE 'Suporte' END) AS "Tipo", 
					ddo.numero AS "Número"
				FROM PRO_DUCG AS c WITH(NOLOCK) 
					INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON c.DUC_IDTY = ddo.id_declaracaoIMP 
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE c.DUC_DUNO = 2 AND c.DUC_EANO = @Ano 
				ORDER BY c.DUC_PNUM, ddo.id				
			END
			ELSE
-- obtem os documentos das adições IMP-CAU para a listagem "Documentos (Adições)"
			IF @IDListagem = 11
			BEGIN
				SELECT c.DUC_IDTY AS id, c.DUC_PNUM AS "Processo", c.DUC_DNOM AS "Importador", c.DUC_NVRF AS "V/ Referência", c.DUC_NORD as "NRM", a.DUA_CODI AS "N.º Adição", ddo.DOC_CODI AS "Documento", 
					(CASE ddo.DDO_TIPO WHEN 1 THEN 'Transporte' WHEN 2 THEN 'Ref. Adicional' ELSE 'Suporte' END) AS "Tipo", 
					ddo.DDO_NUME AS "Número", ddo.DDO_DINI AS "Data"
				FROM PRO_DUCG AS c WITH(NOLOCK) 
					INNER JOIN PRO_DUAD AS a WITH(NOLOCK) ON c.DUC_EANO = a.DUC_EANO AND c.DUC_PNUM = a.DUC_PNUM
					INNER JOIN PRO_DDOC AS ddo WITH(NOLOCK) ON a.DUC_EANO = ddo.DUC_EANO AND a.DUC_PNUM = ddo.DUC_PNUM AND a.DUA_CODI = ddo.DUA_CODI
				WHERE c.DUC_DUNO = 2 AND c.DUC_EANO = @Ano 
				ORDER BY c.DUC_PNUM, a.DUA_CODI, ddo.DDO_CODI					
			END
			ELSE
-- obtem os precedentes gerais IMP-CAU para a listagem "Documentos Precedentes (Gerais)"
			IF @IDListagem = 12
			BEGIN
				SELECT c.DUC_IDTY AS id, c.DUC_PNUM AS "Processo", c.DUC_DNOM AS "Importador", c.DUC_NVRF AS "V/ Referência", c.DUC_NORD as "NRM", doc.DOC_CODI AS "Documento", dpr.numero AS "Número"
				FROM PRO_DUCG AS c WITH(NOLOCK) 
					INNER JOIN tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) ON c.DUC_IDTY = dpr.id_declaracaoIMP 
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
				WHERE c.DUC_DUNO = 2 AND c.DUC_EANO = @Ano 
				ORDER BY c.DUC_PNUM, dpr.id				
			END
			ELSE
-- obtem os precedentes das adições IMP-CAU para a listagem "Documentos Precedentes (Adições)"
			IF @IDListagem = 13
			BEGIN
				SELECT c.DUC_IDTY AS id, c.DUC_PNUM AS "Processo", c.DUC_DNOM AS "Importador", c.DUC_NVRF AS "V/ Referência", c.DUC_NORD as "NRM", a.DUA_CODI AS "N.º Adição",  doc.DOC_CODI AS "Documento", dap.numero AS "Número"
				FROM PRO_DUCG AS c WITH(NOLOCK) 
					INNER JOIN PRO_DUAD AS a WITH(NOLOCK) ON c.DUC_EANO = a.DUC_EANO AND c.DUC_PNUM = a.DUC_PNUM
					INNER JOIN tb_IMP_DeclaracoesAdicoesPrecedentes AS dap WITH(NOLOCK) ON a.DUA_IDEN = dap.id_adicao
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dap.id_documento = doc.DOC_IDTY
				WHERE c.DUC_DUNO = 2 AND c.DUC_EANO = @Ano 
				ORDER BY c.DUC_PNUM, a.DUA_CODI, dap.id					
			END
			ELSE
-- obtem os chassis/matrículas de veículos das adições IMP-CAU para a listagem "Chassis/Matriculas"
			IF @IDListagem = 14
			BEGIN
				SELECT c.DUC_IDTY AS id, c.DUC_PNUM AS "Processo", c.DUC_DNOM AS "Importador", c.DUC_NVRF AS "V/ Referência", c.DUC_NORD as "NRM", a.DUA_CODI AS "N.º Adição", dav.DBT_HOMO AS "H.T.", dav.DBT_MARC AS "Marca", 
					dav.DBT_MODE AS "Modelo", avc.DVC_MATR AS "Matrícula", avc.DVC_CHAS AS "Chassi"
				FROM PRO_DUCG AS c WITH(NOLOCK) 
					INNER JOIN PRO_DUAD AS a WITH(NOLOCK) ON c.DUC_EANO = a.DUC_EANO AND c.DUC_PNUM = a.DUC_PNUM
					INNER JOIN PRO_DUBT AS dav WITH(NOLOCK) ON a.DUC_EANO = dav.DUC_EANO AND a.DUC_PNUM = dav.DUC_PNUM AND a.DUA_CODI = dav.DUA_CODI
					INNER JOIN PRO_DUVE AS avc WITH(NOLOCK) ON dav.DUC_EANO = avc.DUC_EANO AND dav.DUC_PNUM = avc.DUC_PNUM AND dav.DUA_CODI = avc.DUA_CODI AND dav.DBT_CODI = avc.DBT_CODI
				WHERE c.DUC_DUNO = 2 AND c.DUC_EANO = @Ano 
				ORDER BY c.DUC_PNUM, a.DUA_CODI, dav.DBT_CODI, avc.DVC_IDEN		
			END
			ELSE
-- obtem os contentores gerais e das adições IMP-CAU para a listagem "Contentores"
			IF @IDListagem = 15
			BEGIN
				SELECT t.DUC_IDTY AS id, t.DUC_PNUM AS "Processo", t.DUC_DNOM AS "Importador", t.DUC_NVRF AS "V/ Referência", t.DUC_NORD as "NRM", t.DUC_MT18 AS "Navio", t.DUA_CODI AS "N.º Adição", t.DUC_CONT AS "Contentor"
				FROM (SELECT DUC_IDTY, DUC_PNUM, DUC_DNOM, DUC_NVRF, DUC_NORD, DUC_MT18, NULL AS DUA_CODI, DUC_CONT
					FROM PRO_DUCG WITH(NOLOCK) 					
					WHERE DUC_DUNO = 2 AND DUC_CT19 = 1 AND ISNULL(DUC_CONT, '') <> '' AND DUC_EANO = @Ano 
					UNION ALL
					SELECT c.DUC_IDTY, c.DUC_PNUM, c.DUC_DNOM, c.DUC_NVRF, c.DUC_NORD, c.DUC_MT18, a.DUA_CODI, dac.DCO_CNUM
					FROM PRO_DUCG AS c WITH(NOLOCK) 
						INNER JOIN PRO_DUAD AS a WITH(NOLOCK) ON c.DUC_EANO = a.DUC_EANO AND c.DUC_PNUM = a.DUC_PNUM
						INNER JOIN PRO_DCON AS dac WITH(NOLOCK) ON a.DUC_EANO = dac.DUC_EANO AND a.DUC_PNUM = dac.DUC_PNUM AND a.DUA_CODI = dac.DUA_CODI
					WHERE c.DUC_DUNO = 2 AND c.DUC_CT19 = 1 AND c.DUC_EANO = @Ano
				) AS t
				ORDER BY t.DUC_PNUM, t.DUA_CODI, t.DUC_CONT 			
			END
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_Listagens] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_Listagens] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLCC413A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagemGeraXMLCC413A] @IdDeclaracao int, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem CC413A - Alteração da Declaração de Importação	
	SET @FicheiroXML = 				
		(SELECT
			(SELECT
				NULLIF(dcl.DEC_WSUS, '') AS "From", 
				'AT' AS "To", 
				CONVERT(varchar(19), @DataAtual, 120) AS "SendingDateAndTime",
				'IMP-CAU' AS "MessageID", 
				'CC413A' AS "MessageType", 
				NULLIF(duc.DUC_NRLO, '') AS "CorrelationID"
			FOR XML PATH('messageHeader'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI, '') AS "importCustomsOffice", 
				(CASE duc.DUC_DCEN WHEN 1 THEN 'PT' ELSE NULL END) AS "languageCode", 	
				(CASE duc.DUC_ANXB WHEN 'H6' THEN 1 ELSE NULL END) AS "h6Indicator",			
				NULLIF(duc.DUC_NORD, '') AS "MRN", 
				(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE NULLIF(duc.TDE_1CAS, '') END) AS "declarationType", 
				(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE NULLIF(duc.TDE_2CAS, '') END) AS "additionalDeclarationType"
			FOR XML PATH('ImportOperation'), TYPE),
			(SELECT 
				1 AS "sequenceNumber", 
				NULLIF(duc.DOC_CODI, '') AS "type", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_NRAU, '')) AS "referenceNumber", 
				NULLIF(duc.DUC_EORI, '') AS "holderOfTheAuthorisation"
			HAVING ISNULL(duc.DOC_CODI, '') <> ''
			FOR XML PATH('Authorisation'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI3, '') AS "referenceNumber"
			HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
			FOR XML PATH('CustomsOfficePresentation'), TYPE), 
			(SELECT 
				NULLIF(duc.ALF_CODI4, '') AS "referenceNumber"
			HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'I2')
			FOR XML PATH('SupervisingCustomsOffice'), TYPE), 
			(SELECT 
				(CASE WHEN duc.DUC_TPDS IN (0, 1, 6) THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DNOM, '')) END) AS "name", 
				NULLIF((ISNULL(duc.PAI_DLIV, '') + ISNULL(duc.DUC_DNIF, '')), '') AS "identificationNumber", 		
				(SELECT
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DMOR, '')) AS "streetAndNumber", 
					NULLIF(duc.PAI_DLIV, '') AS "country", 
					NULLIF(duc.DUC_DCPO, '') AS "postcode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DLOC, '')) AS "city"
				HAVING duc.DUC_TPDS NOT IN (0, 1, 6)
				FOR XML PATH('Address'), TYPE)
			HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1')
			FOR XML PATH('Importer'), TYPE), 
			(SELECT 		
				(CASE ISNULL(duc.DUC_TPDC, -1) WHEN 2 THEN NULLIF((ISNULL(duc.PAI_DLIV, '') + ISNULL(duc.DUC_DNIF, '')), '') ELSE NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') END) AS "identificationNumber", 
				(SELECT TOP 1 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DCR_NOME, '')) AS "name", 
					NULLIF(DCR_TELE, '') AS "phoneNumber", 
					NULLIF(DCR_EMAI, '') AS "eMailAddress"
				FROM TAB_DECR WITH(NOLOCK)
				WHERE DEC_CODI = duc.DEC_CO14 AND DCR_TIPO = 0 AND (ISNULL(EAD_CODI, '') = '' OR EAD_CODI = duc.ALF_CODI)
				FOR XML PATH('ContactPerson'), TYPE)
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') AS "identificationNumber", 
				duc.DUC_TPDC AS "status"			
			HAVING ISNULL(duc.DUC_TPDC, -1) = 2 AND dcl.DEC_TIPO <> 1
			FOR XML PATH('Representative'), TYPE),
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY oim.DUO_CTIP) AS "sequenceNumber", 
				NULLIF(oim.DUO_CTIP, '') AS "guaranteeType", 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY soi.DUO_CAUC, soi.ALF_CODI, soi.DUO_CORF) AS "sequenceNumber", 			
					(CASE ISNULL(soi.DUO_CORF, '') WHEN '' THEN NULLIF(soi.DUO_CAUC, '') ELSE NULL END) AS "GRN", 
					'EUR' AS "currencyCode", 
					CAST(SUM(ISNULL(soi.DUO_MONT, 0)) AS decimal(18, 2)) AS "amountToBeCovered",  
					(SELECT
						NULLIF(soi.ALF_CODI, '') AS "referenceNumber"
					HAVING ISNULL(soi.ALF_CODI, '') <> ''
					FOR XML PATH('CustomsOfficeOfGuarantee'), TYPE), 
					NULLIF(soi.DUO_CORF, '') AS "otherGuaranteeReference"
				FROM PRO_DUOI AS soi WITH(NOLOCK) 
					INNER JOIN TAB_RREC AS srr WITH(NOLOCK) ON soi.RRE_CODI = srr.RRE_CODI
				WHERE soi.DUC_EANO = duc.DUC_EANO AND soi.DUC_PNUM = duc.DUC_PNUM AND ISNULL(soi.DUO_CTIP, '') = ISNULL(oim.DUO_CTIP, '') AND srr.RRE_DPOT = 1
				GROUP BY soi.DUO_CAUC, soi.ALF_CODI, soi.DUO_CORF
				FOR XML PATH('GuaranteeReference'), TYPE)
			FROM PRO_DUOI AS oim WITH(NOLOCK) 
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON oim.RRE_CODI = rre.RRE_CODI
			WHERE oim.DUC_EANO = duc.DUC_EANO AND oim.DUC_PNUM = duc.DUC_PNUM AND ISNULL(oim.DUO_CTIP, '') <> '' AND rre.RRE_DPOT = 1 AND duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H6')
			GROUP BY oim.DUO_CTIP
			FOR XML PATH('Guarantee'), TYPE),			
			(SELECT 
				1 AS "sequenceNumber", 
				NULLIF(duc.DUC_CAUC, '') AS "deferredPayment"				
			HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H6') AND duc.DUC_CGLB = 1 AND ISNULL(duc.DUC_CAUC, '') <> ''
			FOR XML PATH('DeferredPayment'), TYPE), 
			(SELECT 
				(CASE 
					WHEN (ISNULL(duc.DUC_FRET, 0) > 0) AND (ISNULL(duc.DUC_SEGU, 0) = 0) THEN NULLIF(duc.PAI_MOFT, '')
					WHEN (ISNULL(duc.DUC_FRET, 0) = 0) AND (ISNULL(duc.DUC_SEGU, 0) > 0) THEN NULLIF(duc.PAI_MOSG, '')
					WHEN (ISNULL(duc.PAI_FRET, '') = ISNULL(duc.PAI_SEGU, '')) THEN NULLIF(duc.PAI_MOFT, '')
					ELSE 'EUR'
				END) AS "currency", 
				CAST((CASE 
						WHEN (ISNULL(duc.DUC_FRET, 0) > 0) AND (ISNULL(duc.DUC_SEGU, 0) = 0) THEN ISNULL(duc.DUC_FRET, 0)
						WHEN (ISNULL(duc.DUC_FRET, 0) = 0) AND (ISNULL(duc.DUC_SEGU, 0) > 0) THEN ISNULL(duc.DUC_SEGU, 0)
						WHEN (ISNULL(duc.PAI_FRET, '') = ISNULL(duc.PAI_SEGU, '')) THEN (ISNULL(duc.DUC_FRET, 0) + ISNULL(duc.DUC_SEGU, 0))
						ELSE (ROUND(ISNULL(duc.DUC_FRET, 0) / ISNULL(duc.DUC_TXFR, 0), 2) + ROUND(ISNULL(duc.DUC_SEGU, 0) / ISNULL(duc.DUC_TXSE, 0), 2))
					END) AS decimal(18, 2)) AS "amount"
			HAVING duc.DUC_ANXB = 'H6'
			FOR XML PATH('PostalCharges'), TYPE), 
			(SELECT		
				(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6') THEN NULL ELSE NULLIF(duc.PAI_MO22, '') END) AS "invoiceCurrency", 
				(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6') THEN NULL ELSE CAST(ISNULL(duc.DUC_MT22, 0) AS decimal(18, 2)) END) AS "totalAmountInvoiced", 
				(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(duc.NTR_CO24, '') END) AS "natureOfTransaction", 
				(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') OR duc.TDE_2CAS NOT IN ('U', 'V', 'X', 'Y', 'Z') THEN NULL ELSE CONVERT(varchar(10), duc.DUC_NDAT, 120) END) AS "acceptanceDate", 		
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(funcao, '') AS "role", 
					NULLIF(nif, '') AS "identificationNumber"
				FROM tb_IMP_DeclaracoesIntervenientes WITH(NOLOCK) 		
				WHERE id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('AdditionalSupplyChainActor'), TYPE),
				(SELECT 			
					NULLIF((ISNULL(duc.PAI_CODI1, '') + ISNULL(duc.CLI_NIF, '')), '') AS "identificationNumber" 
				HAVING duc.DUC_ANXB = 'H1' AND ISNULL(duc.CLI_NIF, '') <> ''
				FOR XML PATH('Buyer'), TYPE), 
				(SELECT 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_NOME, '')) AS "name", 			
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_MORA, '')) AS "streetAndNumber", 
						NULLIF(duc.PAI_CODI, '') AS "country", 
						NULLIF(duc.FOR_CPOS, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_LPOS, '')) AS "city"
					FOR XML PATH('Address'), TYPE)
				HAVING duc.DUC_ANXB = 'H1' AND ISNULL(duc.FOR_NOME, '') <> ''			
				FOR XML PATH('Seller'), TYPE), 
				(SELECT 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ENOM, '')) AS "name", 			
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_EMOR, '')) AS "streetAndNumber", 
						NULLIF(duc.PAI_ELIV, '') AS "country", 
						NULLIF(duc.DUC_ECPO, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ELPO, '')) AS "city"
					FOR XML PATH('Address'), TYPE)
				HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(duc.DUC_ENOM, '') <> ''
				FOR XML PATH('Exporter'), TYPE), 
				(SELECT
					NULLIF(duc.CEN_CO20, '') AS "incotermCode", 
					NULLIF(duc.PAE_CODI, '') AS "UNLOCODE", 
					NULLIF(duc.PAI_CODI2, '') AS "country", 					
					(CASE ISNULL(duc.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DE20, '')) END) AS "location",
					(CASE ISNULL(duc.CEN_CO20, '') WHEN 'XXX' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DE20, '')) ELSE NULL END) AS "text"
				HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C')
				FOR XML PATH('DeliveryTerms'), TYPE), 
				(SELECT 
					NULLIF(duc.PAI_PA15, '') AS countryOfDispatch
				HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(duc.PAI_PA15, '') <> ''
				FOR XML PATH('CountryOfDispatch'), TYPE),
				(SELECT
					NULLIF(duc.PAI_PA17, '') AS countryOfDestination, 
					(CASE WHEN duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE duc.PAI_P17B END) AS "regionOfDestination"			
				HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
				FOR XML PATH('Destination'), TYPE), 
				(SELECT
					NULLIF(duc.TAR_CODI, '') AS "type", 
					NULLIF(duc.ARM_CODI, '') AS "identifier"
				HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND duc.TDE_2CAS NOT IN ('B', 'C') AND ISNULL(duc.TAR_CODI, '') <> ''
				FOR XML PATH('Warehouse'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.numero, '')) AS "referenceNumber", 
					doc.DOC_CODI AS "type", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(dpr.qualificador, '') ELSE NULL END) AS "ccQualifier"
				FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
				WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('PreviousDocument'), TYPE), 		
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY DPD_CODI) AS "sequenceNumber", 
					NULLIF(TXM_CODI, '') AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DPD_DESC, '')) AS "text", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(DPD_QUAL, '') ELSE NULL END) AS "ccQualifier" 
				FROM PRO_DUPD WITH(NOLOCK) 					
				WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
				FOR XML PATH('AdditionalInformation'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
					doc.DOC_CODI AS "type", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(ddo.qualificador, '') ELSE NULL END) AS "ccQualifier", 
					(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.entidadeEmissora, '')) END) AS "issuingAuthorityName", 			
					CONVERT(varchar(10), ddo.dataValidade, 120) AS "dateOfValidity"			
				FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 0 
				FOR XML PATH('SupportingDocument'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
					doc.DOC_CODI AS "type", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(ddo.qualificador, '') ELSE NULL END) AS "ccQualifier" 
				FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 2
				FOR XML PATH('AdditionalReference'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(codigo, '') AS "code", 
					montante AS "amount"
				FROM tb_IMP_DeclaracoesAcrescimosDeducoes WITH(NOLOCK) 		
				WHERE id_declaracaoIMP = duc.DUC_IDTY AND duc.DUC_ANXB IN ('H1', 'H5', 'I1', 'I2')
				FOR XML PATH('AdditionsAndDeductions'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(funcao, '') AS "role", 
					NULLIF(nif, '') AS "VATIdentificationNumber"
				FROM tb_IMP_DeclaracoesReferenciasFiscais WITH(NOLOCK) 		
				WHERE id_declaracaoIMP = duc.DUC_IDTY AND duc.DUC_ANXB IN ('H1', 'H6', 'I1')
				FOR XML PATH('AdditionalFiscalReference'), TYPE), 
				(SELECT
					(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_REF7, '')) END) AS "referenceNumberUCR", 
					(CASE WHEN duc.DUC_ANXB IN ('H5', 'H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE duc.DUC_CT19 END) AS "containerIndicator", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(LEFT(duc.MTR_FT21, 1), '') END) AS "modeOfTransportAtTheBorder", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(LEFT(duc.MTR_CODI, 1), '') END) AS "inlandModeOfTransport", 
					ISNULL(duc.DUC_MBRT, 0) AS "grossMass", 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY t.DUC_CONT) AS "sequenceNumber",
						NULLIF(t.DUC_CONT, '') AS "containerIdentificationNumber", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY DUA_CODI) AS "sequenceNumber", 
							DUA_CODI AS "declarationGoodsItemNumber"
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DCO_CNUM = t.DUC_CONT
						FOR XML PATH('GoodsReference'), TYPE)
					FROM (
						SELECT duc.DUC_CONT
						UNION
						SELECT DCO_CNUM
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
						GROUP BY DCO_CNUM
					) AS t
					WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND duc.TDE_2CAS NOT IN ('B', 'C', 'E', 'F') AND ISNULL(t.DUC_CONT, '') <> '' 
					FOR XML PATH('TransportEquipment'), TYPE),
					(SELECT 
						NULLIF(duc.DUC_TLOC, '') AS "typeOfLocation", 
						NULLIF(duc.DUC_QUAL, '') AS "qualifierOfIdentification", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'U' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "UNLOCODE", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'Y' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
						NULLIF(duc.DUC_IADI, '') AS "additionalIdentifier", 
						(SELECT 
							NULLIF(duc.ALF_CODI1, '') AS "referenceNumber"
						HAVING ISNULL(duc.ALF_CODI1, '') <> ''
						FOR XML PATH('CustomsOffice'), TYPE),				 
						(SELECT 
							NULLIF(duc.DUC_ONIF, '') AS "identificationNumber"
						HAVING ISNULL(duc.DUC_ONIF, '') <> ''
						FOR XML PATH('EconomicOperator'), TYPE),
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LAMO, '')) AS "streetAndNumber", 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LALO, '')) AS "city", 
							'PT' AS "country"					
						HAVING ISNULL(duc.DUC_LAMO, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'Z'				
						FOR XML PATH('Address'), TYPE), 
						(SELECT 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 					
							'PT' AS "country"
						HAVING ISNULL(duc.DUC_LACP, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'T'
						FOR XML PATH('PostcodeAddress'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
					FOR XML PATH('LocationOfGoods'), TYPE), 
					(SELECT 
						duc.MTR_TIPO AS "typeOfIdentification", 
						NULLIF(duc.DUC_MT18, '') AS "identificationNumber" 
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C') AND duc.MTR_TIPO IS NOT NULL
					FOR XML PATH('ArrivalTransportMeans'), TYPE), 
					(SELECT
						NULLIF(duc.PAI_PA21, '') AS "nationality"
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C') AND ISNULL(duc.PAI_PA21, '') <> ''
					FOR XML PATH('ActiveBorderTransportMeans'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type"
					FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 1
					FOR XML PATH('TransportDocument'), TYPE)
				FOR XML PATH('Consignment'), TYPE), 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY adi.DUA_CODI) AS "sequenceNumber", 
					adi.DUA_CODI AS "declarationGoodsItemNumber", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') THEN NULL ELSE NULLIF(adi.NTR_CODI, '') END) AS "natureOfTransaction", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') THEN NULL ELSE CAST(adi.DUA_VEST AS decimal(18, 2)) END) AS "statisticalValue", 
					(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.DUA_NRUR, '')) END) AS "referenceNumberUCR", 			
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY aen.id) AS "sequenceNumber", 
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(aen.numeroReferencia, '')) AS "referenceNumber", 	
						NULLIF(aen.numeroEORI, '') AS "holderOfTheAuthorisation"			
					FROM tb_IMP_DeclaracoesAdicoesEntrepostos AS aen WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON aen.id_documento = doc.DOC_IDTY
					WHERE aen.id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4')
					FOR XML PATH('Authorisation'), TYPE), 
					(SELECT
						NULLIF(LEFT(adi.DUA_RG37, 2), '') AS "requestedProcedure",
						NULLIF(RIGHT(adi.DUA_RG37, 2), '') AS "previousProcedure",
						(SELECT
							ROW_NUMBER() OVER(ORDER BY t.coluna) AS "sequenceNumber",
							NULLIF(t.desdobramento, '') AS "additionalProcedure"									
						FROM tb_TBL_Desdobramentos AS ddb WITH(NOLOCK)
							UNPIVOT(desdobramento FOR coluna IN (ddb.desdobramento1, ddb.desdobramento2, ddb.desdobramento3, ddb.desdobramento4, ddb.desdobramento5)) AS t
						WHERE t.id = adi.id_desdobramento AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1')
						FOR XML PATH('AdditionalProcedure'), TYPE) 
					FOR XML PATH('Procedure'), TYPE), 			
					(SELECT 				
						NULLIF((ISNULL(adi.PAI_CODI4, '') + ISNULL(adi.CLI_NIF, '')), '') AS "identificationNumber"
					HAVING duc.DUC_ANXB = 'H1' AND ISNULL(adi.CLI_NIF, '') <> ''
					FOR XML PATH('Buyer'), TYPE), 
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME1, '')) AS "name", 				
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA1, '')) AS "streetAndNumber", 
							NULLIF(adi.PAI_CODI3, '') AS "country", 
							NULLIF(adi.FOR_CPOS1, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS1, '')) AS "city"
						FOR XML PATH('Address'), TYPE)
					HAVING duc.DUC_ANXB = 'H1' AND ISNULL(adi.FOR_NOME1, '') <> ''
					FOR XML PATH('Seller'), TYPE), 
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME, '')) AS "name", 				 
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA, '')) AS "streetAndNumber", 
							NULLIF(adi.PAI_CODI, '') AS "country", 
							NULLIF(adi.FOR_CPOS, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS, '')) AS "city"
						FOR XML PATH('Address'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(adi.FOR_NOME, '') <> '' 
					FOR XML PATH('Exporter'), TYPE), 
					(SELECT
						(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE NULLIF(adi.PAI_CO34, '') END) AS "countryOfOrigin", 
						(CASE WHEN duc.DUC_ANXB IN ('H5', 'H6', 'I2') THEN NULL ELSE NULLIF(adi.PAI_CODI5, '') END) AS "countryOfPreferentialOrigin" 
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1') AND (ISNULL(adi.PAI_CO34, '') <> '' OR ISNULL(adi.PAI_CODI5, '') <> '')
					FOR XML PATH('Origin'), TYPE), 
					(SELECT 
						NULLIF(adi.PAI_CODI1, '') AS countryOfDispatch
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(adi.PAI_CODI1, '') <> ''
					FOR XML PATH('CountryOfDispatch'), TYPE),
					(SELECT
						NULLIF(adi.PAI_CODI2, '') AS countryOfDestination, 
						adi.RES_CODI AS "regionOfDestination"				
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
					FOR XML PATH('Destination'), TYPE), 
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.DUA_DESG, '')) AS "descriptionOfGoods", 
						(CASE WHEN duc.DUC_ANXB IN ('H6', 'I2') THEN NULL ELSE NULLIF(adi.APA_CCUS, '') END) AS "CUSCode", 
						(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE NULLIF(adi.DUA_CO39, '') END) AS "quotaOrderNumber", 
						(CASE WHEN duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') THEN NULL ELSE NULLIF(adi.DUA_TMER, '') END) AS "typeOfGoods", 
						(SELECT 
							NULLIF(LEFT(adi.APA_CP33, 6), '') AS "harmonizedSystemSubheadingCode", 
							NULLIF(SUBSTRING(adi.APA_CP33, 7, 2), '') AS "combinedNomenclatureCode", 
							NULLIF(SUBSTRING(adi.APA_CP33, 9, 2), '') AS "taricCode", 
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.DUA_ORDEM) AS "sequenceNumber",
								NULLIF(t.DUA_TARIC, '') AS "taricAdditionalCode"
							FROM (
								SELECT 1 AS DUA_ORDEM, SUBSTRING(adi.APA_CP33, 11, 4) AS DUA_TARIC
								UNION
								SELECT 2, SUBSTRING(adi.APA_CP33, 15, 4)
								UNION
								SELECT 3, SUBSTRING(adi.APA_CP33, 19, 4) 								
							) AS t
							WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(t.DUA_TARIC, '') <> '' AND ISNULL(t.DUA_TARIC, '') <> '0000'
							FOR XML PATH('TaricAdditionalCode'), TYPE),
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.DUA_ORDEM) AS "sequenceNumber",
								NULLIF(t.DUA_TARIC, '') AS "nationalAdditionalCode"						
							FROM (
								SELECT 1 AS DUA_ORDEM, adi.DUA_1TAR AS DUA_TARIC
								UNION
								SELECT 2, adi.DUA_2TAR
								UNION
								SELECT 3, adi.DUA_3TAR 
								UNION
								SELECT 4, adi.DUA_4TAR 
								UNION
								SELECT 5, adi.DUA_5TAR 								
							) AS t
							WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(t.DUA_TARIC, '') <> '' AND ISNULL(t.DUA_TARIC, '') <> '0000'
							FOR XML PATH('NationalAdditionalCode'), TYPE)
						HAVING ISNULL(LEFT(adi.DUA_RG37, 2), '') <> '71'
						FOR XML PATH('CommodityCode'), TYPE), 
						(SELECT
							(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'I2') THEN NULL ELSE adi.DUA_ML38 END) AS "netMass", 
							(CASE WHEN duc.DUC_ANXB IN ('H6', 'I2') THEN NULL ELSE NULLIF(adi.DUA_US41, 0) END) AS "supplementaryUnits", 
							(CASE WHEN duc.DUC_ANXB = 'H6' THEN NULL ELSE adi.DUA_MB35 END) AS "grossMass"
						FOR XML PATH('GoodsMeasure'), TYPE), 
						(SELECT 
							CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "itemAmountInvoiced"
						HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'I1', 'I2') 
						FOR XML PATH('InvoiceLine'), TYPE), 
						(SELECT
							CAST(ISNULL((SELECT SUM(ISNULL(DUO_MONT, 0)) FROM PRO_DUOI WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI), 0) AS decimal(18, 2)) AS "totalDutiesAndTaxesAmount", 
							(CASE WHEN duc.DUC_ANXB = 'H5' OR (ISNULL(adi.PRE_CO36, '') = '000' AND ISNULL(LEFT(adi.DUA_RG37, 2), '') = '71') THEN NULL ELSE NULLIF(adi.PRE_CO36, '') END) AS "preference", 
							(SELECT
								ROW_NUMBER() OVER(ORDER BY aoi.DUO_IMPO) AS "sequenceNumber", 
								NULLIF(aoi.DUO_IMPO, '') AS "taxType", 												
								CAST(SUM(ISNULL(aoi.DUO_MONT, 0)) AS decimal(18, 2)) AS "payableTaxAmount", 
								(SELECT
									ROW_NUMBER() OVER(ORDER BY DUO_CODI) AS "sequenceNumber", 
									CAST((CASE DUO_TIPO WHEN 1 THEN (ISNULL(DUO_TXVL, 0) / 100) ELSE ISNULL(DUO_TXVL, 0) END) AS decimal(18, 3)) AS "taxRate", 
									NULLIF(UME_CODI, '') AS "measurementUnitAndQualifier", 
									(CASE DUO_QTDE WHEN 0 THEN NULL ELSE DUO_QTDE END) AS "quantity", 
									CAST((CASE DUO_QTDE WHEN 0 THEN ISNULL(DUO_BTRI, 0) ELSE NULL END) AS decimal(18, 2)) AS "amount", 
									CAST(ISNULL(DUO_MONT, 0) AS decimal(18, 2)) AS "taxAmount"
								FROM PRO_DUOI WITH(NOLOCK)
								WHERE DUC_EANO = aoi.DUC_EANO AND DUC_PNUM = aoi.DUC_PNUM AND DUA_CODI = aoi.DUA_CODI AND DUO_IMPO = aoi.DUO_IMPO
								FOR XML PATH('TaxBase'), TYPE) 
							FROM PRO_DUOI AS aoi WITH(NOLOCK)
							WHERE aoi.DUC_EANO = adi.DUC_EANO AND aoi.DUC_PNUM = adi.DUC_PNUM AND aoi.DUA_CODI = adi.DUA_CODI AND ISNULL(aoi.DUO_IMPO, '') <> '' AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
							GROUP BY aoi.DUC_EANO, aoi.DUC_PNUM, aoi.DUA_CODI, aoi.DUO_IMPO
							FOR XML PATH('DutiesAndTaxes'), TYPE) 
						HAVING duc.DUC_ANXB <> 'H6'
						FOR XML PATH('CalculationOfTaxes'), TYPE), 
						(SELECT
							NULLIF(duc.PAI_MO22, '') AS "currency", 
							CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "amount" 
						HAVING duc.DUC_ANXB = 'H6'
						FOR XML PATH('PostalValue'), TYPE)
					FOR XML PATH('Commodity'), TYPE),
					(SELECT
						ROW_NUMBER() OVER(ORDER BY D31_CODI) AS "sequenceNumber", 
						(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE NULLIF(UME_CODI, '') END) AS "typeOfPackages", 
						(CASE D31_TTVL WHEN 1 THEN NULL ELSE CAST(D31_QNTD AS int) END) AS "numberOfPackages", 
						(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(D31_MARC, '')) END) AS "shippingMarks"
					FROM PRO_DU31 WITH(NOLOCK)
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI
					FOR XML PATH('Packaging'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY apr.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(apr.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type", 				
						umv.UME_CODI AS "typeOfPackages", 
						apr.volumes AS "numberOfPackages", 
						umq.UME_CODI AS "measurementUnitAndQualifier", 
						apr.quantidade AS "quantity", 
						apr.numeroAdicao AS "goodsItemIdentifier" 
					FROM tb_IMP_DeclaracoesAdicoesPrecedentes AS apr WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON apr.id_documento = doc.DOC_IDTY
						INNER JOIN TAB_UMED AS umv WITH(NOLOCK) ON apr.id_unidadeMedidaVolumes = umv.UME_IDTY
						LEFT OUTER JOIN TAB_UMED AS umq WITH(NOLOCK) ON apr.id_unidadeMedidaQualificador = umq.UME_IDTY
					WHERE apr.id_adicao = adi.DUA_IDEN 
					FOR XML PATH('PreviousDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ape.id) AS "sequenceNumber", 
						ped.TXM_CODI AS "code", 				
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(numero, '')) AS "text" 				
					FROM tb_IMP_DeclaracoesAdicoesPedidos AS ape WITH(NOLOCK)
						INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ape.id_pedido = ped.TXM_IDTY 					
					WHERE ape.id_adicao = adi.DUA_IDEN
					FOR XML PATH('AdditionalInformation'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ado.DDO_CODI) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ado.DDO_NUME, '')) AS "referenceNumber", 
						NULLIF(ado.DOC_CODI, '') AS "type", 				
						(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE NULLIF(ado.DDO_EEMI, '') END) AS "issuingAuthorityName", 
						NULLIF(ado.UME_CODI, '') AS "measurementUnitAndQualifier", 
						ado.DDO_QTDE AS "quantity", 
						CONVERT(varchar(10), ado.DDO_DINI, 120) AS "dateOfValidity", 
						NULLIF(pai.PAI_PREF, '') AS "currency", 
						ado.DDO_NLIN AS "documentLineItemNumber", 
						CAST(NULLIF(ado.DDO_MONT, 0) AS decimal(18, 2)) AS "amount"
					FROM PRO_DDOC AS ado WITH(NOLOCK) 						
						LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON ado.PAI_CODI = pai.PAI_CODI
					WHERE ado.DUC_EANO = adi.DUC_EANO AND ado.DUC_PNUM = adi.DUC_PNUM AND ado.DUA_CODI = adi.DUA_CODI AND ado.DDO_TIPO = 0
					FOR XML PATH('SupportingDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY DDO_CODI) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DDO_NUME, '')) AS "referenceNumber", 
						NULLIF(DOC_CODI, '') AS "type"				
					FROM PRO_DDOC WITH(NOLOCK) 						
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 2
					FOR XML PATH('AdditionalReference'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY DDO_CODI) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DDO_NUME, '')) AS "referenceNumber", 
						NULLIF(DOC_CODI, '') AS "type"
					FROM PRO_DDOC WITH(NOLOCK) 						
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 1
					FOR XML PATH('TransportDocument'), TYPE), 
					(SELECT 
						(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') THEN NULL ELSE adi.DUA_MAVA END) AS "valuationMethod",
						(SELECT
							ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
							NULLIF(codigo, '') AS "code", 
							montante AS "amount"
						FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK) 		
						WHERE id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H5', 'I1', 'I2')
						FOR XML PATH('AdditionsAndDeductions'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'I1', 'I2')
					FOR XML PATH('CustomsValuation'), TYPE), 
					(SELECT 
						NULLIF(adi.DUA_IAVA, '') AS "valuationIndicators"
					HAVING duc.DUC_ANXB IN ('H1', 'H4', 'H5') AND ISNULL(adi.DUA_IAVA, '') <> '' 
					FOR XML PATH('ValuationAdjustment'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(funcao, '') AS "role", 
						NULLIF(nif, '') AS "VATIdentificationNumber"
					FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais WITH(NOLOCK) 		
					WHERE id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H6', 'I1')
					FOR XML PATH('AdditionalFiscalReference'), TYPE)
				FROM PRO_DUAD AS adi WITH(NOLOCK) 		
				WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
				FOR XML PATH('GoodsShipmentItem'), TYPE)
			FOR XML PATH('GoodsShipment'), TYPE), 
			(SELECT 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.nome, '')) AS "name", 
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.morada, '')) AS "streetAndNumber", 
						NULLIF(pai.PAI_CODI, '') AS "country", 
						NULLIF(dpr.codigoPostal, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.localidade, '')) AS "city"
					FOR XML PATH('Address'), TYPE)
				FROM tb_IMP_DeclaracoesProprietarios AS dpr WITH(NOLOCK) 
					INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dpr.id_pais = pai.PAI_IDTY
				WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('OwnerOfTheGoods'), TYPE), 
				(SELECT
					 NULLIF(duc.DUC_ATLO, '') AS "typeOfLocation", 
					 NULLIF(duc.DUC_AQUA, '') AS "qualifierOfIdentification", 
					 NULLIF(duc.LME_CODI, '') AS "UNLOCODE", 
					 (SELECT
						NULLIF(duc.PAI_CODI3, '') AS "country", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AMOR, '')) AS "streetAndNumber", 						
						NULLIF(duc.DUC_ACPO, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ALOC, '')) AS "city"
					HAVING ISNULL(duc.DUC_AMOR, '') <> ''
					FOR XML PATH('Address'), TYPE)
				HAVING ISNULL(duc.DUC_ATLO, '') <> ''
				FOR XML PATH('FirstPlaceOfUseOrProcessing'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dlt.id) AS "sequenceNumber", 
					NULLIF(dlt.tipo, '') AS "typeOfLocationCode", 
					NULLIF(dlt.qualificador, '') AS "qualifierOfIdentification", 
					NULLIF(lme.LME_CODI, '') AS "UNLOCODE", 
					(SELECT
						NULLIF(pai.PAI_CODI, '') AS "country", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.morada, '')) AS "streetAndNumber", 						
						NULLIF(dlt.codigoPostal, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.localidade, '')) AS "city"
					HAVING ISNULL(dlt.morada, '') <> ''
					FOR XML PATH('Address'), TYPE)
				FROM tb_IMP_DeclaracoesLocaisTransformacao AS dlt WITH(NOLOCK) 
					LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dlt.id_localAutorizado = lme.LME_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dlt.id_pais = pai.PAI_IDTY
				WHERE dlt.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('PlacesOfProcessingOrUse'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dea.id) AS "sequenceNumber", 
					NULLIF(ead.EAD_CODI, '') AS "referenceNumber"					
				FROM tb_IMP_DeclaracoesEstancias AS dea WITH(NOLOCK) 
					INNER JOIN TAB_EADU AS ead WITH(NOLOCK) ON dea.id_estancia = ead.EAD_IDTY
				WHERE dea.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('CustomsOfficeOfDischarge'), TYPE), 
				(SELECT 
					duc.DUC_APRZ AS "period", 
					duc.DUC_APPR AS "automaticExtensionIndicator", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ATXT, '')) AS "text"
				HAVING ISNULL(duc.DUC_APRZ, 0) <> 0
				FOR XML PATH('PeriodForDischarge'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpt.id) AS "sequenceNumber", 
					NULLIF(LEFT(dpt.codigoPautal, 8), '') AS "commodityCode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.designacao, '')) AS "descriptionOfGoods"					
				FROM tb_IMP_DeclaracoesProdutosTransformados AS dpt WITH(NOLOCK) 					
				WHERE dpt.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('ProcessedProducts'), TYPE), 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY dmi.id) AS "sequenceNumber", 
					NULLIF(mid.MIA_CODI, '') AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dmi.descricao, '')) AS "text"					
				FROM tb_IMP_DeclaracoesMeiosIdentificacao AS dmi WITH(NOLOCK) 					
					INNER JOIN TAB_MIAU AS mid WITH(NOLOCK) ON dmi.id_meioIdentificacao = mid.MIA_IDTY
				WHERE dmi.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('IdentificationOfGoods'), TYPE), 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(taxaRendimento, '') AS "RateOfYield"
				FROM tb_IMP_DeclaracoesTaxasRendimento WITH(NOLOCK) 					
				WHERE id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('RateOfYield'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					codigo AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(texto, '')) AS "text"
				FROM tb_IMP_DeclaracoesCondicoesEconomicas WITH(NOLOCK) 					
				WHERE id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('EconomicConditions'), TYPE), 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AAPR, '')) AS "DetailsOfPlannedActivities", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AIAD, '')) AS "AdditionalInformation", 
				(CASE duc.DUC_ANXB WHEN 'H4' THEN duc.DUC_ACMD ELSE NULL END) AS "CalculationOfTheAmountImportDuty"
			HAVING duc.DUC_ANXB IN ('H3', 'H4')
			FOR XML PATH('AttachedRequest'), TYPE)		
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @IdDeclaracao
		FOR XML PATH('CC413A'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLCC413A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLCC413A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLCC414A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [sp_IMP_Declaracoes_MensagemGeraXMLCC414A] @IdDeclaracao int, @Motivo varchar(512), @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem CC414A - Anulação da Declaração de Importação	
	SET @FicheiroXML = 				
		(SELECT
			(SELECT
				NULLIF(dcl.DEC_WSUS, '') AS "From", 
				'AT' AS "To", 
				CONVERT(varchar(19), @DataAtual, 120) AS "SendingDateAndTime",
				'IMP-CAU' AS "MessageID", 
				'CC414A' AS "MessageType", 
				NULLIF(duc.DUC_NRLO, '') AS "CorrelationID"
			FOR XML PATH('messageHeader'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI, '') AS "importCustomsOffice", 								
				NULLIF(duc.DUC_NORD, '') AS "MRN", 
				CONVERT(varchar(19), @DataAtual, 126) AS "invalidationRequestDateAndTime", 
				NULLIF(@Motivo, '') AS "invalidationReason"
			FOR XML PATH('ImportOperation'), TYPE),						
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(duc.DEC_NIF, '')), '') AS "identificationNumber"				
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') AS "identificationNumber", 
				duc.DUC_TPDC AS "status"
			HAVING ISNULL(duc.DUC_TPDC, -1) = 2 AND dcl.DEC_TIPO <> 1
			FOR XML PATH('Representative'), TYPE)		
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @IdDeclaracao
		FOR XML PATH('CC414A'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLCC414A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLCC414A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLCC415A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagemGeraXMLCC415A] @IdDeclaracao int, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem CC415A - Criação da Declaração de Importação	
	SET @FicheiroXML = 				
		(SELECT
			(SELECT
				NULLIF(dcl.DEC_WSUS, '') AS "From", 
				'AT' AS "To", 
				CONVERT(varchar(19), @DataAtual, 120) AS "SendingDateAndTime",
				'IMP-CAU' AS "MessageID", 
				'CC415A' AS "MessageType", 
				NULLIF(duc.DUC_NRLO, '') AS "CorrelationID"
			FOR XML PATH('messageHeader'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI, '') AS "importCustomsOffice", 
				(CASE duc.DUC_DCEN WHEN 1 THEN 'PT' ELSE NULL END) AS "languageCode", 
				(CASE duc.DUC_ANXB WHEN 'H6' THEN 1 ELSE NULL END) AS "h6Indicator", 
				NULLIF(duc.DUC_NRLO, '') AS "LRN", 
				(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE NULLIF(duc.TDE_1CAS, '') END) AS "declarationType", 
				(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE NULLIF(duc.TDE_2CAS, '') END) AS "additionalDeclarationType"
			FOR XML PATH('ImportOperation'), TYPE),
			(SELECT 
				1 AS "sequenceNumber", 
				NULLIF(duc.DOC_CODI, '') AS "type", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_NRAU, '')) AS "referenceNumber", 
				NULLIF(duc.DUC_EORI, '') AS "holderOfTheAuthorisation"
			HAVING ISNULL(duc.DOC_CODI, '') <> ''
			FOR XML PATH('Authorisation'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI3, '') AS "referenceNumber"
			HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
			FOR XML PATH('CustomsOfficePresentation'), TYPE), 
			(SELECT 
				NULLIF(duc.ALF_CODI4, '') AS "referenceNumber"
			HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'I2')
			FOR XML PATH('SupervisingCustomsOffice'), TYPE), 
			(SELECT 
				(CASE WHEN duc.DUC_TPDS IN (0, 1, 6) THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DNOM, '')) END) AS "name", 
				NULLIF((ISNULL(duc.PAI_DLIV, '') + ISNULL(duc.DUC_DNIF, '')), '') AS "identificationNumber", 		
				(SELECT
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DMOR, '')) AS "streetAndNumber", 
					NULLIF(duc.PAI_DLIV, '') AS "country", 
					NULLIF(duc.DUC_DCPO, '') AS "postcode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DLOC, '')) AS "city"
				HAVING duc.DUC_TPDS NOT IN (0, 1, 6)
				FOR XML PATH('Address'), TYPE)
			HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1')
			FOR XML PATH('Importer'), TYPE), 
			(SELECT 		
				(CASE ISNULL(duc.DUC_TPDC, -1) WHEN 2 THEN NULLIF((ISNULL(duc.PAI_DLIV, '') + ISNULL(duc.DUC_DNIF, '')), '') ELSE NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') END) AS "identificationNumber", 
				(SELECT TOP 1 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DCR_NOME, '')) AS "name", 
					NULLIF(DCR_TELE, '') AS "phoneNumber", 
					NULLIF(DCR_EMAI, '') AS "eMailAddress"
				FROM TAB_DECR WITH(NOLOCK)
				WHERE DEC_CODI = duc.DEC_CO14 AND DCR_TIPO = 0 AND (ISNULL(EAD_CODI, '') = '' OR EAD_CODI = duc.ALF_CODI)
				FOR XML PATH('ContactPerson'), TYPE)
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') AS "identificationNumber",
				duc.DUC_TPDC AS "status"			
			HAVING ISNULL(duc.DUC_TPDC, -1) = 2 AND dcl.DEC_TIPO <> 1
			FOR XML PATH('Representative'), TYPE), 
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY oim.DUO_CTIP) AS "sequenceNumber", 
				NULLIF(oim.DUO_CTIP, '') AS "guaranteeType", 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY soi.DUO_CAUC, soi.ALF_CODI, soi.DUO_CORF) AS "sequenceNumber", 			
					(CASE ISNULL(soi.DUO_CORF, '') WHEN '' THEN NULLIF(soi.DUO_CAUC, '') ELSE NULL END) AS "GRN", 
					'EUR' AS "currencyCode", 
					CAST(SUM(ISNULL(soi.DUO_MONT, 0)) AS decimal(18, 2)) AS "amountToBeCovered", 
					(SELECT
						NULLIF(soi.ALF_CODI, '') AS "referenceNumber"
					HAVING ISNULL(soi.ALF_CODI, '') <> ''
					FOR XML PATH('CustomsOfficeOfGuarantee'), TYPE), 
					NULLIF(soi.DUO_CORF, '') AS "otherGuaranteeReference"
				FROM PRO_DUOI AS soi WITH(NOLOCK) 
					INNER JOIN TAB_RREC AS srr WITH(NOLOCK) ON soi.RRE_CODI = srr.RRE_CODI
				WHERE soi.DUC_EANO = duc.DUC_EANO AND soi.DUC_PNUM = duc.DUC_PNUM AND ISNULL(soi.DUO_CTIP, '') = ISNULL(oim.DUO_CTIP, '') AND srr.RRE_DPOT = 1
				GROUP BY soi.DUO_CAUC, soi.ALF_CODI, soi.DUO_CORF
				FOR XML PATH('GuaranteeReference'), TYPE)
			FROM PRO_DUOI AS oim WITH(NOLOCK) 
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON oim.RRE_CODI = rre.RRE_CODI
			WHERE oim.DUC_EANO = duc.DUC_EANO AND oim.DUC_PNUM = duc.DUC_PNUM AND ISNULL(oim.DUO_CTIP, '') <> '' AND rre.RRE_DPOT = 1 AND duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H6')
			GROUP BY oim.DUO_CTIP
			FOR XML PATH('Guarantee'), TYPE), 
			(SELECT 
				1 AS "sequenceNumber", 
				NULLIF(duc.DUC_CAUC, '') AS "deferredPayment"				
			HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H6') AND duc.DUC_CGLB = 1 AND ISNULL(duc.DUC_CAUC, '') <> ''
			FOR XML PATH('DeferredPayment'), TYPE), 
			(SELECT 
				(CASE 
					WHEN (ISNULL(duc.DUC_FRET, 0) > 0) AND (ISNULL(duc.DUC_SEGU, 0) = 0) THEN NULLIF(duc.PAI_MOFT, '')
					WHEN (ISNULL(duc.DUC_FRET, 0) = 0) AND (ISNULL(duc.DUC_SEGU, 0) > 0) THEN NULLIF(duc.PAI_MOSG, '')
					WHEN (ISNULL(duc.PAI_FRET, '') = ISNULL(duc.PAI_SEGU, '')) THEN NULLIF(duc.PAI_MOFT, '')
					ELSE 'EUR'
				END) AS "currency", 
				CAST((CASE 
						WHEN (ISNULL(duc.DUC_FRET, 0) > 0) AND (ISNULL(duc.DUC_SEGU, 0) = 0) THEN ISNULL(duc.DUC_FRET, 0)
						WHEN (ISNULL(duc.DUC_FRET, 0) = 0) AND (ISNULL(duc.DUC_SEGU, 0) > 0) THEN ISNULL(duc.DUC_SEGU, 0)
						WHEN (ISNULL(duc.PAI_FRET, '') = ISNULL(duc.PAI_SEGU, '')) THEN (ISNULL(duc.DUC_FRET, 0) + ISNULL(duc.DUC_SEGU, 0))
						ELSE (ROUND(ISNULL(duc.DUC_FRET, 0) / ISNULL(duc.DUC_TXFR, 0), 2) + ROUND(ISNULL(duc.DUC_SEGU, 0) / ISNULL(duc.DUC_TXSE, 0), 2))
					END) AS decimal(18, 2)) AS "amount"
			HAVING duc.DUC_ANXB = 'H6'
			FOR XML PATH('PostalCharges'), TYPE), 
			(SELECT		
				(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6') THEN NULL ELSE NULLIF(duc.PAI_MO22, '') END) AS "invoiceCurrency", 
				(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6') THEN NULL ELSE CAST(ISNULL(duc.DUC_MT22, 0) AS decimal(18, 2)) END) AS "totalAmountInvoiced", 
				(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(duc.NTR_CO24, '') END) AS "natureOfTransaction", 
				(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') OR duc.TDE_2CAS NOT IN ('U', 'V', 'X', 'Y', 'Z') THEN NULL ELSE CONVERT(varchar(10), duc.DUC_NDAT, 120) END) AS "acceptanceDate", 		
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(funcao, '') AS "role", 
					NULLIF(nif, '') AS "identificationNumber"
				FROM tb_IMP_DeclaracoesIntervenientes WITH(NOLOCK) 		
				WHERE id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('AdditionalSupplyChainActor'), TYPE),
				(SELECT 			
					NULLIF((ISNULL(duc.PAI_CODI1, '') + ISNULL(duc.CLI_NIF, '')), '') AS "identificationNumber" 
				HAVING duc.DUC_ANXB = 'H1' AND ISNULL(duc.CLI_NIF, '') <> ''
				FOR XML PATH('Buyer'), TYPE), 
				(SELECT 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_NOME, '')) AS "name", 			
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_MORA, '')) AS "streetAndNumber", 
						NULLIF(duc.PAI_CODI, '') AS "country", 
						NULLIF(duc.FOR_CPOS, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_LPOS, '')) AS "city"
					FOR XML PATH('Address'), TYPE)
				HAVING duc.DUC_ANXB = 'H1' AND ISNULL(duc.FOR_NOME, '') <> ''			
				FOR XML PATH('Seller'), TYPE), 
				(SELECT 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ENOM, '')) AS "name", 			
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_EMOR, '')) AS "streetAndNumber", 
						NULLIF(duc.PAI_ELIV, '') AS "country", 
						NULLIF(duc.DUC_ECPO, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ELPO, '')) AS "city"
					FOR XML PATH('Address'), TYPE)
				HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(duc.DUC_ENOM, '') <> ''
				FOR XML PATH('Exporter'), TYPE), 
				(SELECT
					NULLIF(duc.CEN_CO20, '') AS "incotermCode", 
					NULLIF(duc.PAE_CODI, '') AS "UNLOCODE", 
					NULLIF(duc.PAI_CODI2, '') AS "country", 					
					(CASE ISNULL(duc.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DE20, '')) END) AS "location",
					(CASE ISNULL(duc.CEN_CO20, '') WHEN 'XXX' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DE20, '')) ELSE NULL END) AS "text"
				HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C')
				FOR XML PATH('DeliveryTerms'), TYPE), 
				(SELECT 
					NULLIF(duc.PAI_PA15, '') AS countryOfDispatch
				HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(duc.PAI_PA15, '') <> ''
				FOR XML PATH('CountryOfDispatch'), TYPE),
				(SELECT
					NULLIF(duc.PAI_PA17, '') AS countryOfDestination, 
					(CASE WHEN duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE duc.PAI_P17B END) AS "regionOfDestination"			
				HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
				FOR XML PATH('Destination'), TYPE), 
				(SELECT
					NULLIF(duc.TAR_CODI, '') AS "type", 
					NULLIF(duc.ARM_CODI, '') AS "identifier"
				HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND duc.TDE_2CAS NOT IN ('B', 'C') AND ISNULL(duc.TAR_CODI, '') <> ''
				FOR XML PATH('Warehouse'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.numero, '')) AS "referenceNumber", 
					doc.DOC_CODI AS "type", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(dpr.qualificador, '') ELSE NULL END) AS "ccQualifier"
				FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
				WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('PreviousDocument'), TYPE), 		
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY DPD_CODI) AS "sequenceNumber", 
					NULLIF(TXM_CODI, '') AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DPD_DESC, '')) AS "text", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(DPD_QUAL, '') ELSE NULL END) AS "ccQualifier" 
				FROM PRO_DUPD WITH(NOLOCK) 					
				WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
				FOR XML PATH('AdditionalInformation'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
					doc.DOC_CODI AS "type", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(ddo.qualificador, '') ELSE NULL END) AS "ccQualifier", 
					(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.entidadeEmissora, '')) END) AS "issuingAuthorityName", 			
					CONVERT(varchar(10), ddo.dataValidade, 120) AS "dateOfValidity"			
				FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 0 
				FOR XML PATH('SupportingDocument'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
					doc.DOC_CODI AS "type", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(ddo.qualificador, '') ELSE NULL END) AS "ccQualifier" 
				FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 2
				FOR XML PATH('AdditionalReference'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(codigo, '') AS "code", 
					montante AS "amount"
				FROM tb_IMP_DeclaracoesAcrescimosDeducoes WITH(NOLOCK) 		
				WHERE id_declaracaoIMP = duc.DUC_IDTY AND duc.DUC_ANXB IN ('H1', 'H5', 'I1', 'I2')
				FOR XML PATH('AdditionsAndDeductions'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(funcao, '') AS "role", 
					NULLIF(nif, '') AS "VATIdentificationNumber"
				FROM tb_IMP_DeclaracoesReferenciasFiscais WITH(NOLOCK) 		
				WHERE id_declaracaoIMP = duc.DUC_IDTY AND duc.DUC_ANXB IN ('H1', 'H6', 'I1')
				FOR XML PATH('AdditionalFiscalReference'), TYPE), 
				(SELECT
					(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_REF7, '')) END) AS "referenceNumberUCR", 
					(CASE WHEN duc.DUC_ANXB IN ('H5', 'H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE duc.DUC_CT19 END) AS "containerIndicator", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(LEFT(duc.MTR_FT21, 1), '') END) AS "modeOfTransportAtTheBorder", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(LEFT(duc.MTR_CODI, 1), '') END) AS "inlandModeOfTransport", 
					ISNULL(duc.DUC_MBRT, 0) AS "grossMass", 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY t.DUC_CONT) AS "sequenceNumber",
						NULLIF(t.DUC_CONT, '') AS "containerIdentificationNumber", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY DUA_CODI) AS "sequenceNumber", 
							DUA_CODI AS "declarationGoodsItemNumber"
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DCO_CNUM = t.DUC_CONT
						FOR XML PATH('GoodsReference'), TYPE)
					FROM (
						SELECT duc.DUC_CONT
						UNION
						SELECT DCO_CNUM
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
						GROUP BY DCO_CNUM
					) AS t
					WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND duc.TDE_2CAS NOT IN ('B', 'C', 'E', 'F') AND ISNULL(t.DUC_CONT, '') <> '' 
					FOR XML PATH('TransportEquipment'), TYPE),
					(SELECT 
						NULLIF(duc.DUC_TLOC, '') AS "typeOfLocation", 
						NULLIF(duc.DUC_QUAL, '') AS "qualifierOfIdentification", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'U' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "UNLOCODE", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'Y' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
						NULLIF(duc.DUC_IADI, '') AS "additionalIdentifier", 
						(SELECT 
							NULLIF(duc.ALF_CODI1, '') AS "referenceNumber"
						HAVING ISNULL(duc.ALF_CODI1, '') <> ''
						FOR XML PATH('CustomsOffice'), TYPE),				 
						(SELECT 
							NULLIF(duc.DUC_ONIF, '') AS "identificationNumber"
						HAVING ISNULL(duc.DUC_ONIF, '') <> ''
						FOR XML PATH('EconomicOperator'), TYPE),
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LAMO, '')) AS "streetAndNumber", 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LALO, '')) AS "city", 
							'PT' AS "country"					
						HAVING ISNULL(duc.DUC_LAMO, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'Z'				
						FOR XML PATH('Address'), TYPE), 
						(SELECT 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 					
							'PT' AS "country"
						HAVING ISNULL(duc.DUC_LACP, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'T'
						FOR XML PATH('PostcodeAddress'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
					FOR XML PATH('LocationOfGoods'), TYPE), 
					(SELECT 
						duc.MTR_TIPO AS "typeOfIdentification", 
						NULLIF(duc.DUC_MT18, '') AS "identificationNumber" 
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C') AND duc.MTR_TIPO IS NOT NULL
					FOR XML PATH('ArrivalTransportMeans'), TYPE), 
					(SELECT
						NULLIF(duc.PAI_PA21, '') AS "nationality"
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C') AND ISNULL(duc.PAI_PA21, '') <> ''
					FOR XML PATH('ActiveBorderTransportMeans'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type"
					FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 1
					FOR XML PATH('TransportDocument'), TYPE)
				FOR XML PATH('Consignment'), TYPE), 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY adi.DUA_CODI) AS "sequenceNumber", 
					adi.DUA_CODI AS "declarationGoodsItemNumber", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') THEN NULL ELSE NULLIF(adi.NTR_CODI, '') END) AS "natureOfTransaction", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') THEN NULL ELSE CAST(adi.DUA_VEST AS decimal(18, 2)) END) AS "statisticalValue", 
					(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.DUA_NRUR, '')) END) AS "referenceNumberUCR", 			
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY aen.id) AS "sequenceNumber", 
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(aen.numeroReferencia, '')) AS "referenceNumber", 	
						NULLIF(aen.numeroEORI, '') AS "holderOfTheAuthorisation"			
					FROM tb_IMP_DeclaracoesAdicoesEntrepostos AS aen WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON aen.id_documento = doc.DOC_IDTY
					WHERE aen.id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4')
					FOR XML PATH('Authorisation'), TYPE), 
					(SELECT
						NULLIF(LEFT(adi.DUA_RG37, 2), '') AS "requestedProcedure",
						NULLIF(RIGHT(adi.DUA_RG37, 2), '') AS "previousProcedure",
						(SELECT
							ROW_NUMBER() OVER(ORDER BY t.coluna) AS "sequenceNumber",
							NULLIF(t.desdobramento, '') AS "additionalProcedure"									
						FROM tb_TBL_Desdobramentos AS ddb WITH(NOLOCK)
							UNPIVOT(desdobramento FOR coluna IN (ddb.desdobramento1, ddb.desdobramento2, ddb.desdobramento3, ddb.desdobramento4, ddb.desdobramento5)) AS t
						WHERE t.id = adi.id_desdobramento AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1')
						FOR XML PATH('AdditionalProcedure'), TYPE) 
					FOR XML PATH('Procedure'), TYPE), 			
					(SELECT 				
						NULLIF((ISNULL(adi.PAI_CODI4, '') + ISNULL(adi.CLI_NIF, '')), '') AS "identificationNumber"
					HAVING duc.DUC_ANXB = 'H1' AND ISNULL(adi.CLI_NIF, '') <> ''
					FOR XML PATH('Buyer'), TYPE), 
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME1, '')) AS "name", 				
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA1, '')) AS "streetAndNumber", 
							NULLIF(adi.PAI_CODI3, '') AS "country", 
							NULLIF(adi.FOR_CPOS1, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS1, '')) AS "city"
						FOR XML PATH('Address'), TYPE)
					HAVING duc.DUC_ANXB = 'H1' AND ISNULL(adi.FOR_NOME1, '') <> ''
					FOR XML PATH('Seller'), TYPE), 
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME, '')) AS "name", 				 
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA, '')) AS "streetAndNumber", 
							NULLIF(adi.PAI_CODI, '') AS "country", 
							NULLIF(adi.FOR_CPOS, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS, '')) AS "city"
						FOR XML PATH('Address'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(adi.FOR_NOME, '') <> '' 
					FOR XML PATH('Exporter'), TYPE), 
					(SELECT
						(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE NULLIF(adi.PAI_CO34, '') END) AS "countryOfOrigin", 
						(CASE WHEN duc.DUC_ANXB IN ('H5', 'H6', 'I2') THEN NULL ELSE NULLIF(adi.PAI_CODI5, '') END) AS "countryOfPreferentialOrigin" 
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1') AND (ISNULL(adi.PAI_CO34, '') <> '' OR ISNULL(adi.PAI_CODI5, '') <> '')
					FOR XML PATH('Origin'), TYPE), 
					(SELECT 
						NULLIF(adi.PAI_CODI1, '') AS countryOfDispatch
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(adi.PAI_CODI1, '') <> ''
					FOR XML PATH('CountryOfDispatch'), TYPE),
					(SELECT
						NULLIF(adi.PAI_CODI2, '') AS countryOfDestination, 
						adi.RES_CODI AS "regionOfDestination"				
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
					FOR XML PATH('Destination'), TYPE), 
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.DUA_DESG, '')) AS "descriptionOfGoods", 
						(CASE WHEN duc.DUC_ANXB IN ('H6', 'I2') THEN NULL ELSE NULLIF(adi.APA_CCUS, '') END) AS "CUSCode", 
						(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE NULLIF(adi.DUA_CO39, '') END) AS "quotaOrderNumber", 
						(CASE WHEN duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') THEN NULL ELSE NULLIF(adi.DUA_TMER, '') END) AS "typeOfGoods", 
						(SELECT 
							NULLIF(LEFT(adi.APA_CP33, 6), '') AS "harmonizedSystemSubheadingCode", 
							NULLIF(SUBSTRING(adi.APA_CP33, 7, 2), '') AS "combinedNomenclatureCode", 
							NULLIF(SUBSTRING(adi.APA_CP33, 9, 2), '') AS "taricCode", 
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.DUA_ORDEM) AS "sequenceNumber",
								NULLIF(t.DUA_TARIC, '') AS "taricAdditionalCode"
							FROM (
								SELECT 1 AS DUA_ORDEM, SUBSTRING(adi.APA_CP33, 11, 4) AS DUA_TARIC
								UNION
								SELECT 2, SUBSTRING(adi.APA_CP33, 15, 4)
								UNION
								SELECT 3, SUBSTRING(adi.APA_CP33, 19, 4)								
							) AS t
							WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(t.DUA_TARIC, '') <> '' AND ISNULL(t.DUA_TARIC, '') <> '0000'
							FOR XML PATH('TaricAdditionalCode'), TYPE),
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.DUA_ORDEM) AS "sequenceNumber",
								NULLIF(t.DUA_TARIC, '') AS "nationalAdditionalCode"						
							FROM (
								SELECT 1 AS DUA_ORDEM, adi.DUA_1TAR AS DUA_TARIC
								UNION
								SELECT 2, adi.DUA_2TAR
								UNION
								SELECT 3, adi.DUA_3TAR 
								UNION
								SELECT 4, adi.DUA_4TAR 
								UNION
								SELECT 5, adi.DUA_5TAR 								
							) AS t
							WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(t.DUA_TARIC, '') <> '' AND ISNULL(t.DUA_TARIC, '') <> '0000'
							FOR XML PATH('NationalAdditionalCode'), TYPE)
						HAVING ISNULL(LEFT(adi.DUA_RG37, 2), '') <> '71'
						FOR XML PATH('CommodityCode'), TYPE), 
						(SELECT
							(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'I2') THEN NULL ELSE adi.DUA_ML38 END) AS "netMass", 
							(CASE WHEN duc.DUC_ANXB IN ('H6', 'I2') THEN NULL ELSE NULLIF(adi.DUA_US41, 0) END) AS "supplementaryUnits", 
							(CASE WHEN duc.DUC_ANXB = 'H6' THEN NULL ELSE adi.DUA_MB35 END) AS "grossMass"
						FOR XML PATH('GoodsMeasure'), TYPE), 
						(SELECT 
							CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "itemAmountInvoiced"
						HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'I1', 'I2') 
						FOR XML PATH('InvoiceLine'), TYPE), 
						(SELECT
							CAST(ISNULL((SELECT SUM(ISNULL(DUO_MONT, 0)) FROM PRO_DUOI WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI), 0) AS decimal(18, 2)) AS "totalDutiesAndTaxesAmount", 
							(CASE WHEN duc.DUC_ANXB = 'H5' OR (ISNULL(adi.PRE_CO36, '') = '000' AND ISNULL(LEFT(adi.DUA_RG37, 2), '') = '71') THEN NULL ELSE NULLIF(adi.PRE_CO36, '') END) AS "preference", 							
							(SELECT
								ROW_NUMBER() OVER(ORDER BY aoi.DUO_IMPO) AS "sequenceNumber", 
								NULLIF(aoi.DUO_IMPO, '') AS "taxType", 												
								CAST(SUM(ISNULL(aoi.DUO_MONT, 0)) AS decimal(18, 2)) AS "payableTaxAmount", 
								(SELECT
									ROW_NUMBER() OVER(ORDER BY DUO_CODI) AS "sequenceNumber", 
									CAST((CASE DUO_TIPO WHEN 1 THEN (ISNULL(DUO_TXVL, 0) / 100) ELSE ISNULL(DUO_TXVL, 0) END) AS decimal(18, 3)) AS "taxRate", 
									NULLIF(UME_CODI, '') AS "measurementUnitAndQualifier", 
									(CASE DUO_QTDE WHEN 0 THEN NULL ELSE DUO_QTDE END) AS "quantity", 
									CAST((CASE DUO_QTDE WHEN 0 THEN ISNULL(DUO_BTRI, 0) ELSE NULL END) AS decimal(18, 2)) AS "amount", 
									CAST(ISNULL(DUO_MONT, 0) AS decimal(18, 2)) AS "taxAmount"
								FROM PRO_DUOI WITH(NOLOCK)
								WHERE DUC_EANO = aoi.DUC_EANO AND DUC_PNUM = aoi.DUC_PNUM AND DUA_CODI = aoi.DUA_CODI AND DUO_IMPO = aoi.DUO_IMPO 
								FOR XML PATH('TaxBase'), TYPE) 
							FROM PRO_DUOI AS aoi WITH(NOLOCK)
							WHERE aoi.DUC_EANO = adi.DUC_EANO AND aoi.DUC_PNUM = adi.DUC_PNUM AND aoi.DUA_CODI = adi.DUA_CODI AND ISNULL(aoi.DUO_IMPO, '') <> '' AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
							GROUP BY aoi.DUC_EANO, aoi.DUC_PNUM, aoi.DUA_CODI, aoi.DUO_IMPO							
							FOR XML PATH('DutiesAndTaxes'), TYPE) 
						HAVING duc.DUC_ANXB <> 'H6'
						FOR XML PATH('CalculationOfTaxes'), TYPE), 
						(SELECT
							NULLIF(duc.PAI_MO22, '') AS "currency", 
							CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "amount" 
						HAVING duc.DUC_ANXB = 'H6'
						FOR XML PATH('PostalValue'), TYPE)
					FOR XML PATH('Commodity'), TYPE),
					(SELECT
						ROW_NUMBER() OVER(ORDER BY D31_CODI) AS "sequenceNumber", 
						(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE NULLIF(UME_CODI, '') END) AS "typeOfPackages", 
						(CASE D31_TTVL WHEN 1 THEN NULL ELSE CAST(D31_QNTD AS int) END) AS "numberOfPackages", 
						(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(D31_MARC, '')) END) AS "shippingMarks"
					FROM PRO_DU31 WITH(NOLOCK)
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI
					FOR XML PATH('Packaging'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY apr.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(apr.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type", 				
						umv.UME_CODI AS "typeOfPackages", 
						apr.volumes AS "numberOfPackages", 
						umq.UME_CODI AS "measurementUnitAndQualifier", 
						apr.quantidade AS "quantity", 
						apr.numeroAdicao AS "goodsItemIdentifier" 
					FROM tb_IMP_DeclaracoesAdicoesPrecedentes AS apr WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON apr.id_documento = doc.DOC_IDTY
						INNER JOIN TAB_UMED AS umv WITH(NOLOCK) ON apr.id_unidadeMedidaVolumes = umv.UME_IDTY
						LEFT OUTER JOIN TAB_UMED AS umq WITH(NOLOCK) ON apr.id_unidadeMedidaQualificador = umq.UME_IDTY
					WHERE apr.id_adicao = adi.DUA_IDEN
					FOR XML PATH('PreviousDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ape.id) AS "sequenceNumber", 
						ped.TXM_CODI AS "code", 				
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(numero, '')) AS "text" 				
					FROM tb_IMP_DeclaracoesAdicoesPedidos AS ape WITH(NOLOCK)
						INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ape.id_pedido = ped.TXM_IDTY 					
					WHERE ape.id_adicao = adi.DUA_IDEN
					FOR XML PATH('AdditionalInformation'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ado.DDO_CODI) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ado.DDO_NUME, '')) AS "referenceNumber", 
						NULLIF(ado.DOC_CODI, '') AS "type", 				
						(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE NULLIF(ado.DDO_EEMI, '') END) AS "issuingAuthorityName", 
						NULLIF(ado.UME_CODI, '') AS "measurementUnitAndQualifier", 
						ado.DDO_QTDE AS "quantity", 
						CONVERT(varchar(10), ado.DDO_DINI, 120) AS "dateOfValidity", 
						NULLIF(pai.PAI_PREF, '') AS "currency", 
						ado.DDO_NLIN AS "documentLineItemNumber", 
						CAST(NULLIF(ado.DDO_MONT, 0) AS decimal(18, 2)) AS "amount"
					FROM PRO_DDOC AS ado WITH(NOLOCK) 						
						LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON ado.PAI_CODI = pai.PAI_CODI
					WHERE ado.DUC_EANO = adi.DUC_EANO AND ado.DUC_PNUM = adi.DUC_PNUM AND ado.DUA_CODI = adi.DUA_CODI AND ado.DDO_TIPO = 0
					FOR XML PATH('SupportingDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY DDO_CODI) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DDO_NUME, '')) AS "referenceNumber", 
						NULLIF(DOC_CODI, '') AS "type"				
					FROM PRO_DDOC WITH(NOLOCK) 						
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 2
					FOR XML PATH('AdditionalReference'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY DDO_CODI) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DDO_NUME, '')) AS "referenceNumber", 
						NULLIF(DOC_CODI, '') AS "type"
					FROM PRO_DDOC WITH(NOLOCK) 						
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 1
					FOR XML PATH('TransportDocument'), TYPE), 
					(SELECT 
						(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') THEN NULL ELSE adi.DUA_MAVA END) AS "valuationMethod",
						(SELECT
							ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
							NULLIF(codigo, '') AS "code", 
							montante AS "amount"
						FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK) 		
						WHERE id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H5', 'I1', 'I2')
						FOR XML PATH('AdditionsAndDeductions'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'I1', 'I2')
					FOR XML PATH('CustomsValuation'), TYPE), 
					(SELECT 
						NULLIF(adi.DUA_IAVA, '') AS "valuationIndicators"
					HAVING duc.DUC_ANXB IN ('H1', 'H4', 'H5') AND ISNULL(adi.DUA_IAVA, '') <> '' 
					FOR XML PATH('ValuationAdjustment'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(funcao, '') AS "role", 
						NULLIF(nif, '') AS "VATIdentificationNumber"
					FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais WITH(NOLOCK) 		
					WHERE id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H6', 'I1')
					FOR XML PATH('AdditionalFiscalReference'), TYPE)
				FROM PRO_DUAD AS adi WITH(NOLOCK) 		
				WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
				FOR XML PATH('GoodsShipmentItem'), TYPE)
			FOR XML PATH('GoodsShipment'), TYPE), 
			(SELECT 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.nome, '')) AS "name", 
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.morada, '')) AS "streetAndNumber", 
						NULLIF(pai.PAI_CODI, '') AS "country", 
						NULLIF(dpr.codigoPostal, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.localidade, '')) AS "city"
					FOR XML PATH('Address'), TYPE)
				FROM tb_IMP_DeclaracoesProprietarios AS dpr WITH(NOLOCK) 
					INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dpr.id_pais = pai.PAI_IDTY
				WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('OwnerOfTheGoods'), TYPE), 
				(SELECT
					 NULLIF(duc.DUC_ATLO, '') AS "typeOfLocation", 
					 NULLIF(duc.DUC_AQUA, '') AS "qualifierOfIdentification", 
					 NULLIF(duc.LME_CODI, '') AS "UNLOCODE", 
					 (SELECT
						NULLIF(duc.PAI_CODI3, '') AS "country", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AMOR, '')) AS "streetAndNumber", 						
						NULLIF(duc.DUC_ACPO, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ALOC, '')) AS "city"
					HAVING ISNULL(duc.DUC_AMOR, '') <> ''
					FOR XML PATH('Address'), TYPE)
				HAVING ISNULL(duc.DUC_ATLO, '') <> ''
				FOR XML PATH('FirstPlaceOfUseOrProcessing'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dlt.id) AS "sequenceNumber", 
					NULLIF(dlt.tipo, '') AS "typeOfLocationCode", 
					NULLIF(dlt.qualificador, '') AS "qualifierOfIdentification", 
					NULLIF(lme.LME_CODI, '') AS "UNLOCODE", 
					(SELECT
						NULLIF(pai.PAI_CODI, '') AS "country", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.morada, '')) AS "streetAndNumber", 						
						NULLIF(dlt.codigoPostal, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.localidade, '')) AS "city"
					HAVING ISNULL(dlt.morada, '') <> ''
					FOR XML PATH('Address'), TYPE)
				FROM tb_IMP_DeclaracoesLocaisTransformacao AS dlt WITH(NOLOCK) 
					LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dlt.id_localAutorizado = lme.LME_IDTY
					LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dlt.id_pais = pai.PAI_IDTY
				WHERE dlt.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('PlacesOfProcessingOrUse'), TYPE),
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dea.id) AS "sequenceNumber", 
					NULLIF(ead.EAD_CODI, '') AS "referenceNumber"					
				FROM tb_IMP_DeclaracoesEstancias AS dea WITH(NOLOCK) 
					INNER JOIN TAB_EADU AS ead WITH(NOLOCK) ON dea.id_estancia = ead.EAD_IDTY
				WHERE dea.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('CustomsOfficeOfDischarge'), TYPE), 
				(SELECT 
					duc.DUC_APRZ AS "period", 
					duc.DUC_APPR AS "automaticExtensionIndicator", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ATXT, '')) AS "text"
				HAVING ISNULL(duc.DUC_APRZ, 0) <> 0
				FOR XML PATH('PeriodForDischarge'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpt.id) AS "sequenceNumber", 
					NULLIF(LEFT(dpt.codigoPautal, 8), '') AS "commodityCode", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.designacao, '')) AS "descriptionOfGoods"					
				FROM tb_IMP_DeclaracoesProdutosTransformados AS dpt WITH(NOLOCK) 					
				WHERE dpt.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('ProcessedProducts'), TYPE), 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY dmi.id) AS "sequenceNumber", 
					NULLIF(mid.MIA_CODI, '') AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dmi.descricao, '')) AS "text"					
				FROM tb_IMP_DeclaracoesMeiosIdentificacao AS dmi WITH(NOLOCK) 					
					INNER JOIN TAB_MIAU AS mid WITH(NOLOCK) ON dmi.id_meioIdentificacao = mid.MIA_IDTY
				WHERE dmi.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('IdentificationOfGoods'), TYPE), 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					NULLIF(taxaRendimento, '') AS "RateOfYield"
				FROM tb_IMP_DeclaracoesTaxasRendimento WITH(NOLOCK) 					
				WHERE id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('RateOfYield'), TYPE), 
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
					codigo AS "code", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(texto, '')) AS "text"
				FROM tb_IMP_DeclaracoesCondicoesEconomicas WITH(NOLOCK) 					
				WHERE id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('EconomicConditions'), TYPE), 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AAPR, '')) AS "DetailsOfPlannedActivities", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AIAD, '')) AS "AdditionalInformation", 
				(CASE duc.DUC_ANXB WHEN 'H4' THEN duc.DUC_ACMD ELSE NULL END) AS "CalculationOfTheAmountImportDuty"
			HAVING duc.DUC_ANXB IN ('H3', 'H4')
			FOR XML PATH('AttachedRequest'), TYPE)
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI				
		WHERE duc.DUC_IDTY = @IdDeclaracao
		FOR XML PATH('CC415A'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLCC415A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLCC415A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLCC432A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagemGeraXMLCC432A] @IdDeclaracao int, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem CC432A - Notificação de Apresentação das Mercadorias da Declaração de Importação	
	SET @FicheiroXML = 				
		(SELECT
			(SELECT
				NULLIF(dcl.DEC_WSUS, '') AS "From", 
				'AT' AS "To", 
				CONVERT(varchar(19), @DataAtual, 120) AS "SendingDateAndTime",
				'IMP-CAU' AS "MessageID", 
				'CC432A' AS "MessageType", 
				NULLIF(duc.DUC_NRLO, '') AS "CorrelationID"
			FOR XML PATH('messageHeader'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI, '') AS "importCustomsOffice", 				
				NULLIF(duc.DUC_NRLO, '') AS "LRN"
			FOR XML PATH('ImportOperation'), TYPE),	
			(SELECT
				NULLIF(duc.ALF_CODI3, '') AS "referenceNumber"
			HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
			FOR XML PATH('CustomsOfficePresentation'), TYPE), 
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(duc.DEC_NIF, '')), '') AS "identificationNumber"
			FOR XML PATH('Declarant'), TYPE), 	
			(SELECT 				
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') AS "identificationNumber",
				duc.DUC_TPDC AS "status"			
			HAVING ISNULL(duc.DUC_TPDC, -1) = 2 AND dcl.DEC_TIPO <> 1
			FOR XML PATH('Representative'), TYPE), 																				
			(SELECT 				
				(SELECT
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY t.DUC_CONT) AS "sequenceNumber",
						NULLIF(t.DUC_CONT, '') AS "containerIdentificationNumber", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY DUA_CODI) AS "sequenceNumber", 
							DUA_CODI AS "declarationGoodsItemNumber"
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DCO_CNUM = t.DUC_CONT
						FOR XML PATH('GoodsReference'), TYPE)
					FROM (
						SELECT duc.DUC_CONT
						UNION
						SELECT DCO_CNUM
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
						GROUP BY DCO_CNUM
					) AS t
					WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND ISNULL(t.DUC_CONT, '') <> '' 
					FOR XML PATH('TransportEquipment'), TYPE), 
					(SELECT 
						NULLIF(duc.DUC_TLOC, '') AS "typeOfLocation", 
						NULLIF(duc.DUC_QUAL, '') AS "qualifierOfIdentification", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'U' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "UNLOCODE", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'Y' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
						NULLIF(duc.DUC_IADI, '') AS "additionalIdentifier", 
						(SELECT 
							NULLIF(duc.ALF_CODI1, '') AS "referenceNumber"
						HAVING ISNULL(duc.ALF_CODI1, '') <> ''
						FOR XML PATH('CustomsOffice'), TYPE),				 
						(SELECT 
							NULLIF(duc.DUC_ONIF, '') AS "identificationNumber"
						HAVING ISNULL(duc.DUC_ONIF, '') <> ''
						FOR XML PATH('EconomicOperator'), TYPE),
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LAMO, '')) AS "streetAndNumber", 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LALO, '')) AS "city", 
							'PT' AS "country"					
						HAVING ISNULL(duc.DUC_LAMO, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'Z'				
						FOR XML PATH('Address'), TYPE), 
						(SELECT 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 					
							'PT' AS "country"
						HAVING ISNULL(duc.DUC_LACP, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'T'
						FOR XML PATH('PostcodeAddress'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
					FOR XML PATH('LocationOfGoods'), TYPE)
				FOR XML PATH('Consignment'), TYPE)			
			FOR XML PATH('GoodsShipment'), TYPE)		
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @IdDeclaracao
		FOR XML PATH('CC432A'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLCC432A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLCC432A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLCC433A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagemGeraXMLCC433A] @IdDeclaracao int, @NumeroNRMAnterior varchar(18), @ElementosAlterados varchar(512), @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem CC433A - Notificação de Apresentação EIDR da Declaração de Importação	
	SET @FicheiroXML = 				
		(SELECT
			(SELECT
				NULLIF(dcl.DEC_WSUS, '') AS "From", 
				'AT' AS "To", 
				CONVERT(varchar(19), @DataAtual, 120) AS "SendingDateAndTime",
				'IMP-CAU' AS "MessageID", 
				'CC433A' AS "MessageType", 
				NULLIF(duc.DUC_NRLO, '') AS "CorrelationID"
			FOR XML PATH('messageHeader'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI, '') AS "importCustomsOffice", 				
				NULLIF(duc.DUC_NRLO, '') AS "LRN"
			FOR XML PATH('ImportOperation'), TYPE),	
			(SELECT 
				1 AS "sequenceNumber", 
				NULLIF(duc.DOC_CODI, '') AS "type", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_NRAU, '')) AS "referenceNumber", 
				NULLIF(duc.DUC_EORI, '') AS "holderOfTheAuthorisation"
			HAVING ISNULL(duc.DOC_CODI, '') <> ''
			FOR XML PATH('Authorisation'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI3, '') AS "referenceNumber"
			HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
			FOR XML PATH('CustomsOfficePresentation'), TYPE), 
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(duc.DEC_NIF, '')), '') AS "identificationNumber"
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') AS "identificationNumber",
				duc.DUC_TPDC AS "status"			
			HAVING ISNULL(duc.DUC_TPDC, -1) = 2 AND dcl.DEC_TIPO <> 1
			FOR XML PATH('Representative'), TYPE), 														
			(SELECT 	
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.numero, '')) AS "referenceNumber", 
					doc.DOC_CODI AS "type", 
					(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(dpr.qualificador, '') ELSE NULL END) AS "ccQualifier"
				FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 		
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
				WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY
				FOR XML PATH('PreviousDocument'), TYPE),			
				(SELECT
					ISNULL(duc.DUC_MBRT, 0) AS "grossMass",
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY t.DUC_CONT) AS "sequenceNumber",
						NULLIF(t.DUC_CONT, '') AS "containerIdentificationNumber", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY DUA_CODI) AS "sequenceNumber", 
							DUA_CODI AS "declarationGoodsItemNumber"
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DCO_CNUM = t.DUC_CONT
						FOR XML PATH('GoodsReference'), TYPE)
					FROM (
						SELECT duc.DUC_CONT
						UNION
						SELECT DCO_CNUM
						FROM PRO_DCON WITH(NOLOCK)
						WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
						GROUP BY DCO_CNUM
					) AS t
					WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND ISNULL(t.DUC_CONT, '') <> '' 
					FOR XML PATH('TransportEquipment'), TYPE), 
					(SELECT 
						NULLIF(duc.DUC_TLOC, '') AS "typeOfLocation", 
						NULLIF(duc.DUC_QUAL, '') AS "qualifierOfIdentification", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'U' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "UNLOCODE", 
						(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'Y' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
						NULLIF(duc.DUC_IADI, '') AS "additionalIdentifier", 
						(SELECT 
							NULLIF(duc.ALF_CODI1, '') AS "referenceNumber"
						HAVING ISNULL(duc.ALF_CODI1, '') <> ''
						FOR XML PATH('CustomsOffice'), TYPE),				 
						(SELECT 
							NULLIF(duc.DUC_ONIF, '') AS "identificationNumber"
						HAVING ISNULL(duc.DUC_ONIF, '') <> ''
						FOR XML PATH('EconomicOperator'), TYPE),
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LAMO, '')) AS "streetAndNumber", 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LALO, '')) AS "city", 
							'PT' AS "country"					
						HAVING ISNULL(duc.DUC_LAMO, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'Z'				
						FOR XML PATH('Address'), TYPE), 
						(SELECT 
							NULLIF(duc.DUC_LACP, '') AS "postcode", 					
							'PT' AS "country"
						HAVING ISNULL(duc.DUC_LACP, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'T'
						FOR XML PATH('PostcodeAddress'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
					FOR XML PATH('LocationOfGoods'), TYPE)
				FOR XML PATH('Consignment'), TYPE),
				(SELECT
					ROW_NUMBER() OVER(ORDER BY adi.DUA_CODI) AS "sequenceNumber", 
					adi.DUA_CODI AS "declarationGoodsItemNumber", 					
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY aen.id) AS "sequenceNumber", 
						doc.DOC_CODI AS "type", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(aen.numeroReferencia, '')) AS "referenceNumber", 	
						NULLIF(aen.numeroEORI, '') AS "holderOfTheAuthorisation"			
					FROM tb_IMP_DeclaracoesAdicoesEntrepostos AS aen WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON aen.id_documento = doc.DOC_IDTY
					WHERE aen.id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4')
					FOR XML PATH('Authorisation'), TYPE), 
					(SELECT
						NULLIF(LEFT(adi.DUA_RG37, 2), '') AS "requestedProcedure",
						NULLIF(RIGHT(adi.DUA_RG37, 2), '') AS "previousProcedure"
					FOR XML PATH('Procedure'), TYPE), 																							
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.DUA_DESG, '')) AS "descriptionOfGoods", 
						adi.DUA_MB35 AS "grossMass"						 						
					FOR XML PATH('Commodity'), TYPE),
					(SELECT
						ROW_NUMBER() OVER(ORDER BY D31_CODI) AS "sequenceNumber", 
						(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE NULLIF(UME_CODI, '') END) AS "typeOfPackages", 
						(CASE D31_TTVL WHEN 1 THEN NULL ELSE CAST(D31_QNTD AS int) END) AS "numberOfPackages", 
						(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(D31_MARC, '')) END) AS "shippingMarks"
					FROM PRO_DU31 WITH(NOLOCK)
					WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI
					FOR XML PATH('Packaging'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY apr.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(apr.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type", 				
						umv.UME_CODI AS "typeOfPackages", 
						apr.volumes AS "numberOfPackages", 
						umq.UME_CODI AS "measurementUnitAndQualifier", 
						apr.quantidade AS "quantity", 
						apr.numeroAdicao AS "goodsItemIdentifier" 
					FROM tb_IMP_DeclaracoesAdicoesPrecedentes AS apr WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON apr.id_documento = doc.DOC_IDTY
						INNER JOIN TAB_UMED AS umv WITH(NOLOCK) ON apr.id_unidadeMedidaVolumes = umv.UME_IDTY
						LEFT OUTER JOIN TAB_UMED AS umq WITH(NOLOCK) ON apr.id_unidadeMedidaQualificador = umq.UME_IDTY
					WHERE apr.id_adicao = adi.DUA_IDEN
					FOR XML PATH('PreviousDocument'), TYPE)
				FROM PRO_DUAD AS adi WITH(NOLOCK) 		
				WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
				FOR XML PATH('GoodsShipmentItem'), TYPE)
			FOR XML PATH('GoodsShipment'), TYPE), 
			(SELECT 
				NULLIF(@NumeroNRMAnterior, '') AS "MRNOfPreviousNotification", 
				NULLIF(@ElementosAlterados, '') AS "changedElements"
			HAVING ISNULL(@NumeroNRMAnterior, '') <> '' 
			FOR XML PATH('declarationAmendments'), TYPE)	
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @IdDeclaracao
		FOR XML PATH('CC433A'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLCC433A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLCC433A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLCC446A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagemGeraXMLCC446A] @IdDeclaracao int, @XMLDocumentos xml, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem CC446A - Entrega de Documentos da Declaração de Importação	
	SET @FicheiroXML = 				
		(SELECT
			(SELECT
				NULLIF(dcl.DEC_WSUS, '') AS "From", 
				'AT' AS "To", 
				CONVERT(varchar(19), @DataAtual, 120) AS "SendingDateAndTime",
				'IMP-CAU' AS "MessageID", 
				'CC446A' AS "MessageType", 
				NULLIF(duc.DUC_NRLO, '') AS "CorrelationID"
			FOR XML PATH('messageHeader'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI, '') AS "importCustomsOffice", 				
				NULLIF(duc.DUC_NRLO, '') AS "LRN", 				
				NULLIF(duc.DUC_NORD, '') AS "MRN", 				
				(CASE WHEN EXISTS(SELECT 1 FROM @XMLDocumentos.nodes('documentosAEnviar/documento') AS t(c)) THEN 1 ELSE 0 END) AS "documentsAvailable"
			FOR XML PATH('ImportOperation'), TYPE),												
			(SELECT 
				ROW_NUMBER() OVER(ORDER BY t.adicao, t.id) AS "sequenceNumber", 
				t.DOC_CODI AS "type", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(t.numero, '')) AS "referenceNumber", 
				dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(t.descricao, '')) AS "description", 
				(SELECT
					ROW_NUMBER() OVER(ORDER BY f.c.value('nome[1]', 'varchar(200)')) AS "sequenceNumber",
					NULLIF(UPPER(SUBSTRING(f.c.value('nome[1]', 'varchar(200)'), (CHARINDEX('.', f.c.value('nome[1]', 'varchar(200)')) + 1), (LEN(f.c.value('nome[1]', 'varchar(200)')) - CHARINDEX('.', f.c.value('nome[1]', 'varchar(200)'))))), '') AS "fileType", 
					NULLIF(f.c.value('base64[1]', 'varchar(MAX)'), '') AS "documentImage"
				FROM @XMLDocumentos.nodes('documentosAEnviar/documento/ficheiro') AS f(c)
				WHERE ISNULL(f.c.value('../adicao[1]', 'int'), 0) = t.adicao AND f.c.value('../id[1]', 'bigint') = t.id
				FOR XML PATH('DocumentsImage'), TYPE)
			FROM (SELECT 0 AS adicao, ddo.id, ddo.numero, doc.DOC_CODI, t.c.value('descricao[1]', 'varchar(512)') AS descricao
				FROM @XMLDocumentos.nodes('documentosAEnviar/documento') AS t(c)
					INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON t.c.value('id[1]', 'bigint') = ddo.id
					INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				WHERE t.c.value('adicao[1]', 'int') IS NULL
				UNION ALL
				SELECT dad.DUA_CODI AS adicao, dad.DDO_IDEN, dad.DDO_NUME, dad.DOC_CODI, t.c.value('descricao[1]', 'varchar(512)') AS descricao
				FROM @XMLDocumentos.nodes('documentosAEnviar/documento') AS t(c)
					INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON t.c.value('id[1]', 'bigint') = dad.DDO_IDEN	
				WHERE t.c.value('adicao[1]', 'int') IS NOT NULL) AS t
			FOR XML PATH('RequestedDocuments'), TYPE)		
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @IdDeclaracao
		FOR XML PATH('CC446A'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLCC446A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLCC446A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLDocsAnexos]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagemGeraXMLDocsAnexos] @IdDeclaracao int, @DocsAnexosXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- constroi XML para lista XML de documentos anexos às mensagens XML CC415A (Criação da declaração), CC413A (Alteração da declaração) e PT498A (Resposta à AT)
	SELECT @DocsAnexosXML = 
		(SELECT
			t.codigo AS "codigo",
			CAST('' AS XML).value('xs:base64Binary(sql:column("t.ficheiro"))', 'varchar(MAX)') AS "conteudoFicheiro"
		FROM (SELECT doc.DOC_CODI AS codigo, ddo.ficheiro 
			FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK)
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
			WHERE ddo.id_declaracaoIMP = @IdDeclaracao AND ddo.ficheiro IS NOT NULL
			UNION ALL
			SELECT dpe.TXM_CODI AS codigo, dpe.DPD_FICH AS ficheiro
			FROM PRO_DUPD AS dpe WITH(NOLOCK)
				INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON dpe.DUC_EANO = ddg.DUC_EANO AND dpe.DUC_PNUM = ddg.DUC_PNUM
			WHERE ddg.DUC_IDTY = @IdDeclaracao AND dpe.DPD_FICH IS NOT NULL
			UNION ALL
			SELECT dad.DOC_CODI AS codigo, dad.DDO_FICH AS ficheiro
			FROM PRO_DDOC AS dad WITH(NOLOCK)
				INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON dad.DUC_EANO = ddg.DUC_EANO AND dad.DUC_PNUM = ddg.DUC_PNUM
			WHERE ddg.DUC_IDTY = @IdDeclaracao AND dad.DDO_FICH IS NOT NULL
			UNION ALL
			SELECT ped.TXM_CODI AS codigo, dap.ficheiro 
			FROM tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK)
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dap.id_pedido = ped.TXM_IDTY
				INNER JOIN PRO_DUAD AS dai WITH(NOLOCK) ON dap.id_adicao = dai.DUA_IDEN
				INNER JOIN PRO_DUCG AS ddg WITH(NOLOCK) ON dai.DUC_EANO = ddg.DUC_EANO AND dai.DUC_PNUM = ddg.DUC_PNUM
			WHERE ddg.DUC_IDTY = @IdDeclaracao AND dap.ficheiro IS NOT NULL
		) AS t
		FOR XML PATH('documento'), ROOT('listaDocumentos'), TYPE)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLDocsAnexos] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLDocsAnexos] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagemGeraXMLPT498A]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagemGeraXMLPT498A] @IdDeclaracao int, @Indicador varchar(1), @Justificacao varchar(2000), @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- constroi XML para ficheiro XML da mensagem PT498A - Resposta à AT da Declaração de Importação	
	SET @FicheiroXML = 				
		(SELECT
			(SELECT
				NULLIF(dcl.DEC_WSUS, '') AS "From", 
				'AT' AS "To", 
				CONVERT(varchar(19), @DataAtual, 120) AS "SendingDateAndTime",
				'IMP-CAU' AS "MessageID", 
				'PT498A' AS "MessageType", 
				NULLIF(duc.DUC_NRLO, '') AS "CorrelationID"
			FOR XML PATH('messageHeader'), TYPE),
			(SELECT
				NULLIF(duc.ALF_CODI, '') AS "importCustomsOffice", 				
				NULLIF(duc.DUC_NRLO, '') AS "LRN",
				NULLIF(duc.DUC_NORD, '') AS "MRN",
				(CASE duc.DUC_DCEN WHEN 1 THEN 'PT' ELSE NULL END) AS "languageCode", 
				(CASE duc.DUC_ANXB WHEN 'H6' THEN 1 ELSE NULL END) AS "h6Indicator"
			FOR XML PATH('ImportOperation'), TYPE),	
			(SELECT 
				NULLIF(duc.ALF_CODI4, '') AS "referenceNumber"
			HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'I2')
			FOR XML PATH('SupervisingCustomsOffice'), TYPE), 
			(SELECT 		
				NULLIF((ISNULL(dcl.PAI_CODI, '') + NULLIF(duc.DEC_NIF, '')), '') AS "identificationNumber"
			FOR XML PATH('Declarant'), TYPE), 				
			(SELECT 				
				NULLIF((ISNULL(dcl.PAI_CODI, '') + ISNULL(duc.DEC_NIF, '')), '') AS "identificationNumber",
				duc.DUC_TPDC AS "status"			
			HAVING ISNULL(duc.DUC_TPDC, -1) = 2 AND dcl.DEC_TIPO <> 1
			FOR XML PATH('Representative'), TYPE), 	
			(SELECT 		
				('2' + NULLIF(RIGHT(duc.DUC_CJUS, 3), '')) AS "functionCode"
			FOR XML PATH('Function'), TYPE), 		
			(SELECT 		
				@Indicador AS "indicator",
				NULLIF(@Justificacao, '') AS "justification", 
				CONVERT(varchar(10), @DataAtual, 120) AS "responseDate"
			FOR XML PATH('Response'), TYPE),												
			(SELECT 
				NULLIF(duc.TDE_1CAS, '') AS "declarationType", 
				NULLIF(duc.TDE_2CAS, '') AS "additionalDeclarationType", 	
				(SELECT 
					1 AS "sequenceNumber", 
					NULLIF(duc.DOC_CODI, '') AS "type", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_NRAU, '')) AS "referenceNumber", 
					NULLIF(duc.DUC_EORI, '') AS "holderOfTheAuthorisation"
				HAVING ISNULL(duc.DOC_CODI, '') <> ''
				FOR XML PATH('Authorisation'), TYPE), 
				(SELECT
					NULLIF(duc.ALF_CODI3, '') AS "referenceNumber"
				HAVING duc.DUC_DCEN = 1 AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
				FOR XML PATH('CustomsOfficePresentation'), TYPE), 
				(SELECT 
					(CASE WHEN duc.DUC_TPDS IN (0, 1, 6) THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DNOM, '')) END) AS "name", 
					NULLIF((ISNULL(duc.PAI_DLIV, '') + ISNULL(duc.DUC_DNIF, '')), '') AS "identificationNumber", 		
					(SELECT
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DMOR, '')) AS "streetAndNumber", 
						NULLIF(duc.PAI_DLIV, '') AS "country", 
						NULLIF(duc.DUC_DCPO, '') AS "postcode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DLOC, '')) AS "city"
					HAVING duc.DUC_TPDS NOT IN (0, 1, 6)
					FOR XML PATH('Address'), TYPE)				
				FOR XML PATH('Importer'), TYPE), 
				(SELECT 							
					(SELECT TOP 1 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DCR_NOME, '')) AS "name", 
						NULLIF(DCR_TELE, '') AS "phoneNumber", 
						NULLIF(DCR_EMAI, '') AS "eMailAddress"
					FROM TAB_DECR WITH(NOLOCK)
					WHERE DEC_CODI = duc.DEC_CO14 AND DCR_TIPO = 0 AND (ISNULL(EAD_CODI, '') = '' OR EAD_CODI = duc.ALF_CODI)
					FOR XML PATH('ContactPerson'), TYPE)
				FOR XML PATH('Declarant'), TYPE), 					
				(SELECT 
					ROW_NUMBER() OVER(ORDER BY oim.DUO_CTIP) AS "sequenceNumber", 
					NULLIF(oim.DUO_CTIP, '') AS "guaranteeType", 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY soi.DUO_CAUC, soi.ALF_CODI, soi.DUO_CORF) AS "sequenceNumber", 			
						(CASE ISNULL(soi.DUO_CORF, '') WHEN '' THEN NULLIF(soi.DUO_CAUC, '') ELSE NULL END) AS "GRN", 
						'EUR' AS "currencyCode", 
						SUM(ISNULL(soi.DUO_MONT, 0)) AS "amountToBeCovered", 
						(SELECT
							NULLIF(soi.ALF_CODI, '') AS "referenceNumber"
						HAVING ISNULL(soi.ALF_CODI, '') <> ''
						FOR XML PATH('CustomsOfficeOfGuarantee'), TYPE), 
						NULLIF(soi.DUO_CORF, '') AS "otherGuaranteeReference"
					FROM PRO_DUOI AS soi WITH(NOLOCK) 
						INNER JOIN TAB_RREC AS srr WITH(NOLOCK) ON soi.RRE_CODI = srr.RRE_CODI
					WHERE soi.DUC_EANO = duc.DUC_EANO AND soi.DUC_PNUM = duc.DUC_PNUM AND ISNULL(soi.DUO_CTIP, '') = ISNULL(oim.DUO_CTIP, '') AND srr.RRE_DPOT = 1
					GROUP BY soi.DUO_CAUC, soi.ALF_CODI, soi.DUO_CORF
					FOR XML PATH('GuaranteeReference'), TYPE)
				FROM PRO_DUOI AS oim WITH(NOLOCK) 
					INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON oim.RRE_CODI = rre.RRE_CODI
				WHERE oim.DUC_EANO = duc.DUC_EANO AND oim.DUC_PNUM = duc.DUC_PNUM AND ISNULL(oim.DUO_CTIP, '') <> '' AND rre.RRE_DPOT = 1 AND duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H6')
				GROUP BY oim.DUO_CTIP
				FOR XML PATH('Guarantee'), TYPE), 
				(SELECT 
					1 AS "sequenceNumber", 
					NULLIF(duc.DUC_CAUC, '') AS "deferredPayment"				
				HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H6') AND duc.DUC_CGLB = 1 AND ISNULL(duc.DUC_CAUC, '') <> ''
				FOR XML PATH('DeferredPayment'), TYPE), 
				(SELECT 
					(CASE 
						WHEN (ISNULL(duc.DUC_FRET, 0) > 0) AND (ISNULL(duc.DUC_SEGU, 0) = 0) THEN NULLIF(duc.PAI_MOFT, '')
						WHEN (ISNULL(duc.DUC_FRET, 0) = 0) AND (ISNULL(duc.DUC_SEGU, 0) > 0) THEN NULLIF(duc.PAI_MOSG, '')
						WHEN (ISNULL(duc.PAI_FRET, '') = ISNULL(duc.PAI_SEGU, '')) THEN NULLIF(duc.PAI_MOFT, '')
						ELSE 'EUR'
					END) AS "currency", 
					(CASE 
						WHEN (ISNULL(duc.DUC_FRET, 0) > 0) AND (ISNULL(duc.DUC_SEGU, 0) = 0) THEN ISNULL(duc.DUC_FRET, 0)
						WHEN (ISNULL(duc.DUC_FRET, 0) = 0) AND (ISNULL(duc.DUC_SEGU, 0) > 0) THEN ISNULL(duc.DUC_SEGU, 0)
						WHEN (ISNULL(duc.PAI_FRET, '') = ISNULL(duc.PAI_SEGU, '')) THEN (ISNULL(duc.DUC_FRET, 0) + ISNULL(duc.DUC_SEGU, 0))
						ELSE (ROUND(ISNULL(duc.DUC_FRET, 0) / ISNULL(duc.DUC_TXFR, 0), 2) + ROUND(ISNULL(duc.DUC_SEGU, 0) / ISNULL(duc.DUC_TXSE, 0), 2))
					END) AS "amount"
				HAVING duc.DUC_ANXB = 'H6'
				FOR XML PATH('PostalCharges'), TYPE), 
				(SELECT		
					(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6') THEN NULL ELSE NULLIF(duc.PAI_MO22, '') END) AS "invoiceCurrency", 
					(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6') THEN NULL ELSE ISNULL(duc.DUC_MT22, 0) END) AS "totalAmountInvoiced", 
					(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(duc.NTR_CO24, '') END) AS "natureOfTransaction", 
					(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') OR duc.TDE_2CAS NOT IN ('U', 'V', 'X', 'Y', 'Z') THEN NULL ELSE CONVERT(varchar(10), duc.DUC_NDAT, 120) END) AS "acceptanceDate", 		
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(funcao, '') AS "role", 
						NULLIF(nif, '') AS "identificationNumber"
					FROM tb_IMP_DeclaracoesIntervenientes WITH(NOLOCK) 		
					WHERE id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('AdditionalSupplyChainActor'), TYPE),
					(SELECT 			
						NULLIF((ISNULL(duc.PAI_CODI1, '') + ISNULL(duc.CLI_NIF, '')), '') AS "identificationNumber" 
					HAVING duc.DUC_ANXB = 'H1' AND ISNULL(duc.CLI_NIF, '') <> ''
					FOR XML PATH('Buyer'), TYPE), 
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_NOME, '')) AS "name", 			
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_MORA, '')) AS "streetAndNumber", 
							NULLIF(duc.PAI_CODI, '') AS "country", 
							NULLIF(duc.FOR_CPOS, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.FOR_LPOS, '')) AS "city"
						FOR XML PATH('Address'), TYPE)
					HAVING duc.DUC_ANXB = 'H1' AND ISNULL(duc.FOR_NOME, '') <> ''			
					FOR XML PATH('Seller'), TYPE), 
					(SELECT 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ENOM, '')) AS "name", 			
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_EMOR, '')) AS "streetAndNumber", 
							NULLIF(duc.PAI_ELIV, '') AS "country", 
							NULLIF(duc.DUC_ECPO, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ELPO, '')) AS "city"
						FOR XML PATH('Address'), TYPE)
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(duc.DUC_ENOM, '') <> ''
					FOR XML PATH('Exporter'), TYPE), 
					(SELECT
						NULLIF(duc.CEN_CO20, '') AS "incotermCode", 
						NULLIF(duc.PAE_CODI, '') AS "UNLOCODE", 
						NULLIF(duc.PAI_CODI2, '') AS "country", 					
						(CASE ISNULL(duc.CEN_CO20, '') WHEN 'XXX' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DE20, '')) END) AS "location",
						(CASE ISNULL(duc.CEN_CO20, '') WHEN 'XXX' THEN dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_DE20, '')) ELSE NULL END) AS "text"
					HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C')
					FOR XML PATH('DeliveryTerms'), TYPE), 
					(SELECT 
						NULLIF(duc.PAI_PA15, '') AS countryOfDispatch
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(duc.PAI_PA15, '') <> ''
					FOR XML PATH('CountryOfDispatch'), TYPE),
					(SELECT
						NULLIF(duc.PAI_PA17, '') AS countryOfDestination, 
						(CASE WHEN duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE duc.PAI_P17B END) AS "regionOfDestination"			
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
					FOR XML PATH('Destination'), TYPE), 
					(SELECT
						NULLIF(duc.TAR_CODI, '') AS "type", 
						NULLIF(duc.ARM_CODI, '') AS "identifier"
					HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND duc.TDE_2CAS NOT IN ('B', 'C') AND ISNULL(duc.TAR_CODI, '') <> ''
					FOR XML PATH('Warehouse'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type", 
						(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(dpr.qualificador, '') ELSE NULL END) AS "ccQualifier"
					FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
					WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('PreviousDocument'), TYPE), 		
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY DPD_CODI) AS "sequenceNumber", 
						NULLIF(TXM_CODI, '') AS "code", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DPD_DESC, '')) AS "text", 
						(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(DPD_QUAL, '') ELSE NULL END) AS "ccQualifier" 
					FROM PRO_DUPD WITH(NOLOCK) 					
					WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
					FOR XML PATH('AdditionalInformation'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type", 
						(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(ddo.qualificador, '') ELSE NULL END) AS "ccQualifier", 
						(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.entidadeEmissora, '')) END) AS "issuingAuthorityName", 			
						CONVERT(varchar(10), ddo.dataValidade, 120) AS "dateOfValidity"			
					FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 0 
					FOR XML PATH('SupportingDocument'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
						doc.DOC_CODI AS "type", 
						(CASE duc.DUC_DCEN WHEN 1 THEN NULLIF(ddo.qualificador, '') ELSE NULL END) AS "ccQualifier" 
					FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
						INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
					WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 2
					FOR XML PATH('AdditionalReference'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(codigo, '') AS "code", 
						montante AS "amount"
					FROM tb_IMP_DeclaracoesAcrescimosDeducoes WITH(NOLOCK) 		
					WHERE id_declaracaoIMP = duc.DUC_IDTY AND duc.DUC_ANXB IN ('H1', 'H5', 'I1', 'I2')
					FOR XML PATH('AdditionsAndDeductions'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(funcao, '') AS "role", 
						NULLIF(nif, '') AS "VATIdentificationNumber"
					FROM tb_IMP_DeclaracoesReferenciasFiscais WITH(NOLOCK) 		
					WHERE id_declaracaoIMP = duc.DUC_IDTY AND duc.DUC_ANXB IN ('H1', 'H6', 'I1')
					FOR XML PATH('AdditionalFiscalReference'), TYPE), 
					(SELECT
						(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_REF7, '')) END) AS "referenceNumberUCR", 
						(CASE WHEN duc.DUC_ANXB IN ('H5', 'H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE duc.DUC_CT19 END) AS "containerIndicator", 
						(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(LEFT(duc.MTR_FT21, 1), '') END) AS "modeOfTransportAtTheBorder", 
						(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') OR duc.TDE_2CAS IN ('B', 'C', 'E', 'F') THEN NULL ELSE NULLIF(LEFT(duc.MTR_CODI, 1), '') END) AS "inlandModeOfTransport", 
						ISNULL(duc.DUC_MBRT, 0) AS "grossMass", 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY t.DUC_CONT) AS "sequenceNumber",
							NULLIF(t.DUC_CONT, '') AS "containerIdentificationNumber", 
							(SELECT 
								ROW_NUMBER() OVER(ORDER BY DUA_CODI) AS "sequenceNumber", 
								DUA_CODI AS "declarationGoodsItemNumber"
							FROM PRO_DCON WITH(NOLOCK)
							WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM AND DCO_CNUM = t.DUC_CONT
							FOR XML PATH('GoodsReference'), TYPE)
						FROM (
							SELECT duc.DUC_CONT
							UNION
							SELECT DCO_CNUM
							FROM PRO_DCON WITH(NOLOCK)
							WHERE DUC_EANO = duc.DUC_EANO AND DUC_PNUM = duc.DUC_PNUM
							GROUP BY DCO_CNUM
						) AS t
						WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') AND duc.TDE_2CAS NOT IN ('B', 'C', 'E', 'F') AND ISNULL(t.DUC_CONT, '') <> '' 
						FOR XML PATH('TransportEquipment'), TYPE),
						(SELECT 
							NULLIF(duc.DUC_TLOC, '') AS "typeOfLocation", 
							NULLIF(duc.DUC_QUAL, '') AS "qualifierOfIdentification", 
							(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'U' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "UNLOCODE", 
							(CASE ISNULL(duc.DUC_QUAL, '') WHEN 'Y' THEN NULLIF(duc.LME_CO30, '') ELSE NULL END) AS "authorisationNumber", 
							NULLIF(duc.DUC_IADI, '') AS "additionalIdentifier", 
							(SELECT 
								NULLIF(duc.ALF_CODI1, '') AS "referenceNumber"
							HAVING ISNULL(duc.ALF_CODI1, '') <> ''
							FOR XML PATH('CustomsOffice'), TYPE),				 
							(SELECT 
								NULLIF(duc.DUC_ONIF, '') AS "identificationNumber"
							HAVING ISNULL(duc.DUC_ONIF, '') <> ''
							FOR XML PATH('EconomicOperator'), TYPE),
							(SELECT
								dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LAMO, '')) AS "streetAndNumber", 
								NULLIF(duc.DUC_LACP, '') AS "postcode", 
								dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_LALO, '')) AS "city", 
								'PT' AS "country"					
							HAVING ISNULL(duc.DUC_LAMO, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'Z'				
							FOR XML PATH('Address'), TYPE), 
							(SELECT 
								NULLIF(duc.DUC_LACP, '') AS "postcode", 					
								'PT' AS "country"
							HAVING ISNULL(duc.DUC_LACP, '') <> '' AND ISNULL(duc.DUC_QUAL, '') = 'T'
							FOR XML PATH('PostcodeAddress'), TYPE)
						HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2')
						FOR XML PATH('LocationOfGoods'), TYPE), 
						(SELECT 
							duc.MTR_TIPO AS "typeOfIdentification", 
							NULLIF(duc.DUC_MT18, '') AS "identificationNumber" 
						HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C') AND duc.MTR_TIPO IS NOT NULL
						FOR XML PATH('ArrivalTransportMeans'), TYPE), 
						(SELECT
							NULLIF(duc.PAI_PA21, '') AS "nationality"
						HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5') AND duc.TDE_2CAS NOT IN ('B', 'C') AND ISNULL(duc.PAI_PA21, '') <> ''
						FOR XML PATH('ActiveBorderTransportMeans'), TYPE),
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY ddo.id) AS "sequenceNumber", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ddo.numero, '')) AS "referenceNumber", 
							doc.DOC_CODI AS "type"
						FROM tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) 		
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
						WHERE ddo.id_declaracaoIMP = duc.DUC_IDTY AND ddo.tipo = 1
						FOR XML PATH('TransportDocument'), TYPE)
					FOR XML PATH('Consignment'), TYPE), 
					(SELECT
						ROW_NUMBER() OVER(ORDER BY adi.DUA_CODI) AS "sequenceNumber", 
						adi.DUA_CODI AS "declarationGoodsItemNumber", 
						(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') THEN NULL ELSE NULLIF(adi.NTR_CODI, '') END) AS "natureOfTransaction", 
						(CASE WHEN duc.DUC_ANXB IN ('H6', 'I1', 'I2') THEN NULL ELSE CAST(adi.DUA_VEST AS decimal(18, 2)) END) AS "statisticalValue", 
						(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.DUA_NRUR, '')) END) AS "referenceNumberUCR", 			
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY aen.id) AS "sequenceNumber", 
							doc.DOC_CODI AS "type", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(aen.numeroReferencia, '')) AS "referenceNumber", 	
							NULLIF(aen.numeroEORI, '') AS "holderOfTheAuthorisation"			
						FROM tb_IMP_DeclaracoesAdicoesEntrepostos AS aen WITH(NOLOCK) 		
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON aen.id_documento = doc.DOC_IDTY
						WHERE aen.id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4')
						FOR XML PATH('Authorisation'), TYPE), 
						(SELECT
							NULLIF(LEFT(adi.DUA_RG37, 2), '') AS "requestedProcedure",
							NULLIF(RIGHT(adi.DUA_RG37, 2), '') AS "previousProcedure",
							(SELECT
								ROW_NUMBER() OVER(ORDER BY t.coluna) AS "sequenceNumber",
								NULLIF(t.desdobramento, '') AS "additionalProcedure"									
							FROM tb_TBL_Desdobramentos AS ddb WITH(NOLOCK)
								UNPIVOT(desdobramento FOR coluna IN (ddb.desdobramento1, ddb.desdobramento2, ddb.desdobramento3, ddb.desdobramento4, ddb.desdobramento5)) AS t
							WHERE t.id = adi.id_desdobramento AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1')
							FOR XML PATH('AdditionalProcedure'), TYPE) 
						FOR XML PATH('Procedure'), TYPE), 			
						(SELECT 				
							NULLIF((ISNULL(adi.PAI_CODI4, '') + ISNULL(adi.CLI_NIF, '')), '') AS "identificationNumber"
						HAVING duc.DUC_ANXB = 'H1' AND ISNULL(adi.CLI_NIF, '') <> ''
						FOR XML PATH('Buyer'), TYPE), 
						(SELECT 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME1, '')) AS "name", 				
							(SELECT
								dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA1, '')) AS "streetAndNumber", 
								NULLIF(adi.PAI_CODI3, '') AS "country", 
								NULLIF(adi.FOR_CPOS1, '') AS "postcode", 
								dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS1, '')) AS "city"
							FOR XML PATH('Address'), TYPE)
						HAVING duc.DUC_ANXB = 'H1' AND ISNULL(adi.FOR_NOME1, '') <> ''
						FOR XML PATH('Seller'), TYPE), 
						(SELECT 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_NOME, '')) AS "name", 				 
							(SELECT
								dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_MORA, '')) AS "streetAndNumber", 
								NULLIF(adi.PAI_CODI, '') AS "country", 
								NULLIF(adi.FOR_CPOS, '') AS "postcode", 
								dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.FOR_LPOS, '')) AS "city"
							FOR XML PATH('Address'), TYPE)
						HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(adi.FOR_NOME, '') <> '' 
						FOR XML PATH('Exporter'), TYPE), 
						(SELECT
							(CASE duc.DUC_ANXB WHEN 'I2' THEN NULL ELSE NULLIF(adi.PAI_CO34, '') END) AS "countryOfOrigin", 
							(CASE WHEN duc.DUC_ANXB IN ('H5', 'H6', 'I2') THEN NULL ELSE NULLIF(adi.PAI_CODI5, '') END) AS "countryOfPreferentialOrigin" 
						HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(adi.PAI_CO34, '') <> ''
						FOR XML PATH('Origin'), TYPE), 
						(SELECT 
							NULLIF(adi.PAI_CODI1, '') AS countryOfDispatch
						HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(adi.PAI_CODI1, '') <> ''
						FOR XML PATH('CountryOfDispatch'), TYPE),
						(SELECT
							NULLIF(adi.PAI_CODI2, '') AS countryOfDestination, 
							adi.RES_CODI AS "regionOfDestination"				
						HAVING duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
						FOR XML PATH('Destination'), TYPE), 
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(adi.DUA_DESG, '')) AS "descriptionOfGoods", 
							(CASE WHEN duc.DUC_ANXB IN ('H6', 'I2') THEN NULL ELSE NULLIF(adi.APA_CCUS, '') END) AS "CUSCode", 
							(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE NULLIF(adi.DUA_CO39, '') END) AS "quotaOrderNumber", 
							(CASE WHEN duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1', 'I2') THEN NULL ELSE NULLIF(adi.DUA_TMER, '') END) AS "typeOfGoods", 
							(SELECT 
								NULLIF(LEFT(adi.APA_CP33, 6), '') AS "harmonizedSystemSubheadingCode", 
								NULLIF(SUBSTRING(adi.APA_CP33, 7, 2), '') AS "combinedNomenclatureCode", 
								NULLIF(SUBSTRING(adi.APA_CP33, 9, 2), '') AS "taricCode", 
								(SELECT
									ROW_NUMBER() OVER(ORDER BY t.DUA_ORDEM) AS "sequenceNumber",
									NULLIF(t.DUA_TARIC, '') AS "taricAdditionalCode"
								FROM (
									SELECT 1 AS DUA_ORDEM, SUBSTRING(adi.APA_CP33, 11, 4) AS DUA_TARIC
									UNION
									SELECT 2, SUBSTRING(adi.APA_CP33, 15, 4)
									UNION
									SELECT 3, SUBSTRING(adi.APA_CP33, 19, 4) 									
								) AS t
								WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'I1') AND ISNULL(t.DUA_TARIC, '') <> '' AND ISNULL(t.DUA_TARIC, '') <> '0000'
								FOR XML PATH('TaricAdditionalCode'), TYPE),
								(SELECT
									ROW_NUMBER() OVER(ORDER BY t.DUA_ORDEM) AS "sequenceNumber",
									NULLIF(t.DUA_TARIC, '') AS "nationalAdditionalCode"						
								FROM (
									SELECT 1 AS DUA_ORDEM, adi.DUA_1TAR AS DUA_TARIC
									UNION
									SELECT 2, adi.DUA_2TAR
									UNION
									SELECT 3, adi.DUA_3TAR 
									UNION
									SELECT 4, adi.DUA_4TAR 
									UNION
									SELECT 5, adi.DUA_5TAR 								
								) AS t
								WHERE duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'I1') AND ISNULL(t.DUA_TARIC, '') <> '' AND ISNULL(t.DUA_TARIC, '') <> '0000'
								FOR XML PATH('NationalAdditionalCode'), TYPE)
							HAVING ISNULL(LEFT(adi.DUA_RG37, 2), '') <> '71'
							FOR XML PATH('CommodityCode'), TYPE), 
							(SELECT
								(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'I2') THEN NULL ELSE adi.DUA_ML38 END) AS "netMass", 
								(CASE WHEN duc.DUC_ANXB IN ('H6', 'I2') THEN NULL ELSE NULLIF(adi.DUA_US41, 0) END) AS "supplementaryUnits", 
								(CASE WHEN duc.DUC_ANXB = 'H6' THEN NULL ELSE adi.DUA_MB35 END) AS "grossMass"
							FOR XML PATH('GoodsMeasure'), TYPE), 
							(SELECT 
								CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "itemAmountInvoiced"
							HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'I1', 'I2') 
							FOR XML PATH('InvoiceLine'), TYPE), 
							(SELECT
								CAST(ISNULL((SELECT SUM(ISNULL(DUO_MONT, 0)) FROM PRO_DUOI WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI), 0) AS decimal(18, 2)) AS "totalDutiesAndTaxesAmount", 
								(CASE WHEN duc.DUC_ANXB = 'H5' OR ISNULL(adi.PRE_CO36, '') = '000' THEN NULL ELSE NULLIF(adi.PRE_CO36, '') END) AS "preference", 
								(SELECT
									ROW_NUMBER() OVER(ORDER BY aoi.DUO_IMPO) AS "sequenceNumber", 
									NULLIF(aoi.DUO_IMPO, '') AS "taxType", 												
									CAST(SUM(ISNULL(aoi.DUO_MONT, 0)) AS decimal(18, 2)) AS "payableTaxAmount", 
									(SELECT
										ROW_NUMBER() OVER(ORDER BY DUO_CODI) AS "sequenceNumber", 
										CAST((CASE DUO_TIPO WHEN 1 THEN (ISNULL(DUO_TXVL, 0) / 100) ELSE ISNULL(DUO_TXVL, 0) END) AS decimal(18, 3)) AS "taxRate", 
										NULLIF(UME_CODI, '') AS "measurementUnitAndQualifier", 
										(CASE DUO_QTDE WHEN 0 THEN NULL ELSE DUO_QTDE END) AS "quantity", 
										(CASE DUO_QTDE WHEN 0 THEN ISNULL(DUO_BTRI, 0) ELSE NULL END) AS "amount", 
										CAST(ISNULL(DUO_MONT, 0) AS decimal(18, 2)) AS "taxAmount"
									FROM PRO_DUOI WITH(NOLOCK)
									WHERE DUC_EANO = aoi.DUC_EANO AND DUC_PNUM = aoi.DUC_PNUM AND DUA_CODI = aoi.DUA_CODI AND DUO_IMPO = aoi.DUO_IMPO 
									FOR XML PATH('TaxBase'), TYPE) 
								FROM PRO_DUOI AS aoi WITH(NOLOCK)
								WHERE aoi.DUC_EANO = adi.DUC_EANO AND aoi.DUC_PNUM = adi.DUC_PNUM AND aoi.DUA_CODI = adi.DUA_CODI AND ISNULL(aoi.DUO_IMPO, '') <> '' AND duc.DUC_ANXB IN ('H1', 'H2', 'H3', 'H4', 'H5')
								GROUP BY aoi.DUC_EANO, aoi.DUC_PNUM, aoi.DUA_CODI, aoi.DUO_IMPO							
								FOR XML PATH('DutiesAndTaxes'), TYPE) 
							HAVING duc.DUC_ANXB <> 'H6'
							FOR XML PATH('CalculationOfTaxes'), TYPE), 
							(SELECT
								NULLIF(duc.PAI_MO22, '') AS "currency", 
								CAST(adi.DUA_VA42 AS decimal(18, 2)) AS "amount" 
							HAVING duc.DUC_ANXB = 'H6'
							FOR XML PATH('PostalValue'), TYPE)
						FOR XML PATH('Commodity'), TYPE),
						(SELECT
							ROW_NUMBER() OVER(ORDER BY D31_CODI) AS "sequenceNumber", 
							(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE NULLIF(UME_CODI, '') END) AS "typeOfPackages", 
							(CASE D31_TTVL WHEN 1 THEN NULL ELSE CAST(D31_QNTD AS int) END) AS "numberOfPackages", 
							(CASE duc.DUC_ANXB WHEN 'H6' THEN NULL ELSE dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(D31_MARC, '')) END) AS "shippingMarks"
						FROM PRO_DU31 WITH(NOLOCK)
						WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI
						FOR XML PATH('Packaging'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY apr.id) AS "sequenceNumber", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(apr.numero, '')) AS "referenceNumber", 
							doc.DOC_CODI AS "type", 				
							umv.UME_CODI AS "typeOfPackages", 
							apr.volumes AS "numberOfPackages", 
							umq.UME_CODI AS "measurementUnitAndQualifier", 
							apr.quantidade AS "quantity", 
							apr.numeroAdicao AS "goodsItemIdentifier" 
						FROM tb_IMP_DeclaracoesAdicoesPrecedentes AS apr WITH(NOLOCK) 		
							INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON apr.id_documento = doc.DOC_IDTY
							INNER JOIN TAB_UMED AS umv WITH(NOLOCK) ON apr.id_unidadeMedidaVolumes = umv.UME_IDTY
							LEFT OUTER JOIN TAB_UMED AS umq WITH(NOLOCK) ON apr.id_unidadeMedidaQualificador = umq.UME_IDTY
						WHERE apr.id_adicao = adi.DUA_IDEN
						FOR XML PATH('PreviousDocument'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY ape.id) AS "sequenceNumber", 
							ped.TXM_CODI AS "code", 				
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(numero, '')) AS "text" 				
						FROM tb_IMP_DeclaracoesAdicoesPedidos AS ape WITH(NOLOCK)
							INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ape.id_pedido = ped.TXM_IDTY 					
						WHERE ape.id_adicao = adi.DUA_IDEN
						FOR XML PATH('AdditionalInformation'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY ado.DDO_CODI) AS "sequenceNumber", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(ado.DDO_NUME, '')) AS "referenceNumber", 
							NULLIF(ado.DOC_CODI, '') AS "type", 				
							(CASE WHEN duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H5', 'H6', 'I2') THEN NULL ELSE NULLIF(ado.DDO_EEMI, '') END) AS "issuingAuthorityName", 
							NULLIF(ado.UME_CODI, '') AS "measurementUnitAndQualifier", 
							ado.DDO_QTDE AS "quantity", 
							CONVERT(varchar(10), ado.DDO_DINI, 120) AS "dateOfValidity", 
							NULLIF(pai.PAI_PREF, '') AS "currency", 
							ado.DDO_NLIN AS "documentLineItemNumber", 
							CAST(NULLIF(ado.DDO_MONT, 0) AS decimal(18, 2)) AS "amount"
						FROM PRO_DDOC AS ado WITH(NOLOCK) 						
							LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON ado.PAI_CODI = pai.PAI_CODI
						WHERE ado.DUC_EANO = adi.DUC_EANO AND ado.DUC_PNUM = adi.DUC_PNUM AND ado.DUA_CODI = adi.DUA_CODI AND ado.DDO_TIPO = 0
						FOR XML PATH('SupportingDocument'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY DDO_CODI) AS "sequenceNumber", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DDO_NUME, '')) AS "referenceNumber", 
							NULLIF(DOC_CODI, '') AS "type"				
						FROM PRO_DDOC WITH(NOLOCK) 						
						WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 2
						FOR XML PATH('AdditionalReference'), TYPE), 
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY DDO_CODI) AS "sequenceNumber", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(DDO_NUME, '')) AS "referenceNumber", 
							NULLIF(DOC_CODI, '') AS "type"
						FROM PRO_DDOC WITH(NOLOCK) 						
						WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DDO_TIPO = 1
						FOR XML PATH('TransportDocument'), TYPE), 
						(SELECT 
							(CASE WHEN duc.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') THEN NULL ELSE adi.DUA_MAVA END) AS "valuationMethod",
							(SELECT
								ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
								NULLIF(codigo, '') AS "code", 
								montante AS "amount"
							FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK) 		
							WHERE id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H5', 'I1', 'I2')
							FOR XML PATH('AdditionsAndDeductions'), TYPE)
						HAVING duc.DUC_ANXB IN ('H1', 'H3', 'H4', 'H5', 'I1', 'I2')
						FOR XML PATH('CustomsValuation'), TYPE), 
						(SELECT 
							NULLIF(adi.DUA_IAVA, '') AS "valuationIndicators"
						HAVING duc.DUC_ANXB IN ('H1', 'H4', 'H5') AND ISNULL(adi.DUA_IAVA, '') <> '' 
						FOR XML PATH('ValuationAdjustment'), TYPE),
						(SELECT 
							ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
							NULLIF(funcao, '') AS "role", 
							NULLIF(nif, '') AS "VATIdentificationNumber"
						FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais WITH(NOLOCK) 		
						WHERE id_adicao = adi.DUA_IDEN AND duc.DUC_ANXB IN ('H1', 'H6', 'I1')
						FOR XML PATH('AdditionalFiscalReference'), TYPE)
					FROM PRO_DUAD AS adi WITH(NOLOCK) 		
					WHERE adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
					FOR XML PATH('GoodsShipmentItem'), TYPE)
				FOR XML PATH('GoodsShipment'), TYPE), 
				(SELECT 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dpr.id) AS "sequenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.nome, '')) AS "name", 
						(SELECT
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.morada, '')) AS "streetAndNumber", 
							NULLIF(pai.PAI_CODI, '') AS "country", 
							NULLIF(dpr.codigoPostal, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpr.localidade, '')) AS "city"
						FOR XML PATH('Address'), TYPE)
					FROM tb_IMP_DeclaracoesProprietarios AS dpr WITH(NOLOCK) 
						INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dpr.id_pais = pai.PAI_IDTY
					WHERE dpr.id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('OwnerOfTheGoods'), TYPE), 
					(SELECT
						 NULLIF(duc.DUC_ATLO, '') AS "typeOfLocation", 
						 NULLIF(duc.DUC_AQUA, '') AS "qualifierOfIdentification", 
						 NULLIF(duc.LME_CODI, '') AS "UNLOCODE", 
						 (SELECT
							NULLIF(duc.PAI_CODI3, '') AS "country", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AMOR, '')) AS "streetAndNumber", 						
							NULLIF(duc.DUC_ACPO, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ALOC, '')) AS "city"
						HAVING ISNULL(duc.DUC_AMOR, '') <> ''
						FOR XML PATH('Address'), TYPE)
					HAVING ISNULL(duc.DUC_ATLO, '') <> ''
					FOR XML PATH('FirstPlaceOfUseOrProcessing'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dlt.id) AS "sequenceNumber", 
						NULLIF(dlt.tipo, '') AS "typeOfLocationCode", 
						NULLIF(dlt.qualificador, '') AS "qualifierOfIdentification", 
						NULLIF(lme.LME_CODI, '') AS "UNLOCODE", 
						(SELECT
							NULLIF(pai.PAI_CODI, '') AS "country", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.morada, '')) AS "streetAndNumber", 						
							NULLIF(dlt.codigoPostal, '') AS "postcode", 
							dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dlt.localidade, '')) AS "city"
						HAVING ISNULL(dlt.morada, '') <> ''
						FOR XML PATH('Address'), TYPE)
					FROM tb_IMP_DeclaracoesLocaisTransformacao AS dlt WITH(NOLOCK) 
						LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dlt.id_localAutorizado = lme.LME_IDTY
						LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON dlt.id_pais = pai.PAI_IDTY
					WHERE dlt.id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('PlacesOfProcessingOrUse'), TYPE),
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dea.id) AS "sequenceNumber", 
						NULLIF(ead.EAD_CODI, '') AS "referenceNumber"					
					FROM tb_IMP_DeclaracoesEstancias AS dea WITH(NOLOCK) 
						INNER JOIN TAB_EADU AS ead WITH(NOLOCK) ON dea.id_estancia = ead.EAD_IDTY
					WHERE dea.id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('CustomsOfficeOfDischarge'), TYPE), 
					(SELECT 
						duc.DUC_APRZ AS "period", 
						duc.DUC_APPR AS "automaticExtensionIndicator", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_ATXT, '')) AS "text"
					HAVING ISNULL(duc.DUC_APRZ, 0) <> 0
					FOR XML PATH('PeriodForDischarge'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY dpt.id) AS "sequenceNumber", 
						NULLIF(LEFT(dpt.codigoPautal, 8), '') AS "commodityCode", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dpt.designacao, '')) AS "descriptionOfGoods"					
					FROM tb_IMP_DeclaracoesProdutosTransformados AS dpt WITH(NOLOCK) 					
					WHERE dpt.id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('ProcessedProducts'), TYPE), 
					(SELECT
						ROW_NUMBER() OVER(ORDER BY dmi.id) AS "sequenceNumber", 
						NULLIF(mid.MIA_CODI, '') AS "code", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(dmi.descricao, '')) AS "text"					
					FROM tb_IMP_DeclaracoesMeiosIdentificacao AS dmi WITH(NOLOCK) 					
						INNER JOIN TAB_MIAU AS mid WITH(NOLOCK) ON dmi.id_meioIdentificacao = mid.MIA_IDTY
					WHERE dmi.id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('IdentificationOfGoods'), TYPE), 
					(SELECT
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						NULLIF(taxaRendimento, '') AS "RateOfYield"
					FROM tb_IMP_DeclaracoesTaxasRendimento WITH(NOLOCK) 					
					WHERE id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('RateOfYield'), TYPE), 
					(SELECT 
						ROW_NUMBER() OVER(ORDER BY id) AS "sequenceNumber", 
						codigo AS "code", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(texto, '')) AS "text"
					FROM tb_IMP_DeclaracoesCondicoesEconomicas WITH(NOLOCK) 					
					WHERE id_declaracaoIMP = duc.DUC_IDTY
					FOR XML PATH('EconomicConditions'), TYPE), 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AAPR, '')) AS "DetailsOfPlannedActivities", 
					dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(NULLIF(duc.DUC_AIAD, '')) AS "AdditionalInformation", 
					(CASE duc.DUC_ANXB WHEN 'H4' THEN duc.DUC_ACMD ELSE NULL END) AS "CalculationOfTheAmountImportDuty"
				HAVING duc.DUC_ANXB IN ('H3', 'H4')
				FOR XML PATH('AttachedRequest'), TYPE)
			HAVING @Indicador = 0
			FOR XML PATH('Counterproposal'), TYPE)	
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @IdDeclaracao
		FOR XML PATH('PT498A'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagemGeraXMLPT498A] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagemGeraXMLPT498A] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagensObtemResposta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagensObtemResposta] @Ambito tinyint, @Tipo varchar(3), @Id int, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @PassPhrase varchar(50), @DataAtual datetime, @CodUtilizador varchar(30), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), 
		@ProxyPassword varchar(100), @AnoDeclaracao int, @NumDeclaracao int, @NumeroRefLocal varchar(22), @CodTipoDeclaracao varchar(4), @NomeTipoDeclaracao varchar(35), @AutorizacaoSaida bit, 
		@EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), @PathCertificado varchar(250), @PwdCertificado varchar(100), @MensagemSoapAction varchar(250), 
		@PublicKeyCertificadoAT nvarchar(4000), @PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), @RequestXML xml, @Resultado int, 
		@ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX), @RespostaXML xml, @FicheirosXML xml, @MensagemXMLBase64 varchar(MAX), @MensagemXML xml, @TipoMensagem varchar(100), 
		@CodigoOperacao int, @EstadoOperacao varchar(3), @XMLNumeroNRM varchar(25), @XMLDataNRM datetime, @XMLNumeroProvisorio varchar(20), @XMLDataControlo datetime, @XMLCodigoFuncao varchar(6), 
		@XMLNumeroLiquidacao varchar(20), @XMLDataLiquidacao datetime, @XMLDataPagamento datetime, @XMLMontante decimal(18, 2), @NumMensagem int, @NomeFicheiro varchar(100), 
		@FicheiroBinario varbinary(MAX), @IndiceInicial int, @IndiceFinal int
-- inicia variáveis	
	SET @PassPhrase = '16345678901234567'
-- inicia processo de obtenção de respostas da declaração
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações do Proxy Authentication nos Parâmetros de Despachos
		SELECT TOP 1 @ProxyAuthentication = PDE_PRXA, @ProxyServer = ISNULL(PDE_PRXS, ''), @ProxyPort = ISNULL(PDE_PRXP, 0), @ProxyUser = ISNULL(PDE_PRXU, ''), 
			@ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, PDE_PRXW)), '')
		FROM TAB_PDES WITH(NOLOCK)
-- obtem configurações do Webservice no declarante da declaração
		SELECT @AnoDeclaracao = duc.DUC_EANO, @NumDeclaracao = duc.DUC_PNUM, @NumeroRefLocal = duc.DUC_NRLO, @CodTipoDeclaracao = duc.TDE_CODI, @NomeTipoDeclaracao = duc.TDE_NOME, 
			@AutorizacaoSaida = duc.DUC_ASAI, @EnderecoWS = dcl.DEC_WSEP, @LoginWS = dcl.DEC_WSUS, 
			@PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSPW)), @PathCertificado = dcl.DEC_WSPC, 
			@PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSWC))			
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @Id	
-- obtem a chave pública do sistema de autenticação na AT em função se o request é para ambiente de testes ou não (porta 814 = Ambiente de Testes)
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT((CASE WHEN CHARINDEX(':814', @EnderecoWS) > 0 THEN 1 ELSE 0 END))
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- processa obtenção das mensagens de resposta
		IF @Ambito IN (0, 1)
		BEGIN
-- em função do âmbito, assume o respetivo soap action
			IF @Ambito = 0
				SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauObterMensagensNaoEntreguesRequest'				                           
			ELSE
				SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauObterMensagensEntreguesRequest'
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido a enviar à AT		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://net.atos.at.impcau.canalWS/' AS net, 'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							(SELECT 
								(SELECT
									NULLIF(@NumeroRefLocal, '') AS "numeroReferenciaLocal"									
								FOR XML PATH('listaNRLs'), TYPE),
								@Tipo AS "tipo"
							FOR XML PATH('obterMensagensNaoEntreguesInput'), TYPE)	
						HAVING @Ambito = 0 -- Mensagens Não Entregues		
						FOR XML PATH('net:IMPCauObterMensagensNaoEntregues'), TYPE), 
						(SELECT 
							(SELECT 
								NULLIF(@NumeroRefLocal, '') AS "numeroReferenciaLocal",
								@Tipo AS "tipo"
							FOR XML PATH('obterMensagensEntreguesInput'), TYPE)	
						HAVING @Ambito = 1 -- Mensagens Entregues						
						FOR XML PATH('net:IMPCauObterMensagensEntregues'), TYPE)
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)				
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)					
-- em função do âmbito, obtem o resultado "OK"/"NOK" retornados do WS			
			IF @Ambito = 0
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauObterMensagensNaoEntreguesResponse/return') AS t(c)					
								
			END
			ELSE
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauObterMensagensEntreguesResponse/return') AS t(c)										
			END
			IF @FaultCode <> '0'
				RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 4, @FaultMessage)
-- obtem o resultado de sucesso resultante da obtenção dos dados do WS
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)'),
				@FicheirosXML = t.c.query('ficheiroResposta')
			FROM @RespostaXML.nodes('declaracao') AS t(c)							
			IF (@FaultCode <> '100') AND (@FaultCode <> '101')
				RAISERROR('A declaração gerou o erro "%s".', 16, 5, @FaultMessage)	
-- obtem todos os ficheiros de resposta associados à declaração
			DECLARE FicheirosXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT 
					t.c.value('nomeFicheiro[1]', 'varchar(100)'), 
					t.c.value('ficheiro[1]', 'varchar(MAX)')
				FROM @FicheirosXML.nodes('ficheiroResposta') AS t(c)
			OPEN FicheirosXML
			FETCH NEXT FROM FicheirosXML INTO @NomeFicheiro, @MensagemXMLBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN 
				SET @CodigoOperacao = NULL
				SET @EstadoOperacao = NULL
-- converte o Base64 para varbinary e depois para xml
				SET @MensagemXML = CAST('' AS XML).value('xs:base64Binary(sql:variable("@MensagemXMLBase64"))', 'varbinary(max)')					
-- obtem da mensagem xml o nome do elemento root como tipo da mensagem obtida
				SELECT @TipoMensagem = t.c.value('local-name(.)', 'varchar(100)')
				FROM @MensagemXML.nodes('*') AS t(c)
-- atualiza declaração em função da mensagem de resposta obtida
				IF @TipoMensagem = 'CC428A'
				BEGIN
					SET @CodigoOperacao = 6
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem CC428A - Aceitação da Declaração
					SELECT @XMLNumeroProvisorio = NULLIF(t.c.value('(ImportOperation/customsRegistrationNumber)[1]', 'varchar(19)'), ''), 
						@XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), ''),
						@XMLDataNRM = t.c.value('(ImportOperation/declarationAcceptanceDateAndTime)[1]', 'datetime')						
					FROM @MensagemXML.nodes('CC428A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, n.º provisório, n.º NRM e data NRM
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 						
						DUC_NPRO = ISNULL(@XMLNumeroProvisorio, DUC_NPRO), 
						DUC_NORD = ISNULL(@XMLNumeroNRM, DUC_NORD), 
						DUC_NDAT = ISNULL(@XMLDataNRM, DUC_NDAT), 
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC456A'
				BEGIN
					SET @CodigoOperacao = 7
					SET @EstadoOperacao = 'RE' 
-- obtem dados da mensagem CC456A - Rejeição da Declaração
					SELECT @XMLNumeroProvisorio = NULLIF(t.c.value('(ImportOperation/customsRegistrationNumber)[1]', 'varchar(19)'), ''), 
						@XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')					
					FROM @MensagemXML.nodes('CC456A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, n.º provisório e n.º NRM 
					UPDATE PRO_DUCG SET 
						DUC_STAT = (CASE 
										WHEN ISNULL(ISNULL(@XMLNumeroNRM, DUC_NORD), '') <> '' THEN 2 
										WHEN ISNULL(ISNULL(@XMLNumeroProvisorio, DUC_NPRO), '') <> '' AND DUC_ESTO = 'NR' THEN 2 
										ELSE 0 
									END), 
						DUC_ESTO = @EstadoOperacao, 						
						DUC_NPRO = ISNULL(@XMLNumeroProvisorio, DUC_NPRO), 
						DUC_NORD = ISNULL(@XMLNumeroNRM, DUC_NORD), 						
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC426A'
				BEGIN
					SET @CodigoOperacao = 8
					SET @EstadoOperacao = 'NR' 
-- obtem dados da mensagem CC426A - Notificação de Registo da Declaração
					SELECT @XMLNumeroProvisorio = NULLIF(t.c.value('(ImportOperation/customsRegistrationNumber)[1]', 'varchar(19)'), '')
					FROM @MensagemXML.nodes('CC426A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação e n.º provisório 
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 						
						DUC_NPRO = ISNULL(@XMLNumeroProvisorio, DUC_NPRO), 							
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC457A'
				BEGIN
					SET @CodigoOperacao = 9
					SET @EstadoOperacao = 'NR' 
-- obtem dados da mensagem CC457A - Notificação de Registo EIDR da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('CC457A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação e n.º NRM
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 						
						DUC_NORD = ISNULL(@XMLNumeroNRM, DUC_NORD), 							
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC404A'
				BEGIN
					SET @CodigoOperacao = 10
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem CC404A - Aceitação da Alteração da Declaração
					SELECT @XMLNumeroProvisorio = NULLIF(t.c.value('(ImportOperation/customsRegistrationNumber)[1]', 'varchar(19)'), ''), 
						@XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('CC404A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, n.º provisório e n.º NRM 
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 						
						DUC_NPRO = ISNULL(@XMLNumeroProvisorio, DUC_NPRO), 
						DUC_NORD = ISNULL(@XMLNumeroNRM, DUC_NORD), 						
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC460A'
				BEGIN
					SET @CodigoOperacao = 11					
-- obtem dados da mensagem CC460A - Notificação de Controlo da Declaração
					SELECT @EstadoOperacao = (CASE 
												WHEN t.c.value('(ImportOperation/notificationType)[1]', 'int') = 1 THEN 'PDA' 
												WHEN (t.c.value('(ImportOperation/notificationType)[1]', 'int') IN (0, 2)) AND (@AutorizacaoSaida = 1) THEN 'CAP' 
												ELSE 'CA' 
											END), 
						@XMLDataControlo = t.c.value('(ImportOperation/notificationDate)[1]', 'datetime')
					FROM @MensagemXML.nodes('CC460A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, data do controlo e flags de CD e CAP
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 						
						DUC_DTCD = @XMLDataControlo, 
						DUC_CRTD = (CASE WHEN @EstadoOperacao IN ('PDA', 'CA') THEN 1 ELSE DUC_CRTD END), 						
						DUC_CRTA = (CASE @EstadoOperacao WHEN 'CAP' THEN 1 ELSE DUC_CRTA END), 						
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC438A'
				BEGIN
					SET @CodigoOperacao = 12
					SET @EstadoOperacao = 'LED' 
-- obtem dados da mensagem CC438A - Lembrete p/ Envio de Documentos da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('CC438A') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 												
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC444A'
				BEGIN
					SET @CodigoOperacao = 13
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem CC444A - Notificação do Resultado do CF da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), ''), 
						@XMLCodigoFuncao = t.c.value('(Function/functionCode)[1]', 'varchar(6)')
					FROM @MensagemXML.nodes('CC444A') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 
						DUC_CRTF = 1, 	
						DUC_CJUS = @XMLCodigoFuncao, 									
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC447A'
				BEGIN
					SET @CodigoOperacao = 14
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem CC447A - Notificação do Resultado do CD da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('CC447A') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 												
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT499A'
				BEGIN
					SET @CodigoOperacao = 15
					SET @EstadoOperacao = 'ND' 
-- obtem dados da mensagem PT499A - Notificação de Dívida da Declaração
					SELECT @XMLNumeroLiquidacao = NULLIF(t.c.value('(DebtNotification/settlement/settlementNumber)[1]', 'varchar(20)'), ''), 
						@XMLDataLiquidacao = t.c.value('(DebtNotification/settlement/settlementDate)[1]', 'datetime'),
						@XMLDataPagamento = t.c.value('(DebtNotification/settlement/paymentTerm)[1]', 'datetime'),
						@XMLMontante = t.c.value('(DebtNotification/settlement/amount)[1]', 'decimal(18, 2)')
					FROM @MensagemXML.nodes('PT499A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, n.º liquidação, data liquidação, data pagamento e dívida aduaneira
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 	
						DUC_REGL = ISNULL(@XMLNumeroLiquidacao, DUC_REGL), 
						DUC_DTRL = ISNULL(@XMLDataLiquidacao, DUC_DTRL), 
						DUC_DPAG = ISNULL(@XMLDataPagamento, DUC_DPAG), 
						DUC_VLRC = ISNULL(@XMLMontante, DUC_VLRC),											
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC451A'
				BEGIN
					SET @CodigoOperacao = 16
					SET @EstadoOperacao = 'SNA' 
-- obtem dados da mensagem CC451A - Saída Não Autorizada da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('CC451A') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 												
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC429A'
				BEGIN
					SET @CodigoOperacao = 17
					SET @EstadoOperacao = 'AS' 
-- obtem dados da mensagem CC429A - Autorização de Saída da Declaração
					SELECT @XMLDataControlo = t.c.value('(ImportOperation/releaseDate)[1]', 'datetime')
					FROM @MensagemXML.nodes('CC429A') AS t(c)
-- atualiza declaração p/ alteração do status, estado operação, AS, data AS e bloqueio
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 												
						DUC_ASAI = 1, 
						DUC_DTAS = @XMLDataControlo, 
						DUC_BLOQ = (CASE WHEN TDE_2CAS NOT IN ('B', 'C', 'D', 'E', 'F') THEN 1 ELSE 0 END), 						
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC431A'
				BEGIN
					SET @CodigoOperacao = 18
					SET @EstadoOperacao = 'LDC' 
-- obtem dados da mensagem CC431A - Lembrete de Expiração do Prazo DC da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('CC431A') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 												
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'CC410A'
				BEGIN
					SET @CodigoOperacao = 19
					SET @EstadoOperacao = 'AP' 
-- obtem dados da mensagem CC410A - Anulação da Declaração
					SELECT @XMLNumeroNRM = NULLIF(t.c.value('(ImportOperation/MRN)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('CC410A') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_DUCG SET 
						DUC_STAT = 3, 
						DUC_ESTO = @EstadoOperacao, 												
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
				IF @TipoMensagem = 'PT400A'
				BEGIN
					SET @CodigoOperacao = 20
-- obtem o estado da operação atual da declaração (existência de SELECT porque outras mensagens anteriores poderão ter alterado o estado da operação)
					SELECT @EstadoOperacao = DUC_ESTO 
					FROM PRO_DUCG WITH(NOLOCK)
					WHERE DUC_IDTY = @Id
-- obtem dados da mensagem PT400A - Informação Adicional
					SELECT @XMLNumeroProvisorio = NULLIF(t.c.value('(ImportOperation/customsRegistrationNumber)[1]', 'varchar(18)'), '')
					FROM @MensagemXML.nodes('PT400A') AS t(c)
-- atualiza declaração p/ alteração do status e estado operação
					UPDATE PRO_DUCG SET 
						DUC_STAT = 2, 
						DUC_ESTO = @EstadoOperacao, 
						DUC_NPRO = ISNULL(@XMLNumeroProvisorio, DUC_NPRO), 												
						DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual
					WHERE DUC_IDTY = @Id
				END
				ELSE
					SET @CodigoOperacao = 99 --Mensagem desconhecida
-- obtem o próximo número do registo da mensagem da declaração
				SET @NumMensagem = ISNULL((SELECT MAX(DRP_CODI) FROM PRO_DURP WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao), 0) + 1
-- insere no detalhe de mensagens os dados da obtenção da mensagem
				INSERT INTO PRO_DURP(DUC_EANO, DUC_PNUM, DRP_CODI, DRP_FLUX, DRP_DATA, DRP_OPER, DRP_ESTO, TDE_CODI, TDE_NOME, DRP_UTIL, DRP_XPED, DRP_XRES, DRP_SUCE, DRP_NFCH, DRP_CFCH)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumMensagem, 0, @DataAtual, @CodigoOperacao, @EstadoOperacao, @CodTipoDeclaracao, @NomeTipoDeclaracao, @CodUtilizador, 
					@RequestXML, @MensagemXML, 1, @NomeFicheiro, CAST(@MensagemXML AS varbinary(MAX)))	
-- para as mensagens CC460A - Notificação de Controlo e CC438A - Lembrete p/ Envio de Documentos, processa o envio de emails de notificação de controlo para spool de acordo com as configurações
				IF (@TipoMensagem = 'CC460A') OR (@TipoMensagem = 'CC438A')
					EXEC sp_IMP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo @id, @Erro OUTPUT
				FETCH NEXT FROM FicheirosXML INTO @NomeFicheiro, @MensagemXMLBase64
			END
			CLOSE FicheirosXML
			DEALLOCATE FicheirosXML
		END
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- insere no detalhe de mensagens os dados da obtenção da declaração
		IF (@RequestXML IS NOT NULL) AND (ISNULL(@RespostaXML, @ResponseXML) IS NOT NULL)
		BEGIN
-- obtem o próximo número do registo da mensagem da declaração
			SET @NumMensagem = ISNULL((SELECT MAX(DRP_CODI) FROM PRO_DURP WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao), 0) + 1
-- insere no detalhe de mensagens os dados da obtenção da mensagem
			INSERT INTO PRO_DURP(DUC_EANO, DUC_PNUM, DRP_CODI, DRP_FLUX, DRP_DATA, DRP_OPER, DRP_ESTO, TDE_CODI, TDE_NOME, DRP_UTIL, DRP_XPED, DRP_XRES, DRP_SUCE, DRP_NFCH, DRP_CFCH)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumMensagem, 0, @DataAtual, ISNULL(@CodigoOperacao, 99), @EstadoOperacao, @CodTipoDeclaracao, @NomeTipoDeclaracao, 
				@CodUtilizador, @RequestXML, ISNULL(@RespostaXML, @ResponseXML), 0, ISNULL(@NomeFicheiro, 'Erro.xml'), CAST(ISNULL(@RespostaXML, @ResponseXML) AS varbinary(MAX)))							
		END
	END CATCH	
-- processa obtenção dos documentos PDF
	IF @Ambito IN (0, 2)
	BEGIN
-- inicia processo de obtenção de documentos PDF da declaração
		BEGIN TRY	
			SET @FaultCode = NULL
			SET @FaultMessage = NULL
			SET @RespostaXML = NULL
			SET @FicheirosXML = NULL
-- em função do âmbito, assume o respetivo soap action
			IF @Ambito = 0
				SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauObterDocumentosPDFNaoEntreguesRequest'
			ELSE
				SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauObterDocumentosPDFEntreguesRequest'
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido a enviar à AT		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://net.atos.at.impcau.canalWS/' AS net, 'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@PwdWSEncriptada AS "wss:Password",
								@ChvSimetricaEncriptada AS "wss:Nonce",
								@DataSistemaEncriptada AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							(SELECT 
								(SELECT
									NULLIF(@NumeroRefLocal, '') AS "numeroReferenciaLocal"								
								FOR XML PATH('listaNRLs'), TYPE),
								@Tipo AS "tipo"
							FOR XML PATH('obterDocumentosPDFNaoEntreguesInput'), TYPE)
						HAVING @Ambito = 0 -- Documentos PDF Não Entregues
						FOR XML PATH('net:IMPCauObterDocumentosPDFNaoEntregues'), TYPE), 
						(SELECT 
							(SELECT 
								NULLIF(@NumeroRefLocal, '') AS "numeroReferenciaLocal",
								@Tipo AS "tipo"
							FOR XML PATH('obterDocumentosEntreguesInput'), TYPE)
						HAVING @Ambito = 2 -- Documentos PDF Entregues
						FOR XML PATH('net:IMPCauObterDocumentosPDFEntregues'), TYPE)
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)																											
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 6, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 7, @FaultMessage)					
-- em função do âmbito, obtem o resultado "OK"/"NOK" retornados do WS			
			IF @Ambito = 0
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauObterDocumentosPDFNaoEntreguesResponse/return') AS t(c)					
			END
			ELSE
			BEGIN
				;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
				SELECT 
					@FaultCode = t.c.value('(resultadoProcessamento/codigoResultado)[1]', 'nvarchar(100)'), 
					@FaultMessage = t.c.value('(resultadoProcessamento/descricaoResultado)[1]', 'nvarchar(MAX)'),
					@RespostaXML = t.c.query('declaracao')
				FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauObterDocumentosPDFEntreguesResponse/return') AS t(c)					
			END
			IF @FaultCode <> '0'
				RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 8, @FaultMessage)			
-- obtem o resultado de sucesso resultante da obtenção dos dados do WS			
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)'),
				@FicheirosXML = t.c.query('ficheiroResposta')
			FROM @RespostaXML.nodes('declaracao') AS t(c)							
			IF (@FaultCode <> '100') AND (@FaultCode <> '101')
				RAISERROR('A declaração gerou o erro "%s".', 16, 9, @FaultMessage)		
-- obtem todos os ficheiros de resposta associados à declaração
			DECLARE FicheirosPDF CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT t.c.value('nomeFicheiro[1]', 'varchar(200)'), 
					t.c.value('ficheiro[1]', 'varchar(MAX)')
				FROM @FicheirosXML.nodes('ficheiroResposta') AS t(c)
			OPEN FicheirosPDF
			FETCH NEXT FROM FicheirosPDF INTO @NomeFicheiro, @MensagemXMLBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN 							
-- converte o Base64 para varbinary 
				SET @FicheiroBinario = CAST('' AS XML).value('xs:base64Binary(sql:variable("@MensagemXMLBase64"))', 'varbinary(max)')
-- obtem do nome do ficheiro o tipo de mensagem
				IF CHARINDEX('.RLQ.', @NomeFicheiro) > 0
					SET @TipoMensagem = 'PT499A'
				ELSE
					IF CHARINDEX('.AUT.', @NomeFicheiro) > 0
						SET @TipoMensagem = 'CC429A'
					ELSE
						IF CHARINDEX('.ANU.', @NomeFicheiro) > 0
							SET @TipoMensagem = 'CC410A'
						ELSE
							IF CHARINDEX('.IAD.', @NomeFicheiro) > 0
								SET @TipoMensagem = 'PT400A'
							ELSE
								IF CHARINDEX('.TRI.', @NomeFicheiro) > 0
									SET @TipoMensagem = 'CC460A'
								ELSE
								BEGIN
									SET @IndiceInicial = CHARINDEX('.CC', @NomeFicheiro) + 1
									SET @IndiceFinal = CHARINDEX('A.', @NomeFicheiro, @IndiceInicial) + 1
									SET @TipoMensagem = SUBSTRING(@NomeFicheiro, @IndiceInicial, (@IndiceFinal - @IndiceInicial))
									IF ISNULL(@TipoMensagem, '') = ''
										SET @TipoMensagem = 'OUTRO'
								END									
-- insere no detalhe de arquivos o ficheiro obtido 
				INSERT INTO PRO_DUFI(DUC_PNUM, DUC_EANO, DUF_DESC, DUF_DATA, DUF_NOMF, DUF_UTIL, DUF_TMSG, DUF_ORIG, DUF_FICH)
				VALUES(@NumDeclaracao, @AnoDeclaracao, @TipoMensagem, @DataAtual, @NomeFicheiro, @CodUtilizador, @TipoMensagem, 1, @FicheiroBinario)
-- processa o envio de emails dos ficheiros das mensagens de PT499A - Notificação de Dívida e CC429A - Autorização de Saída para spool de acordo com as configurações
				IF (@TipoMensagem = 'PT499A') OR (@TipoMensagem = 'CC429A')
					EXEC sp_IMP_Declaracoes_ProcessaEnvioEmailArquivosResposta @AnoDeclaracao, @NumDeclaracao, @TipoMensagem, @NomeFicheiro, @FicheiroBinario, @Erro OUTPUT
				FETCH NEXT FROM FicheirosPDF INTO @NomeFicheiro, @MensagemXMLBase64
			END
			CLOSE FicheirosPDF
			DEALLOCATE FicheirosPDF
		END TRY
		BEGIN CATCH		
-- constroi mensagem de erro detalhada
			SET @NumErro = 1 
			SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
				+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
				+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
		END CATCH	
	END
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagensObtemResposta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagensObtemResposta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_MensagensSubmetePedido]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_MensagensSubmetePedido] @TipoMensagem varchar(8), @Id int, @Motivo varchar(512), @NumeroNRMAnterior varchar(18), 
	@ElementosAlterados varchar(512), @XMLDocumentos xml, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @PassPhrase varchar(50), @DataAtual datetime, @CodUtilizador varchar(30), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, 
		@ProxyUser varchar(100), @ProxyPassword varchar(100), @AnoDeclaracao int, @NumDeclaracao int, @EstadoOperacaoDeclaracao varchar(3), @CodTipoDeclaracao varchar(4), 
		@NomeTipoDeclaracao varchar(35), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), @PathCertificado varchar(250), @PwdCertificado varchar(100), 
		@ListaDocsAnexosXML xml, @MensagemSoapAction varchar(250), @MensagemXML xml, @MensagemTXT varchar(MAX), @MensagemXMLBinario varbinary(MAX), @MensagemXMLBase64 varchar(MAX), 
		@PublicKeyCertificadoAT nvarchar(4000), @PwdWSEncriptada nvarchar(4000), @DataSistemaEncriptada nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), 
		@RequestXML xml, @Resultado int, @ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX), @NumMensagem int
-- inicia variáveis	
	SET @PassPhrase = '16345678901234567'
-- inicia processo de submissão de pedido da declaração
	BEGIN TRY	
		SET @NumErro = 0
		SET @ListaDocsAnexosXML = NULL
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações do Proxy Authentication nos Parâmetros de Despachos
		SELECT TOP 1 @ProxyAuthentication = PDE_PRXA, @ProxyServer = ISNULL(PDE_PRXS, ''), @ProxyPort = ISNULL(PDE_PRXP, 0), @ProxyUser = ISNULL(PDE_PRXU, ''), 
			@ProxyPassword = ISNULL(CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, PDE_PRXW)), '')
		FROM TAB_PDES WITH(NOLOCK)
-- obtem configurações do Webservice no declarante da declaração
		SELECT @AnoDeclaracao = duc.DUC_EANO, @NumDeclaracao = duc.DUC_PNUM, @EstadoOperacaoDeclaracao = duc.DUC_ESTO, @CodTipoDeclaracao = duc.TDE_CODI, 
			@NomeTipoDeclaracao = duc.TDE_NOME, @EnderecoWS = dcl.DEC_WSEP, @LoginWS = dcl.DEC_WSUS, 
			@PwdWS = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSPW)), @PathCertificado = dcl.DEC_WSPC, 
			@PwdCertificado = CONVERT(varchar(100), DecryptByPassphrase(@PassPhrase, dcl.DEC_WSWC))			
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI	
		WHERE duc.DUC_IDTY = @Id
-- obtem a chave pública do sistema de autenticação na AT em função se o request é para ambiente de testes ou não (porta 814 = Ambiente de Testes)
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT((CASE WHEN CHARINDEX(':814', @EnderecoWS) > 0 THEN 1 ELSE 0 END))
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- constroi o XML de acordo com o tipo de mensagem
		IF @TipoMensagem = 'CC413A' -- Alteração da declaração
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauAlterarDeclaracaoRequest'
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLCC413A @Id, @MensagemXML OUTPUT
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLDocsAnexos @Id, @ListaDocsAnexosXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'CC414A' -- Anulação da declaração
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauAnularDeclaracaoRequest'
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLCC414A @Id, @Motivo, @MensagemXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'CC415A' -- Criação da declaração
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauSubmeterDeclaracaoRequest'
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLCC415A @Id, @MensagemXML OUTPUT
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLDocsAnexos @Id, @ListaDocsAnexosXML OUTPUT
		END
		ELSE		
		IF @TipoMensagem = 'CC432A' -- Notificação de Apresentação das Mercadorias
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauNotificarApresentacaoMercadoriasRequest'
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLCC432A @Id, @MensagemXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'CC433A' -- Notificação de Apresentação EIDR
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauNotificarEIRRequest'
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLCC433A @Id, @NumeroNRMAnterior, @ElementosAlterados, @MensagemXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'CC446A' -- Entrega de documentos
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauEntregarDocumentosRequest'
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLCC446A @Id, @XMLDocumentos, @MensagemXML OUTPUT
		END
		ELSE
		IF @TipoMensagem = 'PT498A' -- Resposta à AT
		BEGIN
			SET @MensagemSoapAction = 'http://net.atos.at.impcau.canalWS/IMPCAUCanalWebService/IMPCauRespostaATRequest'
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLPT498A @Id, @ElementosAlterados, @Motivo, @MensagemXML OUTPUT
			EXEC sp_IMP_Declaracoes_MensagemGeraXMLDocsAnexos @Id, @ListaDocsAnexosXML OUTPUT
		END
-- converte o XML gerado para varbinary e depois para Base64
		SET @MensagemTXT = '<?xml version="1.0" encoding="UTF-8"?>' + CAST(@MensagemXML AS varchar(MAX))
		SET @MensagemXMLBinario = CONVERT(varbinary(MAX), @MensagemTXT) 
		SET @MensagemXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@MensagemXMLBinario"))', 'varchar(MAX)') 
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
		EXEC GIDWIN.dbo.SP_Externo_EncriptarDadosAcessoWS @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @DataSistemaEncriptada OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido ao metodo para enviar mensagem à AT
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://net.atos.at.impcau.canalWS/' AS net, 'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv)		
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT
						(SELECT 
							@LoginWS AS "wss:Username", 
							@PwdWSEncriptada AS "wss:Password",
							@ChvSimetricaEncriptada AS "wss:Nonce",
							@DataSistemaEncriptada AS "wss:Created"
						FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem",
							@ListaDocsAnexosXML
						FOR XML PATH('processaPedidoInput'), TYPE)
					HAVING @TipoMensagem = 'CC413A' -- Alteração da declaração
					FOR XML PATH('net:IMPCauAlterarDeclaracao'), TYPE), 
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem"
						FOR XML PATH('processaMensagemInput'), TYPE)
					HAVING @TipoMensagem = 'CC414A' -- Anulação da declaração
					FOR XML PATH('net:IMPCauAnularDeclaracao'), TYPE), 
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem", 
							@ListaDocsAnexosXML
						FOR XML PATH('processaPedidoInput'), TYPE)
					HAVING @TipoMensagem = 'CC415A' -- Criação da declaração
					FOR XML PATH('net:IMPCauSubmeterDeclaracao'), TYPE), 					
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem"
						FOR XML PATH('processaMensagemInput'), TYPE)
					HAVING @TipoMensagem = 'CC432A' -- Notificação de Apresentação das Mercadorias
					FOR XML PATH('net:IMPCauNotificarApresentacaoMercadorias'), TYPE), 
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem"
						FOR XML PATH('processaMensagemInput'), TYPE)
					HAVING @TipoMensagem = 'CC433A' -- Notificação de Apresentação EIR
					FOR XML PATH('net:IMPCauNotificarEIR'), TYPE), 
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem"
						FOR XML PATH('processaMensagemInput'), TYPE)
					HAVING @TipoMensagem = 'CC446A' -- Entrega de documentos
					FOR XML PATH('net:IMPCauEntregarDocumentos'), TYPE), 
					(SELECT 
						(SELECT 
							@MensagemXMLBase64 AS "mensagem", 
							@ListaDocsAnexosXML
						FOR XML PATH('processaPedidoInput'), TYPE)
					HAVING @TipoMensagem = 'PT498A' -- Resposta à AT
					FOR XML PATH('net:IMPCauRespostaAT'), TYPE)
				FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)				
-- obtem o resultado "OK"/"NOK" retornados do WS
		IF @TipoMensagem = 'CC413A' -- Alteração da declaração
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauAlterarDeclaracaoResponse/return/resultadoProcessamento') AS t(c)
		END
		ELSE
		IF @TipoMensagem = 'CC414A' -- Anulação da declaração
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauAnularDeclaracaoResponse/return/resultadoProcessamento') AS t(c)
		END
		ELSE
		IF @TipoMensagem = 'CC415A' -- Criação da declaração
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauSubmeterDeclaracaoResponse/return/resultadoProcessamento') AS t(c)		
		END
		ELSE		
		IF @TipoMensagem = 'CC432A' -- Notificação de Apresentação das Mercadorias
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauNotificarApresentacaoMercadoriasResponse/return/resultadoProcessamento') AS t(c)
		END
		ELSE
		IF @TipoMensagem = 'CC433A' -- Notificação de Apresentação EIR
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauNotificarEIRResponse/return/resultadoProcessamento') AS t(c)
		END
		ELSE
		IF @TipoMensagem = 'CC446A' -- Entrega de documentos
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauEntregarDocumentosResponse/return/resultadoProcessamento') AS t(c)
		END
		ELSE
		IF @TipoMensagem = 'PT498A' -- Resposta à AT
		BEGIN
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env, 'http://net.atos.at.impcau.canalWS/' AS m)		
			SELECT 
				@FaultCode = t.c.value('codigoResultado[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('descricaoResultado[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/m:IMPCauRespostaATResponse/return/resultadoProcessamento') AS t(c)
		END
-- se resultado não for de sucesso, manda erro
		IF @FaultCode <> '0'
			RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 4, @FaultMessage)		
-- atualiza declaração p/ alteração do status e utilizador/data
		UPDATE PRO_DUCG SET DUC_STAT = (CASE @TipoMensagem WHEN 'CC414A' THEN 3 ELSE 1 END), DUC_DENV = @DataAtual, DUC_UALT = @CodUtilizador, DUC_DTAL = @DataAtual 
		WHERE DUC_IDTY = @Id
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH	
-- obtem o próximo número do registo da mensagem da declaração
	SET @NumMensagem = ISNULL((SELECT MAX(DRP_CODI) FROM PRO_DURP WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao), 0) + 1
-- insere no detalhe de mensagens os dados da submissão da declaração
	INSERT INTO PRO_DURP(DUC_EANO, DUC_PNUM, DRP_CODI, DRP_FLUX, DRP_DATA, DRP_OPER, DRP_ESTO, TDE_CODI, TDE_NOME, DRP_UTIL, DRP_XPED, DRP_XRES, DRP_SUCE, DRP_NFCH, DRP_CFCH)
	VALUES(@AnoDeclaracao, @NumDeclaracao, @NumMensagem, 1, @DataAtual, (CASE @TipoMensagem WHEN 'CC415A' THEN 0 WHEN 'CC413A' THEN 1 WHEN 'CC414A' THEN 2 WHEN 'CC432A' THEN 3 WHEN 'CC433A' THEN 4 WHEN 'CC446A' THEN 5 WHEN 'PT498A' THEN 21 ELSE NULL END), 
		@EstadoOperacaoDeclaracao, @CodTipoDeclaracao, @NomeTipoDeclaracao, @CodUtilizador, @MensagemXML, @ResponseXML, (CASE @NumErro WHEN 1 THEN 0 ELSE 1 END),
		(@TipoMensagem + '-' + REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(25), @DataAtual, 121), '-', ''), ':', ''), ' ', ''), '.', '') + '.xml'), CAST(@MensagemXML AS varbinary(MAX)))	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_MensagensSubmetePedido] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_MensagensSubmetePedido] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ProcessaEnvioEmailArquivosResposta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ProcessaEnvioEmailArquivosResposta] @AnoDeclaracao int, @NumDeclaracao int, @NomeMensagem varchar(50), @NomeFicheiro varchar(200), 
	@FicheiroBinario varbinary(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @IdDeclaracao bigint, @EmailDeclarante varchar(100), @EmailCliente varchar(250), @EmailCliente2 varchar(250), @Assunto varchar(250), 
		@Texto varchar(MAX)
-- inicia processo de envio de email de notificação de controlo para spool
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem se ficheiro da mensagem já foi arquivado para definir tipo de ficheiro
		IF @NomeMensagem = 'PT499A' 
		BEGIN
			IF EXISTS(SELECT DUC_PNUM FROM PRO_DUFI WITH(NOLOCK) WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao AND DUF_NOMF LIKE '%.RLQ.%' AND DUF_ORIG = 1 GROUP BY DUC_PNUM, DUC_EANO HAVING COUNT(*) > 1)
				SET @NomeMensagem = @NomeMensagem + '.1'
			ELSE
				SET @NomeMensagem = @NomeMensagem + '.0'
		END
		ELSE
			IF @NomeMensagem = 'CC429A' 
			BEGIN
				IF EXISTS(SELECT DUC_PNUM FROM PRO_DUFI WITH(NOLOCK) WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao AND DUF_NOMF LIKE '%.AUT.%' AND DUF_ORIG = 1 GROUP BY DUC_PNUM, DUC_EANO HAVING COUNT(*) > 1)
					SET @NomeMensagem = @NomeMensagem + '.1'
				ELSE
					SET @NomeMensagem = @NomeMensagem + '.0'
			END
-- obtem os dados para envio na declaração
		SELECT @IdDeclaracao = duc.DUC_IDTY, @EmailDeclarante = dcl.DEC_EMAI, @Assunto = per.DER_EASS, @Texto = per.DER_ETXT, @EmailCliente = cli.CLI_EMAI, 
			@EmailCliente2 = cli.CLI_EMA2
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI
			INNER JOIN TAB_PDER AS per WITH(NOLOCK) ON per.DER_MENS = @NomeMensagem AND per.DER_ACTI = 1
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
		WHERE duc.DUC_EANO = @AnoDeclaracao AND duc.DUC_PNUM = @NumDeclaracao AND ISNULL(dcl.DEC_EMAI, '') <> '' AND ISNULL(cli.CLI_EMAI, '') <> '' AND cli.CLI_IESE = 0			
-- se configurações todas ativas, insere os dados do email do ficheiro da resposta no spool para o email configurado
		IF (ISNULL(@EmailDeclarante, '') <> '') AND (ISNULL(@Assunto, '') <> '') AND (ISNULL(@EmailCliente, '') <> '') 
		BEGIN
-- descodifica assunto e texto do email
			EXEC sp_APL_DescodificaTexto @IdDeclaracao, 'PRO_DUCG', 'DUC_IDTY', @Assunto OUTPUT
			EXEC sp_APL_DescodificaTexto @IdDeclaracao, 'PRO_DUCG', 'DUC_IDTY', @Texto OUTPUT
-- insere pedido de envio de email no spool
			INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_IMPR, IMF_STAT, IMF_DTST, IMF_FBIN, IMF_TIPO, IMF_FROM, IMF_PARA, IMF_ASSU, IMF_TEXT, IMF_NFIC, IMF_CCOP)
			VALUES(@DataAtual, 'SMTP', 0, @DataAtual, @FicheiroBinario, 1, @EmailDeclarante, @EmailCliente, @Assunto, @Texto, @NomeFicheiro, @EmailCliente2)
		END
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ProcessaEnvioEmailArquivosResposta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ProcessaEnvioEmailArquivosResposta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo] @Id int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @EstadoOperacao varchar(3), @EmailDeclarante varchar(50), @Assunto varchar(250), @Texto varchar(MAX)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- inicia processo de envio de email de notificação de controlo para spool
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados para envio na declaração
		SELECT @EstadoOperacao = duc.DUC_ESTO, @EmailDeclarante = dcl.DEC_EMAI, 
			@Assunto = 'Aviso de ' + (CASE duc.DUC_ESTO 
										WHEN 'CA' THEN 'Controlo Aduaneiro' 										
										WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
										WHEN 'PDA' THEN 'Pedido Documentos Adicionais' 
										WHEN 'LED' THEN 'Lembrete de Envio de Documentos' 
										ELSE '?????' 
									END), 
			@Texto = 'Dados da declaração IMP-CAU:' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) +
			         '		.Declaração N.º....: ' + CAST(duc.DUC_PNUM AS varchar(10)) + CHAR(13) + CHAR(10) +
					 '		.NRL.....................: ' + duc.DUC_NRLO + CHAR(13) + CHAR(10) +
					 '		.NRM....................: ' + ISNULL(duc.DUC_NORD, '') + CHAR(13) + CHAR(10) +
					 '		.Cliente.................: ' + ISNULL(duc.DUC_DNOM, '') + CHAR(13) + CHAR(10) +
					 '		.Doc. Transporte...: ' + ISNULL(duc.DUC_CPRT, '') + CHAR(13) + CHAR(10) +
					 '		.Tipo de Controlo..: ' + (CASE duc.DUC_ESTO
														WHEN 'CA' THEN 'Controlo Aduaneiro' 										
														WHEN 'CAP' THEN 'Controlo Aduaneiro à Posteriori' 
														WHEN 'PDA' THEN 'Pedido Documentos Adicionais' 
														WHEN 'LED' THEN 'Lembrete de Envio de Documentos'  
														ELSE '?????' 
													END) + CHAR(13) + CHAR(10) 
		FROM PRO_DUCG AS duc WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON duc.DEC_CO14 = dcl.DEC_CODI
		WHERE duc.DUC_IDTY = @Id
-- insere os dados do email de notificação de controlo no spool para os emails configurados
		INSERT INTO GIDWIN.dbo.FAP_SIMF(IMF_DTCR, IMF_IMPR, IMF_STAT, IMF_DTST, IMF_TIPO, IMF_FROM, IMF_PARA, IMF_ASSU, IMF_TEXT)
		SELECT @DataAtual, 'SMTP', 0, @DataAtual, 1, @EmailDeclarante, DCA_EMAI, @Assunto, @Texto
		FROM TAB_PDCA WITH(NOLOCK)
		WHERE (@EstadoOperacao = 'CAP' AND DCA_ECAI = 1) OR (@EstadoOperacao = 'CA' AND DCA_ECFI = 1) OR (@EstadoOperacao = 'PDA' AND DCA_ECDI = 1) 
			OR (@EstadoOperacao = 'LED' AND (DCA_ECDI = 1 OR DCA_ECFI = 1 OR DCA_ECAI = 1))
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ProcessaEnvioEmailNotificacaoControlo] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ProcessaMensagensObtencaoAutomatica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ProcessaMensagensObtencaoAutomatica] @Tipo tinyint, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE	@NumErro int, @IdDeclaracao int, @NumeroDeclaracao int, @Erro varchar(MAX)
-- inicia variáveis
	SET @Erros = ''
-- obtem declarações IMP-CAU em situação de obtenção de respostas do webservice 
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT DUC_IDTY, DUC_PNUM
		FROM vw_IMP_Declaracoes_WSPendentesResposta
		WHERE DUC_TPEN = @Tipo		
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		SET @Erro = NULL
-- processa a obtenção das respostas da declaração IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_MensagensObtemResposta 0, '', @IdDeclaracao, @IdUtilizador, @Erro OUTPUT		
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A obtenção das respostas da declaração IMP-CAU N.º ' + CAST(@NumeroDeclaracao AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
-- devolve resultado (0: Sucesso; 1: Erro)
	IF @Erros = ''
		RETURN 0
	ELSE
		RETURN 1
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ProcessaMensagensObtencaoAutomatica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ProcessaMensagensObtencaoAutomatica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ProcessaMensagensSubmissaoAutomatica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ProcessaMensagensSubmissaoAutomatica] @Tipo tinyint, @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE	@NumErro int, @ValorMaxLiquidacao numeric(38, 6), @CamposAdicionais int, @TipoMsgXML varchar(8), @IdDeclaracao bigint, @NumeroDeclaracao int, @Erro varchar(MAX)
-- obtem o valor máximo de liquidação configurado para o utilizador
	SELECT @ValorMaxLiquidacao = UTI_VMXL
	FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
	WHERE UTI_IDTY = @IdUtilizador
-- obtem nos campos adicionais qual o tipo de empresa configurada
	SELECT @CamposAdicionais = PDE_CADI
	FROM TAB_PDES WITH(NOLOCK)
-- inicia variáveis
	SET @Erros = ''
-- obtem declarações IMP-CAU em situação de submissão ao webservice ou em situação de apresentação das mercadorias
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT 'CC415A', DUC_IDTY, DUC_PNUM
		FROM vw_IMP_Declaracoes_WSPendentesSubmissao	
		WHERE @Tipo = 0 AND DUC_VLRC <= @ValorMaxLiquidacao 
		UNION 
		SELECT 'CC432A', dim.DUC_IDTY, dim.DUC_PNUM
		FROM PRO_DUCG AS dim WITH(NOLOCK) 
			INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON dim.DEC_CO14 = dcl.DEC_CODI
			INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dim.NDE_CODI = nat.NDE_CODI	
		WHERE @Tipo = 1 AND dim.DUC_DUNO = 2 AND dim.DUC_STAT = 2 AND dim.DUC_ADI5 > 0 AND nat.NDE_FEDI = 1 AND ISNULL(dcl.DEC_WSEP, '') <> '' 
			AND ISNULL(dim.DUC_ESTO, '') IN ('NR', 'RE') AND ISNULL(dim.DUC_VLRC, 0) <= @ValorMaxLiquidacao AND ISNULL(dim.DUC_NPRO, '') <> '' 
			AND ISNULL(dim.TDE_2CAS, '') = 'D' AND dim.DUC_ASAI = 0	
			AND (CASE WHEN @CamposAdicionais IN (1, 2, 3) THEN dim.DUC_VDIR ELSE ISNULL(dim.DUC_TVL6, 0) END) = ISNULL(dim.DUC_TVL6, 0) --FEDEX/TNT, UPS, DHL					
			AND NOT EXISTS(SELECT 1 FROM dbo.fn_IMP_ObtemErrosSubmissaoWS(dim.DUC_IDTY)) 			
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @TipoMsgXML, @IdDeclaracao, @NumeroDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		SET @Erro = NULL
-- processa a submissão da mensagem XML da declaração IMP-CAU
		EXEC @NumErro = sp_IMP_Declaracoes_MensagensSubmetePedido @TipoMsgXML, @IdDeclaracao, NULL, NULL, NULL, NULL, @IdUtilizador, @Erro OUTPUT
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A submissão da mensagem "' + @TipoMsgXML + '" da declaração IMP-CAU N.º ' + CAST(@NumeroDeclaracao AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Declaracoes INTO @TipoMsgXML, @IdDeclaracao, @NumeroDeclaracao
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
-- devolve resultado (0: Sucesso; 1: Erro)
	IF @Erros = ''
		RETURN 0
	ELSE
		RETURN 1
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ProcessaMensagensSubmissaoAutomatica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ProcessaMensagensSubmissaoAutomatica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Declaracoes_ReferenciasFiscaisImportaXLSX]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Declaracoes_ReferenciasFiscaisImportaXLSX] @IdDeclaracao bigint, @Funcao varchar(3), @FicheiroXLSX varchar(MAX), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @FicheiroXML xml
-- inicia transacção para a inserção das referências fiscais
	BEGIN TRANSACTION TspIMPImportaXLSXRefFiscais
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX		
-- insere as referências fiscais do ficheiro que não existam na declaração
		INSERT INTO tb_IMP_DeclaracoesReferenciasFiscais(id_declaracaoIMP, funcao, nif, origem, id_utilizadorControlo, dataControlo)
		SELECT @IdDeclaracao, @Funcao, t.c.value('NIF[1]', 'varchar(17)'), 1, @IdUtilizador, @DataAtual
		FROM @FicheiroXML.nodes('dataset/row') AS t(c) 	
			LEFT OUTER JOIN tb_IMP_DeclaracoesReferenciasFiscais AS drf WITH(NOLOCK) ON drf.id_declaracaoIMP = @IdDeclaracao AND drf.funcao = @Funcao AND drf.nif = t.c.value('NIF[1]', 'varchar(17)')
		WHERE drf.id IS NULL
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPImportaXLSXRefFiscais
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPImportaXLSXRefFiscais
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Declaracoes_ReferenciasFiscaisImportaXLSX] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Declaracoes_ReferenciasFiscaisImportaXLSX] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_IMP_Servicos_Listagens]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_IMP_Servicos_Listagens] @ModoMenu bit, @IDListagem tinyint, @Ano smallint, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @TblID table (ID bigint NOT NULL)
	DECLARE @NumErro int, @DataAtual datetime, @MesAtual tinyint
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
	SET @MesAtual = MONTH(@DataAtual)
	BEGIN TRY	
		SET @NumErro = 0
-- obtem as listagens a apresentar nas declarações de serviços
		IF @ModoMenu = 1
		BEGIN
			SELECT 0 AS id, 'Standard (Global)' AS titulo, 'Vista Standard Global' AS hint, -1 AS imagem, CAST(0 AS bit) AS novoGrupo			
			ORDER BY id, titulo			
		END
		ELSE
		BEGIN
-- obtem as declarações serviço para a listagem "Standard (Global)"
			IF @IDListagem = 0
			BEGIN
				SELECT DUC_IDTY AS id, DUC_PNUM AS "Processo", DUC_DATA AS "Data", ALF_CODI AS "Estância", NDE_CODI AS "Natureza", NDE_NOME AS "Nome Natureza", 
					DUC_DST8 AS "Cód. Cliente", DUC_DNOM AS "Nome Cliente", DUC_CNTN AS "Conta N.º", DUC_UCRI AS "Utilizador", DUC_DTCR AS "Data Criação"
				FROM PRO_DUCG WITH(NOLOCK)
				WHERE DUC_SERV = 1 AND DUC_EANO = @Ano
				ORDER BY DUC_PNUM				
			END			
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_IMP_Servicos_Listagens] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_IMP_Servicos_Listagens] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Intrastat_DuplicaLancamento]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_Intrastat_DuplicaLancamento] @NumLanc int, @AnoLanc int, @NumNovoLanc int, @Utilizador varchar(30) AS
BEGIN
-- se numeração automatica, incrementa Próximo Nº. Lançamento nos Parametros de Intrastat
	UPDATE TAB_PINT SET PIN_PNLN = @NumNovoLanc + 1
	WHERE PIN_PNLN > 0
-- insere novo Lançamento Intrastat como cópia dos Dados Gerais do Lançamento Intrastat especificado
	INSERT INTO INT_LNCC(LNC_EANO, LNC_NUME, LNC_DATA, LNC_TMOV, LNC_MESR, CLI_CODI, CLI_NOME, FOR_CODI, FOR_NOME, LNC_FTNR, LNC_FTDT, DEC_CODI, 
		DEC_NOME, LNC_OBSE, LNC_TFAC, PAI_CODI, PAI_PREF, LNC_CAMB, LNC_TFRE, PAI_CODI1, PAI_PREF1, LNC_CMBF, LNC_TDES, LNC_TMLQ, LNC_TUNS, LNC_VEST, 
		LNC_UCRI, LNC_DCRI, LNC_UALT, LNC_DALT, LNC_IVCB)
	SELECT LNC_EANO, @NumNovoLanc, GETDATE(), LNC_TMOV, LNC_MESR, CLI_CODI, CLI_NOME, FOR_CODI, FOR_NOME, LNC_FTNR, LNC_FTDT, DEC_CODI, DEC_NOME, 
		LNC_OBSE, LNC_TFAC, PAI_CODI, PAI_PREF, LNC_CAMB, LNC_TFRE, PAI_CODI1, PAI_PREF1, LNC_CMBF, LNC_TDES, LNC_TMLQ, LNC_TUNS, LNC_VEST, @Utilizador,
		GETDATE(), @Utilizador, GETDATE(), LNC_IVCB
	FROM INT_LNCC
	WHERE LNC_EANO = @AnoLanc and LNC_NUME = @NumLanc
-- insere Adições como cópia das Adições do Lançamento Intrastat especificado
	INSERT INTO INT_LNCD(LNC_EANO, LNC_NUME, LND_NUME, PAI_CODI, PAI_NOME, PAI_CODI1, PAI_NOME1, CEN_CODI, CEN_NOME, NTR_CODI, NTR_NOME, MTR_CODI, 
		MTR_NOME, PAE_CODI, PAE_NOME, RES_CODI, RES_NOME, NC8_CODI, NC8_DESG, LND_TIVA, LND_VALO, LND_MLIQ, LND_QUNS, LND_VEST)
	SELECT LNC_EANO, @NumNovoLanc, LND_NUME, PAI_CODI, PAI_NOME, PAI_CODI1, PAI_NOME1, CEN_CODI, CEN_NOME, NTR_CODI, NTR_NOME, MTR_CODI, MTR_NOME, 
		PAE_CODI, PAE_NOME, RES_CODI, RES_NOME, NC8_CODI, NC8_DESG, LND_TIVA, LND_VALO, LND_MLIQ, LND_QUNS, LND_VEST
	FROM INT_LNCD
	WHERE LNC_EANO = @AnoLanc and LNC_NUME = @NumLanc
	ORDER BY LND_NUME
END

ALTER AUTHORIZATION ON [SP_Intrastat_DuplicaLancamento] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Intrastat_DuplicaLancamento] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_lancaDocUnicoCaucao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_lancaDocUnicoCaucao] @tipoEnti int, @codEnti varchar(18), @numCaucao varchar(24), @anoCaucao varchar(4), @tipCaucao varchar(1), @codAlfa varchar(8), @nrDocUn int, @AnDocUn int, 
	@dataDocUn datetime, @nat_pnum_eano varchar(15), @nrOrdem varchar(20), @dataNrOrdem datetime, @codCliente varchar(18), @valoDocUn numeric(38,6), @provis bit, @tipo int, @AdicionalIVA int, 
	@IdDeclaracaoDAR int = NULL AS
BEGIN
	SET DATEFORMAT DMY
-- declaracao de variaveis
	DECLARE @MCA_DBCR int, @MCA_LIQD bit, @Valor20Perc numeric(38, 6), @Valor80Perc numeric(38, 6), @NumDiasAdIVA int, @TipoAdIVA varchar(5)
-- busca dados da caução por defeito
	SELECT @MCA_DBCR = CAU_DCTR, @MCA_LIQD = CAU_LIQU
	FROM TAB_CAUC WITH(NOLOCK)
	WHERE CAU_CODI = 'DU'
-- se tipo de movimento da caução for Debito ou Credito 
	IF @MCA_DBCR < 3 
	BEGIN
-- remove movimentos da caucao associados ao documento
		DELETE FROM PRO_MCAU
		WHERE DUC_PNUM = @nrDocUn and DUC_EANO = @AnDocUn and DUC_TIPO = @tipo
-- remove conta corrente da caucao associados ao documento
		DELETE FROM PRO_CCCA
		WHERE DUC_PNUM = @nrDocUn and DUC_EANO = @AnDocUn and DUC_TIPO = @tipo
-- insere movimento da caucao conforme adicional IVA preenchido ou nao
		IF @AdicionalIVA = 0 
		BEGIN
-- exclui do valor da caução a soma do montante IVA da declaração cujo cliente é "Beneficiário IVA" nas declarações DUI2
			IF @IdDeclaracaoDAR IS NULL
			BEGIN
				SET @valoDocUn = @valoDocUn - ISNULL((SELECT SUM(ISNULL(dua.DUA_VIVA, 0))
					FROM PRO_DUCG as duc WITH(NOLOCK) INNER JOIN PRO_DUAD as dua WITH(NOLOCK) ON duc.DUC_PNUM = dua.DUC_PNUM and duc.DUC_EANO = dua.DUC_EANO
					WHERE duc.DUC_BIVA = 1 and duc.DUC_PNUM = @nrDocUn and duc.DUC_EANO = @AnDocUn), 0)
			END
-- insere registo
			INSERT INTO PRO_MCAU (MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO, MCA_CTIP, ALF_ORIG, CAU_CODI, MCA_DATA, MCA_NDOC, MCA_NORD, MCA_DORD, CLI_DEST, MCA_VLTT, MCA_DBCR, MCA_PROV, MCA_LIQD, 
				DUC_PNUM, DUC_EANO, ALF_DEST, DUC_TIPO, id_declaracaoDAR)
			VALUES (@tipoEnti, @codEnti, @numCaucao, @anoCaucao, @tipCaucao, @codAlfa, 'DU', @dataDocUn, @nat_pnum_eano, @nrOrdem, @dataNrOrdem, @codCliente, @valoDocUn, @MCA_DBCR, @provis, 
				@MCA_LIQD, @nrDocUn, @AnDocUn, '', @tipo, @IdDeclaracaoDAR)
		END
		ELSE
		BEGIN
-- para os DUs com Ad. IVA 1931 ou 1961, obtem o valor de tipo Ad. IVA para lançamento nº 1
			IF (@AdicionalIVA = 1931) OR (@AdicionalIVA = 1961)
				SET @TipoAdIVA = 'DIR'
			ELSE
				SET @TipoAdIVA = NULL
-- busca valor das rubricas da liquidacao recapitulativa do documento que nao estejam definidas nos parametros de aplicacao
			SELECT @valoDocUn = isnull(sum(isnull(DUL_MONT, 0)), 0)
			FROM PRO_DULR WITH(NOLOCK) 
			WHERE DUC_PNUM = @nrDocUn and DUC_EANO = @AnDocUn and RRE_CODI not in (select RRE_CDIS from TAB_PAPL WITH(NOLOCK) 
				UNION select RRE_CDRD from TAB_PAPL WITH(NOLOCK) 
				UNION select RRE_CDIN from TAB_PAPL WITH(NOLOCK) 
				UNION select RRE_CDNR from TAB_PAPL WITH(NOLOCK))
-- insere registo
			INSERT INTO PRO_MCAU (MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO, MCA_CTIP, ALF_ORIG, CAU_CODI, MCA_DATA, MCA_NDOC, MCA_NORD, MCA_DORD, CLI_DEST, MCA_VLTT, MCA_DBCR, MCA_PROV, MCA_LIQD, 
				DUC_PNUM, DUC_EANO, ALF_DEST, DUC_TIPO, MCA_TAIV, MCA_AIVA, id_declaracaoDAR)
			VALUES (@tipoEnti, @codEnti, @numCaucao, @anoCaucao, @tipCaucao, @codAlfa, 'DU', @dataDocUn, @nat_pnum_eano, @nrOrdem, @dataNrOrdem, @codCliente, @valoDocUn, @MCA_DBCR, @provis, 
				@MCA_LIQD, @nrDocUn, @AnDocUn, '', @tipo, @TipoAdIVA, @AdicionalIVA, @IdDeclaracaoDAR)
-- busca valor das rubricas da liquidacao recapitulativa do documento que estejam definidas nos parametros de aplicacao
			SELECT @valoDocUn = isnull(sum(isnull(DUL_MONT, 0)), 0)
			FROM PRO_DULR WITH(NOLOCK) 
			WHERE DUC_PNUM = @nrDocUn and DUC_EANO = @AnDocUn and RRE_CODI in (select RRE_CDIS from TAB_PAPL WITH(NOLOCK) 
				UNION select RRE_CDRD from TAB_PAPL WITH(NOLOCK) 
				UNION select RRE_CDIN from TAB_PAPL WITH(NOLOCK) 
				UNION select RRE_CDNR from TAB_PAPL WITH(NOLOCK))
-- exclui do valor da caução a soma do montante IVA da declaração cujo cliente é "Beneficiário IVA"
			SET @valoDocUn = @valoDocUn - ISNULL((SELECT SUM(ISNULL(dua.DUA_VIVA, 0))
				FROM PRO_DUCG as duc WITH(NOLOCK) INNER JOIN PRO_DUAD as dua WITH(NOLOCK) ON duc.DUC_PNUM = dua.DUC_PNUM and duc.DUC_EANO = dua.DUC_EANO
				WHERE duc.DUC_BIVA = 1 and duc.DUC_PNUM = @nrDocUn and duc.DUC_EANO = @AnDocUn), 0)			
-- se valor diferente de zero gera novo movimento
			IF @valoDocUn <> 0 
			BEGIN
-- para os DUs com Ad. IVA 1900 ou 1960 lança mais 1 registo na caução. Se Ad. IVA 1931 ou 1961 lança mais 2 registos na caução 
				IF (@AdicionalIVA = 1900) or (@AdicionalIVA = 1960)
				BEGIN
-- conforme valor de adicional IVA, altera para o numero de dias correspondente
					IF @AdicionalIVA = 1900
						SET @NumDiasAdIVA = 90
					ELSE
						SET @NumDiasAdIVA = day(dateadd(mm, datediff(mm, -1, @dataDocUn), -1))
-- insere registo
					INSERT INTO PRO_MCAU (MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO, MCA_CTIP, ALF_ORIG, CAU_CODI, MCA_DATA, MCA_NDOC, MCA_NORD, MCA_DORD, CLI_DEST, MCA_VLTT, MCA_DBCR, MCA_PROV, MCA_LIQD, DUC_PNUM, 
						DUC_EANO, ALF_DEST, DUC_TIPO, MCA_NDIA, MCA_AIVA, id_declaracaoDAR)
					VALUES (@tipoEnti, @codEnti, @numCaucao, @anoCaucao, @tipCaucao, @codAlfa, 'DU', @dataDocUn, @nat_pnum_eano, @nrOrdem, @dataNrOrdem, @codCliente, @valoDocUn, @MCA_DBCR, @provis, @MCA_LIQD, 
						@nrDocUn, @AnDocUn, '', @tipo, @NumDiasAdIVA, @AdicionalIVA, @IdDeclaracaoDAR)
				END
				ELSE
				BEGIN
-- conforme valor de adicional IVA, calcula o numero de dias correspondente ao lançamento nº 2
					IF @AdicionalIVA = 1961
						SET @NumDiasAdIVA = day(dateadd(mm, datediff(mm, -1, @dataDocUn), -1))
					ELSE
						SET @NumDiasAdIVA = 0
-- calcula 20% do valor de IVA para lançar na caução do tipo DU e 80% para lançar na caução do tipo IVA80
					SET @Valor20Perc = round((@valoDocUn * 20 / 100), 2)
					SET @Valor80Perc = round((@valoDocUn * 80 / 100), 2)
-- insere registo
					INSERT INTO PRO_MCAU (MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO, MCA_CTIP, ALF_ORIG, CAU_CODI, MCA_DATA, MCA_NDOC, MCA_NORD, MCA_DORD, CLI_DEST, MCA_VLTT, MCA_DBCR, MCA_PROV, MCA_LIQD, DUC_PNUM, 
						DUC_EANO, ALF_DEST, DUC_TIPO, MCA_NDIA, MCA_TAIV, MCA_AIVA, id_declaracaoDAR)
					VALUES (@tipoEnti, @codEnti, @numCaucao, @anoCaucao, @tipCaucao, @codAlfa, 'DU', @dataDocUn, @nat_pnum_eano, @nrOrdem, @dataNrOrdem, @codCliente, @Valor20Perc, @MCA_DBCR, @provis, @MCA_LIQD, 
						@nrDocUn, @AnDocUn, '', @tipo, @NumDiasAdIVA, '20IVA', @AdicionalIVA, @IdDeclaracaoDAR)
-- conforme valor de adicional IVA, calcula o numero de dias correspondente ao lançamento nº 3
					IF @AdicionalIVA = 1961
						SET @NumDiasAdIVA = day(dateadd(mm, datediff(mm, -1, @dataDocUn), -1))
					ELSE
						SET @NumDiasAdIVA = 0
-- insere registo
					INSERT INTO PRO_MCAU (MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO, MCA_CTIP, ALF_ORIG, CAU_CODI, MCA_DATA, MCA_NDOC, MCA_NORD, MCA_DORD, CLI_DEST, MCA_VLTT, MCA_DBCR, MCA_PROV, 
						MCA_LIQD, DUC_PNUM, DUC_EANO, ALF_DEST, DUC_TIPO, MCA_NDIA, MCA_TAIV, MCA_AIVA, id_declaracaoDAR)
					VALUES (@tipoEnti, @codEnti, @numCaucao, @anoCaucao, @tipCaucao, @codAlfa, 'IVA80', @dataDocUn, @nat_pnum_eano, @nrOrdem, @dataNrOrdem, @codCliente, @Valor80Perc, @MCA_DBCR, 
						@provis, @MCA_LIQD, @nrDocUn, @AnDocUn, '', @tipo, @NumDiasAdIVA, '80IVA', @AdicionalIVA, @IdDeclaracaoDAR)
				END
			END
		END
	END
END

ALTER AUTHORIZATION ON [SP_lancaDocUnicoCaucao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_lancaDocUnicoCaucao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_LogControlaRelacaoUtilizadorProcesso]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_LogControlaRelacaoUtilizadorProcesso] @Inserir bit, @Utilizador varchar(30) AS
BEGIN
-- remove registo do log do processo existente
	delete from LOG_LOGS
	where LOG_SPID = @@SPID
-- insere novo registo de log para o utilizador
	if @Inserir = 1 
	begin
		insert into LOG_LOGS (LOG_UTIL, LOG_SPID, LOG_DATA)
		values (@Utilizador, @@SPID, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())
	end
END

ALTER AUTHORIZATION ON [SP_LogControlaRelacaoUtilizadorProcesso] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_LogControlaRelacaoUtilizadorProcesso] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_NSTI_AnalisadorDiscrepanciasUPS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_NSTI_AnalisadorDiscrepanciasUPS] @Ano int, @Numero int, @CodOpResponsavel varchar(18), @DadosFicheiro varchar(MAX) AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @i bigint, @Linha varchar(MAX), @TipoLinha varchar(1), @NumCartaPorte varchar(18), @VolsPrevistosStr varchar(5), @VolsPrevistos int, @VolsReaisStr varchar(5), @VolsReais int		
-- cria tabela temporária p/ dados do ficheiro de scan UPS
	CREATE TABLE #DadosFicheiro(ID int IDENTITY NOT NULL, 
		FCH_CPRT varchar(18) COLLATE Latin1_General_CI_AI NOT NULL, 
		NAD_CODI int NULL,
		CLI_EXPE varchar(18) COLLATE Latin1_General_CI_AI NULL, 
		NAD_NOPE varchar(50) COLLATE Latin1_General_CI_AI NULL,
		NAD_VMER numeric(38, 6) NULL,
		NMA_NVOL int NULL,
		FCH_VPRE int NULL, 
		FCH_VREA int NULL, 
		FCH_DIFE int NULL)		
-- verifica se ficheiro termina c/ final de linha ENTER + LINEFEED
	IF SUBSTRING(REVERSE(@DadosFicheiro), 1, 2) <> CHAR(10) + CHAR(13)
		SET @DadosFicheiro = @DadosFicheiro + CHAR(13) + CHAR(10)	
-- obtem primeiro final de linha ENTER
	SET @i = CHARINDEX(CHAR(13) + CHAR(10), @DadosFicheiro)
-- percorre todas as linhas do ficheiro	
	WHILE @i > 0
	BEGIN
-- lê linha do ficheiro
		SET @Linha = SUBSTRING(@DadosFicheiro, 1, @i - 1)
-- obtem o tipo da linha
		SET @TipoLinha = LTRIM(RTRIM(SUBSTRING(@Linha, 1, 1)))
-- obtem dados do ficheiro para o tipo de linha "2"
		IF @TipoLinha = '2'
		BEGIN			
			SET @NumCartaPorte = LTRIM(RTRIM(SUBSTRING(@Linha, 323, 18)))			
			SET @VolsPrevistosStr = LTRIM(RTRIM(SUBSTRING(@Linha, 232, 5)))
			IF ISNUMERIC(@VolsPrevistosStr) = 1
				SET @VolsPrevistos = CAST(@VolsPrevistosStr AS int)
			ELSE	
				SET @VolsPrevistos = 0
			SET @VolsReaisStr = LTRIM(RTRIM(SUBSTRING(@Linha, 237, 5)))
			IF ISNUMERIC(@VolsReaisStr) = 1
				SET @VolsReais = CAST(@VolsReaisStr AS int)
			ELSE	
				SET @VolsReais = 0
-- insere na tabela temporária os dados obtidos do ficheiro e os dados da respetiva declaração	
			INSERT INTO #DadosFicheiro(FCH_CPRT, NAD_CODI, CLI_EXPE, NAD_NOPE, NAD_VMER, NMA_NVOL, FCH_VPRE, FCH_VREA, FCH_DIFE)
			SELECT @NumCartaPorte, adi.NAD_CODI, adi.CLI_EXPE, adi.NAD_NOPE, adi.NAD_VMER, mar.NMA_NVOL, @VolsPrevistos, @VolsReais, (mar.NMA_NVOL - @VolsReais)
			FROM PRO_NADI AS adi LEFT OUTER JOIN PRO_NAMA AS mar ON adi.NST_CODI = mar.NST_CODI AND adi.NST_EANO = mar.NST_EANO AND adi.NAD_CODI = mar.NAD_CODI AND mar.NMA_CODI = 1 AND adi.CLI_OPER = mar.CLI_OPER
				LEFT OUTER JOIN PRO_NADO AS doc ON adi.NST_CODI = doc.NST_CODI AND adi.NST_EANO = doc.NST_EANO AND adi.NAD_CODI = doc.NAD_CODI AND adi.CLI_OPER = doc.CLI_OPER 
			WHERE adi.NST_CODI = @Numero AND adi.NST_EANO = @Ano AND adi.CLI_OPER = @CodOpResponsavel AND doc.DOC_CODI = '740' AND doc.NDO_RFDA = @NumCartaPorte
		END
		ELSE
-- obtem dados do ficheiro para o tipo de linha "8"
			IF @TipoLinha = '8'
			BEGIN
				SET @NumCartaPorte = LTRIM(RTRIM(SUBSTRING(@Linha, 108, 18)))		
-- insere na tabela temporária somente a carta de porte do ficheiro
				INSERT INTO #DadosFicheiro(FCH_CPRT)
				VALUES(@NumCartaPorte)
			END		
-- remove a linha do ficheiro lida e procura novo final de linha ENTER + LINEFEED
		SET @DadosFicheiro = STUFF(@DadosFicheiro, 1, @i + 1, '')
		SET @i = CHARINDEX(CHAR(13) + CHAR(10), @DadosFicheiro)
	END
-- devolve dados das discrepancias 
	SELECT *
	FROM #DadosFicheiro	
-- remove tabela temporária
	DROP TABLE #DadosFicheiro
END

ALTER AUTHORIZATION ON [SP_NSTI_AnalisadorDiscrepanciasUPS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_NSTI_AnalisadorDiscrepanciasUPS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ObtemMascaraFacturacao]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ObtemMascaraFacturacao] @CodCliente varchar(18), @CodNatureza varchar(3), @NumMascaras int OUTPUT, @TipoMascara int OUTPUT, 
	@CodMascara int OUTPUT AS
BEGIN
-- Verificação da existencia de mascara de facturação no cliente
	select @CodMascara = MCF_CODI, @TipoMascara = 1
	from TAB_MCFT
	where CLI_CODI = @CodCliente and NDE_CODI = @CodNatureza
	select @NumMascaras = @@ROWCOUNT
-- Verificação da existencia de mascara de facturação na natureza
	if @NumMascaras = 0
	begin
		select @CodMascara = MNF_CODI, @TipoMascara = 2
		from TAB_MNFT
		where NDE_CODI = @CodNatureza
		select @NumMascaras = @@ROWCOUNT
-- Assume dos parametros de facturação
		if @NumMascaras = 0
		begin
			select @NumMascaras = 1
			select @TipoMascara = 0
			select @CodMascara = 0
		end
	end
END

ALTER AUTHORIZATION ON [SP_ObtemMascaraFacturacao] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ObtemMascaraFacturacao] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ObtemObservacoesParaConta]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ObtemObservacoesParaConta] @CodMascara int, @AnoProcesso int, @NumProcesso int, @CodCliente varchar(18), @CodNatureza varchar(3), @CodOperador varchar(6), 
	@Observacoes varchar(5000) OUTPUT AS
BEGIN
-- Declaração de variaveis
	DECLARE @FormulaObs varchar(MAX)
-- Inicia variaveis
	SET @FormulaObs = ''
-- Verificação da existencia de observações na mascara de facturação no cliente
	SELECT @FormulaObs = ISNULL(CAST(MCF_OBSV AS varchar(MAX)), '')
	FROM TAB_MCFT WITH(NOLOCK)
	WHERE CLI_CODI = (SELECT TOP 1 ISNULL(CLI_CCOR, CLI_CODI) FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_CODI = @CodCliente) AND NDE_CODI = @CodNatureza AND MCF_CODI = @CodMascara
-- Verificação da existencia de observações na mascara de facturação na natureza
	IF @FormulaObs = ''
	BEGIN
		SELECT @FormulaObs = ISNULL(CAST(NDE_OBSV AS varchar(MAX)), '')
		FROM TAB_NDES WITH(NOLOCK)
		WHERE NDE_CODI = @CodNatureza
-- Assume dos parametros de facturação
		IF @FormulaObs = ''
		BEGIN
			SELECT @FormulaObs = ISNULL(CAST(PFC_OBSR AS varchar(MAX)), '')
			FROM TAB_PFCT WITH(NOLOCK)
		END
	END
-- Calcula observações em função da formula de observações obtida
	IF @FormulaObs <> ''
	BEGIN
		SET @Observacoes = ''
		EXEC SP_ObtemValorStringComSQLDinamico @FormulaObs, @Observacoes OUTPUT, @NumProcesso, @AnoProcesso, @CodOperador
	END
	ELSE
		SET @Observacoes = ''
END

ALTER AUTHORIZATION ON [SP_ObtemObservacoesParaConta] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ObtemObservacoesParaConta] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ObtemValorNumericoComSQLDinamico]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ObtemValorNumericoComSQLDinamico] @SQLAExecutar nvarchar(4000), @ValorResultado numeric(38, 6) OUTPUT, @Param1 varchar(100) = '', @Param2 varchar(100) = '', 
	@Param3 varchar(100) = '', @Param4 varchar(100) = '' AS
BEGIN
-- declaracao de variaveis
	DECLARE @LstVarSQL nvarchar(1000)
-- inicia variaveis
	SET @LstVarSQL = N'@OUTValor numeric(38, 6) OUTPUT, @INParam1 varchar(100), @INParam2 varchar(100), @INParam3 varchar(100), @INParam4 varchar(100)'
-- executa sql
	EXEC sp_executesql @SQLAExecutar, @LstVarSQL, @OUTValor = @ValorResultado OUTPUT, @INParam1 = @Param1, @INParam2 = @Param2, @INParam3 = @Param3, @INParam4 = @Param4
END

ALTER AUTHORIZATION ON [SP_ObtemValorNumericoComSQLDinamico] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ObtemValorNumericoComSQLDinamico] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ObtemValorStringComSQLDinamico]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ObtemValorStringComSQLDinamico] @SQLAExecutar nvarchar(MAX), @ValorResultado varchar(5000) OUTPUT, @Param1 varchar(100) = '', @Param2 varchar(100) = '', 
	@Param3 varchar(100) = '', @Param4 varchar(100) = '' AS
BEGIN
-- declaracao de variaveis
	DECLARE @LstVarSQL nvarchar(1000)
-- inicia variaveis
	SET @LstVarSQL = N'@OUTValor varchar(5000) OUTPUT, @INParam1 varchar(100), @INParam2 varchar(100), @INParam3 varchar(100), @INParam4 varchar(100)'
-- executa sql
	EXEC sp_executesql @SQLAExecutar, @LstVarSQL, @OUTValor = @ValorResultado OUTPUT, @INParam1 = @Param1, @INParam2 = @Param2, @INParam3 = @Param3, @INParam4 = @Param4	
END

ALTER AUTHORIZATION ON [SP_ObtemValorStringComSQLDinamico] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ObtemValorStringComSQLDinamico] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_ProcessaAutomaticamenteInterfaceDUContasAutSaida]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_ProcessaAutomaticamenteInterfaceDUContasAutSaida] @Utilizador varchar(30) AS
BEGIN
-- declaração de variaveis
	declare @NumProcesso int, @AnoProcesso int, @TipoDocConta varchar(4), @CodNatureza varchar(3), @NumCartaPorte varchar(18), @TipoMascara int, @NumMascara int, 
		@ValorLiqRecapitulativa numeric(38, 6), @FormulaObs varchar(8000), @OUTObservacoes varchar(5000)
-- obtem lista de processos prontos para gerar Conta ao abrigo do Interface DU/Contas (Aut. Saída)
	DECLARE Processos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
		select d.DUC_PNUM, d.DUC_EANO, d.TDO_DOCU, d.NDE_CODI, d.DUC_CPRT, isnull(d.DUC_VLRC, 0), 
			(isnull(nullif(cast(n.NDE_OBSV as varchar(8000)), ''), (select isnull(cast(PFC_OBSR as varchar(8000)), '') from TAB_PFCT))),
			(case (select count(*) from TAB_MNFT where NDE_CODI = d.NDE_CODI) when 0 then 0 else 2 end), 
			(case (select count(*) from TAB_MNFT where NDE_CODI = d.NDE_CODI) when 0 then 0 else (select TOP 1 MNF_CODI from TAB_MNFT where NDE_CODI = d.NDE_CODI) end)
		from PRO_DUCG as d INNER JOIN TAB_CLIE AS c ON d.DUC_DST8 = c.CLI_CODI 
			INNER JOIN TAB_NDES as n ON d.NDE_CODI = n.NDE_CODI
		where d.DUC_TIPO = 1 and isnull(d.DUC_DST8, '') <> '' and d.DUC_ASAI = 1 and d.DUC_TSHI < 2 AND c.CLI_DUCT = 1 AND n.NDE_CRCO = 1 and isnull(n.NDE_TLCV, -1) = 0  and isnull(d.TDO_DOCU, '') <> '' 
			and (select TOP 1 PDE_IDCV from TAB_PDES) = 1 
			and (select count(*) from FAC_CDOC where CDO_IMEX = 0 and CDO_PANO = d.DUC_EANO and CDO_NPRO = d.DUC_PNUM) = 0
	OPEN Processos
	FETCH NEXT from Processos into @NumProcesso, @AnoProcesso, @TipoDocConta, @CodNatureza, @NumCartaPorte, @ValorLiqRecapitulativa, @FormulaObs, @TipoMascara, @NumMascara
	WHILE @@FETCH_STATUS = 0
	BEGIN
		select @OUTObservacoes = ''
		exec SP_ObtemValorStringComSQLDinamico @FormulaObs, @OUTObservacoes OUTPUT, @NumProcesso, @AnoProcesso
		exec SP_geraContas @NumProcesso, @AnoProcesso, @TipoDocConta, @CodNatureza, @Utilizador, @TipoMascara, @NumMascara, 0.000000, @OUTObservacoes, @ValorLiqRecapitulativa, @NumCartaPorte, 0, NULL, 0
		FETCH NEXT from Processos into @NumProcesso, @AnoProcesso, @TipoDocConta, @CodNatureza, @NumCartaPorte, @ValorLiqRecapitulativa, @FormulaObs, @TipoMascara, @NumMascara
	END
	CLOSE Processos
	DEALLOCATE Processos
END

ALTER AUTHORIZATION ON [SP_ProcessaAutomaticamenteInterfaceDUContasAutSaida] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_ProcessaAutomaticamenteInterfaceDUContasAutSaida] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SAFT_ExportacaoSAFTPortaria3022016]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_SAFT_ExportacaoSAFTPortaria3022016] @SAFTGeral int, @AnoExportacao int, @MesExportacao int, @PeriodoDe datetime, @PeriodoA datetime, @FicheiroSAFT xml OUTPUT, 
	@LinhaXMLEncoding varchar(200) OUTPUT AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @EspacoFiscalEmpresa varchar(5)
-- obtem dados da empresa
	SELECT @EspacoFiscalEmpresa = EMP_ESPF 
	FROM GIDWIN.dbo.FAP_EMPR WITH(NOLOCK)
	WHERE EMP_CODI = DB_NAME()	
-- cria tabela temporária p/ guardar a lista de Documentos de Venda Invoices movimentados no período
	CREATE TABLE #tmpInvoices(TDO_DOCU varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, TDO_NDOC int NOT NULL, TDO_EANO int NOT NULL, TDO_TDOC int NOT NULL, TDO_CLIE varchar(18) COLLATE Latin1_General_CI_AI NOT NULL)
	INSERT INTO #tmpInvoices(TDO_DOCU, TDO_NDOC, TDO_EANO, TDO_TDOC, TDO_CLIE)
	SELECT dve.DVE_TDOC, dve.DVE_NDOC, dve.DVE_EANO, tdo.TDO_TDOC, dve.CLI_CODI
	FROM FAC_DVEN as dve WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU 
	WHERE tdo.TDO_EXSF = 1 and dve.DVE_EANO = @AnoExportacao 
		and CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) as datetime) >= @PeriodoDe and CAST(CONVERT(varchar(10), dve.DVE_DATA, 105) as datetime) <= @PeriodoA		
	UNION 
	SELECT cdo.CDO_TDOC, cdo.CDO_IDEN, cdo.CDO_EANO, tdo.TDO_TDOC, cdo.CLI_CCOR
	FROM FAC_CDOC as cdo WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU 
	WHERE tdo.TDO_EXSF = 1 and tdo.TDO_TDSF <> 'OR' and cdo.CDO_IMPR = 1 and cdo.CDO_EANO = @AnoExportacao 
		and CAST(CONVERT(varchar(10), cdo.CDO_DTEM, 105) as datetime) >= @PeriodoDe and CAST(CONVERT(varchar(10), cdo.CDO_DTEM, 105) as datetime) <= @PeriodoA		
-- cria tabela temporária p/ guardar a lista de Contas Working Documents movimentados no período
	CREATE TABLE #tmpWorkingDocs(TDO_DOCU varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, TDO_NDOC int NOT NULL, TDO_EANO int NOT NULL, TDO_CLIE varchar(18) COLLATE Latin1_General_CI_AI NOT NULL)
	INSERT INTO #tmpWorkingDocs(TDO_DOCU, TDO_NDOC, TDO_EANO, TDO_CLIE)	
	SELECT cdo.CDO_TDOC, cdo.CDO_IDEN, cdo.CDO_EANO, cdo.CLI_CCOR
	FROM FAC_CDOC as cdo WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU 
	WHERE tdo.TDO_EXSF = 1 and tdo.TDO_TDSF = 'OR' and cdo.CDO_IMPR = 1 and cdo.CDO_EANO = @AnoExportacao and @SAFTGeral IN (0, 1) 
		and CAST(CONVERT(varchar(10), cdo.CDO_DTEM, 105) as datetime) >= @PeriodoDe and CAST(CONVERT(varchar(10), cdo.CDO_DTEM, 105) as datetime) <= @PeriodoA		
-- cria tabela temporária p/ guardar a lista de Recibos Payments movimentados no período
	CREATE TABLE #tmpPayments(TDO_DOCU varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, TDO_NDOC int NOT NULL, TDO_EANO int NOT NULL, TDO_CLIE varchar(18) COLLATE Latin1_General_CI_AI NOT NULL)		
	INSERT INTO #tmpPayments(TDO_DOCU, TDO_NDOC, TDO_EANO, TDO_CLIE)
	SELECT rec.REC_TDOC, rec.REC_NDOC, rec.REC_EANO, rec.REC_ENTI
	FROM FAC_RECC as rec WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON rec.REC_TDOC = tdo.TDO_DOCU	
		INNER JOIN FAC_RECD as red WITH(NOLOCK) ON rec.REC_TDOC = red.REC_TDOC and rec.REC_NDOC = red.REC_NDOC and rec.REC_EANO = red.REC_EANO
		INNER JOIN FAC_MVCC as mcc WITH(NOLOCK) ON red.MVC_TDOC = mcc.MVC_TDOC and red.MVC_NDOC = mcc.MVC_NDOC and red.MVC_EANO = mcc.MVC_EANO	
	WHERE tdo.TDO_EXSF = 1 and rec.REC_EANO = @AnoExportacao and @SAFTGeral IN (1, 2) 
		and CAST(CONVERT(varchar(10), rec.REC_DATA, 105) as datetime) >= @PeriodoDe and CAST(CONVERT(varchar(10), rec.REC_DATA, 105) as datetime) <= @PeriodoA
	GROUP BY rec.REC_TDOC, rec.REC_NDOC, rec.REC_EANO, rec.REC_ENTI
-- cria tabela temporária p/ guardar a lista de Clientes movimentados no período
	CREATE TABLE #tmpCustomers(CLI_CODI varchar(18) COLLATE Latin1_General_CI_AI NOT NULL)
	INSERT INTO #tmpCustomers (CLI_CODI)
	SELECT CLI_CODI
	FROM TAB_CLIE WITH(NOLOCK) 
	WHERE CLI_CODI in (SELECT TDO_CLIE FROM #tmpInvoices)
	GROUP BY CLI_CODI
	UNION
	SELECT CLI_CODI
	FROM TAB_CLIE WITH(NOLOCK) 
	WHERE CLI_CODI in (SELECT TDO_CLIE FROM #tmpWorkingDocs)
	GROUP BY CLI_CODI
	UNION
	SELECT CLI_CODI
	FROM TAB_CLIE WITH(NOLOCK) 
	WHERE CLI_CODI in (SELECT TDO_CLIE FROM #tmpPayments)
	GROUP BY CLI_CODI
-- cria tabela temporária p/ guardar a lista de Artigos movimentados no período
	CREATE TABLE #tmpProducts(PRD_TIPO varchar(1) COLLATE Latin1_General_CI_AI NOT NULL, PRD_CODI int NOT NULL)
	INSERT INTO #tmpProducts (PRD_TIPO, PRD_CODI)
	SELECT 'R', det.RFC_CODI
	FROM FAC_DVDT as det WITH(NOLOCK) INNER JOIN TAB_RFCT as rft WITH(NOLOCK) ON det.RFC_CODI = rft.RFC_CODI		
		INNER JOIN #tmpInvoices as tin ON det.DVE_TDOC = tin.TDO_DOCU and det.DVE_NDOC = tin.TDO_NDOC and det.DVE_EANO = tin.TDO_EANO and tin.TDO_TDOC = 1
	WHERE det.DVD_LCRB = 1 and @SAFTGeral IN (1, 2) 
	GROUP BY det.RFC_CODI
	UNION
	SELECT 'D', det.DDO_CODI
	FROM FAC_DCDO as det WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON det.DDO_CODI = ddo.DDO_CODI
		INNER JOIN #tmpInvoices as tin ON det.CDO_TDOC = tin.TDO_DOCU and det.CDO_IDEN = tin.TDO_NDOC and det.CDO_EANO = tin.TDO_EANO and tin.TDO_TDOC = 0		
	WHERE ISNULL(det.DCD_VTOT, 0) > 0 and @SAFTGeral IN (1, 2) 
	GROUP BY det.DDO_CODI
	UNION
	SELECT 'I', det.DIN_CODI
	FROM FAC_ICDO as det WITH(NOLOCK) INNER JOIN TAB_DINE as din WITH(NOLOCK) ON det.DIN_CODI = din.DIN_CODI
		INNER JOIN #tmpInvoices as tin ON det.CDO_TDOC = tin.TDO_DOCU and det.CDO_IDEN = tin.TDO_NDOC and det.CDO_EANO = tin.TDO_EANO and tin.TDO_TDOC = 0		
	WHERE ISNULL(det.ICD_VTOT, 0) > 0 and @SAFTGeral IN (1, 2)
	GROUP BY det.DIN_CODI
	UNION
	SELECT 'I', cab.DIN_HONO
	FROM FAC_CDOC as cab WITH(NOLOCK) INNER JOIN TAB_DINE as din WITH(NOLOCK) ON cab.DIN_HONO = din.DIN_CODI
		INNER JOIN #tmpInvoices as tin ON cab.CDO_TDOC = tin.TDO_DOCU and cab.CDO_IDEN = tin.TDO_NDOC and cab.CDO_EANO = tin.TDO_EANO and tin.TDO_TDOC = 0		
	WHERE ISNULL(cab.CDO_TTHO, 0) > 0 and @SAFTGeral IN (1, 2) 
	GROUP BY cab.DIN_HONO
	UNION
	SELECT 'D', det.DDO_CODI
	FROM FAC_DCDO as det WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON det.DDO_CODI = ddo.DDO_CODI
		INNER JOIN #tmpWorkingDocs as twd ON det.CDO_TDOC = twd.TDO_DOCU and det.CDO_IDEN = twd.TDO_NDOC and det.CDO_EANO = twd.TDO_EANO
	WHERE ISNULL(det.DCD_VTOT, 0) > 0 and @SAFTGeral = 1 
	GROUP BY det.DDO_CODI
	UNION
	SELECT 'I', det.DIN_CODI
	FROM FAC_ICDO as det WITH(NOLOCK) INNER JOIN TAB_DINE as din WITH(NOLOCK) ON det.DIN_CODI = din.DIN_CODI
		INNER JOIN #tmpWorkingDocs as twd ON det.CDO_TDOC = twd.TDO_DOCU and det.CDO_IDEN = twd.TDO_NDOC and det.CDO_EANO = twd.TDO_EANO
	WHERE ISNULL(det.ICD_VTOT, 0) > 0 and @SAFTGeral = 1
	GROUP BY det.DIN_CODI
	UNION
	SELECT 'I', cab.DIN_HONO
	FROM FAC_CDOC as cab WITH(NOLOCK) INNER JOIN TAB_DINE as din WITH(NOLOCK) ON cab.DIN_HONO = din.DIN_CODI
		INNER JOIN #tmpWorkingDocs as twd ON cab.CDO_TDOC = twd.TDO_DOCU and cab.CDO_IDEN = twd.TDO_NDOC and cab.CDO_EANO = twd.TDO_EANO
	WHERE ISNULL(cab.CDO_TTHO, 0) > 0 and @SAFTGeral = 1 
	GROUP BY cab.DIN_HONO
-- atribui linha de encoding (definido no schema) p/ SAF-T para depois ser incluída no ficheiro XML a gerar
	SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="Windows-1252"?>'	
-- constroi XML para ficheiro SAF-T PT	
	;WITH XMLNAMESPACES (DEFAULT 'urn:OECD:StandardAuditFile-Tax:PT_1.04_01')
	SELECT @FicheiroSAFT = 				
		(SELECT (SELECT '1.04_01' as "AuditFileVersion", 
				SUBSTRING(RTRIM(LTRIM((CASE WHEN (ISNULL(EMP_CONS, '') = '') and (ISNULL(EMP_NMAT, '') = '') THEN REPLACE(EMP_NIF, ' ', '') ELSE (ISNULL(EMP_CONS, '') + ' ' + ISNULL(EMP_NMAT, '')) END))), 1, 50) as "CompanyID",
				SUBSTRING(RTRIM(LTRIM(REPLACE(EMP_NIF, ' ', ''))), 1, 9) as "TaxRegistrationNumber",
				(CASE WHEN (@SAFTGeral = 1) and (@MesExportacao = 0) THEN 'F' ELSE 'P' END) as "TaxAccountingBasis",				
				SUBSTRING(RTRIM(LTRIM(EMP_NOME)), 1, 100) as "CompanyName",				
				(SELECT SUBSTRING(RTRIM(LTRIM(EMP_MORA)), 1, 210) as "AddressDetail",
					SUBSTRING(RTRIM(LTRIM(EMP_LOCA)), 1, 50) as "City",
					SUBSTRING(RTRIM(LTRIM(EMP_CPOS)), 1, 8) as "PostalCode",
					'PT' as "Country"
				FOR XML PATH('CompanyAddress'), TYPE),
				@AnoExportacao as "FiscalYear",
				CONVERT(varchar(10), @PeriodoDe, 120) as "StartDate",
				CONVERT(varchar(10), @PeriodoA, 120) as "EndDate",
				'EUR' as "CurrencyCode",
				CONVERT(varchar(10), GETDATE(), 120) as "DateCreated",
				'Global' as "TaxEntity",
				'501698124' as "ProductCompanyTaxID",
				(SELECT GIDWIN.dbo.FNT_Geral_ObtemNumeroCertificacao()) as "SoftwareCertificateNumber",
				'GIDWIN/Singeste' as "ProductID",
				(SELECT TOP 1 CFG_VERS FROM GIDWIN.dbo.FAP_CONF WITH(NOLOCK)) as "ProductVersion",
				SUBSTRING(NULLIF(RTRIM(LTRIM(EMP_TELF)), ''), 1, 20) as "Telephone",
				SUBSTRING(NULLIF(RTRIM(LTRIM(EMP_FAX)), ''), 1, 20) as "Fax",
				SUBSTRING(NULLIF(RTRIM(LTRIM(EMP_EMAI)), ''), 1, 254) as "Email",
				SUBSTRING(NULLIF(RTRIM(LTRIM(EMP_WEB)), ''), 1, 60) as "Website"
			FROM GIDWIN.dbo.FAP_EMPR WITH(NOLOCK)
			WHERE EMP_CODI = DB_NAME()
			FOR XML PATH('Header'), TYPE),
			(SELECT 				
				(SELECT UPPER(CLI_CODI) as "CustomerID",
					'Desconhecido' as "AccountID",
					SUBSTRING(REPLACE(RTRIM(LTRIM(CLI_NIF)), ' ', ''), 1, 30) as "CustomerTaxID",
					SUBSTRING(RTRIM(LTRIM(CLI_NOME)), 1, 100) as "CompanyName",					
					(SELECT SUBSTRING(ISNULL(NULLIF(RTRIM(LTRIM(CLI_MORA)), ''), 'Desconhecido'), 1, 210) as "AddressDetail",
						SUBSTRING(ISNULL(NULLIF(RTRIM(LTRIM(CLI_LOCA)), ''), 'Desconhecido'), 1, 50) as "City",
						SUBSTRING(ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(CLI_CPOS, 1, 8))), ''), 'Desconhecido'), 1, 20) as "PostalCode",
						SUBSTRING(ISNULL(NULLIF(RTRIM(LTRIM(CAST(PAI_CODI as varchar(20)))), ''), 'Desconhecido'), 1, 12) as "Country"
					FOR XML PATH('BillingAddress'), TYPE),					
					SUBSTRING(NULLIF(RTRIM(LTRIM(CLI_TELF)), ''), 1, 20) as "Telephone",
					SUBSTRING(NULLIF(RTRIM(LTRIM(CLI_FAX)), ''), 1, 20) as "Fax",
					SUBSTRING(NULLIF(RTRIM(LTRIM(CLI_EMAI)), ''), 1, 254) as "Email",
					SUBSTRING(NULLIF(RTRIM(LTRIM(CLI_WEB)), ''), 1, 60) as "Website",
					0 as "SelfBillingIndicator"
				FROM TAB_CLIE WITH(NOLOCK)
				WHERE CLI_CODI in (SELECT CLI_CODI FROM #tmpCustomers)
				ORDER BY CLI_CODI
				FOR XML PATH('Customer'), TYPE),												
				(SELECT prd.PRD_TYPE as "ProductType",
					SUBSTRING(prd.PRD_CODE, 1, 60) as "ProductCode",					
					SUBSTRING(RTRIM(LTRIM(prd.PRD_DESC)), 1, 200) as "ProductDescription",
					SUBSTRING(prd.PRD_CODE, 1, 60) as "ProductNumberCode"
				FROM (
					SELECT 'I' as PRD_TYPE, (CASE @SAFTGeral WHEN 2 THEN CAST(DDO_CODI as varchar(60)) ELSE ('D' + CAST(DDO_CODI as varchar(59))) END) as PRD_CODE, DDO_NOME as PRD_DESC
					FROM TAB_DDOC WITH(NOLOCK)
					WHERE DDO_CODI in (SELECT PRD_CODI FROM #tmpProducts WHERE PRD_TIPO = 'D')
					UNION
					SELECT 'S' as PRD_TYPE, (CASE @SAFTGeral WHEN 2 THEN CAST(DIN_CODI as varchar(60)) ELSE ('I' + CAST(DIN_CODI as varchar(59))) END) as PRD_CODE, DIN_NOME as PRD_DESC
					FROM TAB_DINE WITH(NOLOCK)
					WHERE DIN_CODI in (SELECT PRD_CODI FROM #tmpProducts WHERE PRD_TIPO = 'I')
					UNION 
					SELECT (CASE RFC_TIPO WHEN 0 THEN 'I' else 'S' end) as PRD_TYPE, (CASE @SAFTGeral WHEN 2 THEN CAST(RFC_CODI as varchar(60)) ELSE ('R' + CAST(RFC_CODI as varchar(59))) END) as PRD_CODE, RFC_NOME as PRD_DESC
					FROM TAB_RFCT WITH(NOLOCK)
					WHERE RFC_CODI in (SELECT PRD_CODI FROM #tmpProducts WHERE PRD_TIPO = 'R')
				) as prd
				WHERE @SAFTGeral IN (1, 2)
				ORDER BY prd.PRD_CODE
				FOR XML PATH('Product'), TYPE),
				(SELECT TOP 1
					(SELECT 'IVA' as "TaxType",
						TAX_REGI as "TaxCountryRegion",
						tax.TAX_CODE as "TaxCode",
						SUBSTRING(RTRIM(LTRIM(tax.TAX_DESC)), 1, 255) as "Description",
						(CASE ISNULL(tax.TAX_PERC, 0) WHEN 0 THEN 0 ELSE CAST(ISNULL(tax.TAX_PERC, 0) as numeric(38, 2)) END) as "TaxPercentage"
					FROM (
						SELECT 'ISE' as TAX_CODE, 'PT' as TAX_REGI, CAST('Taxa Isenta' as varchar(50)) as TAX_DESC, 0.000000 as TAX_PERC						
						UNION
						SELECT 'RED' as TAX_CODE, 'PT' as TAX_REGI, CAST('Taxa Reduzida' as varchar(50)) as TAX_DESC, 5.000000 as TAX_PERC
						WHERE @AnoExportacao <= 2010
						UNION
						SELECT 'INT' as TAX_CODE, 'PT' as TAX_REGI, CAST('Taxa Intermédia' as varchar(50)) as TAX_DESC, 12.000000 as TAX_PERC						
						WHERE @AnoExportacao <= 2010 
						UNION
						SELECT 'NOR' as TAX_CODE, 'PT' as TAX_REGI, CAST('Taxa Normal' as varchar(50)) as TAX_DESC, 20.000000 as TAX_PERC						
						WHERE @AnoExportacao <= 2010 
						UNION
						SELECT 'RED' as TAX_CODE, 'PT' as TAX_REGI, CAST('Taxa Reduzida' as varchar(50)) as TAX_DESC, 6.000000 as TAX_PERC 						
						WHERE @AnoExportacao >= 2010 
						UNION
						SELECT 'INT' as TAX_CODE, 'PT' as TAX_REGI, CAST('Taxa Intermédia' as varchar(50)) as TAX_DESC, 13.000000 as TAX_PERC						
						WHERE @AnoExportacao >= 2010 
						UNION
						SELECT 'NOR' as TAX_CODE, 'PT' as TAX_REGI, CAST('Taxa Normal' as varchar(50)) as TAX_DESC, 23.000000 as TAX_PERC						
						WHERE @AnoExportacao >= 2010
						UNION
						SELECT 'ISE' as TAX_CODE, 'PT-AC' as TAX_REGI, CAST('Taxa Isenta' as varchar(50)) as TAX_DESC, 0.000000 as TAX_PERC						
						UNION
						SELECT 'NOR' as TAX_CODE, 'PT-AC' as TAX_REGI, CAST('Taxa Normal' as varchar(50)) as TAX_DESC, 16.000000 as TAX_PERC						
						UNION
						SELECT 'ISE' as TAX_CODE, 'PT-MA' as TAX_REGI, CAST('Taxa Isenta' as varchar(50)) as TAX_DESC, 0.000000 as TAX_PERC						
						UNION
						SELECT 'NOR' as TAX_CODE, 'PT-MA' as TAX_REGI, CAST('Taxa Normal' as varchar(50)) as TAX_DESC, 22.000000 as TAX_PERC						
					) as tax
					ORDER BY tax.TAX_PERC
					FOR XML PATH('TaxTableEntry'), TYPE)					
				FROM TAB_PAPL WITH(NOLOCK)
				WHERE @SAFTGeral IN (1, 2)
				FOR XML PATH('TaxTable'), TYPE)
			FOR XML PATH('MasterFiles'), TYPE),			
			(SELECT
				(SELECT ISNULL(SUM(sli.SLI_NUMB), 0) as "NumberOfEntries",
					CAST(ISNULL(SUM(sli.SLI_TDEB), 0) as numeric(38, 2)) as "TotalDebit",
					CAST(ISNULL(SUM(sli.SLI_TCRE), 0) as numeric(38, 2)) as "TotalCredit",
					(SELECT cdo.CDO_INVN as "InvoiceNo",
						cdo.CDO_ATCU as "ATCUD",
						(SELECT (CASE cdo.CDO_ANUL WHEN 1 then 'A' ELSE 'N' END) as "InvoiceStatus",
							CONVERT(varchar(19), ISNULL(cdo.CDO_DTAL, cdo.CDO_DTCR), 126) as "InvoiceStatusDate",
							ISNULL(NULLIF(cdo.CDO_UALT, ''), cdo.CDO_UCRI) as "SourceID",
							'P' as "SourceBilling"							
						FOR XML PATH('DocumentStatus'), TYPE),
						SUBSTRING(ISNULL(cdo.CDO_HASH, '0'), 1, 172) as "Hash",
						CAST(cdo.CDO_HCTR as varchar(70)) as "HashControl",		
						CONVERT(varchar(10), cdo.CDO_DTEM, 120) as "InvoiceDate",
						SUBSTRING(tdo.TDO_TDSF, 1, 2) as "InvoiceType",
						(SELECT 0 as "SelfBillingIndicator",
							0 as "CashVATSchemeIndicator",
							0 as "ThirdPartiesBillingIndicator"
						FOR XML PATH('SpecialRegimes'), TYPE),
						ISNULL(cdo.CDO_UCRI, 'Desconhecido') as "SourceID", 						
						CONVERT(varchar(19), cdo.CDO_DTCR, 126) as "SystemEntryDate", 						
						UPPER(cdo.CLI_CCOR) as "CustomerID",
						(SELECT ROW_NUMBER() OVER(ORDER BY lin.LIN_TIPO, lin.LIN_LNUM) as "LineNumber",														
							SUBSTRING(lin.LIN_PCOD, 1, 60) as "ProductCode",
							SUBSTRING(RTRIM(LTRIM(lin.LIN_PDES)), 1, 200) as "ProductDescription",
							CAST(1.00 as numeric(38, 2)) as "Quantity",
							'Unidade' as "UnitOfMeasure",
							CAST(ABS(lin.LIN_UPRI) as numeric(38, 2)) as "UnitPrice",
							CONVERT(varchar(10), cdo.CDO_DTEM, 120) as "TaxPointDate",							
							SUBSTRING(RTRIM(LTRIM(lin.LIN_DESC)), 1, 200) as "Description",
							CAST((CASE WHEN (tdo.TDO_TMOV = 1) THEN ABS(lin.LIN_UPRI) ELSE NULL END) as numeric(38, 2)) as "DebitAmount",
							CAST((CASE WHEN (tdo.TDO_TMOV <> 1) THEN ABS(lin.LIN_UPRI) ELSE NULL END) as numeric(38, 2)) as "CreditAmount",
							(SELECT 'IVA' as "TaxType",
								(CASE cdo.CDO_TXIV WHEN 23.000000 THEN 'PT' WHEN 22.000000 THEN 'PT-MA' WHEN 16.000000 THEN 'PT-AC' ELSE @EspacoFiscalEmpresa END) as "TaxCountryRegion",
								lin.LIN_TAXC as "TaxCode",
								(CASE lin.LIN_TAXP WHEN 0 THEN 0 ELSE CAST(lin.LIN_TAXP as numeric(38, 2)) END) as "TaxPercentage"								
							FOR XML PATH('Tax'), TYPE),
							SUBSTRING(lin.LIN_TXER, 1, 60) as "TaxExemptionReason",
							SUBSTRING(lin.LIN_TXEC, 1, 3) as "TaxExemptionCode"
						FROM (
							SELECT 0 as LIN_TIPO, 
								det.DCD_LINH as LIN_LNUM,														
								(CASE @SAFTGeral WHEN 2 THEN CAST(det.DDO_CODI as varchar(60)) ELSE ('D' + CAST(det.DDO_CODI as varchar(59))) END) as LIN_PCOD,
								ddo.DDO_NOME as LIN_PDES,								 								
								ISNULL(det.DCD_VTOT, 0) as LIN_UPRI,																
								det.DCD_DESC as LIN_DESC,								
								'ISE' as LIN_TAXC, 
								(SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) as LIN_TAXP,								
								(SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = 'M01') as LIN_TXER,
								'M01' as LIN_TXEC
							FROM FAC_DCDO as det WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON det.DDO_CODI = ddo.DDO_CODI								
							WHERE ISNULL(det.DCD_VTOT, 0) > 0 and det.CDO_EANO = cdo.CDO_EANO and det.CDO_TDOC = cdo.CDO_TDOC and det.CDO_IDEN = cdo.CDO_IDEN
							UNION
							SELECT 1 as LIN_TIPO, 
								det.ICD_LINH as LIN_LNUM,														
								(CASE @SAFTGeral WHEN 2 THEN CAST(det.DIN_CODI as varchar(60)) ELSE ('I' + CAST(det.DIN_CODI as varchar(59))) END) as LIN_PCOD,
								din.DIN_NOME as LIN_PDES,								 								
								ISNULL(det.ICD_VTOT, 0) as LIN_UPRI,																
								det.ICD_DESC as LIN_DESC,								
								(CASE det.ICD_ISEN WHEN 1 THEN 'ISE' ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN 'ISE' ELSE 'NOR' END) END) as LIN_TAXC, 
								(CASE det.ICD_ISEN WHEN 1 THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) ELSE ISNULL(cdo.CDO_TXIV, 0) END) END) as LIN_TAXP,								
								(CASE det.ICD_ISEN WHEN 1 THEN det.IIV_MENC ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.CDO_ISIV ELSE NULL END) END) as LIN_TXER, 
								(CASE det.ICD_ISEN WHEN 1 THEN det.IIV_CODI ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.IIV_CODI ELSE NULL END) END) as LIN_TXEC
							FROM FAC_ICDO as det WITH(NOLOCK) INNER JOIN TAB_DINE as din WITH(NOLOCK) ON det.DIN_CODI = din.DIN_CODI								
							WHERE ISNULL(det.ICD_VTOT, 0) > 0 and det.CDO_EANO = cdo.CDO_EANO and det.CDO_TDOC = cdo.CDO_TDOC and det.CDO_IDEN = cdo.CDO_IDEN
							UNION
							SELECT 1 as LIN_TIPO, 
								13 as LIN_LNUM,														
								(CASE @SAFTGeral WHEN 2 THEN CAST(din.DIN_CODI as varchar(60)) ELSE ('I' + CAST(din.DIN_CODI as varchar(59))) END) as LIN_PCOD,
								din.DIN_NOME as LIN_PDES,								 								
								ISNULL(cdo.CDO_TTHO, 0) as LIN_UPRI,																
								din.DIN_NOME as LIN_DESC,								
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN 'ISE' ELSE 'NOR' END) as LIN_TAXC, 
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) ELSE ISNULL(cdo.CDO_TXIV, 0) END) as LIN_TAXP,								
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.CDO_ISIV ELSE NULL END) as LIN_TXER, 
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.IIV_CODI ELSE NULL END) as LIN_TXEC
							FROM TAB_DINE as din WITH(NOLOCK) 
							WHERE din.DIN_CODI = cdo.DIN_HONO and ISNULL(cdo.CDO_TTHO, 0) > 0
						) as lin
						ORDER BY lin.LIN_TIPO, lin.LIN_LNUM
						FOR XML PATH('Line'), TYPE),
						(SELECT CAST(ISNULL(cdo.CDO_IVA, 0) as numeric(38, 2)) as "TaxPayable",
							CAST((ISNULL(cdo.CDO_TTPR, 0) - ISNULL(cdo.CDO_IVA, 0)) as numeric(38, 2)) as "NetTotal",
							CAST(ISNULL(cdo.CDO_TTPR, 0) as numeric(38, 2)) as "GrossTotal"
						FOR XML PATH('DocumentTotals'), TYPE),
						CAST((CASE ISNULL(cdo.CDO_TTRF, 0) WHEN 0 THEN NULL ELSE ISNULL(cdo.CDO_TTRF, 0) END) as numeric(38, 2)) as "WithholdingTax/WithholdingTaxAmount"			
					FROM FAC_CDOC as cdo WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU 
						INNER JOIN #tmpInvoices as tin ON cdo.CDO_TDOC = tin.TDO_DOCU and cdo.CDO_IDEN = tin.TDO_NDOC and cdo.CDO_EANO = tin.TDO_EANO and tin.TDO_TDOC = 0
					ORDER BY cdo.CDO_TDOC, cdo.CDO_CNUM
					FOR XML PATH('Invoice'), TYPE),
					(SELECT dve.DVE_INVN as "InvoiceNo",
						dve.DVE_ATCU as "ATCUD",
						(SELECT (CASE dve.DVE_ANUL WHEN 1 then 'A' ELSE 'N' END) as "InvoiceStatus",
							CONVERT(varchar(19), ISNULL(dve.DVE_DTAL, dve.DVE_DTCR), 126) as "InvoiceStatusDate",
							ISNULL(NULLIF(dve.DVE_UTIA, ''), dve.DVE_UTIC) as "SourceID",
							'P' as "SourceBilling"							
						FOR XML PATH('DocumentStatus'), TYPE),
						SUBSTRING(ISNULL(dve.DVE_HASH, '0'), 1, 172) as "Hash",
						CAST(dve.DVE_HCTR as varchar(70)) as "HashControl",						
						CONVERT(varchar(10), dve.DVE_DATA, 120) as "InvoiceDate",
						SUBSTRING(tdo.TDO_TDSF, 1, 2) as "InvoiceType",
						(SELECT 0 as "SelfBillingIndicator",
							0 as "CashVATSchemeIndicator",
							0 as "ThirdPartiesBillingIndicator"
						FOR XML PATH('SpecialRegimes'), TYPE),
						ISNULL(dve.DVE_UTIC, 'Desconhecido') as "SourceID", 						
						CONVERT(varchar(19), dve.DVE_DTCR, 126) as "SystemEntryDate", 						
						UPPER(dve.CLI_CODI) as "CustomerID",												
						(SELECT det.DVE_NLIN as "LineNumber",														
							SUBSTRING((CASE @SAFTGeral WHEN 2 THEN CAST(det.RFC_CODI as varchar(59)) ELSE ('R' + CAST(det.RFC_CODI as varchar(59))) END), 1, 60) as "ProductCode",
							SUBSTRING(RTRIM(LTRIM(rft.RFC_NOME)), 1, 200) as "ProductDescription",
							CAST(ISNULL(det.DVD_QUAN, 1) as numeric(38, 2)) as "Quantity",
							'Unidade' as "UnitOfMeasure",
							CAST(ABS(ISNULL(det.DVD_VALO, 0)) as numeric(38, 2)) as "UnitPrice",
							CONVERT(varchar(10), dve.DVE_DATA, 120) as "TaxPointDate",
							ISNULL(dve.DVE_NRDO, (CASE ISNULL(dve.MVC_IDEN, 0) WHEN 0 THEN NULL ELSE (SELECT dbo.fn_Faturacao_ConstroiInvoiceNumber(MVC_TDOC, MVC_SERI, MVC_NDOC) FROM FAC_MVCC WITH(NOLOCK) WHERE MVC_IDEN = dve.MVC_IDEN) END)) as "References/Reference",
							SUBSTRING(RTRIM(LTRIM(det.DVD_NOME)), 1, 200) as "Description",
							CAST((CASE WHEN (tdo.TDO_TMOV = 1) THEN ABS(ROUND((ISNULL(det.DVD_QUAN, 1) * ISNULL(det.DVD_VALO, 0)), 2)) ELSE NULL END) as numeric(38, 2)) as "DebitAmount",
							CAST((CASE WHEN (tdo.TDO_TMOV <> 1) THEN ABS(ROUND((ISNULL(det.DVD_QUAN, 1) * ISNULL(det.DVD_VALO, 0)), 2)) ELSE NULL END) as numeric(38, 2)) as "CreditAmount",
							(SELECT 'IVA' as "TaxType",
								(CASE ISNULL(det.DVD_IVA, 0) WHEN 0 THEN (CASE (SELECT MAX(ISNULL(DVD_IVA, 0)) FROM FAC_DVDT WITH(NOLOCK) WHERE DVD_LCRB = 1 and DVE_TDOC = det.DVE_TDOC and DVE_NDOC = det.DVE_NDOC and DVE_EANO = det.DVE_EANO) WHEN 23.000000 THEN 'PT' WHEN 22.000000 THEN 'PT-MA' WHEN 16.000000 THEN 'PT-AC' ELSE @EspacoFiscalEmpresa END) WHEN 23.000000 THEN 'PT' WHEN 22.000000 THEN 'PT-MA' WHEN 16.000000 THEN 'PT-AC' ELSE @EspacoFiscalEmpresa END) as "TaxCountryRegion",
								(CASE ISNULL(det.DVD_IVA, 0) WHEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) THEN 'ISE' ELSE 'NOR' END) as "TaxCode",
								(CASE ISNULL(det.DVD_IVA, 0) WHEN 0 THEN 0 ELSE CAST(ISNULL(det.DVD_IVA, 0) as numeric(38, 2)) END) as "TaxPercentage"								
							FOR XML PATH('Tax'), TYPE),
							SUBSTRING((CASE ISNULL(det.DVD_IVA, 0) WHEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) THEN det.IIV_MENC ELSE NULL END), 1, 60) as "TaxExemptionReason", 
							SUBSTRING((CASE ISNULL(det.DVD_IVA, 0) WHEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) THEN det.IIV_CODI ELSE NULL END), 1, 3) as "TaxExemptionCode"						
						FROM FAC_DVDT as det WITH(NOLOCK) INNER JOIN TAB_RFCT as rft WITH(NOLOCK) ON det.RFC_CODI = rft.RFC_CODI							
						WHERE det.DVD_LCRB = 1 and det.DVE_TDOC = dve.DVE_TDOC and det.DVE_NDOC = dve.DVE_NDOC and det.DVE_EANO = dve.DVE_EANO
						ORDER BY det.DVE_NLIN
						FOR XML PATH('Line'), TYPE),
						(SELECT CAST(dve.DVE_VIVA as numeric(38, 2)) as "TaxPayable",
							CAST((dve.DVE_VTOT - dve.DVE_VIVA) as numeric(38, 2)) as "NetTotal",
							CAST(dve.DVE_VTOT as numeric(38, 2)) as "GrossTotal"
						FOR XML PATH('DocumentTotals'), TYPE)						
					FROM FAC_DVEN as dve WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU 
						INNER JOIN #tmpInvoices as tin ON dve.DVE_TDOC = tin.TDO_DOCU and dve.DVE_NDOC = tin.TDO_NDOC and dve.DVE_EANO = tin.TDO_EANO and tin.TDO_TDOC = 1					
					ORDER BY dve.DVE_TDOC, dve.DVE_NDOC
					FOR XML PATH('Invoice'), TYPE)
				FROM (
					SELECT COUNT(*) as SLI_NUMB, SUM(CASE WHEN (dve.DVE_ANUL = 0 and tdo.TDO_TMOV <> 1) THEN dve.DVE_VLIQ ELSE 0 END) as SLI_TCRE, 
						SUM(CASE WHEN (dve.DVE_ANUL = 0 and tdo.TDO_TMOV = 1) THEN dve.DVE_VLIQ ELSE 0 END) as SLI_TDEB
					FROM FAC_DVEN as dve WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON dve.DVE_TDOC = tdo.TDO_DOCU 
						INNER JOIN #tmpInvoices as tin ON dve.DVE_TDOC = tin.TDO_DOCU and dve.DVE_NDOC = tin.TDO_NDOC and dve.DVE_EANO = tin.TDO_EANO and tin.TDO_TDOC = 1
					UNION ALL
					SELECT COUNT(*) as SLI_NUMB, SUM(CASE WHEN (cdo.CDO_ANUL = 0 and tdo.TDO_TMOV <> 1) THEN (ISNULL(cdo.CDO_TTDC, 0) + ISNULL(cdo.CDO_TTIN, 0) + ISNULL(cdo.CDO_TTHO, 0)) ELSE 0 END) as SLI_TCRE, 
						SUM(CASE WHEN (cdo.CDO_ANUL = 0 and tdo.TDO_TMOV = 1) THEN (ISNULL(cdo.CDO_TTDC, 0) + ISNULL(cdo.CDO_TTIN, 0) + ISNULL(cdo.CDO_TTHO, 0)) ELSE 0 END) as SLI_TDEB
					FROM FAC_CDOC as cdo WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU 
						INNER JOIN #tmpInvoices as tin ON cdo.CDO_TDOC = tin.TDO_DOCU and cdo.CDO_IDEN = tin.TDO_NDOC and cdo.CDO_EANO = tin.TDO_EANO and tin.TDO_TDOC = 0
				) as sli				
				FOR XML PATH('SalesInvoices'), TYPE),
				(SELECT COUNT(*) as "NumberOfEntries",
					CAST(0 as numeric(38, 2)) as "TotalDebit",
					CAST(ISNULL(SUM(CASE cdo.CDO_ANUL WHEN 0 THEN (ISNULL(cdo.CDO_TTDC, 0) + ISNULL(cdo.CDO_TTIN, 0) + ISNULL(cdo.CDO_TTHO, 0)) ELSE 0 END), 0) as numeric(38, 2)) as "TotalCredit",
					(SELECT cdo.CDO_INVN as "DocumentNumber",
						cdo.CDO_ATCU as "ATCUD",
						(SELECT (CASE cdo.CDO_ANUL WHEN 1 then 'A' ELSE 'N' END) as "WorkStatus", 
							CONVERT(varchar(19), ISNULL(cdo.CDO_DTAL, cdo.CDO_DTCR), 126) as "WorkStatusDate",
							ISNULL(NULLIF(cdo.CDO_UALT, ''), cdo.CDO_UCRI) as "SourceID",
							'P' as "SourceBilling"							
						FOR XML PATH('DocumentStatus'), TYPE),
						SUBSTRING(ISNULL(cdo.CDO_HASH, '0'), 1, 172) as "Hash",
						CAST(cdo.CDO_HCTR as varchar(70)) as "HashControl",		
						CONVERT(varchar(10), cdo.CDO_DTEM, 120) as "WorkDate",
						SUBSTRING(tdo.TDO_TDSF, 1, 2) as "WorkType",						
						ISNULL(cdo.CDO_UCRI, 'Desconhecido') as "SourceID", 						
						CONVERT(varchar(19), cdo.CDO_DTCR, 126) as "SystemEntryDate", 						
						UPPER(cdo.CLI_CCOR) as "CustomerID",
						(SELECT ROW_NUMBER() OVER(ORDER BY lin.LIN_TIPO, lin.LIN_LNUM) as "LineNumber",														
							SUBSTRING(lin.LIN_PCOD, 1, 60) as "ProductCode",
							SUBSTRING(RTRIM(LTRIM(lin.LIN_PDES)), 1, 200) as "ProductDescription",
							CAST(1.00 as numeric(38, 2)) as "Quantity",
							'Unidade' as "UnitOfMeasure",
							CAST(ABS(lin.LIN_UPRI) as numeric(38, 2)) as "UnitPrice",
							CONVERT(varchar(10), cdo.CDO_DTEM, 120) as "TaxPointDate",							
							SUBSTRING(RTRIM(LTRIM(lin.LIN_DESC)), 1, 200) as "Description",
							NULL as "DebitAmount",
							CAST(ABS(lin.LIN_UPRI) as numeric(38, 2)) as "CreditAmount",
							(SELECT 'IVA' as "TaxType",
								(CASE cdo.CDO_TXIV WHEN 23.000000 THEN 'PT' WHEN 22.000000 THEN 'PT-MA' WHEN 16.000000 THEN 'PT-AC' ELSE @EspacoFiscalEmpresa END) as "TaxCountryRegion",
								lin.LIN_TAXC as "TaxCode",
								(CASE lin.LIN_TAXP WHEN 0 THEN 0 ELSE CAST(lin.LIN_TAXP as numeric(38, 2)) END) as "TaxPercentage"								
							FOR XML PATH('Tax'), TYPE),
							SUBSTRING(lin.LIN_TXER, 1, 60) as "TaxExemptionReason",
							SUBSTRING(lin.LIN_TXEC, 1, 3) as "TaxExemptionCode"
						FROM (
							SELECT 0 as LIN_TIPO, 
								det.DCD_LINH as LIN_LNUM,														
								('D' + CAST(det.DDO_CODI as varchar(59))) as LIN_PCOD,
								ddo.DDO_NOME as LIN_PDES,								 								
								ISNULL(det.DCD_VTOT, 0) as LIN_UPRI,																
								det.DCD_DESC as LIN_DESC,								
								'ISE' as LIN_TAXC, 
								(SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) as LIN_TAXP,								
								(SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = 'M01') as LIN_TXER,
								'M01' as LIN_TXEC
							FROM FAC_DCDO as det WITH(NOLOCK) INNER JOIN TAB_DDOC as ddo WITH(NOLOCK) ON det.DDO_CODI = ddo.DDO_CODI								
							WHERE ISNULL(det.DCD_VTOT, 0) > 0 and det.CDO_EANO = cdo.CDO_EANO and det.CDO_TDOC = cdo.CDO_TDOC and det.CDO_IDEN = cdo.CDO_IDEN
							UNION
							SELECT 1 as LIN_TIPO, 
								det.ICD_LINH as LIN_LNUM,														
								('I' + CAST(det.DIN_CODI as varchar(59))) as LIN_PCOD,
								din.DIN_NOME as LIN_PDES,								 								
								ISNULL(det.ICD_VTOT, 0) as LIN_UPRI,																
								det.ICD_DESC as LIN_DESC,								
								(CASE det.ICD_ISEN WHEN 1 THEN 'ISE' ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN 'ISE' ELSE 'NOR' END) END) as LIN_TAXC, 
								(CASE det.ICD_ISEN WHEN 1 THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) ELSE ISNULL(cdo.CDO_TXIV, 0) END) END) as LIN_TAXP,								
								(CASE det.ICD_ISEN WHEN 1 THEN det.IIV_MENC ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.CDO_ISIV ELSE NULL END) END) as LIN_TXER, 
								(CASE det.ICD_ISEN WHEN 1 THEN det.IIV_CODI ELSE (CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.IIV_CODI ELSE NULL END) END) as LIN_TXEC
							FROM FAC_ICDO as det WITH(NOLOCK) INNER JOIN TAB_DINE as din WITH(NOLOCK) ON det.DIN_CODI = din.DIN_CODI								
							WHERE ISNULL(det.ICD_VTOT, 0) > 0 and det.CDO_EANO = cdo.CDO_EANO and det.CDO_TDOC = cdo.CDO_TDOC and det.CDO_IDEN = cdo.CDO_IDEN
							UNION
							SELECT 1 as LIN_TIPO, 
								13 as LIN_LNUM,														
								('I' + CAST(din.DIN_CODI as varchar(59))) as LIN_PCOD,
								din.DIN_NOME as LIN_PDES,								 								
								ISNULL(cdo.CDO_TTHO, 0) as LIN_UPRI,																
								din.DIN_NOME as LIN_DESC,								
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN 'ISE' ELSE 'NOR' END) as LIN_TAXC, 
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN (SELECT PAP_TXIS FROM TAB_PAPL WITH(NOLOCK)) ELSE ISNULL(cdo.CDO_TXIV, 0) END) as LIN_TAXP,								
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.CDO_ISIV ELSE NULL END) as LIN_TXER, 
								(CASE ISNULL(cdo.CDO_IVA, 0) WHEN 0 THEN cdo.IIV_CODI ELSE NULL END) as LIN_TXEC
							FROM TAB_DINE as din WITH(NOLOCK) 
							WHERE din.DIN_CODI = cdo.DIN_HONO and ISNULL(cdo.CDO_TTHO, 0) > 0
						) as lin
						ORDER BY lin.LIN_TIPO, lin.LIN_LNUM
						FOR XML PATH('Line'), TYPE),
						(SELECT CAST(ISNULL(cdo.CDO_IVA, 0) as numeric(38, 2)) as "TaxPayable",
							CAST((ISNULL(cdo.CDO_TTPR, 0) - ISNULL(cdo.CDO_IVA, 0)) as numeric(38, 2)) as "NetTotal",
							CAST(ISNULL(cdo.CDO_TTPR, 0) as numeric(38, 2)) as "GrossTotal"
						FOR XML PATH('DocumentTotals'), TYPE)
					FROM FAC_CDOC AS cdo WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU 
						INNER JOIN #tmpWorkingDocs as twd ON cdo.CDO_TDOC = twd.TDO_DOCU and cdo.CDO_IDEN = twd.TDO_NDOC and cdo.CDO_EANO = twd.TDO_EANO
					ORDER BY cdo.CDO_TDOC, cdo.CDO_CNUM
					FOR XML PATH('WorkDocument'), TYPE)
				FROM FAC_CDOC AS cdo WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON cdo.CDO_TDOC = tdo.TDO_DOCU 
					INNER JOIN #tmpWorkingDocs as twd ON cdo.CDO_TDOC = twd.TDO_DOCU and cdo.CDO_IDEN = twd.TDO_NDOC and cdo.CDO_EANO = twd.TDO_EANO
				HAVING @SAFTGeral IN (0, 1)	
				FOR XML PATH('WorkingDocuments'), TYPE),
				(SELECT COUNT(DISTINCT (rec.REC_TDOC + CAST(rec.REC_NDOC as varchar(20)) + CAST(rec.REC_EANO as varchar(4)))) as "NumberOfEntries",
					CAST(ISNULL(SUM((CASE WHEN (red.REC_VPAG < 0) THEN (ABS(red.REC_VPAG) - ROUND(ABS(red.REC_VPAG) * ISNULL(mcc.MVC_VIVA, 0) / ABS(red.REC_VTOT), 2))	
							ELSE 0 END)), 0) as numeric(38, 2)) as "TotalDebit",
					CAST(ISNULL(SUM((CASE WHEN (red.REC_VPAG >= 0) THEN (ABS(red.REC_VPAG) - ROUND(ABS(red.REC_VPAG) * ISNULL(mcc.MVC_VIVA, 0) / ABS(red.REC_VTOT), 2)) 
							ELSE 0 END)), 0) as numeric(38, 2)) as "TotalCredit",	
					(SELECT rec.REC_INVN as "PaymentRefNo",	
						rec.REC_ATCU as "ATCUD",										
						CONVERT(varchar(10), rec.REC_DATA, 120) as TransactionDate,
						'RG' as "PaymentType",						
						(SELECT 'N' as "PaymentStatus",
							CONVERT(varchar(19), ISNULL(rec.REC_DTAL, rec.REC_DTCR), 126) as "PaymentStatusDate",
							ISNULL(NULLIF(rec.REC_UTIA, ''), rec.REC_UTIC) as "SourceID",
							'P' as "SourcePayment"							
						FOR XML PATH('DocumentStatus'), TYPE),						
						ISNULL(rec.REC_UTIC, 'Desconhecido') as "SourceID", 
						CONVERT(varchar(19), rec.REC_DTCR, 126) as "SystemEntryDate",
						UPPER(rec.REC_ENTI) as "CustomerID",
						(SELECT ROW_NUMBER() OVER(ORDER BY det.REC_DATA, det.MVC_TDOC, det.MVC_NDOC) as "LineNumber",
							(SELECT dbo.fn_Faturacao_ConstroiInvoiceNumber(mcc.MVC_TDOC, mcc.MVC_SERI, mcc.MVC_NDOC) as "OriginatingON",
								CONVERT(varchar(10), det.REC_DATA, 120) as "InvoiceDate"								
							FOR XML PATH('SourceDocumentID'), TYPE),
							CAST(det.REC_VDES as numeric(38, 2)) as "SettlementAmount", 
							CAST((CASE WHEN (det.REC_VPAG < 0) THEN (ABS(det.REC_VPAG) - ROUND(ABS(det.REC_VPAG) * ISNULL(mcc.MVC_VIVA, 0) / ABS(det.REC_VTOT), 2)) ELSE NULL END) as numeric(38, 2)) as "DebitAmount",
							CAST((CASE WHEN (det.REC_VPAG >= 0) THEN (ABS(det.REC_VPAG) - ROUND(ABS(det.REC_VPAG) * ISNULL(mcc.MVC_VIVA, 0) / ABS(det.REC_VTOT), 2)) ELSE NULL END) as numeric(38, 2)) as "CreditAmount"	
						FROM FAC_RECD as det WITH(NOLOCK) INNER JOIN FAC_MVCC as mcc WITH(NOLOCK) ON det.MVC_TDOC = mcc.MVC_TDOC and det.MVC_NDOC = mcc.MVC_NDOC and det.MVC_EANO = mcc.MVC_EANO 
						WHERE det.REC_TDOC = rec.REC_TDOC and det.REC_NDOC = rec.REC_NDOC and det.REC_EANO = rec.REC_EANO
						ORDER BY det.REC_DATA, det.MVC_TDOC, det.MVC_NDOC
						FOR XML PATH('Line'), TYPE),
						(SELECT CAST((SELECT SUM(ROUND(ABS(red.REC_VPAG + red.REC_VDES) * ISNULL(mcc.MVC_VIVA, 0) / ABS(red.REC_VTOT), 2)) FROM FAC_RECD as red WITH(NOLOCK) INNER JOIN FAC_MVCC as mcc WITH(NOLOCK) ON red.MVC_TDOC = mcc.MVC_TDOC and red.MVC_NDOC = mcc.MVC_NDOC and red.MVC_EANO = mcc.MVC_EANO WHERE red.REC_TDOC = rec.REC_TDOC and red.REC_NDOC = rec.REC_NDOC and red.REC_EANO = rec.REC_EANO) as numeric(38, 2)) as "TaxPayable", 							
							CAST(ABS(REC_VTOT) - (SELECT SUM(ROUND(ABS(red.REC_VPAG + red.REC_VDES) * ISNULL(mcc.MVC_VIVA, 0) / ABS(red.REC_VTOT), 2)) FROM FAC_RECD as red WITH(NOLOCK) INNER JOIN FAC_MVCC as mcc WITH(NOLOCK) ON red.MVC_TDOC = mcc.MVC_TDOC and red.MVC_NDOC = mcc.MVC_NDOC and red.MVC_EANO = mcc.MVC_EANO WHERE red.REC_TDOC = rec.REC_TDOC and red.REC_NDOC = rec.REC_NDOC and red.REC_EANO = rec.REC_EANO) as numeric(38, 2)) as "NetTotal", 
							CAST(ABS(REC_VTOT) as numeric(38, 2)) as "GrossTotal", 																					
							CAST(NULLIF(ISNULL(rec.REC_VDES, 0), 0) as numeric(38, 2)) as "Settlement/SettlementAmount"
						FOR XML PATH('DocumentTotals'), TYPE)
					FROM FAC_RECC as rec WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON rec.REC_TDOC = tdo.TDO_DOCU
						INNER JOIN #tmpPayments as tpa ON rec.REC_TDOC = tpa.TDO_DOCU and rec.REC_NDOC = tpa.TDO_NDOC and rec.REC_EANO = tpa.TDO_EANO 
					ORDER BY rec.REC_TDOC, rec.REC_NDOC
					FOR XML PATH('Payment'), TYPE)
				FROM FAC_RECC as rec WITH(NOLOCK) INNER JOIN TAB_TDOC as tdo WITH(NOLOCK) ON rec.REC_TDOC = tdo.TDO_DOCU 
					INNER JOIN FAC_RECD as red WITH(NOLOCK) ON rec.REC_TDOC = red.REC_TDOC and rec.REC_NDOC = red.REC_NDOC and rec.REC_EANO = red.REC_EANO
					INNER JOIN FAC_MVCC as mcc WITH(NOLOCK) ON red.MVC_TDOC = mcc.MVC_TDOC and red.MVC_NDOC = mcc.MVC_NDOC and red.MVC_EANO = mcc.MVC_EANO 
					INNER JOIN #tmpPayments as tpa ON rec.REC_TDOC = tpa.TDO_DOCU and rec.REC_NDOC = tpa.TDO_NDOC and rec.REC_EANO = tpa.TDO_EANO 
				HAVING @SAFTGeral IN (1, 2)				
				FOR XML PATH('Payments'), TYPE)
			FOR XML PATH('SourceDocuments'), TYPE)
		FOR XML PATH('AuditFile'), ELEMENTS)
-- nas opções "Comunicação de Facturas à AT" ou "Exportação SAF-T PT - Portaria 302/2016", atualiza documentos de Contas e Vendas como "Exportados p/ SAF-T"
	IF @SAFTGeral IN (0, 1)
	BEGIN
-- atualiza documentos de Contas com tipo diferente de "OR" como "Exportados p/ SAF-T"
		UPDATE FAC_CDOC SET CDO_ESAF = 1, CDO_DSAF = GETDATE()
		FROM FAC_CDOC as cdo WITH(NOLOCK) 			
			INNER JOIN #tmpInvoices as tin ON cdo.CDO_TDOC = tin.TDO_DOCU and cdo.CDO_IDEN = tin.TDO_NDOC and cdo.CDO_EANO = tin.TDO_EANO and tin.TDO_TDOC = 0
-- atualiza documentos de Vendas como "Exportados p/ SAF-T"		
		UPDATE FAC_DVEN SET DVE_ESAF = 1, DVE_DSAF = GETDATE()
		FROM FAC_DVEN as dve WITH(NOLOCK) 			
			INNER JOIN #tmpInvoices as tin ON dve.DVE_TDOC = tin.TDO_DOCU and dve.DVE_NDOC = tin.TDO_NDOC and dve.DVE_EANO = tin.TDO_EANO and tin.TDO_TDOC = 1	
-- atualiza documentos de Contas do tipo "OR" como "Exportados p/ SAF-T"
		UPDATE FAC_CDOC SET CDO_ESAF = 1, CDO_DSAF = GETDATE()
		FROM FAC_CDOC AS cdo WITH(NOLOCK) 			
			INNER JOIN #tmpWorkingDocs as twd ON cdo.CDO_TDOC = twd.TDO_DOCU and cdo.CDO_IDEN = twd.TDO_NDOC and cdo.CDO_EANO = twd.TDO_EANO
	END
-- remove tabelas temporárias criadas
	DROP TABLE #tmpInvoices	
	DROP TABLE #tmpWorkingDocs
	DROP TABLE #tmpPayments	
	DROP TABLE #tmpCustomers
	DROP TABLE #tmpProducts
END

ALTER AUTHORIZATION ON [SP_SAFT_ExportacaoSAFTPortaria3022016] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SAFT_ExportacaoSAFTPortaria3022016] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SaidasAEX_GeraDeclaracoesDeXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SaidasAEX_GeraDeclaracoesDeXML] @XMLSaidas xml(XMLSC_SaidasAEXToGIDWin), @Utilizador varchar(30), @MensagemErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Acao varchar(1), @CodLocalizacaoMercadorias varchar(17), @Data datetime, @AnoEntradaAEX int, @NumeroEntradaAEX int, @Volumes int, @PesoBruto numeric(38, 6), @NumeroContramarca varchar(6), 
		@NumeroSDS varchar(35), @NumeroOrdem varchar(35), @DataOrdem datetime, @Regime varchar(4), @AutorizacaoSaida bit, @DataAS datetime, @DataIntegracaoAS datetime, @Anulado bit, @MotivoAnulacao varchar(150), 
		@Informacao1 varchar(70), @Informacao2 varchar(70)
	DECLARE @DataAtual datetime, @AnoSaidaAEX int, @NumeroSaidaAEX int, @IDEntradaAEX varchar(20)
-- carrega saídas AEX do XML p/ INSERT
	DECLARE SaidasAEX CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT XML_SAIS.SAI_DATA.value('@Acao[1]', 'varchar(1)'), XML_SAIS.SAI_DATA.value('CodLocalizacaoMercadorias[1]', 'varchar(17)'), XML_SAIS.SAI_DATA.value('Data[1]', 'datetime'), 
			XML_SAIS.SAI_DATA.value('AnoEntradaAEX[1]', 'int'), XML_SAIS.SAI_DATA.value('NumeroEntradaAEX[1]', 'int'), XML_SAIS.SAI_DATA.value('Volumes[1]', 'int'), 
			XML_SAIS.SAI_DATA.value('PesoBruto[1]', 'numeric(38, 6)'), NULLIF(XML_SAIS.SAI_DATA.value('NumeroContramarca[1]', 'varchar(6)'), ''), NULLIF(XML_SAIS.SAI_DATA.value('NumeroSDS[1]', 'varchar(35)'), ''), 
			NULLIF(XML_SAIS.SAI_DATA.value('NumeroOrdem[1]', 'varchar(35)'), ''), XML_SAIS.SAI_DATA.value('DataOrdem[1]', 'datetime'), XML_SAIS.SAI_DATA.value('Regime[1]', 'varchar(4)'), 
			XML_SAIS.SAI_DATA.value('AutorizacaoSaida[1]', 'bit'), XML_SAIS.SAI_DATA.value('DataAS[1]', 'datetime'), XML_SAIS.SAI_DATA.value('DataIntegracaoAS[1]', 'datetime'), 
			XML_SAIS.SAI_DATA.value('Anulado[1]', 'bit'), NULLIF(XML_SAIS.SAI_DATA.value('MotivoAnulacao[1]', 'varchar(150)'), ''), NULLIF(XML_SAIS.SAI_DATA.value('Informacao1[1]', 'varchar(70)'), ''), 
			NULLIF(XML_SAIS.SAI_DATA.value('Informacao2[1]', 'varchar(70)'), '')
		FROM @XMLSaidas.nodes('SaidasAEXToGIDWin/SaidaAEX') as XML_SAIS(SAI_DATA)	
		WHERE XML_SAIS.SAI_DATA.value('@Acao[1]', 'varchar(1)') IN ('I', 'U')
	OPEN SaidasAEX
	FETCH NEXT FROM SaidasAEX INTO @Acao, @CodLocalizacaoMercadorias, @Data, @AnoEntradaAEX, @NumeroEntradaAEX, @Volumes, @PesoBruto, @NumeroContramarca, @NumeroSDS, @NumeroOrdem, @DataOrdem, @Regime, 
		@AutorizacaoSaida, @DataAS, @DataIntegracaoAS, @Anulado, @MotivoAnulacao, @Informacao1, @Informacao2
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- inicia transacção para inserção dados da saída AEX
		BEGIN TRANSACTION	
		BEGIN TRY				
			SET @AnoSaidaAEX = YEAR(@Data)
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem o ID da entrada AEX
			SELECT @IDEntradaAEX = EDG_IDST
			FROM AEX_ENDG WITH(NOLOCK)
			WHERE EDG_EANO = @AnoEntradaAEX AND LME_CODI = @CodLocalizacaoMercadorias AND EDG_NUME = @NumeroEntradaAEX
-- se ação for de "Insert"
			IF @Acao = 'I'
			BEGIN		
-- obtem numero da saída da localização de mercadorias
				SELECT @NumeroSaidaAEX = LME_PNRS
				FROM TAB_LMER
				WHERE LME_CODI = @CodLocalizacaoMercadorias									
-- insere saída AEX
				INSERT INTO AEX_SADG(SDG_EANO, LME_CODI, SDG_NUME, SDG_DATA, EDG_EANO, EDG_NUME, EDG_IDST, SDG_VOLS, SDG_PBRT, SDG_NCTM, SDG_NSDS, SDG_NNRM, SDG_DNRM, SDG_ASAI, SDG_REGI, SDG_INF1, SDG_INF2, 
					SDG_ANUL, SDG_MOTI, SDG_ORIG, SDG_UCRI, SDG_DCRI, SDG_UALT, SDG_DALT, SDG_DTAS, SDG_DT6A)				
				VALUES(@AnoSaidaAEX, @CodLocalizacaoMercadorias, @NumeroSaidaAEX, @Data, @AnoEntradaAEX, @NumeroEntradaAEX, @IDEntradaAEX, @Volumes, @PesoBruto, @NumeroContramarca, @NumeroSDS, @NumeroOrdem, 
					@DataOrdem, @AutorizacaoSaida, @Regime, @Informacao1, @Informacao2, @Anulado, @MotivoAnulacao, 2, @Utilizador, @DataAtual, @Utilizador, @DataAtual, @DataAS, @DataIntegracaoAS)
-- incrementa nº. proxima saída na localização de mercadorias
				UPDATE TAB_LMER SET LME_PNRS = LME_PNRS + 1
				WHERE LME_CODI = @CodLocalizacaoMercadorias	
			END
			ELSE			
			BEGIN				
-- edita saída AEX			
				UPDATE AEX_SADG SET SDG_DATA = @Data, EDG_EANO = @AnoEntradaAEX, EDG_NUME = @NumeroEntradaAEX, EDG_IDST = @IDEntradaAEX, SDG_VOLS = @Volumes, SDG_PBRT = @PesoBruto, SDG_NCTM = @NumeroContramarca, 
					SDG_NSDS = @NumeroSDS, SDG_NNRM = @NumeroOrdem, SDG_DNRM = @DataOrdem, SDG_ASAI = @AutorizacaoSaida, SDG_REGI = @Regime, SDG_INF1 = @Informacao1, SDG_INF2 = @Informacao2, SDG_ANUL = @Anulado, 
					SDG_MOTI = @MotivoAnulacao, SDG_UALT = @Utilizador, SDG_DALT = @DataAtual, SDG_DTAS = @DataAS, SDG_DT6A = @DataIntegracaoAS
				WHERE SDG_EANO = @AnoSaidaAEX AND LME_CODI = @CodLocalizacaoMercadorias AND SDG_NUME = -1 /*UPDATE não funcional daí o valor -1. PAra funcionar deverá ser adicionado no schema o nº. saida AEX facultativo*/
			END
		END TRY
		BEGIN CATCH							
-- constroi mensagem de erro detalhada
			SELECT @MensagemErro = @MensagemErro + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '** ERRO DE SAIDA AEX NAO INSERIDA ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Entrada AEX N.º:' + @CodLocalizacaoMercadorias + ' ' + CAST(@AnoEntradaAEX as varchar(4)) + '.' +  CAST(@NumeroEntradaAEX as varchar(10)) + CHAR(12) +
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
-- em caso de erro faz rollback da transacção iniciada						           
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION	
		END CATCH	
-- se sucesso faz commit da transacção iniciada
		IF @@TRANCOUNT > 0
			COMMIT TRANSACTION			
		FETCH NEXT FROM SaidasAEX INTO @Acao, @CodLocalizacaoMercadorias, @Data, @AnoEntradaAEX, @NumeroEntradaAEX, @Volumes, @PesoBruto, @NumeroContramarca, @NumeroSDS, @NumeroOrdem, @DataOrdem, @Regime, 
			@AutorizacaoSaida, @DataAS, @DataIntegracaoAS, @Anulado, @MotivoAnulacao, @Informacao1, @Informacao2
	END
	CLOSE SaidasAEX
	DEALLOCATE SaidasAEX
END

ALTER AUTHORIZATION ON [SP_SaidasAEX_GeraDeclaracoesDeXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SaidasAEX_GeraDeclaracoesDeXML] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SaidasAEX_ImportaFicheirosSTANDARD]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SaidasAEX_ImportaFicheirosSTANDARD] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml, @ListaErros varchar(MAX), @i int, @Erros varchar(MAX), @PathFicheiroErro varchar(500), 
		@Linha varchar(MAX)
-- verifica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'			
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros a importar (considera apenas ficheiros cuja extensão é ".xml")
	DECLARE FicheirosXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]		
	OPEN FicheirosXML
	FETCH NEXT from FicheirosXML into @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN				
		SET @ListaErros = ''				
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)				
-- obtem o xml do ficheiro xml importado						
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- remove o namespace existente na raiz <SaidasAEXToGIDWin> do XML 
			SET @FicheiroXML = STUFF(CAST(@FicheiroXML as varchar(MAX)), 1, CHARINDEX('>', CAST(@FicheiroXML as varchar(MAX))), '<SaidasAEXToGIDWin>')		
-- processa a geração da declaração de Saída AEX carregada no XML
			EXEC SP_SaidasAEX_GeraDeclaracoesDeXML @FicheiroXML, @Utilizador, @ListaErros OUTPUT				
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Nome Ficheiro XML:  ' + @NomeFicheiro + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN	
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END					
		FETCH NEXT from FicheirosXML into @PathFicheiro, @NomeFicheiro
	END
	CLOSE FicheirosXML
	DEALLOCATE FicheirosXML
-- remove as tabelas temporárias	
	DROP TABLE #ConteudoFicheiro	
END

ALTER AUTHORIZATION ON [SP_SaidasAEX_ImportaFicheirosSTANDARD] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SaidasAEX_ImportaFicheirosSTANDARD] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SaidasAEX_InsereOuEditaViaExportacaoXMLouSDSViaAerea]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SaidasAEX_InsereOuEditaViaExportacaoXMLouSDSViaAerea] @ViaExportacaoXML bit, @Ano int, @Codigo int, @CodOperador varchar(6) = NULL, @NumeroAWB varchar(30), 
	@Utilizador varchar(30), @MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @Erro int, @NumSaidaAEX int, @CodLocMercadorias varchar(17), @AnoEntradaAEX int, @NumEntradaAEX int, @IDEntradaAEX varchar(20), @SaldoVols int, 
		@SaldoPesoBrt numeric(38, 6), @DataAS datetime, @DataHoraMsg6A datetime
-- inicia variaveis
	SET @Erro = 0	
-- inicia transacção para inserção de Saída AEX
	BEGIN TRANSACTION		
	BEGIN TRY
-- verifica se existe Entrada AEX pendente p/ a Ref. Interna (AWB da linha)
		IF EXISTS(SELECT EDG_EANO FROM AEX_ENDG WHERE (EDG_EANO = @Ano or EDG_EANO = (@Ano - 1)) and EDG_REFI = @NumeroAWB and (EDG_SVOL > 0 or EDG_SPBR > 0))
		BEGIN
-- obtem dados da Entrada AEX associada à Ref. Interna (AWB da linha)
			SELECT @AnoEntradaAEX = edg.EDG_EANO, @CodLocMercadorias = edg.LME_CODI, @NumEntradaAEX = edg.EDG_NUME, @IDEntradaAEX = edg.EDG_IDST, @SaldoVols = edg.EDG_SVOL, 
				@SaldoPesoBrt = edg.EDG_SPBR, @DataAS = exm.EXM_DTAS, @DataHoraMsg6A = exm.EXM_DT6A
			FROM AEX_ENDG as edg LEFT OUTER JOIN PRO_EXML as exm ON edg.EDG_ORIG = 1 and edg.EXM_EANO = exm.EXM_EANO and edg.EXM_CODI = exm.EXM_CODI and edg.DEC_CODI = exm.DEC_CODI
			WHERE (edg.EDG_EANO = @Ano or edg.EDG_EANO = (@Ano - 1)) and edg.EDG_REFI = @NumeroAWB and (edg.EDG_SVOL > 0 or edg.EDG_SPBR > 0)
-- verifica se já existe Saída AEX p/ a Entrada AEX obtida, se sim edita saída			
			IF EXISTS(SELECT SDG_EANO FROM AEX_SADG WHERE EDG_EANO = @AnoEntradaAEX and LME_CODI = @CodLocMercadorias and EDG_NUME = @NumEntradaAEX)
			BEGIN
				UPDATE AEX_SADG SET SDG_VOLS = @SaldoVols, SDG_PBRT = @SaldoPesoBrt, SDG_UALT = @Utilizador, SDG_DALT = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
				WHERE EDG_EANO = @AnoEntradaAEX and LME_CODI = @CodLocMercadorias and EDG_NUME = @NumEntradaAEX
			END
			ELSE
			BEGIN
-- obtem numero da entrada da localização de mercadorias
				SELECT @NumSaidaAEX = LME_PNRS
				FROM TAB_LMER
				WHERE LME_CODI = @CodLocMercadorias		
-- insere Dados Gerais da Saída AEX c/ base nos dados de Exportação/XML ou SDS - Via Aérea
				IF @ViaExportacaoXML = 1
				BEGIN
					INSERT INTO AEX_SADG(SDG_EANO, LME_CODI, SDG_NUME, SDG_DATA, EDG_EANO, EDG_NUME, EDG_IDST, SDG_VOLS, SDG_PBRT, SDG_NNRM, SDG_DNRM, 
						SDG_ASAI, SDG_REGI, SDG_ORIG, SDG_UCRI, SDG_DCRI, SDG_UALT, SDG_DALT, SDG_DTAS, SDG_DT6A)
					SELECT YEAR(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), @CodLocMercadorias, @NumSaidaAEX, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @AnoEntradaAEX, @NumEntradaAEX, @IDEntradaAEX, @SaldoVols, @SaldoPesoBrt, 
						EXM_NDGA, EXM_DDGA, EXM_ASAI, '1000', 2, @Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), EXM_DTAS, EXM_DT6A
					FROM PRO_EXML
					WHERE EXM_EANO = @Ano and EXM_CODI = @Codigo and DEC_CODI = @CodOperador 
				END
				ELSE
				BEGIN					
					INSERT INTO AEX_SADG(SDG_EANO, LME_CODI, SDG_NUME, SDG_DATA, EDG_EANO, EDG_NUME, EDG_IDST, SDG_VOLS, SDG_PBRT, SDG_NCTM, SDG_NSDS, SDG_NNRM, SDG_DNRM, 
						SDG_ASAI, SDG_REGI, SDG_ORIG, SDG_UCRI, SDG_DCRI, SDG_UALT, SDG_DALT, SDG_DTAS, SDG_DT6A)
					SELECT TOP 1 YEAR(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), @CodLocMercadorias, @NumSaidaAEX, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @AnoEntradaAEX, @NumEntradaAEX, @IDEntradaAEX, @SaldoVols, @SaldoPesoBrt, 
						dsc.DSC_NCMV, dsd.DSD_NDGI, dsd.DSD_NDAU, CAST(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 105) as datetime), dsd.DSD_ASAI, '1000', 1, @Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
						@Utilizador, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @DataAS, @DataHoraMsg6A
					FROM PRO_SDSD as dsd INNER JOIN PRO_SDSC as dsc ON dsd.DSC_EANO = dsc.DSC_EANO and dsd.DSC_NPRO = dsc.DSC_NPRO
					WHERE dsd.DSC_EANO = @Ano and dsd.DSC_NPRO = @Codigo and dsd.DSD_NRMH = @NumeroAWB and dsd.DSD_ENVI = 1
				END
-- incrementa nº. proxima saída na localização de mercadorias
				UPDATE TAB_LMER SET LME_PNRS = LME_PNRS + 1
				WHERE LME_CODI = @CodLocMercadorias					
			END
		END		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) + ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_SaidasAEX_InsereOuEditaViaExportacaoXMLouSDSViaAerea] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SaidasAEX_InsereOuEditaViaExportacaoXMLouSDSViaAerea] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SaidasAEX_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SaidasAEX_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das saídas AEX para migração de dados no novo sistema GIDWin
		SELECT SDG_EANO, LME_CODI, SDG_NUME, SDG_DATA, EDG_EANO, EDG_NUME, SDG_VOLS, SDG_PBRT, SDG_NCTM, SDG_NSDS, SDG_NNRM, SDG_DNRM, SDG_ASAI, SDG_REGI, SDG_INF1, SDG_INF2, SDG_ANUL, SDG_MOTI
		FROM AEX_SADG WITH(NOLOCK)			
		ORDER BY SDG_EANO, LME_CODI, SDG_NUME
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SaidasAEX_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SaidasAEX_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_GeraDeclaracaoECSDSS]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_GeraDeclaracaoECSDSS] @AnoSDS int, @NumeroSDS int, @CodAeroportoAFiltrar varchar(8), @EstCargaAFiltrar varchar(7), @AWBMasterAFiltrar varchar(30), 
	@CodClienteECSDSSAGerar varchar(18), @CodFornecedorECSDSSAGerar varchar(18), @NumRefUnicoECSDSSAGerar varchar(70), @NumDocumentoECSDSSAGerar varchar(35), @DataDocumentoECSDSSAGerar datetime, 
	@NumDocDeclaracaoSumariaECSDSSAGerar varchar(35), @CodDeclaranteECSDSS varchar(18) OUTPUT, @NumeroECSDSS int OUTPUT, @Utilizador varchar(30), @IdUnicoTS varchar(20), @ManifestoExportacao bit, 
	@DataRequerimento datetime, @AWBMasterValida bit AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @DataAtual datetime, @EstatutoCarga varchar(3), @IDPaisItenerario int, @TotalAdicoes int, @TotalMassaBruta numeric(38,6), @TotalVols int, @CodArtigo varchar(22), 
		@CodPautalArtigo varchar(8), @DescMercadoriaSDS varchar(280), @CodMercUNArtigo varchar(4), @PesoSDS numeric(38,6), @NumeroAWBSDS varchar(35), @DataAWBSDS datetime, 
		@MarcasENumerosSDS varchar(42), @TipoVolsSDS varchar(2), @NumeroVols int, @NumeroDGASDS varchar(24), @DataVooSDS datetime, @IDLinhaAWBSDS int, @NumPartidas int
-- obtem a data atual
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem o estatuto de carga selecionado em modo de SDS Exportação
	IF @ManifestoExportacao = 1
	BEGIN
		IF SUBSTRING(@EstCargaAFiltrar, 2, 1) = '1'
			SET @EstatutoCarga = 'C'
		ELSE
			IF SUBSTRING(@EstCargaAFiltrar, 3, 1) = '1'
				SET @EstatutoCarga = 'X'
			ELSE
				SET @EstatutoCarga = NULL		
	END
-- obtem o número de partidas associadas à AWB quando em modo de SDS Exportação
	IF (@ManifestoExportacao = 1) AND (ISNULL(@AWBMasterAFiltrar, '') <> '') AND (@AWBMasterValida = 1)
	BEGIN
		SELECT @NumPartidas = COUNT(*)
		FROM PRO_SDSD AS lma WITH(NOLOCK) 
			INNER JOIN PRO_SDSD AS lpa WITH(NOLOCK) ON lpa.DOC_CODI = 'N740' AND lma.DSD_IDCR = lpa.DSD_CODR
		WHERE lma.DSC_EANO = @AnoSDS AND lma.DSC_NPRO = @NumeroSDS AND lma.DSD_NRMH = @AWBMasterAFiltrar
	END
	ELSE
		SET @NumPartidas = 0
-- obtem dados do 1º Declarante ECS-DSS existente
	SELECT TOP 1 @CodDeclaranteECSDSS = DCS_CODI, @NumeroECSDSS = DCS_PNPR
	FROM TAB_DECS
-- insere dados gerais da declaração ECS-DSS	
	INSERT INTO PRO_DESS (DSS_EANO, DCS_CODI, DSS_NPRO, DCS_NOME, DSS_TDEC, DSR_NOME, DSR_MORA, DSR_CPOS, DSR_LOCA, PAI_CODI, DSR_NNIF, DSS_IESC, DSS_DATA, DSS_CPRT, DSS_DTVO, DSS_NRLO, 
		LEM_CODI, LEM_DESC, LME_CODI, LME_NOME, DSS_DTDC, DSS_LCDC, EAD_CODI, EAD_NOME, EAD_COD2, EAD_NOM2, DSS_NCRF, CLI_CODI, DSS_CNOM, DSS_CMOR, DSS_CLOC, DSS_CCPO, DSS_CLPO, DSS_CPAI, 
		DSS_CNIF, DSS_CTNF, FOR_CODI, DSS_FNOM, DSS_FMOR, DSS_FLOC, DSS_FCPO, DSS_FLPO, DSS_FPAI, DSS_FNIF, DSS_UCRI, DSS_DCRI, DSS_UALT, DSS_DALT)
	SELECT sds.DSC_EANO, dcs.DCS_CODI, @NumeroECSDSS, dcs.DCS_NOME, dcs.DCS_TDEC, rpr.DSR_NOME, rpr.DSR_MORA, rpr.DSR_CPOS, rpr.DSR_LOCA, rpr.PAI_CODI, rpr.DSR_NNIF, dcs.DCS_IESC, 
		CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), @NumRefUnicoECSDSSAGerar, sds.DSC_DTVO, 
		(CAST(sds.DSC_EANO AS varchar(4)) + 'PT' + REPLICATE('0', 9 - LEN(dcs.DCS_NNIF)) + dcs.DCS_NNIF + 'S' + REPLICATE('0', 6 - LEN(dcs.DCS_PNPR)) + CAST(dcs.DCS_PNPR AS varchar(6))),
		dcs.LEM_CODI, lem.LEM_DESC, dcs.LME_CODI, lme.LME_NOME, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), dcs.DCS_LOCA, dcs.EAD_CODI, ea1.EAD_NOME, dcs.EAD_CODI, ea1.EAD_NOME,  
		@NumRefUnicoECSDSSAGerar, cli.CLI_CODI, cli.CLI_NOME, cli.CLI_MORA, cli.CLI_LOCA, cli.CLI_CPOS, cli.CLI_LPOS, cli.PAI_CODI, 
		cli.CLI_NIF, cli.CLI_TNIF, frn.FOR_CODI, frn.FOR_NOME, frn.FOR_MORA, frn.FOR_LOCA, frn.FOR_CPOS, frn.FOR_LPOS, frn.PAI_CODI, frn.FOR_NIF, @Utilizador, @DataAtual, @Utilizador, @DataAtual
	FROM PRO_SDSC AS sds WITH(NOLOCK) 
		INNER JOIN TAB_DECS AS dcs WITH(NOLOCK) ON dcs.DCS_CODI = @CodDeclaranteECSDSS
		LEFT OUTER JOIN TAB_DCSR AS rpr WITH(NOLOCK) ON dcs.DCS_CODI = rpr.DCS_CODI and rpr.DSR_NUME = (SELECT TOP 1 DSR_NUME FROM TAB_DCSR WITH(NOLOCK) WHERE DCS_CODI = dcs.DCS_CODI)
		LEFT OUTER JOIN TAB_LEMB AS lem WITH(NOLOCK) ON dcs.LEM_CODI = lem.LEM_CODI
		LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON dcs.LME_CODI = lme.LME_CODI
		INNER JOIN TAB_EADU AS ea1 WITH(NOLOCK) ON dcs.EAD_CODI = ea1.EAD_CODI
		INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON cli.CLI_CODI = @CodClienteECSDSSAGerar
		INNER JOIN TAB_FORN AS frn WITH(NOLOCK) ON frn.FOR_CODI = @CodFornecedorECSDSSAGerar
	WHERE sds.DSC_EANO = @AnoSDS and sds.DSC_NPRO = @NumeroSDS
-- incrementa Nº. Proximo Processo do Declarante ECS-DSS
	UPDATE TAB_DECS SET DCS_PNPR = DCS_PNPR + 1
	WHERE DCS_CODI = @CodDeclaranteECSDSS
-- inicia variaveis
	SET @IDPaisItenerario = 1
-- insere detalhe de Itinerário nº.1 com País do Cliente Expedidor
	INSERT INTO PRO_DSSI (DSS_EANO, DCS_CODI, DSS_NPRO, DSI_NUME, PAI_CODI, PAI_NOME)
	SELECT @AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @IDPaisItenerario, cli.PAI_CODI, pai.PAI_NOME
	FROM TAB_CLIE AS cli WITH(NOLOCK) 
		INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON cli.PAI_CODI = pai.PAI_CODI
	WHERE cli.CLI_CODI = @CodClienteECSDSSAGerar
-- incrementa variavel ID do detalhe de Paises do Itenerário
	SET @IDPaisItenerario = @IDPaisItenerario + 1
-- insere detalhe de Itinerário nº.2 com País "GB" fixo em modo Exportação
	IF @ManifestoExportacao = 1
	BEGIN
		INSERT INTO PRO_DSSI (DSS_EANO, DCS_CODI, DSS_NPRO, DSI_NUME, PAI_CODI, PAI_NOME)
		SELECT @AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @IDPaisItenerario, PAI_CODI, PAI_NOME
		FROM TAB_PAIS WITH(NOLOCK)
		WHERE PAI_CODI = 'GB'
-- incrementa variavel ID do detalhe de Paises do Itenerário
		SET @IDPaisItenerario = @IDPaisItenerario + 1
	END
-- insere detalhe de Itinerário nº.2 com País do Fornecedor Destinatário
	INSERT INTO PRO_DSSI (DSS_EANO, DCS_CODI, DSS_NPRO, DSI_NUME, PAI_CODI, PAI_NOME)
	SELECT @AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @IDPaisItenerario, frn.PAI_CODI, pai.PAI_NOME
	FROM TAB_FORN AS frn WITH(NOLOCK) 
		INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON frn.PAI_CODI = pai.PAI_CODI
	WHERE frn.FOR_CODI = @CodFornecedorECSDSSAGerar	
-- inicia variaveis
	SELECT @TotalAdicoes = 0, @TotalMassaBruta = 0, @TotalVols = 0
-- obtem Dados AWB do SDS - Via Aerea
	IF (@ManifestoExportacao = 1) AND (ISNULL(@AWBMasterAFiltrar, '') <> '') AND (@AWBMasterValida = 0)
	BEGIN
		DECLARE DadosAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT art.APA_CODI, SUBSTRING(art.APA_CPAU, 1, 8), art.APA_ATAR, 'Consolidation', SUM(sds.DSD_PESO), @AWBMasterAFiltrar, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), 
				'S/M', tem.TEM_CODI, SUM(sds.DSD_VOLS), NULL, NULL, NULL
			FROM PRO_SDSD AS sds WITH(NOLOCK) 
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
				INNER JOIN TAB_TEMB AS tem WITH(NOLOCK) ON tem.TEM_CODI = 'CT'
			WHERE sds.DSC_EANO = @AnoSDS AND sds.DSC_NPRO = @NumeroSDS AND sds.PAE_CODI = ISNULL(NULLIF(@CodAeroportoAFiltrar, ''), sds.PAE_CODI) 
				AND (
					(sds.DSD_EADC = 'T1' AND SUBSTRING(@EstCargaAFiltrar, 1, 1) = '1') OR (sds.DSD_EADC = 'C' AND SUBSTRING(@EstCargaAFiltrar, 2, 1) = '1') OR
					(sds.DSD_EADC = 'X' AND SUBSTRING(@EstCargaAFiltrar, 3, 1) = '1') OR (sds.DSD_EADC = 'T2' AND SUBSTRING(@EstCargaAFiltrar, 4, 1) = '1') OR
					(sds.DSD_EADC = 'TF' AND SUBSTRING(@EstCargaAFiltrar, 5, 1) = '1') OR (sds.DSD_EADC = 'TD' AND SUBSTRING(@EstCargaAFiltrar, 6, 1) = '1') OR
					(sds.DSD_EADC = 'SS' AND SUBSTRING(@EstCargaAFiltrar, 7, 1) = '1')
				)
				AND (CASE @ManifestoExportacao
						WHEN 1 THEN (CASE 
										WHEN (@EstatutoCarga = 'X') AND (sds.DSD_EADC = 'X') AND (sds.DSD_MRNR NOT LIKE 'LET%') AND (sds.DSD_TCAR = '101') AND (sds.DOC_CODI = 'N740') AND (NOT EXISTS(SELECT SDD_NUME FROM PRO_SSDD WITH(NOLOCK) WHERE DSC_EANO = sds.DSC_EANO AND DSC_NPRO = sds.DSC_NPRO AND DSD_NUME = sds.DSD_NUME AND DOC_CODI = 'N830')) THEN 1
										WHEN (@EstatutoCarga = 'C') AND (sds.DSD_EADC = 'C') THEN 1
										ELSE 0
									END)
						ELSE 1 
					END) = 1
			GROUP BY art.APA_CODI, art.APA_CPAU, art.APA_ATAR, tem.TEM_CODI
	END
	ELSE
	IF (@ManifestoExportacao = 1) AND (ISNULL(@AWBMasterAFiltrar, '') <> '') AND (@AWBMasterValida = 1) AND (@NumPartidas = 0)
	BEGIN
		DECLARE DadosAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT art.APA_CODI, SUBSTRING(art.APA_CPAU, 1, 8), art.APA_ATAR, sds.DSD_DMER, sds.DSD_PESO, sds.DSD_NRMH, sds.DSD_DTED, sds.DSD_MRNR, sds.TEM_CODI, sds.DSD_VOLS, 
				(CASE ISNULL(sds.DSD_NDGA, '') WHEN '' THEN (sdc.DSC_NCMF + sdc.DSC_NCMV) ELSE sds.DSD_NDGA END), sds.DSD_IDNN, sdc.DSC_DTVO
			FROM PRO_SDSD AS sds WITH(NOLOCK) 
				INNER JOIN PRO_SDSC AS sdc WITH(NOLOCK) ON sds.DSC_EANO = sdc.DSC_EANO and sds.DSC_NPRO = sdc.DSC_NPRO
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
			WHERE sds.DSC_EANO = @AnoSDS AND sds.DSC_NPRO = @NumeroSDS AND sds.DSD_NRMH = @AWBMasterAFiltrar					
	END
	ELSE	
	IF (@ManifestoExportacao = 1) AND (ISNULL(@AWBMasterAFiltrar, '') <> '') AND (@AWBMasterValida = 1) AND (@NumPartidas > 0)
	BEGIN
		DECLARE DadosAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT art.APA_CODI, SUBSTRING(art.APA_CPAU, 1, 8), art.APA_ATAR, lpa.DSD_DMER, lpa.DSD_PESO, lpa.DSD_NRMH, lpa.DSD_DTED, lpa.DSD_MRNR, lpa.TEM_CODI, lpa.DSD_VOLS, 
				(CASE ISNULL(lpa.DSD_NDGA, '') WHEN '' THEN (sdc.DSC_NCMF + sdc.DSC_NCMV) ELSE lpa.DSD_NDGA END), lpa.DSD_IDNN, sdc.DSC_DTVO
			FROM PRO_SDSD AS sds WITH(NOLOCK) 
				INNER JOIN PRO_SDSD AS lpa WITH(NOLOCK) ON lpa.DOC_CODI = 'N740' AND sds.DSD_IDCR = lpa.DSD_CODR
				INNER JOIN PRO_SDSC AS sdc WITH(NOLOCK) ON sds.DSC_EANO = sdc.DSC_EANO and sds.DSC_NPRO = sdc.DSC_NPRO
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
			WHERE sds.DSC_EANO = @AnoSDS AND sds.DSC_NPRO = @NumeroSDS AND sds.DSD_NRMH = @AWBMasterAFiltrar				
	END
	ELSE
	BEGIN
		DECLARE DadosAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT art.APA_CODI, SUBSTRING(art.APA_CPAU, 1, 8), art.APA_ATAR, sds.DSD_DMER, sds.DSD_PESO, sds.DSD_NRMH, sds.DSD_DTED, sds.DSD_MRNR, sds.TEM_CODI, sds.DSD_VOLS, 
				(CASE ISNULL(sds.DSD_NDGA, '') WHEN '' THEN (sdc.DSC_NCMF + sdc.DSC_NCMV) ELSE sds.DSD_NDGA END), sds.DSD_IDNN, sdc.DSC_DTVO
			FROM PRO_SDSD AS sds WITH(NOLOCK) 
				INNER JOIN PRO_SDSC AS sdc WITH(NOLOCK) ON sds.DSC_EANO = sdc.DSC_EANO and sds.DSC_NPRO = sdc.DSC_NPRO
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
			WHERE sds.DSC_EANO = @AnoSDS AND sds.DSC_NPRO = @NumeroSDS AND sds.PAE_CODI = ISNULL(NULLIF(@CodAeroportoAFiltrar, ''), sds.PAE_CODI) 
				AND (
					(sds.DSD_EADC = 'T1' AND SUBSTRING(@EstCargaAFiltrar, 1, 1) = '1') OR (sds.DSD_EADC = 'C' AND SUBSTRING(@EstCargaAFiltrar, 2, 1) = '1') OR
					(sds.DSD_EADC = 'X' AND SUBSTRING(@EstCargaAFiltrar, 3, 1) = '1') OR (sds.DSD_EADC = 'T2' AND SUBSTRING(@EstCargaAFiltrar, 4, 1) = '1') OR
					(sds.DSD_EADC = 'TF' AND SUBSTRING(@EstCargaAFiltrar, 5, 1) = '1') OR (sds.DSD_EADC = 'TD' AND SUBSTRING(@EstCargaAFiltrar, 6, 1) = '1') OR
					(sds.DSD_EADC = 'SS' AND SUBSTRING(@EstCargaAFiltrar, 7, 1) = '1')
				)
				AND (CASE @ManifestoExportacao
						WHEN 1 THEN (CASE 
										WHEN (@EstatutoCarga = 'X') AND (sds.DSD_EADC = 'X') AND (sds.DSD_MRNR NOT LIKE 'LET%') AND (sds.DSD_TCAR = '101') AND (sds.DOC_CODI = 'N740') AND (NOT EXISTS(SELECT SDD_NUME FROM PRO_SSDD WITH(NOLOCK) WHERE DSC_EANO = sds.DSC_EANO AND DSC_NPRO = sds.DSC_NPRO AND DSD_NUME = sds.DSD_NUME AND DOC_CODI = 'N830')) THEN 1
										WHEN (@EstatutoCarga = 'C') AND (sds.DSD_EADC = 'C') THEN 1
										ELSE 0
									END)
						ELSE 1 
					END) = 1
	END
	OPEN DadosAWB
	FETCH NEXT FROM DadosAWB INTO @CodArtigo, @CodPautalArtigo, @CodMercUNArtigo, @DescMercadoriaSDS, @PesoSDS, @NumeroAWBSDS, @DataAWBSDS, @MarcasENumerosSDS, @TipoVolsSDS, @NumeroVols, 
		@NumeroDGASDS, @IDLinhaAWBSDS, @DataVooSDS
	WHILE @@FETCH_STATUS = 0
	BEGIN			
		SELECT @TotalAdicoes = @TotalAdicoes + 1, @TotalMassaBruta = @TotalMassaBruta + @PesoSDS, @TotalVols = @TotalVols + @NumeroVols
-- insere detalhe de Adições
		INSERT INTO PRO_DSSA (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, APA_CODI, DSA_CPAU, DSA_DESG, DSA_MPUN, DSA_MBRT, DSD_IDNN)
		VALUES (@AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, @CodArtigo, @CodPautalArtigo, @DescMercadoriaSDS, @CodMercUNArtigo, @PesoSDS, 
			(CASE @ManifestoExportacao 
				WHEN 1 THEN @IDLinhaAWBSDS 
				ELSE NULL 
			END))
-- insere sub-detalhe de Documentos nº.1 com documento '9X01'
		INSERT INTO PRO_DSAD (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAD_NUME, DOC_CODI, DOC_NOME, DAD_NDOC, DAD_DDOC, DAD_AUTO)
		SELECT @AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, 1, DOC_CODI, DOC_NOME, @NumDocumentoECSDSSAGerar, @DataDocumentoECSDSSAGerar, 1
		FROM TAB_DOCU WITH(NOLOCK)
		WHERE DOC_CODI = '9X01' AND (DOC_TRAN = 1 OR DOC_EXPT = 1)
-- insere sub-detalhe de Documentos nº.2 com documento "N740"/"N741"
		INSERT INTO PRO_DSAD (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAD_NUME, DOC_CODI, DOC_NOME, DAD_NDOC, DAD_DDOC, DAD_AUTO)
		SELECT @AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, 2, DOC_CODI, DOC_NOME, @NumeroAWBSDS, @DataAWBSDS, 1
		FROM TAB_DOCU WITH(NOLOCK)
		WHERE DOC_CODI = (CASE 
							WHEN (@ManifestoExportacao = 1) AND (((ISNULL(@AWBMasterAFiltrar, '') <> '') AND (@AWBMasterValida = 0)) OR ((ISNULL(@AWBMasterAFiltrar, '') <> '') AND (@AWBMasterValida = 1) AND (@NumPartidas = 0)) OR (@EstatutoCarga = 'C')) THEN 'N741' 
							ELSE 'N740' 
						END) 
			AND (DOC_TRAN = 1 OR DOC_EXPT = 1)
-- insere sub-detalhe de Marcase Volumes
		INSERT INTO PRO_DSAM (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAM_NUME, DAM_MRNU, TEM_CODI, TEM_NOME, DAM_NVOL, DAM_NPCS, DAM_TIPO)
		SELECT @AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, 1, @MarcasENumerosSDS, TEM_CODI, TEM_NOME, 
			(case when (TEM_PVOL = 0 and TEM_PUNI = 0) or (TEM_PVOL = 0 and TEM_PUNI = 1) then 0 else @NumeroVols end),
			(case when (TEM_PVOL = 0 and TEM_PUNI = 0) or (TEM_PVOL = 1 and TEM_PUNI = 0) then 0 else @NumeroVols end),  
			(case when TEM_PVOL = 0 and TEM_PUNI = 0 then 0 when (TEM_PVOL = 1 and TEM_PUNI = 0) then 1 when (TEM_PVOL = 0 and TEM_PUNI = 1) then 2 else 3 end)
		FROM TAB_TEMB WITH(NOLOCK)
		WHERE TEM_CODI = @TipoVolsSDS
-- insere sub-detalhe de Declaração Sumária
		IF @ManifestoExportacao = 0
		BEGIN
			INSERT INTO PRO_DSAS (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAS_NUME, DAS_TIPO, DAS_NDOC, DAS_CATE, DAS_DATA, DAS_IDCR)
			VALUES (@AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, 1, 'DSE', @NumeroDGASDS, 'X', @DataVooSDS, @IdUnicoTS)
		END
		ELSE
		BEGIN
			IF @EstatutoCarga = 'X'
			BEGIN
				INSERT INTO PRO_DSAS (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAS_NUME, DAS_TIPO, DAS_NDOC, DAS_DATA, DAS_IDCR)
				VALUES (@AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, 1, 'ZZZ', ('Req. Autorizado na data: ' + CONVERT(varchar(10), @DataRequerimento, 105)), @DataRequerimento, @IdUnicoTS)
			END
			ELSE
				IF @EstatutoCarga = 'C'
				BEGIN
					INSERT INTO PRO_DSAS (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAS_NUME, DAS_TIPO, DAS_NDOC, DAS_DATA, DAS_IDCR)
					VALUES (@AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, 1, 'ZZZ', 'Transações Intracomunitárias', @DataRequerimento, @IdUnicoTS)
				END
				ELSE
					IF ISNULL(@NumDocDeclaracaoSumariaECSDSSAGerar, '') <> ''
					BEGIN
						INSERT INTO PRO_DSAS (DSS_EANO, DCS_CODI, DSS_NPRO, DSA_NUME, DAS_NUME, DAS_TIPO, DAS_NDOC, DAS_DATA, DAS_IDCR)
						VALUES (@AnoSDS, @CodDeclaranteECSDSS, @NumeroECSDSS, @TotalAdicoes, 1, 'ZZZ', @NumDocDeclaracaoSumariaECSDSSAGerar, @DataRequerimento, @IdUnicoTS)
					END
		END			
		FETCH NEXT FROM DadosAWB INTO @CodArtigo, @CodPautalArtigo, @CodMercUNArtigo, @DescMercadoriaSDS, @PesoSDS, @NumeroAWBSDS, @DataAWBSDS, @MarcasENumerosSDS, @TipoVolsSDS, @NumeroVols, 
			@NumeroDGASDS, @IDLinhaAWBSDS, @DataVooSDS
	END
	CLOSE DadosAWB
	DEALLOCATE DadosAWB
-- actualiza valores torais da declaração ECS-DSS	
	UPDATE PRO_DESS SET DSS_NADI = @TotalAdicoes, DSS_MBRT = @TotalMassaBruta, DSS_TVOL = @TotalVols
	WHERE DSS_EANO = @AnoSDS and DCS_CODI = @CodDeclaranteECSDSS and DSS_NPRO = @NumeroECSDSS
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_GeraDeclaracaoECSDSS] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_GeraDeclaracaoECSDSS] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_GeraManifestoExp]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_SDSViaAerea_GeraManifestoExp] @AnoSDSOrigem int, @NumeroSDSOrigem int, @DataVoo datetime, @NumContramarcaVar varchar(6), @Utilizador varchar(30), 
	@FechoContentores bit, @CodEstancia varchar(8), @EnvioCMOficial bit, @IDEntidadeDesconsolidacao int, @CodPaisDestino varchar(2), @EstCarga varchar(3), 
	@AWBMasterT1 varchar(30), @AWBMasterX varchar(30), @NumECSDSS varchar(30), @DataECSDSS datetime, @LstAWBScanXML xml, @NomeBDOrigem varchar(6) = NULL AS
BEGIN
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @DataAtual datetime, @NumeroSDS int, @AnoSDS int, @InsereManifesto bit, @NumLinhaAWB int, @NumeroAWB varchar(30), @CodDocumento varchar(5), @NomeDocumento varchar(70), 
		@LocalEmissaoDocumento varchar(30), @DataEmissaoDocumento datetime, @EntidadeEmissaoDocumento varchar(60), @CodPais varchar(2), @NomePais varchar(35), 
		@TipoManifesto varchar(2), @CodAeroportoDest varchar(8), @NomeAeroportoDest varchar(35), @CodAeroportoEsc varchar(8), @NomeAeroportoEsc varchar(35), 
		@CodAeroportoOrig varchar(8), @NomeAeroportoOrig varchar(35), @TemCTU bit, @MencaoEXP bit, @EstatutoCarga varchar(3), @IdOriginalShipper varchar(50), 
		@NomeOriginalShipper varchar(75), @IdShipper varchar(50), @NomeShipper varchar(75), @IdDestinatario varchar(50), @NomeDestinatario varchar(75), 
		@IdNotificado varchar(50), @IdConsignatario varchar(50), @DescMercadorias varchar(150), @MarcasNumeros varchar(25), @CodTipoEmb varchar(2), @NomeTipoEmb varchar(35), 
		@PesoBrt numeric(38, 6), @Vols int, @TipoCarga varchar(3), @CodLocMercadorias varchar(17), @NomeLocMercadorias varchar(70), @CodAeroportoEmb varchar(8), 
		@NomeAeroportoEmb varchar(35), @Poseima bit, @TipoOrigem int, @IDAdicaoXML int, @Valor numeric(38, 6), @NumOrdemDAU varchar(22), @DataEntrada datetime, @NumTD int, 
		@Depositario varchar(50), @IDLinhaAWB int, @ApenasDeposito bit, @NomeEntidadeDesconsolidar varchar(70), @NIFEntidadeDesconsolidar varchar(20), 
		@PesoBrtInicial numeric(38, 6), @VolsInicial int, @MoradaOriginalShipper varchar(100), @MoradaDestinatario varchar(100), @NovoNumLinhaAWB int, 
		@IDStrInternoOrigem varchar(20), @IDStrInternoDestino varchar(20), @IDStrRelacaoOrigem varchar(20), @IDStrRelacaoDestino varchar(20), @CargaPerigosa bit, 
		@IntegraXML bit, @CodAlfandega varchar(8), @NomeAlfandega varchar(35), @NumeroVoo varchar(35), @CodPaisVoo varchar(2), @CodPostalOriginalShipper varchar(17), 
		@LocalidadeOriginalShipper varchar(35), @NumDocPrecedente varchar(70), @CodArtigo varchar(22), @CodPautalArtigo varchar(22), @DataHoraPrevista datetime, 
		@CodPedido varchar(5), @NomePedido varchar(150), @TextoPedido varchar(512), @NomeBDOrigemCompleto varchar(8), @SQLSelect varchar(MAX)
	DECLARE @TblLinhasAWBSDSOrigem TABLE(DSD_NRMH varchar(30) NOT NULL, DOC_CODI varchar(5) NOT NULL, DOC_NOME varchar(70) NULL, DSD_LOED varchar(30) NOT NULL, 
		DSD_DTED datetime NOT NULL, DSD_EEED varchar(60) NOT NULL, PAI_CODI varchar(2) NOT NULL, PAI_NOME varchar(35) NULL, PAE_CODI varchar(8) NOT NULL, 
		PAE_NOME varchar(35) NULL, PAE_CODI1 varchar(8) NOT NULL, PAE_NOME1 varchar(35) NULL, PAE_CODI2 varchar(8) NOT NULL, PAE_NOME2 varchar(35) NULL, 
		DSD_TCTU bit NOT NULL, DSD_TMEX bit NOT NULL, DSD_EADC varchar(3) NOT NULL, DSD_IDOS varchar(50) NULL, DSD_NOOS varchar(75) NULL, DSD_IDNS varchar(50) NULL, 
		DSD_NONS varchar(75) NOT NULL, DSD_IDED varchar(50) NULL, DSD_NOMD varchar(75) NULL, DSD_IDEN varchar(50) NULL, DSD_IDEC varchar(50) NOT NULL, 
		DSD_DMER varchar(150) NOT NULL, DSD_MRNR varchar(25) NOT NULL, TEM_CODI varchar(2) NOT NULL, TEM_NOME varchar(35) NOT NULL, DSD_PESO numeric(38, 6) NOT NULL, 
		DSD_VOLS int NOT NULL, DSD_TCAR varchar(3) NOT NULL, LME_CODI varchar(17) NULL, PAE_CODI3 varchar(8) NOT NULL, PAE_NOME3 varchar(35) NULL, 
		DSD_VALO numeric(38, 6) NOT NULL, DSD_DTEN datetime NULL, PDD_IDDE varchar(20) NULL,  DSD_IDNN int NOT NULL, DSD_PDEP bit NOT NULL, DSD_PES2 numeric(38, 6) NOT NULL, 
		DSD_VOL2 int NOT NULL, DSD_MOOS varchar(100) NULL, DSD_MORD varchar(100) NULL, DSD_CPER bit NOT NULL, EAD_CODI varchar(8) NOT NULL, EAD_NOME varchar(35) NOT NULL, 
		DSD_CPOS varchar(17) NULL, DSD_LOOS varchar(35) NULL, DSD_NDPR varchar(70) NULL, APA_CODI varchar(22) NULL, DSD_CPAU varchar(22) NULL, TXM_CODI varchar(5) NULL, 
		TXM_DESC varchar(150) NULL, DSD_PTXT varchar(512) NULL)
-- inicia variaveis
	SET @AnoSDS = YEAR(@DataVoo)
	SET @IntegraXML = (CASE WHEN @IDEntidadeDesconsolidacao IS NULL THEN 1 ELSE 0 END)
	SET @NomeBDOrigemCompleto = ISNULL((NULLIF(@NomeBDOrigem, '') + '..'), '')
-- se operação não for de "Fecho de Contentores" nem "Envio CM Oficial", insere novo manifesto
	IF (@FechoContentores = 0) AND (@EnvioCMOficial = 0)
	BEGIN
		IF @IDEntidadeDesconsolidacao IS NULL
			SET @InsereManifesto = 1
		ELSE
			IF EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WHERE DSC_TIPO = 1 AND DSC_IXML = @IntegraXML AND DSC_EANO = @AnoSDS AND EAD_CODI = @CodEstancia AND CAST(CONVERT(varchar(10), DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataVoo, 105) AS datetime) AND DSC_NCMV = @NumContramarcaVar)
				SET @InsereManifesto = 0
			ELSE
				SET @InsereManifesto = 1
	END
	ELSE
-- se operação for de "Envio CM Oficial", procede à copia dos Dados AWB
		IF (@FechoContentores = 0) AND (@EnvioCMOficial = 1)
			SET @InsereManifesto = 0
		ELSE
-- se operação for de "Fecho de Contentores" verifica se manifesto de exportação p/ a data de voo já existe
			IF (@FechoContentores = 1) AND (@EnvioCMOficial = 0)
			BEGIN
				IF EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WHERE DSC_TIPO = 1 and DSC_IXML = @IntegraXML and DSC_EANO = @AnoSDS and EAD_CODI = @CodEstancia and CAST(CONVERT(varchar(10), DSC_DTVO, 105) as datetime) = CAST(CONVERT(varchar(10), @DataVoo, 105) as datetime))
					SET @InsereManifesto = 0
				ELSE
					SET @InsereManifesto = 1
			END		
			ELSE
				RETURN
-- procede à inserção de manifesto de exportação se for caso disso
	IF @InsereManifesto = 1
	BEGIN		
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()					
-- obtem dados dos Parâmetros de SDS - Via Aérea
		SELECT TOP 1 @NumeroSDS = PSD_PRNR, 
			@NumeroVoo = ISNULL((CASE @CodEstancia WHEN 'PT000020' THEN NULLIF(PSD_NVEP, '') ELSE NULLIF(PSD_NVEL, '') END), ''), 			
			@CodPaisVoo = ISNULL((CASE @CodEstancia WHEN 'PT000020' THEN NULLIF(PAI_CODI1, '') ELSE NULLIF(PAI_CODI, '') END), 'QU'), 
			@DataHoraPrevista = CAST(CONVERT(varchar(10), @DataVoo, 105) + ' ' + ISNULL(CONVERT(varchar(12), (CASE @CodEstancia WHEN 'PT000020' THEN PSD_HPEP ELSE PSD_HPEL END), 114), '00:00:00:000') AS datetime)			
		FROM TAB_PSDS
-- constroi o SELECT para obtenção dos dados do Manifesto SDS de Importação ou Exportação, quer seja na própria BD ou em BD diferente
		SET @SQLSelect = 'SELECT ' + LTRIM(STR(@AnoSDS, 4)) + ', ' + LTRIM(STR(@NumeroSDS, 20)) + ', 1, ISNULL(psd.PDD_IDRP, dsc.DSC_IDRP), ISNULL(psd.PDD_IDTP , dsc.DSC_IDTP), ISNULL(psd.PDD_IDTS, dsc.DSC_IDTR), ISNULL(psd.PDD_NRAP, dsc.DSC_NRAP), ISNULL(psd.PDD_AEMI, dsc.DSC_AEMI), dsc.EAD_CODI, dsc.EAD_NOME, ISNULL(psd.PDD_NVPR, dsc.DSC_NVPR), CAST(''' + CONVERT(varchar(10), @DataVoo, 105) + ''' AS datetime), ISNULL(psd.EAD_CODI, dsc.EAD_CODI1), ISNULL(ead.EAD_NOME, dsc.EAD_NOME1), 
				(RIGHT(dsc.EAD_CODI, 3) + ''4'' + ''' + LTRIM(STR(@AnoSDS, 4)) + '''), ''' + @NumContramarcaVar + ''', ''' + @Utilizador + ''', CAST(''' + CONVERT(varchar(10), @DataAtual, 105) + ' ' + CONVERT(varchar(12), @DataAtual, 114) + ''' AS datetime), ''' + @Utilizador + ''', CAST(''' + CONVERT(varchar(10), @DataAtual, 105) + ' ' + CONVERT(varchar(12), @DataAtual, 114) + ''' AS datetime), ' + STR(@IntegraXML, 1) + ', 
				ISNULL((CASE dsc.EAD_CODI WHEN ''PT000020'' THEN psd.PDD_IDDP ELSE psd.PDD_IDDL END), dsc.DSC_IDDP), 
				ISNULL(NULLIF(''' + @NumeroVoo + ''', ''''), dsc.DSC_NVOO), pvo.PAI_CODI, pvo.PAI_NOME,
				CAST(''' + CONVERT(varchar(10), @DataHoraPrevista, 105) + ' ' + CONVERT(varchar(12), @DataHoraPrevista, 114) + ''' AS datetime), dsc.DSC_PPRV, dsc.DSC_VPRV, 
				(CASE WHEN (dsc.DSC_TIPO = 1) OR (psd.PDD_IDEN IS NOT NULL) THEN ''' + REPLACE(CONVERT(numeric(38, 10), @DataAtual), '.', '') + ''' ELSE dsc.DSC_IDCM END)
			FROM ' + @NomeBDOrigemCompleto + 'PRO_SDSC AS dsc WITH(NOLOCK) 			
				LEFT OUTER JOIN ' + @NomeBDOrigemCompleto + 'TAB_PSDD AS psd WITH(NOLOCK) ON psd.PDD_IDEN = ' + ISNULL(LTRIM(STR(@IDEntidadeDesconsolidacao, 20)), '-1') + '
				LEFT OUTER JOIN ' + @NomeBDOrigemCompleto + 'TAB_EADU AS ead WITH(NOLOCK) ON psd.EAD_CODI = ead.EAD_CODI
				LEFT OUTER JOIN TAB_PAIS AS pvo WITH(NOLOCK) ON ''' + @CodPaisVoo + ''' = pvo.PAI_CODI	
			WHERE dsc.DSC_EANO = ' + LTRIM(STR(@AnoSDSOrigem, 4)) + ' AND dsc.DSC_NPRO = ' + LTRIM(STR(@NumeroSDSOrigem, 20))	
-- insere novo Manifesto de Exportação SDS - Via Aérea com base nos dados de outro manifesto
		INSERT INTO PRO_SDSC(DSC_EANO, DSC_NPRO, DSC_TIPO, DSC_IDRP, DSC_IDTP, DSC_IDTR, DSC_NRAP, DSC_AEMI, EAD_CODI, EAD_NOME, DSC_NVPR, DSC_DTVO, EAD_CODI1, EAD_NOME1, 
			DSC_NCMF, DSC_NCMV, DSC_UCRI, DSC_DCRI, DSC_UALT, DSC_DALT, DSC_IXML, DSC_IDDP, DSC_NVOO, PAI_CODI, PAI_NOME, DSC_DPRV, DSC_PPRV, DSC_VPRV, DSC_IDCM)
		EXEC (@SQLSelect)
-- incrementa Nº. Proximo manifesto no Parâmetros de SDS - Via Aérea
		UPDATE TAB_PSDS SET PSD_PRNR = PSD_PRNR + 1
-- inicia contador das linhas AWB
		SET @NovoNumLinhaAWB = 1		
	END
	ELSE
	BEGIN
		IF @IDEntidadeDesconsolidacao IS NULL
		BEGIN
			SELECT TOP 1 @NumeroSDS = DSC_NPRO, @NovoNumLinhaAWB = (ISNULL((SELECT MAX(DSD_NUME) FROM PRO_SDSD WHERE DSC_EANO = PRO_SDSC.DSC_EANO and DSC_NPRO = PRO_SDSC.DSC_NPRO), 0) + 1)
			FROM PRO_SDSC WITH(NOLOCK)
			WHERE DSC_TIPO = 1 and DSC_IXML = @IntegraXML and DSC_ACTI = @FechoContentores and DSC_EANO = @AnoSDS and EAD_CODI = @CodEstancia 
				and CAST(CONVERT(varchar(10), DSC_DTVO, 105) as datetime) = CAST(CONVERT(varchar(10), @DataVoo, 105) as datetime)
		END
		ELSE
		BEGIN
			SELECT TOP 1 @NumeroSDS = DSC_NPRO, @NovoNumLinhaAWB = (ISNULL((SELECT MAX(DSD_NUME) FROM PRO_SDSD WHERE DSC_EANO = PRO_SDSC.DSC_EANO and DSC_NPRO = PRO_SDSC.DSC_NPRO), 0) + 1)
			FROM PRO_SDSC WITH(NOLOCK)
			WHERE DSC_TIPO = 1 and DSC_IXML = @IntegraXML and DSC_EANO = @AnoSDS and EAD_CODI = @CodEstancia 
				and CAST(CONVERT(varchar(10), DSC_DTVO, 105) as datetime) = CAST(CONVERT(varchar(10), @DataVoo, 105) as datetime) and DSC_NCMV = @NumContramarcaVar			
		END
	END
-- se operação de "Fecho de Contentores" ou  "Envio CM Oficial", processa outras atualizações
	IF (@NumeroSDS IS NOT NULL) and ((@FechoContentores = 1) or (@EnvioCMOficial = 1))
	BEGIN
-- cria tabela temporária de relação de IDs INTERNOS STR entre as linhas AWB de origem e de destino 
		CREATE TABLE #tmpRELACAOLINHASAWB(IDSTRLINHAORIG varchar(20) COLLATE Latin1_General_CI_AI NOT NULL, IDSTRLINHADEST varchar(20) COLLATE Latin1_General_CI_AI NOT NULL)	
-- obtem as linhas AWB c/ "Env." não selecionado se operação de "Fecho de Contentores", e todas se operação de "Envio CM Oficial" e que ainda não existam no manifesto de destino e com o campo "Poseima" não selecionado
		DECLARE LinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT d.DSD_NUME, d.DSD_NRMH, d.DOC_CODI, d.DOC_NOME, d.DSD_LOED, d.DSD_DTED, d.DSD_EEED, d.PAI_CODI, d.PAI_NOME, d.DSD_TIPO, d.PAE_CODI, d.PAE_NOME, d.PAE_CODI1, d.PAE_NOME1, 
				d.PAE_CODI2, d.PAE_NOME2, d.DSD_TCTU, d.DSD_TMEX, d.DSD_EADC, d.DSD_IDOS, d.DSD_NOOS, d.DSD_IDNS, d.DSD_NONS, d.DSD_IDED, d.DSD_NOMD, d.DSD_IDEN, d.DSD_IDEC, d.DSD_DMER, 
				d.DSD_MRNR, d.TEM_CODI, d.TEM_NOME, d.DSD_PESO, d.DSD_VOLS, d.DSD_TCAR, d.LME_CODI, d.LME_NOME, d.PAE_CODI3, d.PAE_NOME3, d.DSD_CAPO, d.DSD_ORIG, d.EXA_CHVE, d.DSD_VALO, 
				d.DSD_NDAU, d.DSD_DTEN, d.DSD_TDEP, d.DSD_DEPO, d.DSD_IDNN, d.DSD_PDEP, d.DSD_NEAD, d.DSD_CEAD, d.DSD_PES2, d.DSD_VOL2, d.DSD_MOOS, d.DSD_MORD, d.DSD_IDCR, d.DSD_CODR, d.DSD_CPOS, 
				d.DSD_LOOS, d.DSD_NDPR, d.APA_CODI, d.DSD_CPAU, d.TXM_CODI, d.TXM_DESC, d.DSD_PTXT
			FROM PRO_SDSD AS d WITH(NOLOCK)
			WHERE d.DSD_ENVI = (CASE WHEN (@FechoContentores = 1) AND (@LstAWBScanXML IS NULL) THEN 0 ELSE d.DSD_ENVI END) AND d.DSD_CAPO = 0 AND d.DSC_EANO = @AnoSDSOrigem 
				AND d.DSC_NPRO = @NumeroSDSOrigem AND (NOT EXISTS(SELECT DSD_NUME FROM PRO_SDSD WITH(NOLOCK) WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NRMH = d.DSD_NRMH))	
				AND ((@LstAWBScanXML IS NULL) OR ((@LstAWBScanXML IS NOT NULL) AND (d.DSD_NRMH IN (SELECT XML_MSGR.MSG_DATA.value('.[1]', 'varchar(30)') FROM @LstAWBScanXML.nodes('DadosAWB/AWB') as XML_MSGR(MSG_DATA)))))
		OPEN LinhasAWB
		FETCH NEXT FROM LinhasAWB INTO @NumLinhaAWB, @NumeroAWB, @CodDocumento, @NomeDocumento, @LocalEmissaoDocumento, @DataEmissaoDocumento, @EntidadeEmissaoDocumento, @CodPais, @NomePais, 
			@TipoManifesto, @CodAeroportoDest, @NomeAeroportoDest, @CodAeroportoEsc, @NomeAeroportoEsc, @CodAeroportoOrig, @NomeAeroportoOrig, @TemCTU, @MencaoEXP, @EstatutoCarga, 
			@IdOriginalShipper, @NomeOriginalShipper, @IdShipper, @NomeShipper, @IdDestinatario, @NomeDestinatario, @IdNotificado, @IdConsignatario, @DescMercadorias, @MarcasNumeros, @CodTipoEmb, 
			@NomeTipoEmb, @PesoBrt, @Vols, @TipoCarga, @CodLocMercadorias, @NomeLocMercadorias, @CodAeroportoEmb, @NomeAeroportoEmb, @Poseima, @TipoOrigem, @IDAdicaoXML, @Valor, @NumOrdemDAU, 
			@DataEntrada, @NumTD, @Depositario, @IDLinhaAWB, @ApenasDeposito, @NomeEntidadeDesconsolidar, @NIFEntidadeDesconsolidar, @PesoBrtInicial, @VolsInicial, @MoradaOriginalShipper, 
			@MoradaDestinatario, @IDStrInternoOrigem, @IDStrRelacaoOrigem, @CodPostalOriginalShipper, @LocalidadeOriginalShipper, @NumDocPrecedente, @CodArtigo, @CodPautalArtigo, @CodPedido, 
			@NomePedido, @TextoPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- se operação de "Envio CM Oficial" obtem ID de origem p/ relação
			IF @EnvioCMOficial = 1
			BEGIN				
				SELECT @IDStrRelacaoDestino = IDSTRLINHADEST
				FROM #tmpRELACAOLINHASAWB
				WHERE IDSTRLINHAORIG = @IDStrRelacaoOrigem
			END
			ELSE
				SET @IDStrRelacaoDestino = NULL
-- calcula ID string interno para nova linha AWB
			SET @IDStrInternoDestino = REPLACE(CONVERT(numeric(38, 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), '.', ',')
-- insere linha AWB no manifesto de destino		
			INSERT INTO PRO_SDSD(DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DOC_NOME, DSD_LOED, DSD_DTED, DSD_EEED, PAI_CODI, PAI_NOME, DSD_TIPO, PAE_CODI, PAE_NOME, PAE_CODI1, PAE_NOME1, 
				PAE_CODI2, PAE_NOME2, DSD_TCTU, DSD_TMEX, DSD_EADC, DSD_IDOS, DSD_NOOS, DSD_IDNS, DSD_NONS, DSD_IDED, DSD_NOMD, DSD_IDEN, DSD_IDEC, DSD_DMER, DSD_MRNR, TEM_CODI, TEM_NOME, 
				DSD_PESO, DSD_VOLS, DSD_TCAR, LME_CODI, LME_NOME, PAE_CODI3, PAE_NOME3, DSD_CAPO, DSD_DNOW, DSD_ORIG, EXA_CHVE, DSD_VALO, DSD_NDAU, DSD_DTEN, DSD_TDEP, DSD_DEPO, DSD_PDEP, 
				DSD_IDCR, DSD_CODR, DSD_NEAD, DSD_CEAD, DSD_PES2, DSD_VOL2, DSD_MOOS, DSD_MORD, DSD_ENVI, DSD_IDFC, DSD_CPOS, DSD_LOOS, DSD_NDPR, APA_CODI, DSD_CPAU, TXM_CODI, TXM_DESC, DSD_PTXT)
			VALUES(@AnoSDS, @NumeroSDS, @NovoNumLinhaAWB, @NumeroAWB, @CodDocumento, @NomeDocumento, @LocalEmissaoDocumento, @DataEmissaoDocumento, @EntidadeEmissaoDocumento, @CodPais, @NomePais, 
				@TipoManifesto, @CodAeroportoDest, @NomeAeroportoDest, @CodAeroportoEsc, @NomeAeroportoEsc, @CodAeroportoOrig, @NomeAeroportoOrig, @TemCTU, @MencaoEXP, @EstatutoCarga, @IdOriginalShipper, 
				@NomeOriginalShipper, @IdShipper, @NomeShipper, @IdDestinatario, @NomeDestinatario, @IdNotificado, @IdConsignatario, @DescMercadorias, @MarcasNumeros, @CodTipoEmb, @NomeTipoEmb, @PesoBrt, 
				@Vols, @TipoCarga, @CodLocMercadorias, @NomeLocMercadorias, @CodAeroportoEmb, @NomeAeroportoEmb, @Poseima, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @TipoOrigem, @IDAdicaoXML, @Valor, 
				@NumOrdemDAU, @DataEntrada, @NumTD, @Depositario, @ApenasDeposito, @IDStrInternoDestino, @IDStrRelacaoDestino, @NomeEntidadeDesconsolidar, @NIFEntidadeDesconsolidar, @PesoBrtInicial, 
				@VolsInicial, @MoradaOriginalShipper, @MoradaDestinatario, (CASE WHEN (@FechoContentores = 1) AND (@IDLinhaAWB IS NOT NULL) THEN 1 ELSE @EnvioCMOficial END), 
				(CASE @FechoContentores WHEN 1 THEN @IDLinhaAWB ELSE NULL END), @CodPostalOriginalShipper, @LocalidadeOriginalShipper, @NumDocPrecedente, @CodArtigo, @CodPautalArtigo, @CodPedido, 
				@NomePedido, @TextoPedido)
-- se operação de "Envio CM Oficial", procede à inserção da relação na tabela temporária
			IF @EnvioCMOficial = 1
			BEGIN
				INSERT INTO #tmpRELACAOLINHASAWB(IDSTRLINHAORIG, IDSTRLINHADEST)
				VALUES(@IDStrInternoOrigem, @IDStrInternoDestino)
			END				
-- insere detalhe de documentos na linha AWB no manifesto de destino		
			INSERT INTO PRO_SSDD(DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC, SDD_ORIG)
			SELECT @AnoSDS, @NumeroSDS, @NovoNumLinhaAWB, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC, SDD_ORIG
			FROM PRO_SSDD WITH(NOLOCK)
			WHERE DSC_EANO = @AnoSDSOrigem and DSC_NPRO = @NumeroSDSOrigem and DSD_NUME = @NumLinhaAWB
-- se operação de "Fecho de Contentores", remove ligação à adição de Exportação/XML na linha AWB de origem, caso exista
			IF @FechoContentores = 1
			BEGIN
				UPDATE PRO_SDSD SET EXA_CHVE = NULL
				WHERE DSC_EANO = @AnoSDSOrigem and DSC_NPRO = @NumeroSDSOrigem and DSD_NUME = @NumLinhaAWB and EXA_CHVE IS NOT NULL
			END
			ELSE
-- se operação de "Envio CM Oficial", remove detalhe de documentos e linha AWB
				IF @EnvioCMOficial = 1
				BEGIN
					DELETE FROM PRO_SSDD
					WHERE DSC_EANO = @AnoSDSOrigem and DSC_NPRO = @NumeroSDSOrigem and DSD_NUME = @NumLinhaAWB
					DELETE FROM PRO_SDSD
					WHERE DSC_EANO = @AnoSDSOrigem and DSC_NPRO = @NumeroSDSOrigem and DSD_NUME = @NumLinhaAWB
				END
-- incrementa contador das linhas AWB
			SET @NovoNumLinhaAWB = @NovoNumLinhaAWB + 1		
-- espera 50 milisegundos para não obter IDs string interno igual à linha AWB anterior			
			WAITFOR DELAY '00:00:00.050'	
			FETCH NEXT FROM LinhasAWB INTO @NumLinhaAWB, @NumeroAWB, @CodDocumento, @NomeDocumento, @LocalEmissaoDocumento, @DataEmissaoDocumento, @EntidadeEmissaoDocumento, @CodPais, @NomePais, 
				@TipoManifesto, @CodAeroportoDest, @NomeAeroportoDest, @CodAeroportoEsc, @NomeAeroportoEsc, @CodAeroportoOrig, @NomeAeroportoOrig, @TemCTU, @MencaoEXP, @EstatutoCarga, 
				@IdOriginalShipper, @NomeOriginalShipper, @IdShipper, @NomeShipper, @IdDestinatario, @NomeDestinatario, @IdNotificado, @IdConsignatario, @DescMercadorias, @MarcasNumeros, @CodTipoEmb, 
				@NomeTipoEmb, @PesoBrt, @Vols, @TipoCarga, @CodLocMercadorias, @NomeLocMercadorias, @CodAeroportoEmb, @NomeAeroportoEmb, @Poseima, @TipoOrigem, @IDAdicaoXML, @Valor, @NumOrdemDAU, 
				@DataEntrada, @NumTD, @Depositario, @IDLinhaAWB, @ApenasDeposito, @NomeEntidadeDesconsolidar, @NIFEntidadeDesconsolidar, @PesoBrtInicial, @VolsInicial, @MoradaOriginalShipper, 
				@MoradaDestinatario, @IDStrInternoOrigem, @IDStrRelacaoOrigem, @CodPostalOriginalShipper, @LocalidadeOriginalShipper, @NumDocPrecedente, @CodArtigo, @CodPautalArtigo, @CodPedido, 
				@NomePedido, @TextoPedido
		END
		CLOSE LinhasAWB
		DEALLOCATE LinhasAWB
-- se operação de "Envio CM Oficial", desativa o Manifesto de Exportação SDS - Via Aérea de origem (= Fecho de Contentores ativo)
		IF (@FechoContentores = 1) AND (@LstAWBScanXML IS NULL)
		BEGIN
			UPDATE PRO_SDSC SET DSC_ACTI = 0, DSC_UINA = @Utilizador, DSC_DINA = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
			WHERE DSC_EANO = @AnoSDSOrigem and DSC_NPRO = @NumeroSDSOrigem
		END
		ELSE
-- se operação de "Envio CM Oficial", remove o próprio Manifesto de Exportação SDS - Via Aérea de origem	
			IF @EnvioCMOficial = 1
			BEGIN
				DELETE FROM PRO_SDSC 
				WHERE DSC_EANO = @AnoSDSOrigem and DSC_NPRO = @NumeroSDSOrigem
			END
-- remove tabela temporária
		DROP TABLE #tmpRELACAOLINHASAWB			
	END
	ELSE
-- se operação de "Desconsolidar Manifesto", processa outras atualizações
		IF (@NumeroSDS IS NOT NULL) and (@IDEntidadeDesconsolidacao IS NOT NULL)
		BEGIN	
-- cria tabela temporária p/ paises a filtrar
			CREATE TABLE #tmpPAISES(CODPAIS varchar(2) COLLATE Latin1_General_CI_AI NOT NULL)
			IF @CodPaisDestino = '0'
			BEGIN
				INSERT INTO #tmpPAISES(CODPAIS)
				SELECT PAI_CODI
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI IN ('AO', 'CV', 'ST')
			END
			ELSE
			BEGIN
				INSERT INTO #tmpPAISES(CODPAIS)
				SELECT PAI_CODI
				FROM TAB_PAIS WITH(NOLOCK)
				WHERE PAI_CODI = @CodPaisDestino
			END
-- cria tabela temporária p/ estatutos de carga a filtrar
			CREATE TABLE #tmpESTCARGA(CODIGO varchar(3) COLLATE Latin1_General_CI_AI NOT NULL)
			IF @EstCarga = '0'
			BEGIN
				INSERT INTO #tmpESTCARGA(CODIGO)
				VALUES('T1')
				INSERT INTO #tmpESTCARGA(CODIGO)
				VALUES('X')
			END
			ELSE
			BEGIN
				INSERT INTO #tmpESTCARGA(CODIGO)
				VALUES(@EstCarga)
			END	
-- constroi o SELECT para obtenção dos dados AWB do Manifesto SDS de Importação, quer seja na própria BD ou em BD diferente
			SET @SQLSelect = 'SELECT d.DSD_NRMH, d.DOC_CODI, d.DOC_NOME, d.DSD_LOED, d.DSD_DTED, d.DSD_EEED, d.PAI_CODI, d.PAI_NOME, d.PAE_CODI, d.PAE_NOME, d.PAE_CODI1, d.PAE_NOME1, 
					d.PAE_CODI2, d.PAE_NOME2, d.DSD_TCTU, d.DSD_TMEX, d.DSD_EADC, d.DSD_IDOS, d.DSD_NOOS, d.DSD_IDNS, d.DSD_NONS, d.DSD_IDED, d.DSD_NOMD, d.DSD_IDEN, d.DSD_IDEC, d.DSD_DMER, d.DSD_MRNR, 
					d.TEM_CODI, d.TEM_NOME, d.DSD_PESO, d.DSD_VOLS, d.DSD_TCAR, (CASE c.EAD_CODI WHEN ''PT000020'' THEN psd.LME_CODI1 ELSE psd.LME_CODI END), d.PAE_CODI3, d.PAE_NOME3, d.DSD_VALO, d.DSD_DTEN, (CASE c.EAD_CODI WHEN ''PT000020'' THEN psd.PDD_IDDP ELSE psd.PDD_IDDL END), d.DSD_IDNN, d.DSD_PDEP, d.DSD_PES2, 
					d.DSD_VOL2, d.DSD_MOOS, d.DSD_MORD, d.DSD_CPER, c.EAD_CODI, c.EAD_NOME, d.DSD_CPOS, d.DSD_LOOS, d.DSD_NDPR, d.APA_CODI, d.DSD_CPAU, d.TXM_CODI, d.TXM_DESC, d.DSD_PTXT
				FROM ' + @NomeBDOrigemCompleto + 'PRO_SDSD AS d WITH(NOLOCK)
					INNER JOIN ' + @NomeBDOrigemCompleto + 'PRO_SDSC AS c WITH(NOLOCK) ON d.DSC_EANO = c.DSC_EANO and d.DSC_NPRO = c.DSC_NPRO					 
					INNER JOIN ' + @NomeBDOrigemCompleto + 'TAB_PSDD AS psd WITH(NOLOCK) ON psd.PDD_IDEN = ' + ISNULL(LTRIM(STR(@IDEntidadeDesconsolidacao, 20)), '-1') + '					
				WHERE d.DSD_ENVI = 1 AND d.DSD_ANUL = 0 AND ISNULL(d.DSD_NDGI, '''') <> '''' 
					AND d.DSC_EANO = ' + LTRIM(STR(@AnoSDSOrigem, 4)) + ' AND d.DSC_NPRO = ' + LTRIM(STR(@NumeroSDSOrigem, 20))							
-- insere os dados AWB do Manifesto SDS de Importação da própria BD ou da BD diferente na tabela tmp
			INSERT INTO @TblLinhasAWBSDSOrigem(DSD_NRMH, DOC_CODI, DOC_NOME, DSD_LOED, DSD_DTED, DSD_EEED, PAI_CODI, PAI_NOME, PAE_CODI, PAE_NOME, PAE_CODI1, PAE_NOME1, 
				PAE_CODI2, PAE_NOME2, DSD_TCTU, DSD_TMEX, DSD_EADC, DSD_IDOS, DSD_NOOS, DSD_IDNS, DSD_NONS, DSD_IDED, DSD_NOMD, DSD_IDEN, DSD_IDEC, DSD_DMER, DSD_MRNR, 
				TEM_CODI, TEM_NOME, DSD_PESO, DSD_VOLS, DSD_TCAR, LME_CODI, PAE_CODI3, PAE_NOME3, DSD_VALO, DSD_DTEN, PDD_IDDE, DSD_IDNN, DSD_PDEP, DSD_PES2, DSD_VOL2, 
				DSD_MOOS, DSD_MORD, DSD_CPER, EAD_CODI, EAD_NOME, DSD_CPOS, DSD_LOOS, DSD_NDPR, APA_CODI, DSD_CPAU, TXM_CODI, TXM_DESC, DSD_PTXT)
			EXEC (@SQLSelect)								
-- obtem as linhas AWB c/ "Env." selecionado, não "Anuladas", c/ "Nº. NDGI" preenchido e cujo "País" do "Aeroporto Destino" e "Estatuto de Carga" sejam iguais aos especificados 
			DECLARE LinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT awb.DSD_NRMH, awb.DOC_CODI, awb.DOC_NOME, awb.DSD_LOED, awb.DSD_DTED, awb.DSD_EEED, awb.PAI_CODI, awb.PAI_NOME, awb.PAE_CODI, awb.PAE_NOME, 
					awb.PAE_CODI1, awb.PAE_NOME1, awb.PAE_CODI2, awb.PAE_NOME2, awb.DSD_TCTU, awb.DSD_TMEX, awb.DSD_EADC, awb.DSD_IDOS, awb.DSD_NOOS, awb.DSD_IDNS, 
					awb.DSD_NONS, awb.DSD_IDED, awb.DSD_NOMD, awb.DSD_IDEN, awb.DSD_IDEC, awb.DSD_DMER, awb.DSD_MRNR, awb.TEM_CODI, awb.TEM_NOME, awb.DSD_PESO, awb.DSD_VOLS, 
					awb.DSD_TCAR, awb.LME_CODI, lme.LME_NOME, awb.PAE_CODI3, awb.PAE_NOME3, awb.DSD_VALO, awb.DSD_DTEN, awb.PDD_IDDE, awb.DSD_IDNN, awb.DSD_PDEP, awb.DSD_PES2, 
					awb.DSD_VOL2, awb.DSD_MOOS, awb.DSD_MORD, awb.DSD_CPER, awb.EAD_CODI, awb.EAD_NOME, awb.DSD_CPOS, awb.DSD_LOOS, awb.DSD_NDPR, awb.APA_CODI, awb.DSD_CPAU, 
					awb.TXM_CODI, awb.TXM_DESC, awb.DSD_PTXT
				FROM @TblLinhasAWBSDSOrigem AS awb
					INNER JOIN TAB_PAER AS pd WITH(NOLOCK) ON awb.PAE_CODI = pd.PAE_CODI
					LEFT OUTER JOIN TAB_LMER AS lme WITH(NOLOCK) ON awb.LME_CODI = lme.LME_CODI
				WHERE pd.PAI_CODI IN (SELECT CODPAIS FROM #tmpPAISES) AND awb.DSD_EADC IN (SELECT CODIGO FROM #tmpESTCARGA)				
			OPEN LinhasAWB
			FETCH NEXT FROM LinhasAWB INTO @NumeroAWB, @CodDocumento, @NomeDocumento, @LocalEmissaoDocumento, @DataEmissaoDocumento, @EntidadeEmissaoDocumento, @CodPais, @NomePais, 
				@CodAeroportoDest, @NomeAeroportoDest, @CodAeroportoEsc, @NomeAeroportoEsc, @CodAeroportoOrig, @NomeAeroportoOrig, @TemCTU, @MencaoEXP, @EstatutoCarga, @IdOriginalShipper, 
				@NomeOriginalShipper, @IdShipper, @NomeShipper, @IdDestinatario, @NomeDestinatario, @IdNotificado, @IdConsignatario, @DescMercadorias, @MarcasNumeros, @CodTipoEmb, @NomeTipoEmb, 
				@PesoBrt, @Vols, @TipoCarga, @CodLocMercadorias, @NomeLocMercadorias, @CodAeroportoEmb, @NomeAeroportoEmb, @Valor, @DataEntrada, @Depositario, @IDLinhaAWB, @ApenasDeposito, 
				@PesoBrtInicial, @VolsInicial, @MoradaOriginalShipper, @MoradaDestinatario, @CargaPerigosa, @CodAlfandega, @NomeAlfandega, @CodPostalOriginalShipper, @LocalidadeOriginalShipper, 
				@NumDocPrecedente, @CodArtigo, @CodPautalArtigo, @CodPedido, @NomePedido, @TextoPedido
			WHILE @@FETCH_STATUS = 0
			BEGIN	
-- calcula ID string interno para nova linha AWB
				SET @IDStrInternoDestino = REPLACE(CONVERT(numeric(38, 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), '.', ',')
-- insere linha AWB no manifesto de destino		
				INSERT INTO PRO_SDSD(DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DOC_NOME, DSD_LOED, DSD_DTED, DSD_EEED, PAI_CODI, PAI_NOME, DSD_TIPO, PAE_CODI, PAE_NOME, PAE_CODI1, 
					PAE_NOME1, PAE_CODI2, PAE_NOME2, DSD_TCTU, DSD_TMEX, DSD_EADC, DSD_IDOS, DSD_NOOS, DSD_IDNS, DSD_NONS, DSD_IDED, DSD_NOMD, DSD_IDEN, DSD_IDEC, DSD_DMER, DSD_MRNR, TEM_CODI, 
					TEM_NOME, DSD_PESO, DSD_VOLS, DSD_TCAR, LME_CODI, LME_NOME, PAE_CODI3, PAE_NOME3, DSD_DNOW, DSD_VALO, DSD_DTEN, DSD_DEPO, DSD_PDEP, DSD_IDCR, DSD_PES2, DSD_VOL2, DSD_MOOS, 
					DSD_MORD, DSD_CPER, DSD_IDOR, DSD_MAWB, DSD_CPOS, DSD_LOOS, DSD_NDPR, APA_CODI, DSD_CPAU, TXM_CODI, TXM_DESC, DSD_PTXT)
				VALUES(@AnoSDS, @NumeroSDS, @NovoNumLinhaAWB, @NumeroAWB, @CodDocumento, @NomeDocumento, @LocalEmissaoDocumento, @DataEmissaoDocumento, @EntidadeEmissaoDocumento, @CodPais, @NomePais, 'C', 
					@CodAeroportoDest, @NomeAeroportoDest, @CodAeroportoEsc, @NomeAeroportoEsc, @CodAeroportoOrig, @NomeAeroportoOrig, @TemCTU, @MencaoEXP, @EstatutoCarga, @IdOriginalShipper, 
					@NomeOriginalShipper, @IdShipper, @NomeShipper, @IdDestinatario, @NomeDestinatario, @IdNotificado, @IdConsignatario, @DescMercadorias, @MarcasNumeros, @CodTipoEmb, @NomeTipoEmb, @PesoBrt, 
					@Vols, @TipoCarga, @CodLocMercadorias, @NomeLocMercadorias, @CodAeroportoEmb, @NomeAeroportoEmb, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), @Valor, @DataEntrada, @Depositario, 
					@ApenasDeposito, @IDStrInternoDestino, @PesoBrtInicial, @VolsInicial, @MoradaOriginalShipper, @MoradaDestinatario, @CargaPerigosa, @IDLinhaAWB, 
					(CASE @EstatutoCarga WHEN 'T1' THEN @AWBMasterT1 ELSE @AWBMasterX END), @CodPostalOriginalShipper, @LocalidadeOriginalShipper, @NumDocPrecedente, @CodArtigo, @CodPautalArtigo, 
					@CodPedido, @NomePedido, @TextoPedido)		
-- insere detalhe de documento "4D01" na linha AWB no manifesto de destino apenas quando a linha é "T1"
				IF @EstatutoCarga = 'T1' 
				BEGIN
					INSERT INTO PRO_SSDD(DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC)		
					SELECT @AnoSDS, @NumeroSDS, @NovoNumLinhaAWB, 1, DOC_CODI, DOC_NOME, @NumECSDSS, @DataECSDSS, @CodAlfandega, @NomeAlfandega, 'T'
					FROM TAB_DOCU WITH(NOLOCK)
					WHERE DOC_CODI = '4D01'
				END					
-- incrementa contador das linhas AWB
				SET @NovoNumLinhaAWB = @NovoNumLinhaAWB + 1		
-- espera 50 milisegundos para não obter IDs string interno igual à linha AWB anterior			
				WAITFOR DELAY '00:00:00.050'	
				FETCH NEXT FROM LinhasAWB INTO @NumeroAWB, @CodDocumento, @NomeDocumento, @LocalEmissaoDocumento, @DataEmissaoDocumento, @EntidadeEmissaoDocumento, @CodPais, @NomePais, 
					@CodAeroportoDest, @NomeAeroportoDest, @CodAeroportoEsc, @NomeAeroportoEsc, @CodAeroportoOrig, @NomeAeroportoOrig, @TemCTU, @MencaoEXP, @EstatutoCarga, @IdOriginalShipper, 
					@NomeOriginalShipper, @IdShipper, @NomeShipper, @IdDestinatario, @NomeDestinatario, @IdNotificado, @IdConsignatario, @DescMercadorias, @MarcasNumeros, @CodTipoEmb, @NomeTipoEmb, 
					@PesoBrt, @Vols, @TipoCarga, @CodLocMercadorias, @NomeLocMercadorias, @CodAeroportoEmb, @NomeAeroportoEmb, @Valor, @DataEntrada, @Depositario, @IDLinhaAWB, @ApenasDeposito, 
					@PesoBrtInicial, @VolsInicial, @MoradaOriginalShipper, @MoradaDestinatario, @CargaPerigosa, @CodAlfandega, @NomeAlfandega, @CodPostalOriginalShipper, @LocalidadeOriginalShipper, 
					@NumDocPrecedente, @CodArtigo, @CodPautalArtigo, @CodPedido, @NomePedido, @TextoPedido
			END
			CLOSE LinhasAWB
			DEALLOCATE LinhasAWB	
-- remove tabelas temporárias
			DROP TABLE #tmpPAISES
			DROP TABLE #tmpESTCARGA
		END		
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_GeraManifestoExp] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_GeraManifestoExp] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_GeraXMLEnvioManifesto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_GeraXMLEnvioManifesto] @AnoProcesso int, @NumProcesso int, @FicheiroXML xml, @Utilizador varchar(30), @MsgErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @DataHoraAtual datetime, @ProxyAuthentication bit, @ProxyServer varchar(100), 
		@ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), @WebServiceLocation nvarchar(250), @LoginAcesso varchar(20), @PwdAcesso varchar(50), 
		@PathCertificado varchar(250), @PwdCertificado varchar(50), @Resultado int, @FicheiroXMLBinario varbinary(MAX), @FicheiroXMLBase64 varchar(MAX),@RequestXML xml, 
		@ResponseXML xml, @ResultadoResponse nvarchar(MAX), @FaultMessage varchar(MAX)
	BEGIN TRY
-- inicia variáveis
		SET @MsgErro = NULL	
		SET @FaultMessage = NULL		
		SET @DataHoraAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- obtem configurações de Proxy Authentication
		SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), 
			@ProxyPassword = ISNULL(PAP_PPWD, '')		
		FROM TAB_PAPL	
-- obtem endereço Location do WebService p/ comunicação aos webservices do SDS - Via Aérea dos Depositários
		SELECT @WebServiceLocation = PSD_WSTR, @LoginAcesso = PSD_UTTR, @PwdAcesso = PSD_PWTR, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC
		FROM TAB_PSDS
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)		
-- converte o ficheiro XML gerado para varbinary e depois para Base64
		SET @FicheiroXMLBinario = CONVERT(varbinary(MAX), CAST(@FicheiroXML AS varchar(MAX))) 
		SET @FicheiroXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@FicheiroXMLBinario"))', 'varchar(MAX)') 		
-- constroi estrutura XML com os dados do pedido ao metodo submitMessages a enviar à AT
		;WITH XMLNAMESPACES ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' as wsse, 
			'http://server.ws.sds.dgita.gov.pt/' as ser, 
			'http://schemas.xmlsoap.org/soap/envelope/' as soapenv)
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT
						(SELECT @LoginAcesso "wsse:Username", @PwdAcesso "wsse:Password"
						FOR XML PATH('wsse:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wsse:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT @LoginAcesso "sender", 
						(SELECT @FicheiroXMLBase64
						FOR XML PATH('messages'), TYPE)
					FOR XML PATH('ser:submit'), TYPE)		
				FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN..SP_Externo_EnviarDadosWS @RequestXML, @WebServiceLocation, 'http://server.ws.sds.dgita.gov.pt/Traders/submit', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as "SOAP-ENV")
		SELECT @FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)		
-- obtem o resultado "OK"/"NOK" retornados do WS
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as S, 'http://server.ws.sds.dgita.gov.pt/' as ns0)		
		SELECT TOP 1 @ResultadoResponse = XML_MSGR.MSG_DATA.value('.[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('S:Envelope/S:Body/ns0:submitResponse/return') as XML_MSGR(MSG_DATA)			
-- se resultado não for "OK", manda erro
		IF @ResultadoResponse <> 'OK'
			RAISERROR('Erro no envio do webservice "%s".', 16, 3, @ResultadoResponse)		
-- atualiza processo SDS - Via Aérea p/ alteração do status e utilizador/data
		/*esta atualização, para já, é efetuada na aplicação devido ao envio/produção do ficheiro XML*/
-- atualiza linhas AWB do processo SDS - Via Aérea p/ alteração do status e data de envio do manifesto
		/*esta atualização, para já, é efetuada na aplicação devido ao envio/produção do ficheiro XML*/
	END TRY
	BEGIN CATCH	
		SET @MsgErro = ERROR_MESSAGE()
	END CATCH	
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_GeraXMLEnvioManifesto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_GeraXMLEnvioManifesto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_GeraXMLEnvioMovimentosSaida]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_GeraXMLEnvioMovimentosSaida] @AnoProcesso int, @NumProcesso int, @ViaWebservice bit, @Utilizador varchar(30), @FicheiroXML xml OUTPUT, 
	@LinhaXMLEncoding varchar(200) OUTPUT, @NomeFicheiroXML varchar(200) OUTPUT, @MsgErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @DataHoraAtual datetime, @CodLocMercadoriaArmDTPLIS varchar(17), @CodLocMercadoriaArmDTPOPO varchar(17), @ProxyAuthentication bit, @ProxyServer varchar(100), 
		@ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), @WebServiceLocation nvarchar(250), @LoginAcesso varchar(20), @PwdAcesso varchar(50), 
		@PathCertificado varchar(250), @PwdCertificado varchar(50), @Resultado int, @FicheiroXMLBinario varbinary(MAX), @FicheiroXMLBase64 varchar(MAX),@RequestXML xml, 
		@ResponseXML xml, @ResultadoResponse nvarchar(MAX), @FaultMessage varchar(MAX)
	BEGIN TRY
-- inicia variáveis
		SET @MsgErro = NULL	
		SET @FaultMessage = NULL		
-- obtem os armazéns DTP p/ LIS e OPO configurados nos Parâmetros de SDS - Via Aérea
		SELECT TOP 1 @CodLocMercadoriaArmDTPLIS = LME_CODI2, @CodLocMercadoriaArmDTPOPO = LME_CODI3
		FROM TAB_PSDS
-- inicia variáveis
		SET @DataHoraAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- constroi XML para ficheiro de envio do relatório de descarga SDS - Via Aérea
		;WITH XMLNAMESPACES ('http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperCargoMovement' AS m, 
			'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypes' AS dt,  
			'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypesMovement' AS dtm,
			DEFAULT 'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperCargoMovement')
		SELECT @FicheiroXML = 
			(SELECT 
				(SELECT (CAST(dsc.DSC_EANO AS varchar(4)) + 'M' + CAST(dsc.DSC_NPRO AS varchar(20)) + dsc.EAD_CODI) AS "dt:MessageIdentification", 
					CONVERT(varchar(19), @DataHoraAtual, 120) AS "dt:MessageDate",
					('PT' + dsc.DSC_IDDP) AS "dt:MessageSender",
					(dsc.DSC_NCMF + dsc.DSC_NCMV) AS "dt:CustomsReferenceNumber",
					('PT' + dsc.DSC_IDDP) AS "dt:WarehouseKeeper"
				FOR XML PATH('m:MessageInformation'), TYPE),			
				(SELECT 				
					(SELECT 'CreateAndFinalize' AS "dt:Action"					
					FOR XML PATH('m:Action'), TYPE), 
					(SELECT ('PT' + dsc.DSC_IDRP) AS "dt:CargoAgent", 
						dsd.DSD_NRMH AS "dt:ExternalReferenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dsd.DSD_DMER) AS "dt:DetailedDesignation", 
						(CASE RIGHT(dsc.EAD_CODI, 3) WHEN '020' THEN @CodLocMercadoriaArmDTPOPO ELSE @CodLocMercadoriaArmDTPLIS END) AS "dt:TemporaryStorageWarehouseIdentification", 
						CONVERT(varchar(19), dsd.DUI_DINI, 120) AS "dt:MovementDate", 
						CAST(dsd.DSD_PESO AS decimal(18, 3)) AS "dt:GrossWeight", 
						dsd.DSD_VOLS AS "dt:NumberOfPackages", 
						dsd.TEM_CODI AS "dt:NatureOfVolumes", 
						dsd.DSD_MRNR AS "dt:MarksAndNumbers", 
						dsd.DSD_TCAR AS "dt:CargoType"
					FOR XML PATH('m:GoodsDetails'), TYPE),
					(SELECT 'Exit' AS "dtm:MovementType", 
						('PT' + dsc.DSC_IDDP) AS "dtm:TransportCompany"
					FOR XML PATH('m:OtherDetails'), TYPE),
					(SELECT dsd.DOC_CODI AS "dt:Type", 					
						dsd.DSD_NRMH AS "dt:Number"
					FOR XML PATH('m:CustomsDocument'), TYPE),
					(SELECT dsd.DSD_DTRD AS "dt:Type", 					
						dsd.DSD_DNRD AS "dt:Number"
					FOR XML PATH('m:AssociatedDocument'), TYPE)				
				FROM VW_SDSViaAerea_MovimentoSaidaDadosAWB AS dsd
				WHERE dsd.DSC_EANO = dsc.DSC_EANO AND dsd.DSC_NPRO = dsc.DSC_NPRO AND ISNULL(dsd.DSD_DNRD, '') <> '' AND ISNULL(dsd.SIN_CODI, '') <> ''
				FOR XML PATH('m:Item'), TYPE)			
			FROM PRO_SDSC AS dsc 
			WHERE dsc.DSC_EANO = @AnoProcesso AND dsc.DSC_NPRO = @NumProcesso
			FOR XML PATH('m:AirWarehouseKeeperCargoMovement'), ELEMENTS)
-- processa envio de ficheiro XML gerado p/ Webservice
		IF @ViaWebservice = 0
		BEGIN
-- atribui linha de encoding para depois ser incluída no ficheiro XML a gerar
			SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="UTF-8"?>'	
-- obtem dados do processo SDS - Via Aérea p/ construção do nome do ficheiro XML a ser gerado
			SELECT @NomeFicheiroXML = ('ms-' + DSC_NCMF + DSC_NCMV + '-' + REPLACE(REPLACE(REPLACE(CONVERT(varchar(19), @DataHoraAtual, 120), ' ', ''), ':', ''), '-', '') + '.xml')		
			FROM PRO_SDSC
			WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso			
		END	
		ELSE
		BEGIN
-- obtem configurações de Proxy Authentication
			SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), 
				@ProxyPassword = ISNULL(PAP_PPWD, '')		
			FROM TAB_PAPL	
-- obtem endereço Location do WebService p/ comunicação aos webservices do SDS - Via Aérea dos Depositários
			SELECT @WebServiceLocation = PSD_WEBS, @LoginAcesso = PSD_UTIL, @PwdAcesso = PSD_PASS, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC
			FROM TAB_PSDS
-- valida se o path p/ o certificado é válido
			EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
			IF @Resultado = 0
				RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)			
-- converte o ficheiro XML gerado para varbinary e depois para Base64
			SET @FicheiroXMLBinario = CONVERT(varbinary(MAX), CAST(@FicheiroXML AS varchar(MAX))) 
			SET @FicheiroXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@FicheiroXMLBinario"))', 'varchar(MAX)') 		
-- constroi estrutura XML com os dados do pedido ao metodo submitMessages a enviar à AT
			;WITH XMLNAMESPACES ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' as wsse, 
				'http://server.ws.sds.dgita.gov.pt/' as ser, 
				'http://schemas.xmlsoap.org/soap/envelope/' as soapenv)
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT @LoginAcesso "wsse:Username", @PwdAcesso "wsse:Password"
							FOR XML PATH('wsse:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wsse:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT ('PT' + @LoginAcesso) "sender", 
							(SELECT @FicheiroXMLBase64
							FOR XML PATH('messages'), TYPE)
						FOR XML PATH('ser:submitMessages'), TYPE)		
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN..SP_Externo_EnviarDadosWS @RequestXML, @WebServiceLocation, 'http://server.ws.sds.dgita.gov.pt/WarehouseKeepers/submitMessages', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as "SOAP-ENV")
			SELECT @FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)			
-- obtem o resultado "OK"/"NOK" retornados do WS
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as S, 'http://server.ws.sds.dgita.gov.pt/' as ns0)		
			SELECT TOP 1 @ResultadoResponse = XML_MSGR.MSG_DATA.value('.[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('S:Envelope/S:Body/ns0:submitMessagesResponse/return') as XML_MSGR(MSG_DATA)	
-- se resultado não for "OK", manda erro
			IF @ResultadoResponse <> 'OK'
				RAISERROR('Erro no envio do webservice "%s".', 16, 3, @ResultadoResponse)			
		END		
-- atualiza processo SDS - Via Aérea p/ alteração do status e utilizador/data
		UPDATE PRO_SDSC SET DSC_STMS = 1, DSC_NRES = DSC_NRES + 1, DSC_UEMS = @Utilizador, DSC_DEMS = @DataHoraAtual 
		WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso
-- atualiza linhas AWB do processo SDS - Via Aérea p/ alteração do status e data de envio do movimento de saída
		UPDATE PRO_SDSD SET DSD_STMS = 1, DSD_DEMS = @DataHoraAtual
		FROM VW_SDSViaAerea_MovimentoSaidaDadosAWB AS SDSDVA_MSDAWB
		WHERE PRO_SDSD.DSC_EANO = SDSDVA_MSDAWB.DSC_EANO AND PRO_SDSD.DSC_NPRO = SDSDVA_MSDAWB.DSC_NPRO AND PRO_SDSD.DSD_NUME = SDSDVA_MSDAWB.DSD_NUME AND 
			PRO_SDSD.DSC_EANO = @AnoProcesso AND PRO_SDSD.DSC_NPRO = @NumProcesso AND ISNULL(SDSDVA_MSDAWB.DSD_DNRD, '') <> '' AND ISNULL(SDSDVA_MSDAWB.SIN_CODI, '') <> ''
	END TRY
	BEGIN CATCH	
		SET @MsgErro = ERROR_MESSAGE()
	END CATCH			
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_GeraXMLEnvioMovimentosSaida] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_GeraXMLEnvioMovimentosSaida] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_GeraXMLEnvioRelatorioDescarga]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_GeraXMLEnvioRelatorioDescarga] @AnoProcesso int, @NumProcesso int, @ViaWebservice bit, @Create bit, @TipoCarga varchar(3), @Utilizador varchar(30), 
	@FicheiroXML xml OUTPUT, @LinhaXMLEncoding varchar(200) OUTPUT, @NomeFicheiroXML varchar(200) OUTPUT, @MsgErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @DataHoraAtual datetime, @DataMovimentacaoRef datetime, @CodLocMercadoriaArmDTPLIS varchar(17), @CodLocMercadoriaArmDTPOPO varchar(17), @IDDepositario varchar(20), 
		@ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), @WebServiceLocation nvarchar(250), 
		@LoginAcesso varchar(20), @PwdAcesso varchar(50), @PathCertificado varchar(250), @PwdCertificado varchar(50), @Resultado int, @FicheiroXMLBinario varbinary(max), 
		@FicheiroXMLBase64 varchar(MAX),@RequestXML xml, @ResponseXML xml, @ResultadoResponse nvarchar(MAX), @CriteriosDHL bit, @FaultMessage varchar(MAX)
	BEGIN TRY
-- inicia variáveis
		SET @MsgErro = NULL	
		SET @FaultMessage = NULL		
-- verifica se é c/ os critérios DHL
		IF @TipoCarga = 'XXX'
		BEGIN
			SET @CriteriosDHL = 1
			SET @TipoCarga = NULL
		END
		ELSE
			SET @CriteriosDHL = 0
-- obtem os armazéns DTP p/ LIS e OPO configurados nos Parâmetros de SDS - Via Aérea
		SELECT TOP 1 @CodLocMercadoriaArmDTPLIS = LME_CODI2, @CodLocMercadoriaArmDTPOPO = LME_CODI3
		FROM TAB_PSDS
-- inicia variáveis
		SET @DataHoraAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
		SET @DataMovimentacaoRef = DATEADD(MINUTE, -10, @DataHoraAtual)
-- constroi XML para ficheiro de envio do relatório de descarga SDS - Via Aérea
		;WITH XMLNAMESPACES ('http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperCargoReport' AS r, 
			'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypes' AS dt,  
			'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypesReport' AS dtr,
			DEFAULT 'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperCargoReport')
		SELECT @FicheiroXML = 
			(SELECT 
				(SELECT (CAST(dsc.DSC_EANO AS varchar(4)) + 'M' + CAST(dsc.DSC_NPRO AS varchar(20)) + dsc.EAD_CODI) AS "dt:MessageIdentification", 
					CONVERT(varchar(19), @DataHoraAtual, 120) AS "dt:MessageDate",
					('PT' + dsc.DSC_IDDP) AS "dt:MessageSender",
					(dsc.DSC_NCMF + dsc.DSC_NCMV) AS "dt:CustomsReferenceNumber",
					('PT' + dsc.DSC_IDDP) AS "dt:WarehouseKeeper"
				FOR XML PATH('r:MessageInformation'), TYPE),
				(CASE @Create WHEN 1 THEN NULL ELSE 'EndOfOperationsUnload' END) AS "Action", 
				(SELECT 				
					(SELECT (CASE dsd.DSD_ESTI WHEN 1 THEN 'UpdateAndFinalize' WHEN 2 THEN 'Remove' ELSE 'CreateAndFinalize' END) AS "dt:Action", 
						(CASE WHEN (dsd.DSD_ESTI = 0) AND (dsd.DSD_CAPO = 1) then 'CARGA EM EXCESSO' WHEN (dsd.DSD_ESTI = 1) THEN 'Alteracao Volume/Peso.' WHEN (dsd.DSD_ESTI = 2) THEN 'FALTA A DESCARGA' ELSE NULL END) AS "dt:Justification"
					FOR XML PATH('r:Action'), TYPE), 
					(SELECT ('PT' + dsc.DSC_IDRP) AS "dt:CargoAgent", 
						dsd.DSD_NRMH AS "dt:ExternalReferenceNumber", 
						dbo.FNT_Geral_SubstituiCaracteresXMLInvalidos(dsd.DSD_DMER) AS "dt:DetailedDesignation", 
						(CASE RIGHT(dsc.EAD_CODI, 3) WHEN '020' THEN @CodLocMercadoriaArmDTPOPO ELSE @CodLocMercadoriaArmDTPLIS END) AS "dt:TemporaryStorageWarehouseIdentification", 
						CONVERT(varchar(19), @DataMovimentacaoRef, 120) AS "dt:MovementDate", 
						CAST(dsd.DSD_PESO AS decimal(18, 3)) AS "dt:GrossWeight", 
						dsd.DSD_VOLS AS "dt:NumberOfPackages", 
						dsd.TEM_CODI AS "dt:NatureOfVolumes", 
						dsd.DSD_MRNR AS "dt:MarksAndNumbers", 
						dsd.DSD_TCAR AS "dt:CargoType"
					FOR XML PATH('r:GoodsDetails'), TYPE),
					(SELECT 'Unload' AS "dtr:MovementType", 
						(CASE dsd.DSD_CPER WHEN 1 THEN 'Yes' ELSE 'No' END) AS "dtr:DangerousGoods", 
						(CASE WHEN dsd.PAE_CODI IN ('LIS', 'OPO') THEN 'No' ELSE 'Yes' END) AS "dtr:Transhipment", 
						(CASE WHEN dsd.PAE_CODI IN ('LIS', 'OPO') THEN NULL ELSE (dsd.PAI_CODI + dsd.PAE_CODI) END) AS "dtr:DestinationAirport"
					FOR XML PATH('r:OtherDetails'), TYPE),
					(SELECT dsd.DOC_CODI AS "dt:Type", 					
						dsd.DSD_NRMH AS "dt:Number"
					FOR XML PATH('r:CustomsDocument'), TYPE)	
				FROM VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes AS dsd 
					LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON duc.DUC_DUNO IN (1, 2) AND dsd.DSD_NRMH = duc.DUC_CPRT AND dsd.EAD_CODI = duc.ALF_CODI AND CAST(CONVERT(varchar(10), dsd.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime)
					LEFT OUTER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI
				WHERE dsd.DSC_EANO = dsc.DSC_EANO AND dsd.DSC_NPRO = dsc.DSC_NPRO AND dsd.DSD_TCAR = ISNULL(NULLIF(@TipoCarga, ''), dsd.DSD_TCAR) 
					AND ((@CriteriosDHL = 0) OR (@CriteriosDHL = 1 AND dsd.DSD_VOLS = duc.DUC_VSCA AND ((nat.NDE_FEDI = 1) OR (duc.DUC_ARTI IS NOT NULL))))
				FOR XML PATH('r:Item'), TYPE)			
			FROM PRO_SDSC AS dsc 
			WHERE dsc.DSC_EANO = @AnoProcesso AND dsc.DSC_NPRO = @NumProcesso
			FOR XML PATH('r:AirWarehouseKeeperCargoReport'), ELEMENTS)
-- processa envio de ficheiro XML gerado p/ Webservice
		IF @ViaWebservice = 0
		BEGIN
-- atribui linha de encoding para depois ser incluída no ficheiro XML a gerar
			SET @LinhaXMLEncoding = '<?xml version="1.0" encoding="UTF-8"?>'	
-- obtem dados do processo SDS - Via Aérea p/ construção do nome do ficheiro XML a ser gerado
			SELECT @NomeFicheiroXML = ('rd-' + DSC_NCMF + DSC_NCMV + '-' + REPLACE(REPLACE(REPLACE(CONVERT(varchar(19), @DataHoraAtual, 120), ' ', ''), ':', ''), '-', '') + '.xml'), 
				@IDDepositario = DSC_IDDP
			FROM PRO_SDSC
			WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso	
		END	
		ELSE
		BEGIN
-- obtem configurações de Proxy Authentication
			SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), 
				@ProxyPassword = ISNULL(PAP_PPWD, '')		
			FROM TAB_PAPL	
-- obtem endereço Location do WebService p/ comunicação aos webservices do SDS - Via Aérea dos Depositários
			SELECT @WebServiceLocation = PSD_WEBS, @LoginAcesso = PSD_UTIL, @PwdAcesso = PSD_PASS, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC
			FROM TAB_PSDS
-- valida se o path p/ o certificado é válido
			EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
			IF @Resultado = 0
				RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)			
-- converte o ficheiro XML gerado para varbinary e depois para Base64
			SET @FicheiroXMLBinario = CONVERT(varbinary(MAX), CAST(@FicheiroXML AS varchar(MAX))) 
			SET @FicheiroXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@FicheiroXMLBinario"))', 'varchar(MAX)') 		
-- constroi estrutura XML com os dados do pedido ao metodo submitMessages a enviar à AT
			;WITH XMLNAMESPACES ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' as wsse, 
				'http://server.ws.sds.dgita.gov.pt/' as ser, 
				'http://schemas.xmlsoap.org/soap/envelope/' as soapenv)
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT @LoginAcesso "wsse:Username", @PwdAcesso "wsse:Password"
							FOR XML PATH('wsse:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wsse:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT ('PT' + @LoginAcesso) "sender", 
							(SELECT @FicheiroXMLBase64
							FOR XML PATH('messages'), TYPE)
						FOR XML PATH('ser:submitMessages'), TYPE)		
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)		
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN..SP_Externo_EnviarDadosWS @RequestXML, @WebServiceLocation, 'http://server.ws.sds.dgita.gov.pt/WarehouseKeepers/submitMessages', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as "SOAP-ENV")
			SELECT @FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)			
-- obtem o resultado "OK"/"NOK" retornados do WS
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as S, 'http://server.ws.sds.dgita.gov.pt/' as ns0)		
			SELECT TOP 1 @ResultadoResponse = XML_MSGR.MSG_DATA.value('.[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('S:Envelope/S:Body/ns0:submitMessagesResponse/return') as XML_MSGR(MSG_DATA)	
-- se resultado não for "OK", manda erro
			IF @ResultadoResponse <> 'OK'
				RAISERROR('Erro no envio do webservice "%s".', 16, 3, @ResultadoResponse)			
		END
-- atualiza processo SDS - Via Aérea p/ alteração do status e utilizador/data
		UPDATE PRO_SDSC SET 
			DSC_STRD = (CASE @Create WHEN 1 THEN 1 ELSE 2 END), 
			DSC_NRER = DSC_NRER + 1,
			DSC_UERC = (CASE @Create WHEN 1 THEN @Utilizador ELSE DSC_UERC END), 
			DSC_DERC = (CASE @Create WHEN 1 THEN @DataHoraAtual ELSE DSC_DERC END),
			DSC_UERF = (CASE @Create WHEN 1 THEN DSC_UERF ELSE @Utilizador END), 
			DSC_DERF = (CASE @Create WHEN 1 THEN DSC_DERF ELSE @DataHoraAtual END)	
		WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso
-- atualiza linhas AWB do processo SDS - Via Aérea p/ alteração do status e data de envio do relatório de descarga
		UPDATE PRO_SDSD SET 
			DSD_STRD = (CASE dsp.DSD_ESTI WHEN 1 THEN 2 WHEN 2 THEN 3 ELSE 1 END), 
			DSD_DERD = @DataHoraAtual
		FROM PRO_SDSD AS dsd WITH(NOLOCK) 
			INNER JOIN VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes AS dsp ON dsd.DSD_IDNN = dsp.DSD_IDNN
			LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON duc.DUC_DUNO IN (1, 2) AND dsp.DSD_NRMH = duc.DUC_CPRT AND dsp.EAD_CODI = duc.ALF_CODI AND CAST(CONVERT(varchar(10), dsp.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime)
			LEFT OUTER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI
		WHERE dsd.DSC_EANO = @AnoProcesso AND dsd.DSC_NPRO = @NumProcesso AND dsd.DSD_TCAR = ISNULL(NULLIF(@TipoCarga, ''), dsd.DSD_TCAR) 
			AND ((@CriteriosDHL = 0) OR (@CriteriosDHL = 1 AND dsd.DSD_VOLS = duc.DUC_VSCA AND ((nat.NDE_FEDI = 1) OR (duc.DUC_ARTI IS NOT NULL))))
	END TRY
	BEGIN CATCH	
		SET @MsgErro = ERROR_MESSAGE()
	END CATCH
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_GeraXMLEnvioRelatorioDescarga] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_GeraXMLEnvioRelatorioDescarga] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_ImportaFicheiroICS2]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_SDSViaAerea_ImportaFicheiroICS2] @AnoProcesso int, @NumProcesso int, @FicheiroXLSX varchar(MAX), @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET ARITHABORT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @FicheiroXML xml, @CodDocumento varchar(5), @NomeDocumento varchar(70), @CodEstanciaProcesso varchar(8), @NomeEstanciaProcesso varchar(35), 
		@NumLinhaAWB int, @NumeroDocumento varchar(30), @NumDocumento int
-- inicia transacção para a inserção dos dados ICS2
	BEGIN TRANSACTION TspIMPImportaXLSXDadosICS2
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- converte para xml
		SET @FicheiroXML = @FicheiroXLSX
-- obtem dados do manifesto SDS - Via Aérea
		SELECT @CodEstanciaProcesso = EAD_CODI, @NomeEstanciaProcesso = EAD_NOME
		FROM PRO_SDSC WITH(NOLOCK) 
		WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso
-- obtem os documentos do ficheiro
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT sdd.DSD_NUME, t.c.value('statuses[1]', 'varchar(30)'), doc.DOC_CODI, doc.DOC_NOME
			FROM @FicheiroXML.nodes('dataset/row') AS t(c) 
				INNER JOIN PRO_SDSD AS sdd WITH(NOLOCK) ON sdd.DSC_EANO = @AnoProcesso AND sdd.DSC_NPRO = @NumProcesso AND t.c.value('hawbNumber[1]', 'varchar(30)') = sdd.DSD_NRMH
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ISNULL(NULLIF(t.c.value('coddoc[1]', 'varchar(5)'), ''), 'N355') = doc.DOC_CODI
			WHERE NOT EXISTS(SELECT 1 FROM PRO_SSDD WITH(NOLOCK) WHERE DSC_EANO = sdd.DSC_EANO AND DSC_NPRO = sdd.DSC_NPRO AND DSD_NUME = sdd.DSD_NUME AND DOC_CODI = @CodDocumento)
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @NumLinhaAWB, @NumeroDocumento, @CodDocumento, @NomeDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem o número p/ novo documento a inserir na linha AWB
			SET @NumDocumento = ISNULL((SELECT COUNT(*)
										FROM PRO_SSDD WITH(NOLOCK)
										WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso AND DSD_NUME = @NumLinhaAWB), 0) + 1
-- insere o documento do ficheiro na linha AWB
			INSERT INTO PRO_SSDD(DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC)
			VALUES(@AnoProcesso, @NumProcesso, @NumLinhaAWB, @NumDocumento, @CodDocumento, @NomeDocumento, @NumeroDocumento, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), @CodEstanciaProcesso, @NomeEstanciaProcesso, 'T')
			FETCH NEXT FROM Documentos INTO @NumLinhaAWB, @NumeroDocumento, @CodDocumento, @NomeDocumento
		END
		CLOSE Documentos
		DEALLOCATE Documentos				
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION TspIMPImportaXLSXDadosICS2
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION TspIMPImportaXLSXDadosICS2
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_ImportaFicheiroICS2] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_ImportaFicheiroICS2] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_ImportaFicheiroTXTManifesto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_SDSViaAerea_ImportaFicheiroTXTManifesto] @Scan bit, @AnoProcesso int, @NumProcesso int, @FicheiroTXT varchar(MAX), @Utilizador varchar(30) AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @IntegracaoIMPCAUAtiva bit, @CamposAdicionais int, @i int, @Linha varchar(2000), @IDLinhaTXT int, @TipoLinhaTXT varchar(3), @CodTipoDocTXT varchar(4), @NumeroAWBTXT varchar(30), 
		@CodPaisApp varchar(2), @TxCambioApp numeric(38, 6), @DataHoraAtual datetime, @TipoProcesso int, @CodEstanciaProcesso varchar(8), @DataVooProcesso datetime, 
		@TipoEdicao int, @LinhaAWB varchar(2000), @LinhaDET varchar(2000), @LinhaDOC varchar(200), @ProcessaEdicao int, @NumLinhaAWB int, @DataVooFechoCont datetime, 
		@NumContramarcaVarFechoCont varchar(6), @LstAWBFechoCont xml, @AWBValida bit, @CodPedido varchar(5), @NomePedido varchar(150), @TextoPedido varchar(512)
-- cria tabela temporária p/ conteudo do ficheiro	
	CREATE TABLE #tmpDadosFicheiro(ID int NOT NULL IDENTITY(1, 1), 
		TIPO_LINHA varchar(3) COLLATE Latin1_General_CI_AI NOT NULL, 
		TIPO_DOC varchar(4) COLLATE Latin1_General_CI_AI NOT NULL, 
		NUM_AWB varchar(30) COLLATE Latin1_General_CI_AI NOT NULL, 
		DADOS_LINHA varchar(2000) COLLATE Latin1_General_CI_AI NOT NULL, 
		ERRO bit NOT NULL, 
		MSG_ERRO varchar(2000) COLLATE Latin1_General_CI_AI NULL)
-- obtem o valor dos "Campos Adicionais"
	SELECT @IntegracaoIMPCAUAtiva = PDE_ICAU, @CamposAdicionais = PDE_CADI --(1=FEDEX; 2=UPS; 3=DHL; 4=TNT; 5=CTT)
	FROM TAB_PDES WITH(NOLOCK)
-- carrega o conteudo do ficheiro TXT p/ tabela tmp
	WHILE ISNULL(@FicheiroTXT, '') <> ''
	BEGIN		
-- obtem dados de linha do ficheiro TXT	
		SET @i = CHARINDEX(CHAR(13) + CHAR(10), @FicheiroTXT)
		IF @i = 0
			SET @i = LEN(@FicheiroTXT) + 1
		SET @Linha = SUBSTRING(@FicheiroTXT, 1, @i - 1)
		SET @TipoLinhaTXT = RTRIM(LTRIM(SUBSTRING(@Linha, 1, 3)))
-- trata cada tipo de linha			
		IF (@TipoLinhaTXT = 'DET') AND (@CamposAdicionais <> 3) --na linha DET no ficheiro (exceto DHL), adiciona caracter na posição 517
			SET @Linha = STUFF(@Linha, 516, 0, ' ')
		ELSE
			IF @TipoLinhaTXT = 'HEA'
			BEGIN
				SET @CodTipoDocTXT = '.'
				SET @NumeroAWBTXT = '.'
			END
			ELSE
				IF @TipoLinhaTXT = 'AWB'
				BEGIN
					SET @CodTipoDocTXT = RTRIM(LTRIM(SUBSTRING(@Linha, 34, 4)))
					IF (@CodTipoDocTXT = 'N741') AND (@CamposAdicionais = 3) --se tipo documento for N741 no ficheiro (somente DHL), adiciona caracter "-" na carta de porte
						SET @Linha = STUFF(@Linha, 4, 30, SUBSTRING(@Linha, 4, 3) + '-' + SUBSTRING(@Linha, 7, 26))
					SET @NumeroAWBTXT = RTRIM(LTRIM(SUBSTRING(@Linha, 4, 30)))
				END		
-- insere na tabela tmp os dados da linha 		
		INSERT INTO #tmpDadosFicheiro(TIPO_LINHA, TIPO_DOC, NUM_AWB, DADOS_LINHA, ERRO)
		VALUES(@TipoLinhaTXT, @CodTipoDocTXT, @NumeroAWBTXT, @Linha, 0)
-- remove a linha do ficheiro TXT		
		SET @FicheiroTXT = STUFF(@FicheiroTXT, 1, @i + 1, '')
	END
-- obtem país da moeda base da aplicação
	SELECT @CodPaisApp = PAI_CODI, @TxCambioApp = ISNULL(PAP_TAXA, 1)
	FROM TAB_PAPL WITH(NOLOCK)
-- obtem dados do pedido eletrónico "S1TOT"
	SELECT @CodPedido = TXM_CODI, @NomePedido = TXM_DESC, @TextoPedido = LEFT(TXM_TEXT, 512)
	FROM TAB_TXML WITH(NOLOCK) 
	WHERE TXM_CODI = 'S1TOT'
-- obtem dados do manifesto SDS - Via Aérea
	SELECT @TipoProcesso = DSC_TIPO, @CodEstanciaProcesso = EAD_CODI, @DataVooProcesso = DSC_DTVO
	FROM PRO_SDSC WITH(NOLOCK)
	WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso
-- obtem tipo de edição configurado
	SELECT @TipoEdicao = (CASE @TipoProcesso WHEN 0 THEN PSD_ERIM ELSE PSD_EREX END)
	FROM TAB_PSDS WITH(NOLOCK)
-- valida se ficheiro TXT corresponde ao manifesto selecionado		
	IF NOT EXISTS(SELECT ID
		FROM #tmpDadosFicheiro		
		WHERE TIPO_LINHA = 'HEA' AND RTRIM(LTRIM(SUBSTRING(DADOS_LINHA, 75, 8))) = @DataVooProcesso AND RTRIM(LTRIM(SUBSTRING(DADOS_LINHA, 83, 8))) = @CodEstanciaProcesso 
			AND RTRIM(LTRIM(SUBSTRING(DADOS_LINHA, 91, 3))) = (CASE @TipoProcesso WHEN 0 THEN 'IN' ELSE 'OUT' END))
	BEGIN
		RAISERROR('Os dados do ficheiro não correspondem ao manifesto selecionado!', 16, 1)
		RETURN
	END				
-- obtem as linhas de dados AWB
	DECLARE DadosAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 	
		SELECT awb.ID, awb.TIPO_DOC, awb.NUM_AWB, awb.DADOS_LINHA, det.DADOS_LINHA, doc.DADOS_LINHA
		FROM #tmpDadosFicheiro AS awb 
			INNER JOIN #tmpDadosFicheiro AS det ON awb.TIPO_DOC = det.TIPO_DOC AND awb.NUM_AWB = det.NUM_AWB AND det.TIPO_LINHA = 'DET'
			LEFT OUTER JOIN #tmpDadosFicheiro AS doc ON det.TIPO_DOC = doc.TIPO_DOC AND det.NUM_AWB = doc.NUM_AWB AND doc.TIPO_LINHA = 'DOC'			
		WHERE awb.TIPO_LINHA = 'AWB'
		ORDER BY awb.ID
	OPEN DadosAWB
	FETCH NEXT from DadosAWB INTO @IDLinhaTXT, @CodTipoDocTXT, @NumeroAWBTXT, @LinhaAWB, @LinhaDET, @LinhaDOC
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		BEGIN TRY
-- se exportação e Tipo AWB não seja "N741" ou Tipo Carga não seja "Carga Geral" e AWB já existir noutro manifesto de exportação, não trata AWB
			IF (@TipoProcesso = 1) AND ((@CodTipoDocTXT <> 'N741') OR (RTRIM(LTRIM(SUBSTRING(@LinhaDET, 526, 3))) <> '099')) AND (EXISTS(SELECT sdc.DSC_NPRO FROM PRO_SDSC as sdc INNER JOIN PRO_SDSD as sdd ON sdc.DSC_EANO = sdd.DSC_EANO and sdc.DSC_NPRO = sdd.DSC_NPRO WHERE (sdd.DSC_EANO = @AnoProcesso OR sdd.DSC_EANO = @AnoProcesso - 1) AND sdc.DSC_TIPO = 1 AND sdd.DSD_ASAI = 1 AND sdd.DSD_NRMH = @NumeroAWBTXT))
				SET @AWBValida = 0
			ELSE
				SET @AWBValida = 1
-- se AWB for válida, procede à sua inserção ou edição
			IF @AWBValida = 1
			BEGIN
-- obtem a data hora atual
				SET @DataHoraAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()		
-- verifica se AWB já existe no manifesto SDS selecionado	
				IF EXISTS(SELECT DSD_NUME FROM PRO_SDSD WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso AND DOC_CODI = @CodTipoDocTXT AND DSD_NRMH = @NumeroAWBTXT)
				BEGIN		
-- em modo normal (não Scan), verifica se efetua a edição dos dados
					IF @Scan = 0
					BEGIN						
						SELECT @NumLinhaAWB = DSD_NUME, @ProcessaEdicao = (CASE WHEN (DSD_ANUL = 1) OR (DSD_ESTA IN ('FIN', 'APU')) THEN 0 
							ELSE (CASE @TipoEdicao WHEN 2 THEN 
									(CASE WHEN (PAE_CODI <> RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 155, 5)))) OR (PAE_CODI1 <> RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))) 
										OR (PAE_CODI2 <> RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))) OR (DSD_EADC <> RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3)))) 
										OR (TEM_CODI <> RTRIM(LTRIM(SUBSTRING(@LinhaDET, 507, 2)))) OR (DSD_VOLS <> CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 517, 9))) AS int)) 
										OR (DSD_PESO <> (CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 509, 8))) AS numeric(38, 6)) / 1000)) 
										OR (DSD_VALO <> (CASE CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) WHEN 0 THEN 0 ELSE (SELECT ROUND(CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) / ISNULL((CASE @CodPaisApp WHEN ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) THEN @TxCambioApp ELSE (SELECT TOP 1 (CASE @TipoProcesso WHEN 0 THEN ISNULL(CPA_VEND, 1) ELSE ISNULL(CPA_COMP, 1) END) FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataHoraAtual, 105) + ' 23:58:58' AS datetime) ORDER BY CPA_DATA DESC) END), 1), 0)) END)) 
										OR (DSD_DEPO <> RTRIM(LTRIM(SUBSTRING(@LinhaDET, 578, 9)))) THEN 2 
									ELSE 0 END) 
								ELSE @TipoEdicao END) 
							END) 
						FROM PRO_SDSD 
						WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso AND DOC_CODI = @CodTipoDocTXT AND DSD_NRMH = @NumeroAWBTXT
-- processa a edição de todos os campos				
						IF @ProcessaEdicao = 1
						BEGIN
							UPDATE PRO_SDSD SET DSD_LOED = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 38, 30))), 
								DSD_DTED = CONVERT(datetime, CONVERT(varchar(10), RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 68, 19))), 120), 120), 
								DSD_EEED = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 87, 60))), 
								PAI_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 151, 2))), 
								PAI_NOME = (SELECT PAI_NOME FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 151, 2)))), 
								DSD_TIPO = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 153, 2))), 
								PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 155, 5))), 
								PAE_NOME = (SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 155, 5)))), 
								PAE_CODI1 = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5))), 
								PAE_NOME1 = (SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))), 
								PAE_CODI2 = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5))), 
								PAE_NOME2 = (SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))), 
								DSD_EADC = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))), 
								DSD_IDOS = 'QU', 
								DSD_NOOS = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 27, 75))), 
								DSD_IDNS = 'QU', 
								DSD_NONS = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 122, 75))), 
								DSD_IDED = 'QU', 
								DSD_NOMD = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 217, 75))), 
								DSD_IDEN = RTRIM(LTRIM((CASE @IntegracaoIMPCAUAtiva WHEN 1 THEN REPLACE(SUBSTRING(@LinhaDET, 292, 20), '/NIF/', '') ELSE SUBSTRING(@LinhaDET, 292, 20) END))), 
								DSD_IDEC = RTRIM(LTRIM((CASE @IntegracaoIMPCAUAtiva WHEN 1 THEN REPLACE(SUBSTRING(@LinhaDET, 312, 20), '/NIF/', '') ELSE SUBSTRING(@LinhaDET, 312, 20) END))), 
								DSD_DMER = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 332, 150))), 
								DSD_MRNR = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 482, 25))), 
								TEM_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 507, 2))), 
								TEM_NOME = (SELECT TEM_NOME FROM TAB_TEMB WITH(NOLOCK) WHERE TEM_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 507, 2)))), 
								DSD_PESO = (CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 509, 8))) AS numeric(38, 6)) / 1000), 
								DSD_VOLS = CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 517, 9))) AS int), 
								DSD_TCAR = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 526, 3))), 
								LME_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 529, 25))), 
								LME_NOME = (SELECT LME_NOME FROM TAB_LMER WITH(NOLOCK) WHERE LME_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 529, 25)))), 
								PAE_CODI3 = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 554, 5))), 
								PAE_NOME3 = (SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 554, 5)))), 
								DSD_DNOW = @DataHoraAtual, 
								DSD_ORIG = 1, 
								DSD_VALO = (CASE CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) WHEN 0 THEN 0 ELSE (SELECT ROUND(CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) / ISNULL((CASE @CodPaisApp WHEN ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) THEN @TxCambioApp ELSE (SELECT TOP 1 (CASE @TipoProcesso WHEN 0 THEN ISNULL(CPA_VEND, 1) ELSE ISNULL(CPA_COMP, 1) END) FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataHoraAtual, 105) + ' 23:58:58' AS datetime) ORDER BY CPA_DATA DESC) END), 1), 0)) END), 
								DSD_DEPO = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 578, 9))), 
								DSD_IDCR = REPLACE(CONVERT(numeric(38, 10), @DataHoraAtual), '.', ','), 
								DSD_PES2 = (CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 509, 8))) AS numeric(38, 6)) / 1000), 
								DSD_VOL2 = CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 517, 9))) AS int), 
								DSD_MOOS = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 587, 100))), 
								DSD_MORD = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 687, 100))), 
								DSD_PSIM = (CASE WHEN @CamposAdicionais <> 3 THEN CAST(0 AS bit) WHEN @CodTipoDocTXT = 'N741' THEN CAST(1 AS bit) WHEN ((SELECT COUNT(*) FROM AEX_ENDG WHERE EDG_EANO = YEAR(GETDATE()) and EDG_REFI = @NumeroAWBTXT) > 0) AND (RTRIM(LTRIM(SUBSTRING(@LinhaDET, 27, 75))) NOT LIKE 'DHL%') THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END), 
								DSD_CPER = (CASE RTRIM(LTRIM(SUBSTRING(@LinhaDET, 787, 1))) WHEN '1' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END), 
								DSD_CPOS = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 788, 17))), 
								DSD_LOOS = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 805, 35))), 
								DSD_NDPR = (CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 840, 70))) ELSE NULL END), 
								DSD_CPAU = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 910, 22))),
								TXM_CODI = (CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN @CodPedido ELSE NULL END), 
								TXM_DESC = (CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN @NomePedido ELSE NULL END), 
								DSD_PTXT = (CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN @TextoPedido ELSE NULL END)
							WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso AND DSD_NUME = @NumLinhaAWB
						END
						ELSE 
-- processa a edição somente dos campos criticos
						IF @ProcessaEdicao = 2 
						BEGIN
							UPDATE PRO_SDSD SET PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 155, 5))), 
								PAE_NOME = (SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 155, 5)))),
								PAE_CODI1 = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5))), 
								PAE_NOME1 = (SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))), 
								PAE_CODI2 = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5))), 
								PAE_NOME2 = (SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))),
								DSD_EADC = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))), 
								TEM_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 507, 2))), 
								TEM_NOME = (SELECT TEM_NOME FROM TAB_TEMB WITH(NOLOCK) WHERE TEM_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 507, 2)))), 
								DSD_VOLS = CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 517, 9))) AS int), 
								DSD_PESO = (CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 509, 8))) AS numeric(38, 6)) / 1000), 
								DSD_VALO = (CASE CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) WHEN 0 THEN 0 ELSE (SELECT ROUND(CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) / ISNULL((CASE @CodPaisApp WHEN ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) THEN @TxCambioApp ELSE (SELECT TOP 1 (CASE @TipoProcesso WHEN 0 THEN ISNULL(CPA_VEND, 1) ELSE ISNULL(CPA_COMP, 1) END) FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataHoraAtual, 105) + ' 23:58:58' AS datetime) ORDER BY CPA_DATA DESC) END), 1), 0)) END), 
								DSD_DEPO = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 578, 9)))
							WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso AND DSD_NUME = @NumLinhaAWB												
						END					
					END				
				END
				ELSE
				BEGIN
-- obtem o próximo número da linha AWB
					SELECT @NumLinhaAWB = ISNULL(MAX(DSD_NUME), 0) + 1 
					FROM PRO_SDSD
					WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso
-- insere nova linha AWB								
					INSERT INTO PRO_SDSD(DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DOC_NOME, DSD_LOED, DSD_DTED, DSD_EEED, PAI_CODI, PAI_NOME, DSD_TIPO, PAE_CODI, PAE_NOME, PAE_CODI1, 
						PAE_NOME1, PAE_CODI2, PAE_NOME2, DSD_EADC, DSD_IDOS, DSD_NOOS, DSD_IDNS, DSD_NONS, DSD_IDED, DSD_NOMD, DSD_IDEN, DSD_IDEC, DSD_DMER, DSD_MRNR, TEM_CODI, TEM_NOME, 
						DSD_PESO, DSD_VOLS, DSD_TCAR, LME_CODI, LME_NOME, PAE_CODI3, PAE_NOME3, DSD_DNOW, DSD_ORIG, DSD_VALO, DSD_DEPO, DSD_IDCR, DSD_PES2, DSD_VOL2, DSD_MOOS, DSD_MORD, 
						DSD_PSIM, DSD_CPER, DSD_CPOS, DSD_LOOS, DSD_NDPR, DSD_CPAU, TXM_CODI, TXM_DESC, DSD_PTXT)
					VALUES(@AnoProcesso, @NumProcesso, @NumLinhaAWB, @NumeroAWBTXT, @CodTipoDocTXT, (SELECT DOC_NOME FROM TAB_DOCU WITH(NOLOCK) WHERE DOC_CODI = @CodTipoDocTXT), 
						RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 38, 30))), --DSD_LOED
						CONVERT(datetime, CONVERT(varchar(10), RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 68, 19))), 120), 120), --DSD_DTED
						RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 87, 60))), --DSD_EEED
						RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 151, 2))), --PAI_CODI
						(SELECT PAI_NOME FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 151, 2)))), --PAI_NOME
						RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 153, 2))), --DSD_TIPO
						RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 155, 5))), --PAE_CODI
						(SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 155, 5)))), --PAE_NOME
						RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5))), --PAE_CODI1
						(SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))), --PAE_NOME1
						RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5))), --PAE_CODI2
						(SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaAWB, 160, 5)))), --PAE_NOME2
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))), --DSD_EADC
						'QU', --DSD_IDOS
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 27, 75))), --DSD_NOOS
						'QU', --DSD_IDNS
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 122, 75))), --DSD_NONS
						'QU', --DSD_IDED
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 217, 75))), --DSD_NOMD
						RTRIM(LTRIM((CASE @IntegracaoIMPCAUAtiva WHEN 1 THEN REPLACE(SUBSTRING(@LinhaDET, 292, 20), '/NIF/', '') ELSE SUBSTRING(@LinhaDET, 292, 20) END))), --DSD_IDEN
						RTRIM(LTRIM((CASE @IntegracaoIMPCAUAtiva WHEN 1 THEN REPLACE(SUBSTRING(@LinhaDET, 312, 20), '/NIF/', '') ELSE SUBSTRING(@LinhaDET, 312, 20) END))), --DSD_IDEC
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 332, 150))), --DSD_DMER
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 482, 25))), --DSD_MRNR
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 507, 2))), --TEM_CODI
						(SELECT TEM_NOME FROM TAB_TEMB WITH(NOLOCK) WHERE TEM_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 507, 2)))), --TEM_NOME
						(CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 509, 8))) AS numeric(38, 6)) / 1000), --DSD_PESO
						CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 517, 9))) AS int), --DSD_VOLS
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 526, 3))), --DSD_TCAR
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 529, 25))), --LME_CODI
						(SELECT LME_NOME FROM TAB_LMER WITH(NOLOCK) WHERE LME_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 529, 25)))), --LME_NOME
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 554, 5))), --PAE_CODI3
						(SELECT PAE_NOME FROM TAB_PAER WITH(NOLOCK) WHERE PAE_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDET, 554, 5)))), --PAE_NOME3
						@DataHoraAtual, --DSD_DNOW
						1, --DSD_ORIG
						(CASE CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) WHEN 0 THEN 0 ELSE (SELECT ROUND(CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 563, 12))) AS int) / ISNULL((CASE @CodPaisApp WHEN ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) THEN @TxCambioApp ELSE (SELECT TOP 1 (CASE @TipoProcesso WHEN 0 THEN ISNULL(CPA_VEND, 1) ELSE ISNULL(CPA_COMP, 1) END) FROM TAB_CPAI WITH(NOLOCK) WHERE PAI_CODI = ISNULL(NULLIF(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 561, 2))), ''), @CodPaisApp) AND CPA_DATA <= CAST(CONVERT(varchar(10), @DataHoraAtual, 105) + ' 23:58:58' AS datetime) ORDER BY CPA_DATA DESC) END), 1), 0)) END), --DSD_VALO
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 578, 9))), --DSD_DEPO
						REPLACE(CONVERT(numeric(38, 10), @DataHoraAtual), '.', ','), --DSD_IDCR
						(CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 509, 8))) AS numeric(38, 6)) / 1000), --DSD_PES2
						CAST(RTRIM(LTRIM(SUBSTRING(@LinhaDET, 517, 9))) AS int), --DSD_VOL2
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 587, 100))), --DSD_MOOS
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 687, 100))), --DSD_MORD
						(CASE WHEN @CamposAdicionais <> 3 THEN CAST(0 AS bit) WHEN @CodTipoDocTXT = 'N741' THEN CAST(1 AS bit) WHEN ((SELECT COUNT(*) FROM AEX_ENDG WHERE EDG_EANO = YEAR(GETDATE()) and EDG_REFI = @NumeroAWBTXT) > 0) AND (RTRIM(LTRIM(SUBSTRING(@LinhaDET, 27, 75))) NOT LIKE 'DHL%') THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END), --DSD_PSIM
						(CASE RTRIM(LTRIM(SUBSTRING(@LinhaDET, 787, 1))) WHEN '1' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END), --DSD_CPER
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 788, 17))), --DSD_CPOS
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 805, 35))), --DSD_LOOS
						(CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 840, 70))) ELSE NULL END), --DSD_NDPR
						RTRIM(LTRIM(SUBSTRING(@LinhaDET, 910, 22))), --DSD_CPAU 
						(CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN @CodPedido ELSE NULL END), --TXM_CODI 
						(CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN @NomePedido ELSE NULL END), --TXM_DESC, 
						(CASE WHEN RTRIM(LTRIM(SUBSTRING(@LinhaDET, 4, 3))) IN ('TD', 'X') THEN @TextoPedido ELSE NULL END)) --DSD_PTXT
-- insere detalhe de documento, se existir
					IF ISNULL(@LinhaDOC, '') <> ''
					BEGIN
						INSERT INTO PRO_SSDD (DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC)
						VALUES(@AnoProcesso, @NumProcesso, @NumLinhaAWB, 1, 
							RTRIM(LTRIM(SUBSTRING(@LinhaDOC, 4, 5))), --DOC_CODI
							(SELECT DOC_NOME FROM TAB_DOCU WITH(NOLOCK) WHERE DOC_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDOC, 4, 5)))), --DOC_NOME
							RTRIM(LTRIM(SUBSTRING(@LinhaDOC, 9, 30))), --SDD_NDOC
							CONVERT(datetime, CONVERT(varchar(10), RTRIM(LTRIM(SUBSTRING(@LinhaDOC, 39, 8))), 112), 112), --SDD_DDOC
							RTRIM(LTRIM(SUBSTRING(@LinhaDOC, 47, 8))), --EAD_CODI
							(SELECT EAD_NOME FROM TAB_EADU WITH(NOLOCK) WHERE EAD_CODI = RTRIM(LTRIM(SUBSTRING(@LinhaDOC, 47, 8)))), --EAD_NOME
							RTRIM(LTRIM(SUBSTRING(@LinhaDOC, 55, 1)))) --SDD_SDOC					
					END
				END
			END
-- espera 5 milisegundos para não obter IDs string interno igual à linha AWB anterior			
			WAITFOR DELAY '00:00:00.015'
		END TRY
		BEGIN CATCH			
			UPDATE #tmpDadosFicheiro SET ERRO = 1, MSG_ERRO = ERROR_MESSAGE()
			WHERE ID = @IDLinhaTXT
		END CATCH
		FETCH NEXT from DadosAWB INTO @IDLinhaTXT, @CodTipoDocTXT, @NumeroAWBTXT, @LinhaAWB, @LinhaDET, @LinhaDOC
	END
	CLOSE DadosAWB
	DEALLOCATE DadosAWB	
-- na importação de Dados AWB Scan, obtem AWBs que não existem no ficheiro TXT mas que existem no Manifesto SDS c/ origem na Exportação/XML
	IF @Scan = 1
	BEGIN
-- obtem dados do Manifesto de Exportação SDS ativo c/ "Integra/XML" seguinte ao atual
		SELECT TOP 1 @DataVooFechoCont = DSC_DTVO, @NumContramarcaVarFechoCont = DSC_NCMV
		FROM PRO_SDSC
		WHERE DSC_TIPO = 1 AND DSC_IXML = 1 AND DSC_ACTI = 1 AND DSC_EANO = @AnoProcesso AND EAD_CODI = @CodEstanciaProcesso 
			AND CAST(CONVERT(varchar(10), DSC_DTVO, 105) AS datetime) > CAST(CONVERT(varchar(10), @DataVooProcesso, 105) AS datetime)
		ORDER BY DSC_DTVO
-- se existir Manifesto de Exportação SDS ativo, obtem a lista de AWBs que não existem no ficheiro TXT mas que existem no Manifesto SDS c/ origem na Exportação/XML
		IF @DataVooFechoCont IS NOT NULL
		BEGIN
			SET @LstAWBFechoCont = 
			(SELECT 
				(SELECT dsd.DSD_NRMH AS "AWB"
				FROM PRO_SDSD AS dsd 
					LEFT OUTER JOIN #tmpDadosFicheiro AS awb ON dsd.DOC_CODI = awb.TIPO_DOC AND dsd.DSD_NRMH = awb.NUM_AWB
				WHERE dsd.DSC_EANO = @AnoProcesso AND dsd.DSC_NPRO = @NumProcesso AND dsd.DSD_ORIG = 2 AND dsd.EXA_CHVE IS NOT NULL AND awb.ID IS NULL
				FOR XML PATH(''), TYPE)		
			FOR XML PATH('DadosAWB'), ELEMENTS)
-- se existir AWBs que não existem no ficheiro TXT mas que existem no Manifesto SDS c/ origem na Exportação/XML, passa-as p/ outro Manifesto de Exportação SDS
			IF EXISTS(SELECT XML_LAWB.AWB_DATA.value('.[1]', 'varchar(30)') FROM @LstAWBFechoCont.nodes('DadosAWB/AWB') as XML_LAWB(AWB_DATA))	
			BEGIN
				EXEC SP_SDSViaAerea_GeraManifestoExp @AnoProcesso, @NumProcesso, @DataVooFechoCont, @NumContramarcaVarFechoCont, @Utilizador, 1, @CodEstanciaProcesso, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, @LstAWBFechoCont
-- coloca as AWBs que passaram p/ outro Manifesto de Exportação SDS com "Env." a false
				UPDATE PRO_SDSD SET DSD_ENVI = 0
				WHERE DSC_EANO = @AnoProcesso AND DSC_NPRO = @NumProcesso AND DSD_ENVI = 1 AND DSD_NRMH IN (SELECT XML_MSGR.MSG_DATA.value('.[1]', 'varchar(30)') FROM @LstAWBFechoCont.nodes('DadosAWB/AWB') as XML_MSGR(MSG_DATA))
			END
		END
	END	
-- devolve as linhas do ficheiro TXT c/ erro
	SELECT ID, TIPO_LINHA, TIPO_DOC, NUM_AWB, MSG_ERRO
	FROM #tmpDadosFicheiro
	WHERE ERRO = 1	
-- remove as tabelas temporárias	
	DROP TABLE #tmpDadosFicheiro	
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_ImportaFicheiroTXTManifesto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_ImportaFicheiroTXTManifesto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_IntegraAirCustomsNotification]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_IntegraAirCustomsNotification] @MsgControl bit, @AnoManifesto int, @NumManifesto int, @Utilizador varchar(30), @DocumentoXML xml, @Resultado int OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis
	DECLARE @Handle int, @IdMensagem varchar(35), @DataMensagem datetime, @NumContramarcaDocXML varchar(14), @NumeroAWBLinhaXML varchar(30), @DataAutLinhaXML datetime, 
		@TipoAutLinhaXML varchar(30), @TipoDocAutLinhaXML varchar(4), @NumDocAutLinhaXML varchar(30), @TipoControlLinhaXML varchar(10), @ResultadoLinhaXML int, 
		@IDDepositario varchar(20)
-- prepara documento XML com Namespace para poder ser utilizado como Handle
	EXEC sp_xml_preparedocument @Handle OUTPUT, @DocumentoXML, '<air:AirCustomsNotification xmlns:air="http://sds.aduaneiro.portaldasfinancas.gov.pt/AirCustomsNotification" xmlns:air1="http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypes"/>'
-- obtem do Relatório de Descarga XML o Nº. Contramarca
	SELECT @IdMensagem = MessageIdentification, @DataMensagem = MessageDate, @NumContramarcaDocXML = CustomsReferenceNumber
	FROM OPENXML(@Handle, N'/air:AirCustomsNotification')
	WITH (MessageIdentification varchar(35) 'air:MessageInformation/air:MessageIdentification', MessageDate datetime 'air:MessageInformation/air:MessageDate', 
		CustomsReferenceNumber varchar(14) 'air:MessageInformation/air:CustomsReferenceNumber')
-- verifica se o Relatório de Descarga XML corresponde ao Manifesto seleccionado
	IF EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND (DSC_NCMF + DSC_NCMV) = @NumContramarcaDocXML)
	BEGIN
-- verifica se o Relatório de Descarga XML já foi integrado
		IF NOT EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSC_RPRD LIKE '%' + @IdMensagem + '%' AND DSC_RPRD LIKE '%' + CONVERT(varchar(23), @DataMensagem, 121) + '%')
		BEGIN		
-- obtem lista de linhas AWB do Relatório de Descarga 
			DECLARE LstLinhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT CustomsDocumentNumber, AuthorizationDate, AuthorizationType, TypeDocument, NumberDocument, TypeControl					
				FROM OPENXML(@Handle, N'/air:AirCustomsNotification/air:Cargos/air:Cargo')
				WITH (CustomsDocumentNumber varchar(30) 'air:CustomsDocument/air1:Number', AuthorizationDate datetime 'air:Authorization/air:AuthorizationDate', 
					AuthorizationType varchar(30) 'air:Authorization/air:AuthorizationType', TypeDocument varchar(4) 'air:Authorization/air:CustomsDocument/air1:Type', 
					NumberDocument varchar(30) 'air:Authorization/air:CustomsDocument/air1:Number', TypeControl varchar(10) 'air:Control/air:Type')
			OPEN LstLinhas
			FETCH NEXT FROM LstLinhas INTO @NumeroAWBLinhaXML, @DataAutLinhaXML, @TipoAutLinhaXML, @TipoDocAutLinhaXML, @NumDocAutLinhaXML, @TipoControlLinhaXML
			WHILE @@FETCH_STATUS = 0
			BEGIN
-- actualiza dados da linha AWB p/ Relatório de Saída				
				UPDATE PRO_SDSD SET DSD_SIRD = (CASE @MsgControl WHEN 1 THEN 4 ELSE 5 END), DSD_DIRD = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
					DSD_ADRD = (CASE @MsgControl WHEN 1 THEN DSD_ADRD ELSE @DataAutLinhaXML END), DSD_ATRD = (CASE @MsgControl WHEN 1 THEN DSD_ATRD ELSE @TipoAutLinhaXML END), 
					DSD_DTRD = (CASE @MsgControl WHEN 1 THEN DSD_DTRD ELSE @TipoDocAutLinhaXML END), DSD_DNRD = (CASE @MsgControl WHEN 1 THEN DSD_DNRD ELSE @NumDocAutLinhaXML END), 
					DSD_CTRD = (CASE @MsgControl WHEN 1 THEN @TipoControlLinhaXML ELSE DSD_CTRD END)
				WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_NRMH = @NumeroAWBLinhaXML						
				FETCH NEXT FROM LstLinhas INTO @NumeroAWBLinhaXML, @DataAutLinhaXML, @TipoAutLinhaXML, @TipoDocAutLinhaXML, @NumDocAutLinhaXML, @TipoControlLinhaXML
			END
			CLOSE LstLinhas
			DEALLOCATE LstLinhas
-- actualiza dados do manifesto SDS
			UPDATE PRO_SDSC SET DSC_STRD = (CASE @MsgControl WHEN 1 THEN 4 ELSE 5 END), DSC_NRRD = DSC_NRRD + 1, DSC_URRD = @Utilizador, DSC_DRRD = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
				DSC_RPRD = '-> AIR CUSTOMS NOTIFICATION: ' + CHAR(13) + CHAR(10) + 
				'	#Data Integração: ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121) + CHAR(13) + CHAR(10) +
				'	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) +
				'	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) +
				'	#MessageDate: ' + CONVERT(varchar(23), @DataMensagem, 121) + CHAR(13) + CHAR(10) +
				'	#Resultado: ' + (CASE @MsgControl WHEN 1 THEN 'Control Notification' ELSE 'Authorization Notification' END) + CHAR(13) + CHAR(10) +					
				'===============================================================================================================================' + CHAR(13) + CHAR(10) +
				ISNULL(CAST(DSC_RPRD AS varchar(MAX)), '')					
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- devolve resultado
			SET @Resultado = 1			
		END
		ELSE
			SET @Resultado = 5
	END
	ELSE
		SET @Resultado = 4
-- remove Handle criado para documento XML
	EXEC sp_xml_removedocument @Handle
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_IntegraAirCustomsNotification] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_IntegraAirCustomsNotification] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_IntegraAirCustomsResponse]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_IntegraAirCustomsResponse] @RelatorioSaida bit, @AnoManifesto int, @NumManifesto int, @Utilizador varchar(30), @DocumentoXML xml, @Resultado int OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis
	DECLARE @Handle int, @IdMensagem varchar(35), @DataMensagem datetime, @NumContramarcaDocXML varchar(14), @DocXMLValido int, @ListaErrosDocXML varchar(8000), 
		@DescricaoErroDocXML varchar(250), @ListaAvisosDocXML varchar(8000), @NumeroAWBLinhaXML varchar(30), @AcaoLinhaXML int, @ResultadoLinhaXML int, @LstXMLErros xml, 
		@LstXMLAvisos xml, @ListaErrosLinhaXML varchar(8000), @ListaAvisosLinhaXML varchar(8000), @IDDepositario varchar(20)
-- prepara documento XML com Namespace para poder ser utilizado como Handle
	EXEC sp_xml_preparedocument @Handle OUTPUT, @DocumentoXML, '<sds:AirCustomsResponse xmlns:sds="http://sds.aduaneiro.portaldasfinancas.gov.pt/AirCustomsResponse" xmlns:dt="http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypes"/>'
-- obtem do Relatório de Descarga XML o Nº. Contramarca e se Envio válido 
	SELECT @IdMensagem = MessageIdentification, @DataMensagem = MessageDate, @NumContramarcaDocXML = CustomsReferenceNumber, 
		@DocXMLValido = (CASE UPPER(Result) WHEN 'REJECTED' THEN 0 WHEN 'PENDING' THEN 2 ELSE 1 END)
	FROM OPENXML(@Handle, N'/sds:AirCustomsResponse')
	WITH (MessageIdentification varchar(35) 'sds:MessageInformation/sds:MessageIdentification', MessageDate datetime 'sds:MessageInformation/sds:MessageDate', 
		CustomsReferenceNumber varchar(14) 'sds:MessageInformation/sds:CustomsReferenceNumber', 
		Result varchar(10) 'sds:MessageInformation/sds:ActionResult/sds:Result')
-- verifica se o Relatório de Descarga XML corresponde ao Manifesto seleccionado
	IF EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND (DSC_NCMF + DSC_NCMV) = @NumContramarcaDocXML)
	BEGIN
-- verifica se o Relatório de Descarga XML já foi integrado
		IF NOT EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSC_RPRD LIKE '%' + @IdMensagem + '%' AND DSC_RPRD LIKE '%' + CONVERT(varchar(23), @DataMensagem, 121) + '%')
		BEGIN	
			SET @ListaErrosDocXML = ''
			SET @ListaAvisosDocXML = ''
-- obtem lista de erros gerais do Relatório de Descarga 
			DECLARE LstErros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT ISNULL(MessageDescription, '')
				FROM OPENXML(@Handle, N'/sds:AirCustomsResponse/sds:MessageInformation/sds:ActionResult/sds:Errors/sds:Error')
				WITH (MessageDescription varchar(250) 'sds:MessageDescription')
			OPEN LstErros
			FETCH NEXT FROM LstErros INTO @DescricaoErroDocXML
			WHILE @@FETCH_STATUS = 0
			BEGIN				
				SET @ListaErrosDocXML = @ListaErrosDocXML + '		. ' + @DescricaoErroDocXML + CHAR(13) + CHAR(10)
				FETCH NEXT FROM LstErros INTO @DescricaoErroDocXML
			END
			CLOSE LstErros
			DEALLOCATE LstErros		
-- obtem lista de avisos gerais do Relatório de Descarga 
			DECLARE LstAvisos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT ISNULL(MessageDescription, '')
				FROM OPENXML(@Handle, N'/sds:AirCustomsResponse/sds:MessageInformation/sds:ActionResult/sds:Warnings/sds:Warning')
				WITH (MessageDescription varchar(250) 'sds:MessageDescription')
			OPEN LstAvisos
			FETCH NEXT FROM LstAvisos INTO @DescricaoErroDocXML
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ListaAvisosDocXML = @ListaAvisosDocXML + '		. ' + @DescricaoErroDocXML + CHAR(13) + CHAR(10)
				FETCH NEXT FROM LstAvisos INTO @DescricaoErroDocXML
			END
			CLOSE LstAvisos
			DEALLOCATE LstAvisos	
-- obtem lista de linhas AWB do Relatório de Descarga 
			DECLARE LstLinhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT NumberCustomsDocument, (CASE UPPER(Action) WHEN 'UPDATE' THEN 2 WHEN 'FINALIZE' THEN 3 ELSE 1 END), 
					(CASE UPPER(Result) WHEN 'REJECTED' THEN 2 WHEN 'PENDING' THEN 3 ELSE 1 END), Errors, Warnings
				FROM OPENXML(@Handle, N'/sds:AirCustomsResponse/sds:Cargos/sds:Cargo')
				WITH (NumberCustomsDocument varchar(30) 'sds:CustomsDocument/dt:Number', Action varchar(10) 'sds:ActionResult/sds:Action', 
					Result varchar(10) 'sds:ActionResult/sds:Result', Errors xml 'sds:ActionResult/sds:Errors', Warnings xml 'sds:ActionResult/sds:Warnings')
			OPEN LstLinhas
			FETCH NEXT FROM LstLinhas INTO @NumeroAWBLinhaXML, @AcaoLinhaXML, @ResultadoLinhaXML, @LstXMLErros, @LstXMLAvisos
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ListaErrosLinhaXML = ''
				SET @ListaAvisosLinhaXML = ''
-- obtem lista de erros da linha AWB
				DECLARE LstErrosLinha CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
					WITH XMLNAMESPACES ('http://sds.aduaneiro.portaldasfinancas.gov.pt/AirCustomsResponse' as sds)
					SELECT ISNULL(XML_ERRS.ERR_DATA.value('sds:MessageDescription[1]', 'varchar(250)'), '')
					FROM @LstXMLErros.nodes('sds:Errors/sds:Error') as XML_ERRS(ERR_DATA)																							
				OPEN LstErrosLinha
				FETCH NEXT FROM LstErrosLinha INTO @DescricaoErroDocXML
				WHILE @@FETCH_STATUS = 0
				BEGIN
					select @ListaErrosLinhaXML = @ListaErrosLinhaXML + '	. ' + @DescricaoErroDocXML + CHAR(13) + CHAR(10)
					FETCH NEXT FROM LstErrosLinha INTO @DescricaoErroDocXML
				END
				CLOSE LstErrosLinha
				DEALLOCATE LstErrosLinha
-- obtem lista de avisos da linha AWB
				DECLARE LstAvisosLinha CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
					WITH XMLNAMESPACES ('http://sds.aduaneiro.portaldasfinancas.gov.pt/AirCustomsResponse' as sds)
					SELECT ISNULL(XML_WARS.WAR_DATA.value('sds:MessageDescription[1]', 'varchar(250)'), '')
					FROM @LstXMLAvisos.nodes('sds:Warnings/sds:Warning') as XML_WARS(WAR_DATA)																							
				OPEN LstAvisosLinha
				FETCH NEXT FROM LstAvisosLinha INTO @DescricaoErroDocXML
				WHILE @@FETCH_STATUS = 0
				BEGIN
					select @ListaAvisosLinhaXML = @ListaAvisosLinhaXML + '	. ' + @DescricaoErroDocXML + CHAR(13) + CHAR(10)
					FETCH NEXT FROM LstAvisosLinha INTO @DescricaoErroDocXML
				END
				CLOSE LstAvisosLinha
				DEALLOCATE LstAvisosLinha				
-- actualiza dados da linha AWB p/ Relatório de Saída
				IF @RelatorioSaida = 1
				BEGIN
					UPDATE PRO_SDSD SET DSD_SIRD = @AcaoLinhaXML, DSD_DIRD = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), DSD_RIRD = @ResultadoLinhaXML, 
						DSD_EIRD = NULLIF((CASE @ListaErrosLinhaXML WHEN '' THEN '' ELSE '#ERROS:' + CHAR(13) + CHAR(10) + @ListaErrosLinhaXML END) 
							+ (CASE @ListaAvisosLinhaXML WHEN '' THEN '' ELSE '#AVISOS:' + CHAR(13) + CHAR(10) + @ListaAvisosLinhaXML END), '')					
					WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_NRMH = @NumeroAWBLinhaXML													
				END
				ELSE
				BEGIN		
					UPDATE PRO_SDSD SET DSD_SIMS = 1, DSD_DIMS = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), DSD_RIMS = @ResultadoLinhaXML, 
						DSD_EIMS = NULLIF((CASE @ListaErrosLinhaXML WHEN '' THEN '' ELSE '#ERROS:' + CHAR(13) + CHAR(10) + @ListaErrosLinhaXML END) 
							+ (CASE @ListaAvisosLinhaXML WHEN '' THEN '' ELSE '#AVISOS:' + CHAR(13) + CHAR(10) + @ListaAvisosLinhaXML END), '')					
					WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_NRMH = @NumeroAWBLinhaXML		
				END
				FETCH NEXT FROM LstLinhas INTO @NumeroAWBLinhaXML, @AcaoLinhaXML, @ResultadoLinhaXML, @LstXMLErros, @LstXMLAvisos
			END
			CLOSE LstLinhas
			DEALLOCATE LstLinhas
-- actualiza dados do manifesto SDS
			IF @RelatorioSaida = 1
			BEGIN				
				UPDATE PRO_SDSC SET DSC_STRD = 3, DSC_NRRD = DSC_NRRD + 1, DSC_URRD = @Utilizador, DSC_DRRD = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
					DSC_RPRD = '-> AIR CUSTOMS RESPONSE: ' + CHAR(13) + CHAR(10) + 
					'	#Data Integração: ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121) + CHAR(13) + CHAR(10) +
					'	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) +
					'	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) +
					'	#MessageDate: ' + CONVERT(varchar(23), @DataMensagem, 121) + CHAR(13) + CHAR(10) +
					'	#Resultado: ' + (CASE @DocXMLValido WHEN 1 THEN 'Accepted' WHEN 2 THEN 'Pending' ELSE 'Rejected' END) + CHAR(13) + CHAR(10) +				   
					(CASE @ListaErrosDocXML WHEN '' THEN '' ELSE '	#Erros: ' + CHAR(13) + CHAR(10) + @ListaErrosDocXML END) +
					(CASE @ListaAvisosDocXML WHEN '' THEN '' ELSE '	#Avisos: ' + CHAR(13) + CHAR(10) + @ListaAvisosDocXML END) +
					(CASE WHEN (@DocXMLValido = 3) AND  (@ListaErrosDocXML = '') THEN '	#Erros Linhas: ' + CHAR(13) + CHAR(10) + '		. «Verificar erros nas linhas AWB»' + CHAR(13) + CHAR(10) ELSE '' END) +
					'===============================================================================================================================' + CHAR(13) + CHAR(10) +
					ISNULL(CAST(DSC_RPRD AS varchar(MAX)), '')					
				WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- se houver erros globais, coloca as linhas AWB c/ erro global				
				IF @ListaErrosDocXML <> ''
				BEGIN					
					SELECT @IDDepositario = DSC_IDDP
					FROM PRO_SDSC
					WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto					
					
					UPDATE PRO_SDSD SET DSD_SIRD = 4, DSD_DIRD = NULL, DSD_RIRD = 2, DSD_EIRD = '#ERROS (GLOBAIS):' + CHAR(13) + CHAR(10) + @ListaErrosDocXML					
					WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_EADC <> 'C' AND DSD_TIPO <> 'TR' AND DSD_DEPO = @IDDepositario AND DSD_ENVI = 1 AND DSD_STRD > 0 AND DSD_SIRD = 0 
						AND DSD_RIRD IS NULL
				END
			END
			ELSE
			BEGIN
				UPDATE PRO_SDSC SET DSC_STMS = 3, DSC_NRMS = DSC_NRMS + 1, DSC_URMS = @Utilizador, DSC_DRMS = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
					DSC_RPMS = '-> AIR CUSTOMS RESPONSE: ' + CHAR(13) + CHAR(10) + 
					'	#Data Integração: ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121) + CHAR(13) + CHAR(10) +
					'	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) +
					'	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) +
					'	#MessageDate: ' + CONVERT(varchar(23), @DataMensagem, 121) + CHAR(13) + CHAR(10) +
					'	#Resultado: ' + (CASE @DocXMLValido WHEN 1 THEN 'Accepted' WHEN 2 THEN 'Pending' ELSE 'Rejected' END) + CHAR(13) + CHAR(10) +				   
					(CASE @ListaErrosDocXML WHEN '' THEN '' ELSE '	#Erros: ' + CHAR(13) + CHAR(10) + @ListaErrosDocXML END) +
					(CASE @ListaAvisosDocXML WHEN '' THEN '' ELSE '	#Avisos: ' + CHAR(13) + CHAR(10) + @ListaAvisosDocXML END) +
					(CASE WHEN (@DocXMLValido = 3) AND  (@ListaErrosDocXML = '') THEN '	#Erros Linhas: ' + CHAR(13) + CHAR(10) + '		. «Verificar erros nas linhas AWB»' + CHAR(13) + CHAR(10) ELSE '' END) +
					'===============================================================================================================================' + CHAR(13) + CHAR(10) +
					ISNULL(CAST(DSC_RPMS AS varchar(MAX)), '')					
				WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
			END
-- devolve resultado
			IF @DocXMLValido = 1
				SET @Resultado = 1
			ELSE
				IF @DocXMLValido = 2
					SET @Resultado = 2			
				ELSE
					SET @Resultado = 3
		END
		ELSE
			SET @Resultado = 5
	END
	ELSE
		SET @Resultado = 4
-- remove Handle criado para documento XML
	EXEC sp_xml_removedocument @Handle
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_IntegraAirCustomsResponse] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_IntegraAirCustomsResponse] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_IntegraAirManifestResponse]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_IntegraAirManifestResponse] @AnoManifesto int, @NumManifesto int, @Utilizador varchar(30), @DocumentoXML xml, @Resultado int OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis
	DECLARE @Handle int, @IdMensagem varchar(35), @DataMensagem datetime, @NumContramarcaDocXML varchar(14), @DocXMLValido bit, @ListaErrosSistemaDocXML varchar(8000), 
		@DescricaoErroDocXML varchar(250), @ListaErrosGeraisDocXML varchar(8000), @LinhaXMLValida int, @AccaoLinhaXML varchar(10), @NumDGALinhaXML varchar(24), @NumAWBLinhaXML varchar(30), 
		@EstOperacaoLinhaXML varchar(3), @NumDGAItemLinhaXML varchar(50), @ListaErrosLinhaXML varchar(8000), @AnoProcesso int, @NumProcesso int, @NumAdicao int, @ProxNumeroDeclSumaria int, 
		@DeclSumariaAuto int, @CodRelDeclSumaria varchar(20), @IDIntDeclSumaria varchar(20), @IDIntDeclSumaria1Adicao varchar(20), @LstXMLErrosTransport xml, @LstXMLErrosItem xml, 
		@MensagemErro varchar(8000), @NumLinhaIncidencia int, @DataIncidencia datetime, @HoraIncidencia datetime, @IdDeclaracaoDAR int, @IdUtilizador int, @IdDeclaracaoIMP bigint, 
		@ArtigoFranquia int, @ContextoIMP int, @TipoManifesto int, @DataVooManifesto datetime, @DataAtual datetime
-- prepara documento XML com Namespace para poder ser utilizado como Handle
	EXEC sp_xml_preparedocument @Handle OUTPUT, @DocumentoXML, '<air:AirManifestResponse Success="No" xmlns:air="http://sds.dgaiec.min-financas.pt/AirManifestResponse"/>'
-- obtem do documento XML o Nº. Contramarca e se Envio válido 
	SELECT @IdMensagem = MessageIdentification, @DataMensagem = MessageDate, @NumContramarcaDocXML = CustomsReferenceNumber, 
		@DocXMLValido = (CASE UPPER(MessageCorrelationInformation) WHEN 'NO' THEN 0 ELSE 1 END)
	FROM OPENXML(@Handle, N'/air:AirManifestResponse')
	WITH (MessageIdentification varchar(35) 'air:MessageInformation/air:MessageIdentification', 
		MessageDate datetime 'air:MessageInformation/air:MessageDate', 
		CustomsReferenceNumber varchar(14) 'air:CustomsProcess/air:CustomsReferenceNumber', 
		MessageCorrelationInformation varchar(10) 'air:MessageCorrelationInformation/air:MessageCorrelationValid')
-- verifica se o documento XML corresponde ao Manifesto seleccionado
	IF EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto and DSC_NPRO = @NumManifesto and (DSC_NCMF + DSC_NCMV) = @NumContramarcaDocXML)
	BEGIN
-- verifica se o documento XML já foi integrado
		IF NOT EXISTS(SELECT DSC_NPRO FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto and DSC_NPRO = @NumManifesto and DSC_RESP like '%' + @IdMensagem + '%' and DSC_RESP like '%' + CONVERT(varchar(23), @DataMensagem, 121) + '%')
		BEGIN
			SET @ListaErrosSistemaDocXML = ''
			SET @ListaErrosGeraisDocXML = ''
-- obtem lista de erros de sistema
			DECLARE LstErrosSistema CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT ISNULL(MessageDescription, '')
				FROM OPENXML(@Handle, N'/air:AirManifestResponse/air:SystemErrorMessages/air:Message')
				WITH (MessageDescription varchar(250) 'air:MessageDescription')
			OPEN LstErrosSistema
			FETCH NEXT FROM LstErrosSistema INTO @DescricaoErroDocXML
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ListaErrosSistemaDocXML = @ListaErrosSistemaDocXML + '		. ' + @DescricaoErroDocXML + CHAR(13) + CHAR(10)
				FETCH NEXT FROM LstErrosSistema INTO @DescricaoErroDocXML
			END
			CLOSE LstErrosSistema
			DEALLOCATE LstErrosSistema		
-- obtem lista de erros gerais do manifesto
			DECLARE LstErrosGerais CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT ISNULL(MessageDescription, '')
				FROM OPENXML(@Handle, N'/air:AirManifestResponse/air:Messages/air:Errors/air:Message')
				WITH (MessageDescription varchar(250) 'air:MessageDescription')
			OPEN LstErrosGerais
			FETCH NEXT FROM LstErrosGerais INTO @DescricaoErroDocXML
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ListaErrosGeraisDocXML = @ListaErrosGeraisDocXML + '		. ' + @DescricaoErroDocXML + CHAR(13) + CHAR(10)
				FETCH NEXT FROM LstErrosGerais INTO @DescricaoErroDocXML
			END
			CLOSE LstErrosGerais
			DEALLOCATE LstErrosGerais	
-- obtem dados do Manifesto SDS - Via Aérea
			SELECT @TipoManifesto = DSC_TIPO, @DataVooManifesto = DSC_DTVO
			FROM PRO_SDSC WITH(NOLOCK) 				
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- obtem lista de linhas AWB do manifesto
			DECLARE LstLinhas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT (CASE UPPER(Success) WHEN 'YES' THEN 1 WHEN 'NO' THEN 0 ELSE 2 END), 
					UPPER(Action), CustomsDocumentNumber, STUFF(ExternalItemNumber, 1, 1, ''), ISNULL(ItemState, ''), CustomsItemNumber, ErrorsTransport, ErrorsItem
				FROM OPENXML(@Handle, N'/air:AirManifestResponse/air:TransportDocumentList/air:TransportDocument/air:ItemList/air:Item')
				with (Success varchar(10) '@Success', 
					Action varchar(10) '@Action', 
					CustomsDocumentNumber varchar(24) '../../air:CustomsDocumentNumber', 
					ExternalItemNumber varchar(30) 'air:ExternalItemNumber', 
					ItemState varchar(3) 'air:ItemState',
					CustomsItemNumber varchar(50) 'air:CustomsItemNumber', 
					ErrorsTransport xml '../../air:Messages/air:Errors', 
					ErrorsItem xml 'air:Messages/air:Errors')
			OPEN LstLinhas
			FETCH NEXT FROM LstLinhas INTO @LinhaXMLValida, @AccaoLinhaXML, @NumDGALinhaXML, @NumAWBLinhaXML, @EstOperacaoLinhaXML, @NumDGAItemLinhaXML, @LstXMLErrosTransport, @LstXMLErrosItem
			WHILE @@FETCH_STATUS = 0
			BEGIN				
				SET @ListaErrosLinhaXML = ''
-- obtem lista de erros da linha AWB
				DECLARE LstErrosLinha CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
					WITH XMLNAMESPACES ('http://sds.dgaiec.min-financas.pt/AirManifestResponse' as air)
					SELECT ISNULL(XML_ERRS.ERR_TRNP.value('air:MessageDescription[1]', 'varchar(250)'), '')
					FROM @LstXMLErrosTransport.nodes('air:Errors/air:Message') as XML_ERRS(ERR_TRNP)										
					UNION
					SELECT ISNULL(XML_ERRS.ERR_ITEM.value('air:MessageDescription[1]', 'varchar(250)'), '')
					FROM @LstXMLErrosItem.nodes('air:Errors/air:Message') as XML_ERRS(ERR_ITEM)										
				OPEN LstErrosLinha
				FETCH NEXT FROM LstErrosLinha INTO @DescricaoErroDocXML
				WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @ListaErrosLinhaXML = @ListaErrosLinhaXML + '	. ' + @DescricaoErroDocXML + CHAR(13) + CHAR(10)
					FETCH NEXT FROM LstErrosLinha INTO @DescricaoErroDocXML
				END
				CLOSE LstErrosLinha
				DEALLOCATE LstErrosLinha
-- obtem data atual GMT
				SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- actualiza dados da linha AWB
				UPDATE PRO_SDSD SET 
					DSD_ESTA = (CASE 
									WHEN (DSD_ESTA IN ('FIN', 'APU')) THEN DSD_ESTA
									WHEN (@AccaoLinhaXML = 'CREATE') and (@LinhaXMLValida = 0) and (ISNULL(DSD_ESTA, '') = '') THEN DSD_ESTA 
									WHEN (@LinhaXMLValida = 2) and (@EstOperacaoLinhaXML = '') THEN DSD_ESTA 
									ELSE @EstOperacaoLinhaXML 
								END),
					DSD_DERR = (CASE @ListaErrosLinhaXML 
									WHEN '' THEN NULL 
									ELSE '#ERROS:' + CHAR(13) + CHAR(10) + @ListaErrosLinhaXML 
								END),
					DSD_STAT = (CASE @AccaoLinhaXML 
									WHEN 'CREATE' THEN (CASE @LinhaXMLValida WHEN 1 THEN 2 ELSE 3 END) 
									WHEN 'UPDATE' THEN (CASE @LinhaXMLValida WHEN 1 THEN 5 WHEN 0 THEN 6 ELSE (CASE @EstOperacaoLinhaXML WHEN '' THEN 6 ELSE 5 END) END) 
									ELSE (CASE @LinhaXMLValida WHEN 1 THEN 8 WHEN 0 THEN 9 ELSE (CASE @EstOperacaoLinhaXML WHEN '' THEN 9 ELSE 8 END) END) 
								END),
					DSD_NDGA = @NumDGALinhaXML, 
					DSD_NDGI = @NumDGAItemLinhaXML, 
					DSD_ASAI = (CASE 
									WHEN (@AccaoLinhaXML = 'CREATE') AND (@LinhaXMLValida = 1) THEN 1 
									ELSE DSD_ASAI 
								END)
				WHERE DSC_EANO = @AnoManifesto and DSC_NPRO = @NumManifesto and DSD_NRMH = @NumAWBLinhaXML	
-- se manifesto SDS - Via Aérea for de importação e linha AWB tiver "N.º DGA Item" atribuído, processa atualizações nas respetivas declarações de importação DUI2, IMP-CAU ou DAR
				IF (@TipoManifesto = 0) AND (ISNULL(@NumDGAItemLinhaXML, '') <> '')
				BEGIN
					SET @NumProcesso = NULL
					SET @AnoProcesso = NULL
					SET @ArtigoFranquia = NULL
					SET @ContextoIMP = NULL
					SET @IdDeclaracaoIMP = NULL
-- obtem dados da Declaração de Importação se tiver "Artigo Franquia" definido
					SELECT @NumProcesso = DUC_PNUM, @AnoProcesso = DUC_EANO, @ArtigoFranquia = DUC_ARTI, @ContextoIMP = DUC_DUNO, @IdDeclaracaoIMP = DUC_IDTY			
					FROM PRO_DUCG WITH(NOLOCK) 								
					WHERE DUC_DUNO IN (1, 2) AND DUC_CPRT = @NumAWBLinhaXML AND CAST(CONVERT(varchar(10), DUC_DTVO, 105) as datetime) = CAST(CONVERT(varchar(10), @DataVooManifesto, 105) as datetime)
						AND (SELECT COUNT(*) FROM PRO_DUOD WITH(NOLOCK) WHERE DUC_EANO = PRO_DUCG.DUC_EANO AND DUC_PNUM = PRO_DUCG.DUC_PNUM) > 0
-- verifica se se trata de uma Declaração de Importação
					IF @NumProcesso IS NOT NULL
					BEGIN
-- actualiza DU Importação relacionado com linha AWB
						UPDATE PRO_DUCG SET 
							DUC_LC27 = @NumDGAItemLinhaXML, 
							DUC_ASAI = (CASE WHEN (@EstOperacaoLinhaXML IN ('FIN', 'APU')) AND (DUC_ARTI IS NOT NULL) THEN 1 ELSE DUC_ASAI END),
							DUC_NORD = (CASE WHEN (@EstOperacaoLinhaXML IN ('FIN', 'APU')) AND (DUC_ARTI IS NOT NULL) THEN RIGHT(@NumDGALinhaXML, 18) ELSE DUC_NORD END),
							DUC_NDAT = (CASE WHEN (@EstOperacaoLinhaXML IN ('FIN', 'APU')) AND (DUC_ARTI IS NOT NULL) THEN CAST(CONVERT(varchar(10), @DataAtual, 105) as datetime) ELSE DUC_NDAT END)					
						WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso
-- actualiza adições do DU Importação relacionado com linha AWB
						UPDATE PRO_DUAD SET 
							DUA_QUAL = (CASE @ContextoIMP WHEN 2 THEN DUA_QUAL ELSE 'X' END), 
							DUA_DANO = (CASE @ContextoIMP WHEN 2 THEN DUA_DANO ELSE CAST(SUBSTRING(@NumDGAItemLinhaXML, 10, 4) AS int) END), 
							DUA_DNUM = SUBSTRING(@NumDGAItemLinhaXML, 14, 6), 
							DOC_CODI = (CASE @ContextoIMP WHEN 2 THEN DOC_CODI ELSE '785' END), 
							EAD_CODI = (CASE @ContextoIMP WHEN 2 THEN EAD_CODI ELSE ('PT000' + SUBSTRING(@NumDGAItemLinhaXML, 6, 3)) END), 
							DUA_DDAT = @DataVooManifesto, 
							MTR_CODI = (CASE @ContextoIMP WHEN 2 THEN MTR_CODI ELSE '4' END), 
							DUA_LINH = (CASE @ContextoIMP WHEN 2 THEN DUA_LINH ELSE SUBSTRING(@NumDGAItemLinhaXML, 20, 6) END)						
						WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso			
-- processa atualizações especificas em função se DUI2 ou IMP-CAU
						IF @ContextoIMP = 1
						BEGIN								
-- obtem as adições da Declaração de Importação
							DECLARE LstAdicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
								SELECT DUA_CODI									
								FROM PRO_DUAD WITH(NOLOCK) 								
								WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso
								ORDER BY DUA_CODI
							OPEN LstAdicoes
							FETCH NEXT FROM LstAdicoes INTO @NumAdicao
							WHILE @@FETCH_STATUS = 0
							BEGIN
-- para cada adição, verifica se linha "Sumária" do anexo de Declaração Sumária já existe					
								IF EXISTS(SELECT DRA_CODI FROM PRO_DURA WITH(NOLOCK) WHERE DRA_QUAL = 'X' AND DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao)
								BEGIN
									IF @NumAdicao = 1
									BEGIN
										SELECT TOP 1 @IDIntDeclSumaria1Adicao = DRA_IDCR
										FROM PRO_DURA WITH(NOLOCK) 
										WHERE DRA_QUAL = 'X' AND DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao
									END
-- actualiza linha "Sumária" do anexo de Declaração Sumária							
									UPDATE PRO_DURA set 
										DOC_CODI = '785', 
										DRA_APDT = @DataVooManifesto, 
										DRA_APAN = CAST(SUBSTRING(@NumDGAItemLinhaXML, 10, 4) AS int)
									WHERE DRA_QUAL = 'X' AND DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao
								END
								ELSE
								BEGIN
									IF @NumAdicao = 1
									BEGIN
										SET @DeclSumariaAuto = 0
										SET @CodRelDeclSumaria = NULL
										SET @IDIntDeclSumaria = REPLACE(LTRIM(STR(CAST(@DataAtual AS numeric(38,6)), 20, 6)), '.', ',')
										SET @IDIntDeclSumaria1Adicao = @IDIntDeclSumaria
									END
									ELSE
									BEGIN
										SET @DeclSumariaAuto = 1
										SET @CodRelDeclSumaria = @IDIntDeclSumaria1Adicao
										SET @IDIntDeclSumaria = REPLACE(LTRIM(STR(CAST(@DataAtual AS numeric(38,6)), 20, 6)), '.', ',')							
									END
									SET @ProxNumeroDeclSumaria = (ISNULL((SELECT MAX(DRA_CODI) FROM PRO_DURA WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao), 0) + 1)
-- insere linha "Sumária" do anexo de Declaração Sumária
									INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APDT, DRA_QUAL, DRA_CODR, DRA_AUTO, DRA_IDCR)
									VALUES(@AnoProcesso, @NumProcesso, @NumAdicao, @ProxNumeroDeclSumaria, '785', CAST(SUBSTRING(@NumDGAItemLinhaXML, 10, 4) AS int), 
										SUBSTRING(@NumDGAItemLinhaXML, 14, 12), 'NP', @DataVooManifesto, 'X', @CodRelDeclSumaria, @DeclSumariaAuto, @IDIntDeclSumaria)
								END							
								FETCH NEXT FROM LstAdicoes INTO @NumAdicao
							END
							CLOSE LstAdicoes
							DEALLOCATE LstAdicoes					
						END
						ELSE --Declaração Importação IMP-CAU
						BEGIN							
-- obtem o ID do utilizador
							SELECT @IdUtilizador = UTI_IDTY
							FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
							WHERE UTI_UTIL = @Utilizador
-- procede à inserção/atualização do documento precedente c/ código "N337"						
							IF NOT EXISTS(SELECT id FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY WHERE dpr.id_declaracaoIMP = @IdDeclaracaoIMP AND doc.DOC_CODI = 'N337')
							BEGIN
								INSERT INTO tb_IMP_DeclaracoesPrecedentes(id_declaracaoIMP, id_documento, numero, dataContramarca, origem, id_utilizadorControlo, dataControlo)
								SELECT @IdDeclaracaoIMP, DOC_IDTY, STUFF(@NumDGAItemLinhaXML, 3, 3, '000'), @DataVooManifesto, 3, @IdUtilizador, @DataAtual
								FROM TAB_DOCU WITH(NOLOCK)
								WHERE DOC_CODI = 'N337'
							END
							ELSE
							BEGIN
								UPDATE tb_IMP_DeclaracoesPrecedentes SET 
									numero = STUFF(@NumDGAItemLinhaXML, 3, 3, '000'), 
									dataContramarca = @DataVooManifesto, 
									id_utilizadorControlo = @IdUtilizador, 
									dataControlo = @DataAtual								
								FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 									
									INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
								WHERE dpr.id_declaracaoIMP = @IdDeclaracaoIMP AND doc.DOC_CODI = 'N337'
							END
						END												
-- se estado da operação da AWB for "FIN" ou "APU" e declaração tiver "Artigo Franquia" definido, processa a inserção da incidência "A00"
						IF (@EstOperacaoLinhaXML IN ('FIN', 'APU')) AND (@ArtigoFranquia IS NOT NULL)
						BEGIN
-- obtem dados para registo de incidência
							SET @NumLinhaIncidencia = (ISNULL((SELECT MAX(DUI_CODI) FROM PRO_DUIN WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso), 0) + 1)
							SET @DataIncidencia = CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)
							SET @HoraIncidencia = @DataAtual							
-- insere a incidência "A00"							
							INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM)
							SELECT @AnoProcesso, @NumProcesso, @NumLinhaIncidencia, SIN_CODI, SIN_DESP, @DataIncidencia, @HoraIncidencia, @DataIncidencia, @HoraIncidencia
							FROM TAB_SINC WITH(NOLOCK) 
							WHERE SIN_CODI = 'A00'							
						END
					END
					ELSE
					BEGIN
						SET @IdDeclaracaoDAR = NULL					
-- verifica se se trata de uma Declaração DAR
						SELECT TOP 1 @IdDeclaracaoDAR = dar.id 
						FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 							
						WHERE dar.documentoTransporte = @NumAWBLinhaXML AND CAST(CONVERT(varchar(10), dar.dataVoo, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataVooManifesto, 105) AS datetime)
							AND EXISTS(SELECT id FROM tb_DeclaracoesDARManifestos WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
-- se for Declaração DAR, procede à inserção/atualização do documento precedente c/ código "N337"
						IF @IdDeclaracaoDAR IS NOT NULL
						BEGIN							
-- obtem o ID do utilizador
							SELECT @IdUtilizador = UTI_IDTY
							FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
							WHERE UTI_UTIL = @Utilizador
-- procede à inserção/atualização do documento precedente c/ código "N337"						
							IF NOT EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY WHERE dpr.id_declaracaoDAR = @IdDeclaracaoDAR AND doc.DOC_CODI = 'N337')
							BEGIN
								INSERT INTO tb_DeclaracoesDARPrecedentes(id_declaracaoDAR, id_documento, numero, id_utilizadorControlo, dataControlo, origem, dataContramarca)
								SELECT @IdDeclaracaoDAR, DOC_IDTY, STUFF(@NumDGAItemLinhaXML, 3, 3, '000'), @IdUtilizador, @DataAtual, 2, @DataVooManifesto
								FROM TAB_DOCU WITH(NOLOCK) 
								WHERE DOC_CODI = 'N337'
							END
							ELSE
							BEGIN
								UPDATE tb_DeclaracoesDARPrecedentes SET 
									numero = STUFF(@NumDGAItemLinhaXML, 3, 3, '000'), 
									id_utilizadorControlo = @IdUtilizador, 
									dataControlo = @DataAtual, 
									dataContramarca = @DataVooManifesto
								FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) 									
									INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
								WHERE dpr.id_declaracaoDAR = @IdDeclaracaoDAR AND doc.DOC_CODI = 'N337'
							END
						END
					END				
				END
				ELSE
-- se linha AWB tem "Aut. Saída" e pertence a um SDS do tipo "Exportação", insere ou edita registo de Saida AEX correspondente
					IF (@TipoManifesto = 1) AND (ISNULL(@NumDGAItemLinhaXML, '') <> '') AND (EXISTS(SELECT DSD_NUME FROM PRO_SDSD WITH(NOLOCK) WHERE DSD_ASAI = 1 AND DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_NRMH = @NumAWBLinhaXML))
						EXEC SP_SaidasAEX_InsereOuEditaViaExportacaoXMLouSDSViaAerea 0, @AnoManifesto, @NumManifesto, NULL, @NumAWBLinhaXML, @Utilizador, @MensagemErro OUTPUT															
				FETCH NEXT FROM LstLinhas INTO @LinhaXMLValida, @AccaoLinhaXML, @NumDGALinhaXML, @NumAWBLinhaXML, @EstOperacaoLinhaXML, @NumDGAItemLinhaXML, @LstXMLErrosTransport, @LstXMLErrosItem
			END
			CLOSE LstLinhas
			DEALLOCATE LstLinhas
-- actualiza dados do manifesto SDS
			UPDATE PRO_SDSC SET 
				DSC_NRRR = DSC_NRRR + 1, 
				DSC_UDRR = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
				DSC_RESP = '-> AIR MANIFEST RESPONSE: ' + CHAR(13) + CHAR(10) + 
							'	#Data Integração: ' + CONVERT(varchar(23), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 121) + CHAR(13) + CHAR(10) +
							'	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) +
							'	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) +
							'	#MessageDate: ' + CONVERT(varchar(23), @DataMensagem, 121) + CHAR(13) + CHAR(10) +
							'	#Sucess: ' + (case @DocXMLValido when 0 then 'No' else 'Yes' end) + CHAR(13) + CHAR(10) +				   
							(case @ListaErrosSistemaDocXML when '' then '' else '	#Erros Sistema: ' + CHAR(13) + CHAR(10) + @ListaErrosSistemaDocXML end) +
							(case @ListaErrosGeraisDocXML when '' then '' else '	#Erros Gerais: ' + CHAR(13) + CHAR(10) + @ListaErrosGeraisDocXML end) +
							(case when (@DocXMLValido = 0) and  (@ListaErrosSistemaDocXML = '') and (@ListaErrosGeraisDocXML = '') then '	#Erros Linhas: ' + CHAR(13) + CHAR(10) + '		. «Verificar erros nas linhas AWB»' + CHAR(13) + CHAR(10) else '' end) +
							'===============================================================================================================================' + CHAR(13) + CHAR(10) +
				ISNULL(cast(DSC_RESP as varchar(max)), '')					
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- devolve resultado
			IF @DocXMLValido = 1
				SET @Resultado = 1
			ELSE
				SET @Resultado = 2			
		END
		ELSE
			SET @Resultado = 4
	END
	ELSE
		SET @Resultado = 3
-- remove Handle criado para documento XML
	EXEC sp_xml_removedocument @Handle
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_IntegraAirManifestResponse] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_IntegraAirManifestResponse] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_IntegraWSAirCustomsResponseNotification]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_IntegraWSAirCustomsResponseNotification] @Utilizador varchar(20), @IDIntegracao int OUTPUT, @MsgErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @WebServiceLocation nvarchar(250), @LoginAcesso varchar(20), @PwdAcesso varchar(50), @PathCertificado varchar(250), @PwdCertificado varchar(50), 	
		@ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), @RequestXML xml, @ResponseXML xml, 
		@Resultado int, @DataHoraAtual datetime, @ID int, @IDMsg varchar(50), @MsgXML xml, @NumContramarca varchar(14), @ResultadoMsgXML varchar(10), @TipoMsgXML int, 
		@MsgControlNotification bit, @AnoManifestoSDS int, @NumManifestoSDS int, @RelatorioDescargaSDS int, @MsgControl bit, @FaultMessage varchar(MAX)
	BEGIN TRY
-- inicia variáveis
		SET @MsgErro = NULL	
		SET @FaultMessage = NULL
-- obtem configurações de Proxy Authentication
		SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), 
			@ProxyPassword = ISNULL(PAP_PPWD, '')
		FROM TAB_PAPL	
-- obtem endereço Location do WebService p/ comunicação aos webservices do SDS - Via Aérea dos Depositários
		SELECT @WebServiceLocation = PSD_WEBS, @LoginAcesso = PSD_UTIL, @PwdAcesso = PSD_PASS, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC
		FROM TAB_PSDS
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)		
-- constroi estrutura XML com os dados do pedido ao metodo retrieveNewOutputMessagesIds a enviar à AT
		;WITH XMLNAMESPACES ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' as wsse, 
			'http://server.ws.sds.dgita.gov.pt/' as ser, 
			'http://schemas.xmlsoap.org/soap/envelope/' as soapenv)
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT 
						(SELECT @LoginAcesso "wsse:Username", @PwdAcesso "wsse:Password"
						FOR XML PATH('wsse:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wsse:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT ('PT' + @LoginAcesso) "receiver"
					FOR XML PATH('ser:retrieveNewOutputMessagesIds'), TYPE)		
				FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soapenv:Envelope'), ELEMENTS)
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN..SP_Externo_EnviarDadosWS @RequestXML, @WebServiceLocation, 'http://server.ws.sds.dgita.gov.pt/WarehouseKeepers/retrieveOutputMessagesByIdsRequest', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro "Interno DLL" na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as "SOAP-ENV")
		SELECT @FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)			
-- cria tabela tmp p/ guardar IDs do response do metodo do webservice
		CREATE TABLE #tmpResultadoIDs (ID int NOT NULL IDENTITY (1, 1), MSGID nvarchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)	
-- obtem os IDs retornados do WS p/ tabela tmp	
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as S, 'http://server.ws.sds.dgita.gov.pt/' as ns0)
		INSERT INTO #tmpResultadoIDs (MSGID)
		SELECT XML_MSGR.MSG_DATA.value('.[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('S:Envelope/S:Body/ns0:retrieveNewOutputMessagesIdsResponse/return') as XML_MSGR(MSG_DATA)
-- se existirem IDs, obtem mensagens XML respetivas
		IF EXISTS(SELECT ID FROM #tmpResultadoIDs)
		BEGIN
-- constroi estrutura XML com os dados do pedido ao metodo retrieveOutputMessagesByIds a enviar à AT
			;WITH XMLNAMESPACES ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' as wsse, 
				'http://server.ws.sds.dgita.gov.pt/' as ser, 
				'http://schemas.xmlsoap.org/soap/envelope/' as soapenv)
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT 
							(SELECT @LoginAcesso "wsse:Username", @PwdAcesso "wsse:Password"
							FOR XML PATH('wsse:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wsse:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT ('PT' + @LoginAcesso) "receiver",
							(SELECT MSGID "outputMessagesIds"
							FROM #tmpResultadoIDs
							FOR XML PATH(''), TYPE)
						FOR XML PATH('ser:retrieveOutputMessagesByIds'), TYPE)		
					FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Envelope'), ELEMENTS)
-- processa envio do DT para o WebService da AT	
			EXEC GIDWIN..SP_Externo_EnviarDadosWS @RequestXML, @WebServiceLocation, 'http://server.ws.sds.dgita.gov.pt/WarehouseKeepers/retrieveNewOutputMessagesIdsRequest', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- cria tabela tmp p/ guardar XML do response do metodo do webservice
			CREATE TABLE #tmpResultadoMSGs (ID int NOT NULL IDENTITY (1, 1), MSG nvarchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)		
-- obtem as MSGs retornadas do WS p/ tabela tmp			
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as S, 'http://server.ws.sds.dgita.gov.pt/' as ns0)
			INSERT INTO #tmpResultadoMSGs (MSG)
			SELECT XML_MSGR.MSG_DATA.value('.[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('S:Envelope/S:Body/ns0:retrieveOutputMessagesByIdsResponse/return') as XML_MSGR(MSG_DATA)
-- obtem o ID e data/hora atuais da Integração WS
			SET @IDIntegracao = (ISNULL((SELECT MAX(DSI_CODI) FROM HST_SDSI), 0) + 1)
			SET @DataHoraAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- insere as mensagens XML e respetivos IDs na tabela de Histórico de Integrações WS SDS - Via Aérea
			INSERT INTO HST_SDSI(DSI_CODI, DSI_DATA, DSI_MSGI, DSI_MSGD, DSI_STAT, DSI_DTST)
			SELECT @IDIntegracao, @DataHoraAtual, ids.MSGID, CONVERT(varchar(MAX), CAST('' AS XML).value('xs:base64Binary(sql:column("MSG"))', 'varbinary(MAX)')), 0, @DataHoraAtual
			FROM #tmpResultadoMSGs AS msg INNER JOIN #tmpResultadoIDs AS ids ON msg.ID = ids.ID
-- processa a integração das msgs XML obtidas		
			DECLARE MsgsXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT DSI_IDEN, DSI_MSGI, DSI_MSGD
				FROM HST_SDSI
				WHERE DSI_CODI = @IDIntegracao
			OPEN MsgsXML
			FETCH NEXT FROM MsgsXML INTO @ID, @IDMsg, @MsgXML
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @NumContramarca = NULL
				SET @TipoMsgXML = 0
				SET @ResultadoMsgXML = NULL
				SET @AnoManifestoSDS = NULL
				SET @NumManifestoSDS = NULL
				SET @RelatorioDescargaSDS = NULL
-- obtem o "Nº. Contramarca" na msg XML de AirCustomsResponse	
				;WITH XMLNAMESPACES ('http://sds.aduaneiro.portaldasfinancas.gov.pt/AirCustomsResponse' as air, 'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypes' as air1)
				SELECT @NumContramarca = XML_MSGR.MSG_DATA.value('air:CustomsReferenceNumber[1]', 'varchar(14)'), @ResultadoMsgXML = XML_MSGR.MSG_DATA.value('(air:ActionResult/air:Result)[1]', 'varchar(10)')
				FROM @MsgXML.nodes('air:AirCustomsResponse/air:MessageInformation') as XML_MSGR(MSG_DATA)			
-- se o "Nº. Contramarca" vazio, obtem o "Nº. Contramarca" na msg XML de AirCustomsNotification 
				IF ISNULL(@NumContramarca, '') = ''
				BEGIN
					;WITH XMLNAMESPACES ('http://sds.aduaneiro.portaldasfinancas.gov.pt/AirCustomsNotification' as air, 'http://sds.aduaneiro.portaldasfinancas.gov.pt/AirWarehouseKeeperDataTypes' as air1)
					SELECT @NumContramarca = XML_MSGR.MSG_DATA.value('air:CustomsReferenceNumber[1]', 'varchar(14)'), @ResultadoMsgXML = 'Accepted', 
						@MsgControlNotification = (CASE WHEN ISNULL(XML_MSGR.MSG_DATA.value('(../air:Cargos/air:Cargo/air:Control/air:Type)[1]', 'varchar(4)'), '') <> '' THEN 1 ELSE 0 END)
					FROM @MsgXML.nodes('air:AirCustomsNotification/air:MessageInformation') as XML_MSGR(MSG_DATA)				
					IF ISNULL(@NumContramarca, '') <> ''
					BEGIN
						IF @MsgControlNotification = 0
							SET @TipoMsgXML = 2
						ELSE
							SET @TipoMsgXML = 3
					END
				END			
				ELSE
					SET @TipoMsgXML = 1
-- se msg XML for do tipo AirCustomsResponse ou AirCustomsNotification, obtem manifesto associado à Contramarca obtida
				IF @TipoMsgXML > 0
				BEGIN				
					SELECT @AnoManifestoSDS = DSC_EANO, @NumManifestoSDS = DSC_NPRO, @RelatorioDescargaSDS = (CASE DSC_STMS WHEN 0 THEN 1 ELSE 0 END)
					FROM PRO_SDSC 
					WHERE DSC_TIPO = 0 AND (DSC_NCMF + DSC_NCMV) = @NumContramarca
-- se existe manifesto SDS de Importação p/ a Contramarca processa a integração dos dados da msg XML AirCustomsResponse ou AirCustomsNotification
					IF @AnoManifestoSDS IS NOT NULL
					BEGIN									
						IF @TipoMsgXML = 1
							EXEC SP_SDSViaAerea_IntegraAirCustomsResponse @RelatorioDescargaSDS, @AnoManifestoSDS, @NumManifestoSDS, @Utilizador, @MsgXML, @Resultado OUTPUT 
						ELSE
						BEGIN
							SET @MsgControl = (CASE @TipoMsgXML WHEN 3 THEN 1 ELSE 0 END)
							EXEC SP_SDSViaAerea_IntegraAirCustomsNotification @MsgControl, @AnoManifestoSDS, @NumManifestoSDS, @Utilizador, @MsgXML, @Resultado OUTPUT
						END
					END
					ELSE
						SET @Resultado = 99
				END	
				ELSE
					SET @Resultado = 99
-- atualiza estado na tabela de histórico de integrações WS do DSD - Via Aérea						
				UPDATE HST_SDSI SET DSI_STAT = (CASE WHEN (@Resultado > 2) THEN 2 ELSE 1 END), DSI_DTST = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
					DSI_TMSG = NULLIF(@TipoMsgXML, 0), DSI_RDES = ISNULL(@RelatorioDescargaSDS, 1), DSI_NCTM = @NumContramarca, DSI_RESG = @ResultadoMsgXML, 
					DSC_EANO = @AnoManifestoSDS, DSC_NPRO = @NumManifestoSDS
				WHERE DSI_IDEN = @ID 						
				FETCH NEXT FROM MsgsXML INTO @ID, @IDMsg, @MsgXML
			END
			CLOSE MsgsXML
			DEALLOCATE MsgsXML
-- apaga tabela tmp		
			DROP TABLE #tmpResultadoMSGs
		END	
-- apaga tabela tmp
		DROP TABLE #tmpResultadoIDs
	END TRY
	BEGIN CATCH	
		SET @MsgErro = ERROR_MESSAGE()
	END CATCH
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_IntegraWSAirCustomsResponseNotification] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_IntegraWSAirCustomsResponseNotification] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_IntegraWSAirManifestResponse]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_IntegraWSAirManifestResponse] @AnoManifesto int, @NumManifesto int, @NumContramarca varchar(14), @Utilizador varchar(20), @Erros bit OUTPUT, 
	@IDIntegracao int OUTPUT, @MsgErro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variaveis 
	DECLARE @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100), @WebServiceLocation nvarchar(250), 
		@LoginAcesso varchar(20), @PwdAcesso varchar(50), @PathCertificado varchar(250), @PwdCertificado varchar(50), @Resultado int, @RequestXML xml, @ResponseXML xml, 
		@DataHoraAtual datetime, @ID int, @MsgXML xml, @IDMsgXML varchar(50), @ResultadoMsgXML varchar(10), @FaultMessage varchar(MAX)
	BEGIN TRY
-- inicia variáveis
		SET @MsgErro = NULL	
		SET @FaultMessage = NULL
-- obtem configurações de Proxy Authentication
		SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), 
			@ProxyPassword = ISNULL(PAP_PPWD, '')
		FROM TAB_PAPL	
-- obtem endereço Location do WebService p/ comunicação aos webservices do SDS - Via Aérea dos Transportadores
		SELECT @WebServiceLocation = PSD_WSTR, @LoginAcesso = PSD_UTTR, @PwdAcesso = PSD_PWTR, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC
		FROM TAB_PSDS
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)		
-- constroi estrutura XML com os dados do pedido ao metodo retrieveByCustomsProcessNumber a enviar à AT
		;WITH XMLNAMESPACES ('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' as wsse, 
			'http://server.ws.sds.dgita.gov.pt/' as ser, 
			'http://schemas.xmlsoap.org/soap/envelope/' as soapenv)
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT 
						(SELECT @LoginAcesso "wsse:Username", @PwdAcesso "wsse:Password"
						FOR XML PATH('wsse:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wsse:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soapenv:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT @LoginAcesso "receiver",
						@NumContramarca "customsProcessNumber"
					FOR XML PATH('ser:retrieveByCustomsProcessNumber'), TYPE)		
				FOR XML PATH('soapenv:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soapenv:Envelope'), ELEMENTS)
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN..SP_Externo_EnviarDadosWS @RequestXML, @WebServiceLocation, 'http://server.ws.sds.dgita.gov.pt/Traders/retrieveByCustomsProcessNumber', @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT	
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as "SOAP-ENV")
		SELECT @FaultMessage = XML_MSGR.MSG_DATA.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') as XML_MSGR(MSG_DATA)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)
-- cria tabela tmp p/ guardar XML do response do metodo do webservice
		CREATE TABLE #tmpResultadoMSGs (ID int NOT NULL IDENTITY (1, 1), MSG nvarchar(MAX) COLLATE Latin1_General_CI_AI NOT NULL)		
-- obtem as MSGs retornadas do WS p/ tabela tmp			
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as S, 'http://server.ws.sds.dgita.gov.pt/' as ns0)
		INSERT INTO #tmpResultadoMSGs (MSG)
		SELECT XML_MSGR.MSG_DATA.value('.[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('S:Envelope/S:Body/ns0:retrieveByCustomsProcessNumberResponse/return') as XML_MSGR(MSG_DATA)
-- obtem o ID e data/hora atuais da Integração WS
		SET @Erros = 0
		SET @IDIntegracao = (ISNULL((SELECT MAX(DSI_CODI) FROM HST_SDSI), 0) + 1)
		SET @DataHoraAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- insere as mensagens XML e respetivos IDs na tabela de Histórico de Integrações WS SDS - Via Aérea
		INSERT INTO HST_SDSI(DSI_CODI, DSI_DATA, DSI_MSGI, DSI_MSGD, DSI_STAT, DSI_DTST)
		SELECT @IDIntegracao, @DataHoraAtual, 'n.d.', CONVERT(varchar(MAX), CAST('' AS XML).value('xs:base64Binary(sql:column("MSG"))', 'varbinary(MAX)')), 0, @DataHoraAtual
		FROM #tmpResultadoMSGs
-- processa a integração das msgs XML obtidas		
		DECLARE MsgsXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DSI_IDEN, DSI_MSGD
			FROM HST_SDSI
			WHERE DSI_CODI = @IDIntegracao
		OPEN MsgsXML
		FETCH NEXT FROM MsgsXML INTO @ID, @MsgXML
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @IDMsgXML = NULL 
			SET @ResultadoMsgXML = NULL
-- obtem o "ID" na msg XML de AirManifestResponse	
			;WITH XMLNAMESPACES ('http://sds.dgaiec.min-financas.pt/AirManifestResponse' as air)
			SELECT @IDMsgXML = XML_MSGR.MSG_DATA.value('air:MessageIdentification[1]', 'varchar(50)'), @ResultadoMsgXML = XML_MSGR.MSG_DATA.value('../@Success[1]', 'varchar(10)')
			FROM @MsgXML.nodes('air:AirManifestResponse/air:MessageInformation') as XML_MSGR(MSG_DATA)			
-- processa a integração dos dados da msg XML AirManifestResponse			
			EXEC SP_SDSViaAerea_IntegraAirManifestResponse @AnoManifesto, @NumManifesto, @Utilizador, @MsgXML, @Resultado OUTPUT	
-- assinala erro na integração 
			IF (@Erros = 0) AND (@Resultado > 1)
				SET @Erros = 1
-- atualiza estado na tabela de histórico de integrações WS do DSD - Via Aérea						
			UPDATE HST_SDSI SET DSI_MSGI = @IDMsgXML, DSI_STAT = (CASE WHEN (@Resultado > 2) THEN 2 ELSE 1 END), DSI_DTST = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
				DSI_TMSG = 4, DSI_RDES = 0, DSI_NCTM = @NumContramarca, DSI_RESG = @ResultadoMsgXML, DSC_EANO = @AnoManifesto, DSC_NPRO = @NumManifesto
			WHERE DSI_IDEN = @ID 						
			FETCH NEXT FROM MsgsXML INTO @ID, @MsgXML
		END
		CLOSE MsgsXML
		DEALLOCATE MsgsXML
-- apaga tabela tmp		
		DROP TABLE #tmpResultadoMSGs
	END TRY
	BEGIN CATCH	
		SET @MsgErro = ERROR_MESSAGE()
	END CATCH
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_IntegraWSAirManifestResponse] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_IntegraWSAirManifestResponse] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemDadosAWB]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemDadosAWB] @Tipo tinyint, @IdManifesto int, @NumeroAWBMaster varchar(30), @CodAeroporto varchar(8), @XMLEstatutosCarga xml, 
	 @XMLDadosAWB xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;	
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @NumeroAWBMasterValida bit, @NumPartidas int
	BEGIN TRY	
		SET @NumErro = 0	
-- obtem a data atual
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()			
-- se Manifesto SDS Exportação, obtem se AWB é válida
		IF (@Tipo = 1) AND (ISNULL(@NumeroAWBMaster, '') <> '') AND (EXISTS(SELECT 1 FROM PRO_SDSC AS sdc WITH(NOLOCK) INNER JOIN PRO_SDSD AS sda WITH(NOLOCK) ON sdc.DSC_EANO = sda.DSC_EANO AND sdc.DSC_NPRO = sda.DSC_NPRO WHERE sdc.DSC_IDEN = @IdManifesto AND sda.DSD_NRMH = @NumeroAWBMaster))
			SET @NumeroAWBMasterValida = 1
		ELSE
			SET @NumeroAWBMasterValida = 0
-- se Manifesto SDS Exportação com AWB válida, obtem o número de partidas associadas à AWB
		IF (@Tipo = 1) AND (@NumeroAWBMasterValida = 1)
		BEGIN
			SELECT @NumPartidas = COUNT(*)
			FROM PRO_SDSC AS sdc WITH(NOLOCK)
				INNER JOIN PRO_SDSD AS sda WITH(NOLOCK) ON sdc.DSC_EANO = sda.DSC_EANO AND sdc.DSC_NPRO = sda.DSC_NPRO
				INNER JOIN PRO_SDSD AS lpa WITH(NOLOCK) ON lpa.DOC_CODI = 'N740' AND sda.DSD_IDCR = lpa.DSD_CODR
			WHERE sdc.DSC_IDEN = @IdManifesto AND sda.DSD_NRMH = @NumeroAWBMaster
		END
		ELSE
			SET @NumPartidas = 0
-- para Manifesto SDS Exportação com AWB inválida, obtem Dados AWB cujas linhas tem o estatuto de carga igual ao especificado 
		IF (@Tipo = 1) AND (ISNULL(@NumeroAWBMaster, '') <> '') AND (@NumeroAWBMasterValida = 0)
		BEGIN	
			SET @XMLDadosAWB =				
				(SELECT 
					art.APA_CODI AS "artigo", 					
					'Consolidation' AS "designacao", 
					SUM(sda.DSD_PESO) AS "massaBruta", 
					'N741' AS "codigoDocumento", 
					@NumeroAWBMaster AS "numeroDocumento", 					
					'S/M' AS "marcas", 
					tem.TEM_CODI AS "tipoEmbalagem", 
					SUM(sda.DSD_VOLS) AS "volumes", 
					NULL AS "numeroPrecedente", 
					NULL AS "idLinhaAWB"
				FROM PRO_SDSC AS sdc WITH(NOLOCK)
					INNER JOIN PRO_SDSD AS sda WITH(NOLOCK) ON sdc.DSC_EANO = sda.DSC_EANO AND sdc.DSC_NPRO = sda.DSC_NPRO
					INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
					INNER JOIN TAB_TEMB AS tem WITH(NOLOCK) ON tem.TEM_CODI = 'CT'
					INNER JOIN @XMLEstatutosCarga.nodes('EstatutosCarga/Estatuto') AS e(d) ON sda.DSD_EADC = e.d.value('.[1]', 'varchar(2)')
				WHERE sdc.DSC_IDEN = @IdManifesto AND ((sda.DSD_EADC = 'C')
						OR ((sda.DSD_EADC = 'X') AND (sda.DSD_MRNR NOT LIKE 'LET%') AND (sda.DSD_TCAR = '101') AND (sda.DOC_CODI = 'N740') AND (NOT EXISTS(SELECT 1 FROM PRO_SSDD WITH(NOLOCK) WHERE DSC_EANO = sda.DSC_EANO AND DSC_NPRO = sda.DSC_NPRO AND DSD_NUME = sda.DSD_NUME AND DOC_CODI = 'N830')))
					)
				GROUP BY art.APA_CODI, art.APA_CPAU, art.APA_ATAR, tem.TEM_CODI
				FOR XML PATH('adicao'), ROOT('adicoes'), TYPE)
		END
		ELSE
-- para Manifesto SDS Exportação com AWB válida e sem partidas associadas, obtem Dados AWB da AWB especificada
		IF (@Tipo = 1) AND (ISNULL(@NumeroAWBMaster, '') <> '') AND (@NumeroAWBMasterValida = 1) AND (@NumPartidas = 0)
		BEGIN			
			SET @XMLDadosAWB =				
				(SELECT 
					art.APA_CODI AS "artigo", 					
					sda.DSD_DMER AS "designacao", 
					sda.DSD_PESO AS "massaBruta",
					'N741' AS "codigoDocumento",  
					sda.DSD_NRMH AS "numeroDocumento", 					
					sda.DSD_MRNR AS "marcas", 
					sda.TEM_CODI AS "tipoEmbalagem", 
					sda.DSD_VOLS AS "volumes", 
					(CASE ISNULL(sda.DSD_NDGA, '') WHEN '' THEN (sdc.DSC_NCMF + sdc.DSC_NCMV) ELSE sda.DSD_NDGA END) AS "numeroPrecedente", 
					sda.DSD_IDNN AS "idLinhaAWB"
				FROM PRO_SDSC AS sdc WITH(NOLOCK)
					INNER JOIN PRO_SDSD AS sda WITH(NOLOCK) ON sdc.DSC_EANO = sda.DSC_EANO AND sdc.DSC_NPRO = sda.DSC_NPRO				
					INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
				WHERE sdc.DSC_IDEN = @IdManifesto AND sda.DSD_NRMH = @NumeroAWBMaster	
				FOR XML PATH('adicao'), ROOT('adicoes'), TYPE)				
		END
		ELSE	
-- para Manifesto SDS Exportação com AWB válida e com partidas associadas, obtem Dados AWB das partidas associadas à AWB especificada
		IF (@Tipo = 1) AND (ISNULL(@NumeroAWBMaster, '') <> '') AND (@NumeroAWBMasterValida = 1) AND (@NumPartidas > 0) 
		BEGIN			
			SET @XMLDadosAWB =				
				(SELECT 
					art.APA_CODI AS "artigo", 
					lpa.DSD_DMER AS "designacao", 
					lpa.DSD_PESO AS "massaBruta", 
					'N740' AS "codigoDocumento", 
					lpa.DSD_NRMH AS "numeroDocumento", 
					lpa.DSD_MRNR AS "marcas", 
					lpa.TEM_CODI AS "tipoEmbalagem", 
					lpa.DSD_VOLS AS "volumes", 
					(CASE ISNULL(lpa.DSD_NDGA, '') WHEN '' THEN (sdc.DSC_NCMF + sdc.DSC_NCMV) ELSE lpa.DSD_NDGA END) AS "numeroPrecedente", 
					lpa.DSD_IDNN AS "idLinhaAWB"
				FROM PRO_SDSC AS sdc WITH(NOLOCK)
					INNER JOIN PRO_SDSD AS sda WITH(NOLOCK) ON sdc.DSC_EANO = sda.DSC_EANO AND sdc.DSC_NPRO = sda.DSC_NPRO		
					INNER JOIN PRO_SDSD AS lpa WITH(NOLOCK) ON lpa.DOC_CODI = 'N740' AND sda.DSD_IDCR = lpa.DSD_CODR				
					INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
				WHERE sdc.DSC_IDEN = @IdManifesto AND sda.DSD_NRMH = @NumeroAWBMaster	
				FOR XML PATH('adicao'), ROOT('adicoes'), TYPE)					
		END
-- para Manifesto SDS Importação ou Exportação sem AWB especificada, obtem Dados AWB cujas linhas tem o estatuto de carga igual ao especificado e o aeroporto destino igual ao especificado
		ELSE
		BEGIN		
			SET @XMLDadosAWB =				
				(SELECT 
					art.APA_CODI AS "artigo", 
					sda.DSD_DMER AS "designacao", 
					sda.DSD_PESO AS "massaBruta", 
					(CASE WHEN (@Tipo = 1) AND (sda.DSD_EADC = 'C') THEN 'N741' ELSE 'N740' END) AS "codigoDocumento", 
					sda.DSD_NRMH AS "numeroDocumento", 
					sda.DSD_MRNR AS "marcas", 
					sda.TEM_CODI AS "tipoEmbalagem", 
					sda.DSD_VOLS AS "volumes", 
					(CASE ISNULL(sda.DSD_NDGA, '') WHEN '' THEN (sdc.DSC_NCMF + sdc.DSC_NCMV) ELSE sda.DSD_NDGA END) AS "numeroPrecedente", 
					sda.DSD_IDNN AS "idLinhaAWB"
				FROM PRO_SDSC AS sdc WITH(NOLOCK)
					INNER JOIN PRO_SDSD AS sda WITH(NOLOCK) ON sdc.DSC_EANO = sda.DSC_EANO AND sdc.DSC_NPRO = sda.DSC_NPRO						
					INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON art.APA_CODI = '00000000'
					INNER JOIN @XMLEstatutosCarga.nodes('EstatutosCarga/Estatuto') AS e(d) ON sda.DSD_EADC = e.d.value('.[1]', 'varchar(2)')
				WHERE sdc.DSC_IDEN = @IdManifesto AND sda.PAE_CODI = ISNULL(NULLIF(@CodAeroporto, ''), sda.PAE_CODI) 	
					AND ((@Tipo = 0) 
						OR (sda.DSD_EADC = 'C')
						OR ((sda.DSD_EADC = 'X') AND (sda.DSD_MRNR NOT LIKE 'LET%') AND (sda.DSD_TCAR = '101') AND (sda.DOC_CODI = 'N740') AND (NOT EXISTS(SELECT 1 FROM PRO_SSDD WITH(NOLOCK) WHERE DSC_EANO = sda.DSC_EANO AND DSC_NPRO = sda.DSC_NPRO AND DSD_NUME = sda.DSD_NUME AND DOC_CODI = 'N830')))
					)					
				FOR XML PATH('adicao'), ROOT('adicoes'), TYPE)	
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemDadosAWB] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemDadosAWB] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemIDManifesto]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemIDManifesto] @Tipo tinyint, @DataVoo datetime, @CodEstancia varchar(8), @ContramarcaV varchar(6), @NumeroAWBMaster varchar(30), 
	@Id int OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;	
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @IdManifesto int
	BEGIN TRY	
		SET @NumErro = 0		
-- obtem ID do Manifesto SDS- Via Aérea
		IF (@Id IS NULL) AND (ISNULL(@NumeroAWBMaster, '') = '')
		BEGIN
			SELECT TOP 1 @Id = sdc.DSC_IDEN
			FROM PRO_SDSC AS sdc WITH(NOLOCK)
			WHERE sdc.DSC_TIPO = @Tipo AND sdc.EAD_CODI = @CodEstancia AND CAST(CONVERT(varchar(10), sdc.DSC_DTVO, 105) AS datetime) = @DataVoo AND sdc.DSC_NCMV = @ContramarcaV
				AND EXISTS(SELECT 1 FROM PRO_SDSD WITH(NOLOCK) WHERE DSC_EANO = sdc.DSC_EANO AND DSC_NPRO = sdc.DSC_NPRO)
		END
		ELSE
-- obtem ID da linha AWB no Manifesto SDS- Via Aérea
		IF (@Id IS NOT NULL) AND (ISNULL(@NumeroAWBMaster, '') <> '')
		BEGIN
			SET @IdManifesto = @Id
			SET @Id = NULL
			SELECT TOP 1 @Id = sda.DSD_IDNN
			FROM PRO_SDSC AS sdc WITH(NOLOCK)
				INNER JOIN PRO_SDSD AS sda WITH(NOLOCK) ON sdc.DSC_EANO = sda.DSC_EANO AND sdc.DSC_NPRO = sda.DSC_NPRO
			WHERE sdc.DSC_IDEN = @IdManifesto AND sda.DSD_NRMH = @NumeroAWBMaster
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemIDManifesto] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_IntegracaoDSS_ObtemIDManifesto] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirManifestInformation]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirManifestInformation] @AnoManifesto int, @NumManifesto int, @SoFranquias bit, @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @NomeCamposAdicionais varchar(10), @EntidadeEmissoraAWB varchar(60), @CodLocMercadoriaArmDTPLIS varchar(17), 
		@CodLocMercadoriaArmDTPOPO varchar(17)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem o nome da tipologia de empresa definida nos Campos Adicionais dos Parâmetros de Despachos
	SELECT TOP 1 @NomeCamposAdicionais = (CASE PDE_CADI WHEN 1 THEN 'FEDEX' WHEN 2 THEN 'UPS' WHEN 3 THEN 'DHL' ELSE NULL END)
	FROM TAB_PDES WITH(NOLOCK)
-- obtem os armazéns DTP p/ LIS e OPO configurados nos Parâmetros de SDS - Via Aérea
	SELECT TOP 1 @EntidadeEmissoraAWB = NULLIF(PSD_EEED, ''), @CodLocMercadoriaArmDTPLIS = LME_CODI2, @CodLocMercadoriaArmDTPOPO = LME_CODI3
	FROM TAB_PSDS WITH(NOLOCK)
-- constroi XML para ficheiro XML da mensagem AirManifestInformation
	;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestInformation' AS ns, 'http://simtem.at.gov.pt/WS/AirTypes' AS t)
	SELECT @FicheiroXML = 				
		(SELECT
			(SELECT
				(CAST(sds.DSC_EANO AS varchar(4)) + 'M' + CAST(sds.DSC_NPRO AS varchar(20)) + sds.EAD_CODI) AS "t:Identification", 			
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), @DataAtual), 120) AS "t:DateAndTime",					
				NULLIF(sds.DSC_IDTR, '') AS "t:Sender", 
				NULLIF(sds.DSC_IDRP, '') AS "t:PersonLodging"
			FOR XML PATH('ns:MessageInformation'), TYPE),
			(SELECT
				(sds.DSC_NCMF + sds.DSC_NCMV) AS "ns:CustomsReferenceNumber", 
				(CASE sds.DSC_TIPO WHEN 1 THEN 'Load' ELSE 'Unload' END) AS "ns:MovementType",  
				(SELECT
					@NomeCamposAdicionais AS "t:Name", 
					NULLIF(sds.DSC_IDTP, '') AS "t:IdentificationNumber"
				FOR XML PATH('ns:Carrier'), TYPE), 								
				NULL AS "ns:ActionManifest" /*FACULTATIVO - PREENCHER APENAS EM MODO ANULAÇÃO DO MANIFESTO com valor fixo "Annul"*/
			FOR XML PATH('ns:GeneralData'), TYPE),			
			(SELECT		
				(SELECT
					(CASE lin.DSD_ESTI WHEN 1 THEN 'Create' WHEN 2 THEN 'Update' WHEN 3 THEN 'Annul' END) AS "ns:Action", 				
					(SELECT 
						(SELECT 			
							(SELECT 			
								sds.EAD_CODI AS "t:ReferenceNumber"
							FOR XML PATH('ns:SupervisingCustomsOffice'), TYPE), 
							(SELECT 			
								NULLIF(lin.EAD_CODI, '') AS "t:ReferenceNumber"
							FOR XML PATH('ns:CustomsOfficeOfDeparture'), TYPE), 
							(SELECT 			
								sds.EAD_CODI AS "t:ReferenceNumber"
							FOR XML PATH('ns:CustomsOfficeOfDestination'), TYPE)
						FOR XML PATH('ns:CustomsOffices'), TYPE), 
						(SELECT 
							(RIGHT(STR(sds.DSC_EANO, 4), 2) + NULLIF(sds.DSC_IDRP, '') + REPLICATE('0', (9 - LEN(CAST(lin.DSD_IDNN AS varchar(20))))) + CAST(lin.DSD_IDNN AS varchar(20))) AS "ns:LocalReferenceNumber", /*ANO(2)+DSC_IDRP+DSD_IDNN(9)*/	
							NULLIF(lin.DSD_NDGA, '') AS "ns:MainReferenceNumber", 
							NULLIF(lin.DSD_NDSC, '') AS "ns:DocumentNumber", 							
							'D3' AS "ns:SpecificCircumstanceIndicator"							
						FOR XML PATH('ns:References'), TYPE), 
						lin.DSD_EADC AS "ns:DeclarationType", 
						'A' AS "ns:AdditionalDeclarationType", 
						lin.DSD_PESO AS "ns:TotalGrossMass" 
					FOR XML PATH('ns:GeneralData'), TYPE),								
					(SELECT 						
						(SELECT
							'C525' AS "t:Type", 
							sds.DSC_NRAP AS "t:ReferenceNumber"
						FOR XML PATH('ns:Authorisation'), TYPE) 			
					FOR XML PATH('ns:Authorisations'), TYPE), 
					(SELECT		
						(SELECT
							ISNULL(@EntidadeEmissoraAWB, NULLIF(sds.DSC_IDRP, '')) AS "t:Name", 
							NULLIF(sds.DSC_IDRP, '') AS "t:IdentificationNumber"
						FOR XML PATH('ns:Declarant'), TYPE), 
						(SELECT							
							NULLIF(LEFT(lin.DSD_NOOS, 70), '') AS "t:Name",
							(SELECT
								NULLIF(LEFT(lin.DSD_MOOS, 70), '') AS "t:Street", 
								0 AS "t:Number", 								
								lin.PAI_CODI AS "t:Country", 
								NULLIF(lin.DSD_CPOS, '') AS "t:Postcode",
								NULLIF(lin.DSD_LOOS, '') AS "t:City"
							FOR XML PATH('t:Address'), TYPE)
						HAVING ISNULL(lin.DSD_NOOS, '') <> ''
						FOR XML PATH('ns:Consignor'), TYPE), 
						(SELECT
							lin.DSD_IDEC AS "t:Name", 
							lin.DSD_IDEC AS "t:IdentificationNumber"							
						FOR XML PATH('ns:Consignee'), TYPE), 
						(SELECT
							lin.DSD_IDEC AS "t:Name", 
							lin.DSD_IDEC AS "t:IdentificationNumber"
						FOR XML PATH('ns:AuthorizedChartererToUnfold'), TYPE), 
						(SELECT
							NULLIF(lin.DSD_IDEN, '') AS "t:Name", 
							NULLIF(lin.DSD_IDEN, '') AS "t:IdentificationNumber"							
						HAVING ISNULL(lin.DSD_IDEN, '') <> ''
						FOR XML PATH('ns:NotifyParty'), TYPE), 
						(SELECT 
							t.funcao AS "t:Role", 
							LEFT(t.identificacao, 17) AS "t:IdentificationNumber"						
						FROM (SELECT 'CS' AS funcao, sds.DSC_IDRP AS identificacao
							UNION
							SELECT 'FW' AS funcao, sds.DSC_IDRP AS identificacao
							UNION
							SELECT 'WH' AS funcao, lin.DSD_DEPO AS identificacao) AS t
						WHERE ISNULL(t.identificacao, '') <> ''
						FOR XML PATH('ns:AdditionalSupplyChainActor'), ROOT('ns:AdditionalSupplyChainActors'), TYPE), 
						(SELECT
							@NomeCamposAdicionais AS "t:Name", 
							sds.DSC_IDRP AS "t:IdentificationNumber"						
						FOR XML PATH('ns:HolderOfTheTransitProcedure'), TYPE)
					FOR XML PATH('ns:Operators'), TYPE), 
					(SELECT 	
						(SELECT 
							(CASE sds.DSC_TIPO WHEN 1 THEN (CASE sds.EAD_CODI WHEN 'PT000020' THEN 'PTOPO' ELSE 'PTLIS' END) ELSE (ISNULL(lin.PAI_CODI2, '') + lin.PAE_CODI1) END) AS "t:UNLOCODE"						
						FOR XML PATH('ns:PlaceOfLoading'), TYPE),
						(SELECT 
							(CASE sds.DSC_TIPO WHEN 1 THEN (ISNULL(lin.PAI_CODI2, '') + lin.PAE_CODI1) ELSE (CASE sds.EAD_CODI WHEN 'PT000020' THEN 'PTOPO' ELSE 'PTLIS' END) END) AS "t:UNLOCODE"						
						FOR XML PATH('ns:PlaceOfUnloading'), TYPE),																	
						(SELECT 
							(ISNULL(lin.PAI_CODI4, '') + lin.PAE_CODI3) AS "t:UNLOCODE"
						FOR XML PATH('ns:FirstAirportOfShipment'), TYPE), 
						(SELECT 
							(ISNULL(lin.PAI_CODI1, '') + lin.PAE_CODI) AS "t:UNLOCODE"
						FOR XML PATH('ns:AirportOfDestination'), TYPE),
						(SELECT
							'B' AS "t:TypeOfLocation", 
							'Y' AS "t:QualifierOfIdentification", 
							(CASE sds.EAD_CODI WHEN 'PT000020' THEN @CodLocMercadoriaArmDTPOPO ELSE @CodLocMercadoriaArmDTPLIS END) AS "t:AuthorisationNumber"
						FOR XML PATH('ns:LocationOfGoods'), TYPE)
					FOR XML PATH('ns:Location'), TYPE),
					(SELECT						
						NULLIF(lin.PAI_CODI1, '') AS "ns:CountryOfDestination", 
						(SELECT 
							41 AS "ns:TypeOfIdentification", 
							NULLIF(sds.DSC_NVOO, '') AS "ns:IdentificationNumber", 
							CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DPRV), 120) AS "ns:EstimatedDateAndTimeOfArrivalAtTheAirportOfUnloading"
						HAVING sds.DSC_TIPO = 0													
						FOR XML PATH('ns:ArrivalTransportMeans'), TYPE), 
						(SELECT 
							40 AS "ns:TypeOfIdentification", 
							NULLIF(sds.DSC_NVOO, '') AS "ns:IdentificationNumber", 
							sds.PAI_CODI AS "ns:Nationality"
						HAVING sds.DSC_TIPO = 1
						FOR XML PATH('ns:DepartureTransportMeans'), TYPE) 
					FOR XML PATH('ns:TransportInformation'), TYPE), 					
					(SELECT 	
						(SELECT
							lin.DOC_CODI AS "t:Type", 
							NULLIF(lin.DSD_NRMH, '') AS "t:ReferenceNumber"
						FOR XML PATH('ns:TransportDocument'), TYPE), 
						(SELECT 
							'N830' AS "t:Type", 
							NULLIF(lin.DSD_NDPR, '') AS "t:ReferenceNumber", 
							1 AS "t:GoodsItemIdentifier"
						HAVING ISNULL(lin.DSD_NDPR, '') <> ''
						FOR XML PATH('ns:PreviousDocument'), TYPE), 
						(SELECT 
							DOC_CODI AS "t:Type", 
							SDD_NDOC AS "t:ReferenceNumber"
						FROM PRO_SSDD WITH(NOLOCK)
						WHERE DSC_EANO = lin.DSC_EANO AND DSC_NPRO = lin.DSC_NPRO AND DSD_NUME = lin.DSD_NUME
						FOR XML PATH('ns:SupportingDocument'), TYPE), 
						(SELECT 
							lin.TXM_CODI AS "t:Code", 
							NULLIF(lin.DSD_PTXT, '') AS "t:Text"
						HAVING ISNULL(lin.TXM_CODI, '') <> ''
						FOR XML PATH('ns:AdditionalInformation'), TYPE)
					FOR XML PATH('ns:DocumentsAndInformation'), TYPE),
					(SELECT 
						(SELECT 
							(SELECT 
								1 AS "ns:GoodsItemNumber", 
								NULLIF(lin.DSD_NDGI, '') AS "ns:CustomsItemNumber"/*,								
								(SELECT 
									NULL AS "ns:UnloadCustomsReferenceNumber", 
									NULL AS "ns:TransportDocumentReferenceNumber"
								FOR XML PATH('ns:IncomingInformation'), TYPE)*/ /*AGUARDA INFO DE PL PARA GERAR OU NÃO ESTE BLOCO*/
							FOR XML PATH('ns:GeneralData'), TYPE),														
							(SELECT 							
								NULLIF(lin.DSD_DMER, '') AS "ns:DescriptionOfGoods", 								
								(SELECT 
									LEFT(NULLIF(lin.DSD_CPAU, ''), 6) AS "t:HarmonizedSystemSubHeadingCode", 
									NULLIF(SUBSTRING(lin.DSD_CPAU, 7, 2), '') AS "t:CombinedNomenclatureCode" 
								FOR XML PATH('ns:CommodityCode'), TYPE),								
								(CASE lin.DSD_TCAR WHEN '099' THEN 'General' WHEN '101' THEN 'Express' WHEN '112' THEN 'Combined' ELSE NULL END) AS "ns:CargoType", 
								lin.DSD_PESO AS "ns:GrossMass", 
								(SELECT 								
									lin.TEM_CODI AS "ns:TypeOfPackages", 
									lin.DSD_VOLS AS "ns:NumberOfPackages", 
									NULLIF(lin.DSD_MRNR, '') AS "ns:ShippingMarks"
								FOR XML PATH('ns:Packaging'), TYPE)
							FOR XML PATH('ns:Goods'), TYPE)							
						FOR XML PATH('ns:GoodsItem'), TYPE)										
					FOR XML PATH('ns:GoodsItems'), TYPE), 
					(CASE WHEN (lin.DSD_ESTI = 1) AND (lin.DSD_CAPO = 1) THEN 'CARGA A MAIS' ELSE NULLIF(lin.DSD_JUST, '') END) AS "ns:Justification" 
				FROM VW_SDSViaAerea_EnvioManifestoDadosAWBPendentes AS lin WITH(NOLOCK) 		
				WHERE lin.DSC_EANO = sds.DSC_EANO AND lin.DSC_NPRO = sds.DSC_NPRO AND (CASE @SoFranquias WHEN 0 THEN 1 ELSE ISNULL(lin.DSD_AFRQ, 0) END) > 0
				FOR XML PATH('ns:TransportDocument'), TYPE)
			FOR XML PATH('ns:TransportDocuments'), TYPE)
		FROM PRO_SDSC AS sds WITH(NOLOCK) 			
		WHERE sds.DSC_EANO = @AnoManifesto AND sds.DSC_NPRO = @NumManifesto
		FOR XML PATH('ns:AirManifestInformation'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirManifestInformation] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirManifestInformation] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirTransportInformation]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirTransportInformation] @AnoManifesto int, @NumManifesto int, @AcaoMensagem varchar(10), @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @CfgAbrevEmpresa varchar(3), @NomeBDParaSDSExportacao varchar(8), @SQLSelect varchar(MAX)
	DECLARE @TblDadosSDSExportacao TABLE(DSC_TIPO int NOT NULL, DSC_IDRP varchar(20) NOT NULL, DSC_IDTP varchar(20) NOT NULL, DSC_NRAP varchar(40) NOT NULL, 
		EAD_CODI varchar(8) NOT NULL, DSC_NCMF varchar(8) NOT NULL, DSC_NCMV varchar(6) NOT NULL, DSC_NVOO varchar(35) NULL, DSC_IDEN int NOT NULL, DSC_DPRV datetime NULL, 
		DSC_PPRV numeric(38, 6) NOT NULL, DSC_VPRV int NOT NULL, DSC_DEFT datetime NULL, DSC_IDCM varchar(20) NOT NULL, PAE_CLIS varchar(8) NULL, PAI_CLIS varchar(2) NULL, 
		PAE_COPO varchar(8) NULL, PAI_COPO varchar(2) NULL)	
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem o nome da tipologia de empresa definida nos Campos Adicionais dos Parâmetros de Despachos
	SELECT TOP 1 @CfgAbrevEmpresa = (CASE PDE_CADI WHEN 1 THEN 'FED' WHEN 2 THEN 'UPS' WHEN 3 THEN 'DHL' ELSE NULL END)
	FROM TAB_PDES WITH(NOLOCK)
-- obtem o nome da BD de Manifestos SDS de Exportação dos Parâmetros SDS - Via Aérea
	SELECT TOP 1 @NomeBDParaSDSExportacao = ISNULL((CASE PSD_BDEX WHEN 1 THEN (NULLIF(PSD_NBDE, '') + '..') ELSE NULL END), '')
	FROM TAB_PSDS WITH(NOLOCK)
-- constroi o SELECT para obtenção dos dados do Manifesto SDS de Exportação, quer seja na própria BD ou em BD diferente
	SET @SQLSelect = 'SELECT sde.DSC_TIPO, sde.DSC_IDRP, sde.DSC_IDTP, sde.DSC_NRAP, sde.EAD_CODI, sde.DSC_NCMF, sde.DSC_NCMV, sde.DSC_NVOO, sde.DSC_IDEN, sde.DSC_DPRV, sde.DSC_PPRV, sde.DSC_VPRV, sde.DSC_DEFT, 
			sde.DSC_IDCM, ele.PAE_CODI, ele.PAI_CODI, epe.PAE_CODI, epe.PAI_CODI
		FROM PRO_SDSC AS sds WITH(NOLOCK) 				
			INNER JOIN ' + @NomeBDParaSDSExportacao + 'TAB_PSDS AS psd WITH(NOLOCK) ON 1 = 1			
			INNER JOIN ' + @NomeBDParaSDSExportacao + 'PRO_SDSC AS sde WITH(NOLOCK) ON sde.DSC_TIPO = 1 AND sds.DSC_IDCM = sde.DSC_IDCM	
			LEFT OUTER JOIN ' + @NomeBDParaSDSExportacao + 'TAB_PAER AS ele WITH(NOLOCK) ON psd.PAE_CODI = ele.PAE_CODI
			LEFT OUTER JOIN ' + @NomeBDParaSDSExportacao + 'TAB_PAER AS epe WITH(NOLOCK) ON psd.PAE_CODI1 = epe.PAE_CODI
		WHERE sds.DSC_EANO = ' + LTRIM(STR(@AnoManifesto, 4)) + ' AND sds.DSC_NPRO = ' + LTRIM(STR(@NumManifesto, 20))
-- insere os dados do Manifesto SDS de Exportação da própria BD ou da BD diferente na tabela tmp
	INSERT INTO @TblDadosSDSExportacao(DSC_TIPO, DSC_IDRP, DSC_IDTP, DSC_NRAP, EAD_CODI, DSC_NCMF, DSC_NCMV, DSC_NVOO, DSC_IDEN, DSC_DPRV, DSC_PPRV, DSC_VPRV, DSC_DEFT, 
		DSC_IDCM, PAE_CLIS, PAI_CLIS, PAE_COPO, PAI_COPO)
	EXEC (@SQLSelect)	
-- constroi XML para ficheiro XML da mensagem AirTransportInformation
	;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirTransportInformation' AS ns, 'http://simtem.at.gov.pt/WS/AirTypes' AS t)
	SELECT @FicheiroXML = 						
		(SELECT
			(SELECT
				(CAST(sds.DSC_EANO AS varchar(4)) + 'M' + CAST(sds.DSC_NPRO AS varchar(20)) + sds.EAD_CODI) AS "t:Identification", 				
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), @DataAtual), 120) AS "t:DateAndTime",
				NULLIF(sds.DSC_IDTR, '') AS "t:Sender", 
				NULLIF(sds.DSC_IDRP, '') AS "t:PersonLodging"
			FOR XML PATH('ns:MessageInformation'), TYPE),
			(SELECT
				sds.DSC_IDCM AS "ns:LocalReferenceNumber", 
				(SELECT 			
					sds.EAD_CODI AS "t:ReferenceNumber"
				FOR XML PATH('ns:SupervisingCustomsOffice'), TYPE), 
				(CASE WHEN @AcaoMensagem IN ('Update', 'Annul') THEN (sds.DSC_NCMF + sds.DSC_NCMV) ELSE NULL END) AS "ns:CustomsReferenceNumber",
				@AcaoMensagem AS "ns:Action", 
				(CASE @AcaoMensagem WHEN 'Update' THEN 'Alteracao Elementos. ' WHEN 'Annul' THEN 'Voo Cancelado. ' ELSE NULL END) AS "ns:Justification"				
			FOR XML PATH('ns:CustomsProcess'), TYPE),	
			(SELECT			
				'ANA' AS "ns:AirportAuthorityCode", 
				(CASE sds.EAD_CODI WHEN 'PT000020' THEN 'PTOPO' ELSE 'PTLIS' END) AS "ns:AirportCode",
				(@CfgAbrevEmpresa + sds.DSC_IDCM) AS "ns:AirportAuthorityReferenceNumber"
			FOR XML PATH('ns:AirportAuthorityProcess'), TYPE),	
			(SELECT
				'AirTransport' AS "ns:TransportType", 
				'41' AS "ns:TypeOfIdentification", 
				ISNULL(NULLIF(sds.DSC_NVOO, ''), sde.DSC_NVOO) AS "ns:TransportIdentification"
			FOR XML PATH('ns:Transport'), TYPE),	
			(SELECT
				(SELECT
					t.FlightNumber AS "ns:FlightNumber"
				FROM (SELECT sds.DSC_IDEN AS ManifestType, sds.DSC_NVOO AS FlightNumber
					UNION ALL					
					SELECT sde.DSC_IDEN AS ManifestType, sde.DSC_NVOO AS FlightNumber) AS t
				WHERE t.ManifestType IS NOT NULL AND ISNULL(FlightNumber, '') <> ''
				FOR XML PATH(''), TYPE),
				(SELECT
					t.FlightNumberType AS "ns:FlightNumberType"
				FROM (SELECT sds.DSC_IDEN AS ManifestType, 'MainArrivalFlightNumber' AS FlightNumberType
					UNION ALL					
					SELECT sde.DSC_IDEN AS ManifestType, 'MainDepartureFlightNumber' AS FlightNumberType) AS t
				WHERE t.ManifestType IS NOT NULL
				FOR XML PATH(''), TYPE),				
				'CargoMailScheduled' AS "ns:FlightType", 
				(SELECT
					t.TraficDistributionType AS "ns:TraficDistribution"
				FROM (SELECT sds.DSC_IDEN AS ManifestType, 'Arrival' AS TraficDistributionType
					UNION ALL					
					SELECT sde.DSC_IDEN AS ManifestType, 'Departure' AS TraficDistributionType) AS t
				WHERE t.ManifestType IS NOT NULL
				FOR XML PATH(''), TYPE),				
				'InSchengen' AS "ns:FlightClassification", 
				'ComercialScale' AS "ns:OperationType", 
				'Cargo' AS "ns:AirPlaneType", 
				'CargoMailSchedule' AS "ns:Nature"
			FOR XML PATH('ns:Flight'), TYPE),
			(SELECT
				(SELECT
					'C525' AS "ns:Type", 
					sds.DSC_NRAP AS "ns:ReferenceNumber"
				HAVING ISNULL(sds.DSC_NRAP, '') <> ''
				FOR XML PATH('ns:AuthorisationAtEntry'), TYPE),		
				(SELECT
					'C525' AS "ns:Type", 
					sde.DSC_NRAP AS "ns:ReferenceNumber"
				HAVING ISNULL(sde.DSC_NRAP, '') <> ''
				FOR XML PATH('ns:AuthorisationAtExit'), TYPE)
			FOR XML PATH('ns:Authorisations'), TYPE),
			(SELECT
				(CASE WHEN sds.DSC_IDEN IS NULL THEN NULL ELSE (CASE sds.EAD_CODI WHEN 'PT000020' THEN (ISNULL(epi.PAI_CODI, '') + epi.PAE_CODI) ELSE (ISNULL(eli.PAI_CODI, '') + eli.PAE_CODI) END) END) AS "ns:OriginAirportCode", 
				(CASE WHEN sde.DSC_IDEN IS NULL THEN NULL ELSE (CASE sde.EAD_CODI WHEN 'PT000020' THEN (ISNULL(sde.PAI_COPO, '') + sde.PAE_COPO) ELSE (ISNULL(sde.PAI_CLIS, '') + sde.PAE_CLIS) END) END) AS "ns:DestinyAirportCode" 
			FOR XML PATH('ns:Route'), TYPE), 
			(SELECT
				(CASE sds.EAD_CODI WHEN 'PT000020' THEN psd.LME_CODI1 ELSE psd.LME_CODI END) AS "ns:EstimatedPlaceOfArrival", 
				(CASE WHEN sds.DSC_DEFT IS NOT NULL THEN (CASE sds.EAD_CODI WHEN 'PT000020' THEN psd.LME_CODI1 ELSE psd.LME_CODI END) ELSE NULL END) AS "ns:ConfirmedPlaceOfArrival", 
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DPRV), 120) AS "ns:EstimatedDateAndTimeOfArrival",
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DEFT), 120) AS "ns:ConfirmedDateAndTimeOfArrival", 
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DEFT), 120) AS "ns:ActualDateAndTimeOfArrival"						
			HAVING sds.DSC_IDEN IS NOT NULL
			FOR XML PATH('ns:Arrival'), TYPE),
			(SELECT
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sde.DSC_DPRV), 120) AS "ns:EstimatedDateAndTimeOfDeparture", 
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sde.DSC_DEFT), 120) AS "ns:ActualDateAndTimeOfDeparture"
			HAVING sde.DSC_IDEN IS NOT NULL
			FOR XML PATH('ns:Departure'), TYPE), 
			(SELECT
				(SELECT
					t.TraficDistributionType AS "ns:ManifestType"
				FROM (SELECT sds.DSC_IDEN AS ManifestType, 'Unload' AS TraficDistributionType
					UNION ALL					
					SELECT sde.DSC_IDEN AS ManifestType, 'Load' AS TraficDistributionType) AS t
				WHERE t.ManifestType IS NOT NULL
				FOR XML PATH(''), TYPE),				
				'Combined' AS "ns:CargoType", 
				(CASE WHEN sde.DSC_IDEN IS NULL THEN NULL ELSE (CASE sde.EAD_CODI WHEN 'PT000020' THEN psd.LME_CODI1 ELSE psd.LME_CODI END) END) AS "ns:LoadPlace", 
				(CASE WHEN sds.DSC_IDEN IS NULL THEN NULL ELSE (CASE sds.EAD_CODI WHEN 'PT000020' THEN psd.LME_CODI1 ELSE psd.LME_CODI END) END) AS "ns:UnloadPlace", 
				ISNULL(sde.DSC_PPRV, 0.000000) AS "ns:LoadTotalGrossMass", 
				ISNULL(sde.DSC_VPRV, 0) AS "ns:LoadTotalNumberOfPackages", 
				ISNULL(sds.DSC_PPRV, 0.000000) AS "ns:UnloadTotalGrossMass", 
				ISNULL(sds.DSC_VPRV, 0) AS "ns:UnloadTotalNumberOfPackages", 
				0 AS "ns:UnloadTotalNumberOfMailBags", 				
				0 AS "ns:TranshipmentTotalNumberOfMailBags", 				
				0.000000 AS "ns:TransitTotalGrossMass", 
				0 AS "ns:TransitTotalNumberOfPackages"
			FOR XML PATH('ns:Manifests'), TYPE),
			(SELECT
				(SELECT
					t.RoleName AS "ns:Role", 
					'EORI' AS "ns:IdentificationType", 					
					t.RoleIdentificationNr AS "ns:IdentificationNumber"
				FROM (SELECT 'EntryAirCompany' AS RoleName, sds.DSC_IDTP AS RoleIdentificationNr
					UNION ALL					
					SELECT 'ExitAirCompany' AS RoleName, sde.DSC_IDTP AS RoleIdentificationNr
					UNION ALL
					SELECT 'EntryDeclarant' AS RoleName, sds.DSC_IDRP AS RoleIdentificationNr
					UNION ALL					
					SELECT 'ExitDeclarant' AS RoleName, sde.DSC_IDRP AS RoleIdentificationNr) AS t				
				WHERE ISNULL(t.RoleIdentificationNr, '') <> ''
				FOR XML PATH('ns:Operator'), TYPE)
			FOR XML PATH('ns:Operators'), TYPE), 
			(SELECT 
				(SELECT
					ISNULL(NULLIF(psd.PSD_EEED, ''), ISNULL(sds.DSC_IDTP, sde.DSC_IDTP)) AS "ns:CargoAgentName", 
					ISNULL(sds.DSC_IDTP, sde.DSC_IDTP) AS "ns:CargoAgentIdentification", 
					ISNULL(sde.DSC_PPRV, 0.000000) AS "ns:LoadGrossMass", 
					ISNULL(sde.DSC_VPRV, 0) AS "ns:LoadNumberOfPackages", 
					ISNULL(sds.DSC_PPRV, 0.000000) AS "ns:UnloadGrossMass", 
					ISNULL(sds.DSC_VPRV, 0) AS "ns:UnloadNumberOfPackages", 
					0.000000 AS "ns:TransitGrossMass", 
					0 AS "ns:TransitNumberOfPackages"
				FOR XML PATH('ns:CargoAgent'), TYPE)
			FOR XML PATH('ns:CargoAgents'), TYPE)
		FROM PRO_SDSC AS sds WITH(NOLOCK) 				
			LEFT OUTER JOIN TAB_PSDS AS psd WITH(NOLOCK) ON 1 = 1			
			LEFT OUTER JOIN TAB_PAER AS eli WITH(NOLOCK) ON psd.PAE_CODI = eli.PAE_CODI
			LEFT OUTER JOIN TAB_PAER AS epi WITH(NOLOCK) ON psd.PAE_CODI1 = epi.PAE_CODI
			LEFT OUTER JOIN @TblDadosSDSExportacao AS sde ON sde.DSC_TIPO = 1 AND sds.DSC_IDCM = sde.DSC_IDCM			
		WHERE sds.DSC_EANO = @AnoManifesto AND sds.DSC_NPRO = @NumManifesto
		FOR XML PATH('ns:AirTransportInformation'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirTransportInformation] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirTransportInformation] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersMovementInformation]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersMovementInformation] @CodEstanciaManifesto varchar(8), @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @CodLocMercadoriaArmDTPLIS varchar(17), @CodLocMercadoriaArmDTPOPO varchar(17)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- obtem os armazéns DTP p/ LIS e OPO configurados nos Parâmetros de SDS - Via Aérea
	SELECT TOP 1 @CodLocMercadoriaArmDTPLIS = LME_CODI2, @CodLocMercadoriaArmDTPOPO = LME_CODI3
	FROM TAB_PSDS WITH(NOLOCK)
-- constroi XML para ficheiro XML da mensagem AirWarehouseKeepersMovementInformation
	;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementInformation' AS ns, 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes' AS t)
	SELECT @FicheiroXML = 				
		(SELECT
			(SELECT
				(CAST(sds.DSC_EANO AS varchar(4)) + 'M' + CAST(sds.DSC_NPRO AS varchar(20)) + sds.EAD_CODI) AS "t:Identification", 				
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), @DataAtual), 120) AS "t:DateAndTime",
				NULLIF(sds.DSC_IDTR, '') AS "t:Sender", 
				NULLIF(sds.DSC_IDRP, '') AS "t:PersonLodging"
			FOR XML PATH('ns:MessageInformation'), TYPE),
			(SELECT				
				(SELECT					
					sds.DSC_IDRP AS "t:IdentificationNumber"					
				FOR XML PATH('ns:Declarant'), TYPE)		
			FOR XML PATH('ns:GeneralData'), TYPE),
			(SELECT
				'Create' AS "ns:Action", 			
				(lin.DSC_NCMF + lin.DSC_NCMV) AS "ns:CustomsReferenceNumber",									
				(RIGHT(STR(sds.DSC_EANO, 4), 2) + NULLIF(sds.DSC_IDRP, '') + REPLICATE('0', (9 - LEN(CAST(lin.DSD_IDNN AS varchar(20))))) + CAST(lin.DSD_IDNN AS varchar(20))) AS "ns:LocalReferenceNumber", 
				(SELECT 
					41 AS "t:TypeOfIdentification", 
					NULLIF(lin.DSC_NVOO, '') AS "t:IdentificationNumber"		
				FOR XML PATH('ns:DepartureTransportMeans'), TYPE),				
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), lin.DSC_DPRV), 120) AS "ns:EstimatedDateAndTimeOfDeparture",				
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), lin.DSC_DEFT), 120) AS "ns:DateAndTimeOfArrivalOfGoods", 
				(SELECT
					'B' AS "t:TypeOfLocation", 
					'Y' AS "t:QualifierOfIdentification", 					
					(CASE lin.EAD_CODI WHEN 'PT000020' THEN @CodLocMercadoriaArmDTPOPO ELSE @CodLocMercadoriaArmDTPLIS END) AS "t:AuthorisationNumber"					
				FOR XML PATH('ns:LocationOfGoods'), TYPE), 				
				(SELECT 		
					lin.DOC_CODI AS "t:Type", 
					NULLIF(lin.DSD_NRMH, '') AS "t:ReferenceNumber"										
				FOR XML PATH('ns:TransportDocument'), TYPE),
				(SELECT 
					'N830' AS "t:Type", 
					NULLIF(lin.DSD_NDPR, '') AS "t:ReferenceNumber", 
					1 AS "t:GoodsItemIdentifier"
				HAVING ISNULL(lin.DSD_NDPR, '') <> ''					
				FOR XML PATH('ns:PreviousDocument'), TYPE), 	
				lin.DSD_TCAR AS "ns:CargoType", 
				(SELECT 
					NULLIF(lin.TEM_CODI, '') AS "t:TypeOfPackages", 
					lin.DSD_VOLS AS "t:NumberOfPackages", 
					NULLIF(lin.DSD_MRNR, '') AS "t:ShippingMarks"
				FOR XML PATH('ns:Packaging'), TYPE),
				lin.DSD_PESO AS "ns:GrossMass"
			FROM VW_SDSViaAerea_MovimentoSaidaDadosAWB AS lin WITH(NOLOCK) 						
			WHERE lin.DSC_TIPO = 0 AND ISNULL(lin.DSD_DNRD, '') <> '' AND ISNULL(lin.SIN_CODI, '') <> '' AND lin.EAD_CODI = @CodEstanciaManifesto
			FOR XML PATH('ns:EntryMovement'), ROOT('ns:EntryMovements'), TYPE), 				
			(SELECT
				'Create' AS "ns:Action", 				
				(lin.DSC_NCMF + lin.DSC_NCMV) AS "ns:CustomsReferenceNumber",	
				NULLIF(lin.DSD_NDGA, '') AS "ns:MainReferenceNumber", 
				NULLIF(lin.DSD_NDGI, '') AS "ns:CustomsItemNumber", 
				(RIGHT(STR(sds.DSC_EANO, 4), 2) + NULLIF(sds.DSC_IDRP, '') + REPLICATE('0', (9 - LEN(CAST(lin.DSD_IDNN AS varchar(20))))) + CAST(lin.DSD_IDNN AS varchar(20))) AS "ns:LocalReferenceNumber", 				
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), lin.DSC_DEFT), 120) AS "ns:DateAndTimeOfExitOfGoodsFromTemporaryStorage", 
				(SELECT
					'B' AS "t:TypeOfLocation", 
					'Y' AS "t:QualifierOfIdentification", 					
					(CASE lin.EAD_CODI WHEN 'PT000020' THEN @CodLocMercadoriaArmDTPOPO ELSE @CodLocMercadoriaArmDTPLIS END) AS "t:AuthorisationNumber"	
				FOR XML PATH('ns:LocationOfGoods'), TYPE), 
				(SELECT 							
					lin.DOC_CODI AS "t:Type", 
					NULLIF(lin.DSD_NRMH, '') AS "t:ReferenceNumber"														
				FOR XML PATH('ns:TransportDocument'), TYPE), 	
				lin.DSD_TCAR AS "ns:CargoType",
				(SELECT 
					NULLIF(lin.TEM_CODI, '') AS "t:TypeOfPackages", 
					lin.DSD_VOLS AS "t:NumberOfPackages", 
					NULLIF(lin.DSD_MRNR, '') AS "t:ShippingMarks"
				FOR XML PATH('ns:Packaging'), TYPE),
				lin.DSD_PESO AS "ns:GrossMass", 
				(SELECT 
					lin.DSD_DTRD AS "t:Type", 
					NULLIF(lin.DSD_DNRD, '') AS "t:ReferenceNumber"	
				FOR XML PATH('ns:DocumentAuthorisingTheGoodsToBeReleased'), TYPE)				
			FROM VW_SDSViaAerea_MovimentoSaidaDadosAWB AS lin WITH(NOLOCK) 						
			WHERE lin.DSC_TIPO = 1 AND ISNULL(lin.DSD_DNRD, '') <> '' AND ISNULL(lin.SIN_CODI, '') <> '' AND lin.EAD_CODI = @CodEstanciaManifesto
			FOR XML PATH('ns:ExitMovement'), ROOT('ns:ExitMovements'), TYPE)			
		FROM PRO_SDSC AS sds WITH(NOLOCK)
			INNER JOIN (SELECT TOP 1 DSC_EANO, DSC_NPRO 
				FROM VW_SDSViaAerea_MovimentoSaidaDadosAWB 
				WHERE ISNULL(DSD_DNRD, '') <> '' AND ISNULL(SIN_CODI, '') <> '' AND EAD_CODI = @CodEstanciaManifesto
				GROUP BY DSC_EANO, DSC_NPRO) AS t ON sds.DSC_EANO = t.DSC_EANO AND sds.DSC_NPRO = t.DSC_NPRO
		FOR XML PATH('ns:AirWarehouseKeepersMovementInformation'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersMovementInformation] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersMovementInformation] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersReportInformation]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersReportInformation] @AnoManifesto int, @NumManifesto int, @SoCriacao bit, @TipoCarga varchar(3), @FicheiroXML xml OUTPUT AS
BEGIN 
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @CodLocMercadoriaArmDTPLIS varchar(17), @CodLocMercadoriaArmDTPOPO varchar(17)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()	
-- obtem os armazéns DTP p/ LIS e OPO configurados nos Parâmetros de SDS - Via Aérea
	SELECT TOP 1 @CodLocMercadoriaArmDTPLIS = LME_CODI2, @CodLocMercadoriaArmDTPOPO = LME_CODI3
	FROM TAB_PSDS WITH(NOLOCK)
-- constroi XML para ficheiro XML da mensagem AirWarehouseKeepersReportInformation
	;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportInformation' AS ns, 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes' AS t)
	SELECT @FicheiroXML = 				
		(SELECT
			(SELECT
				(CAST(sds.DSC_EANO AS varchar(4)) + 'M' + CAST(sds.DSC_NPRO AS varchar(20)) + sds.EAD_CODI) AS "t:Identification", 				
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), @DataAtual), 120) AS "t:DateAndTime",
				NULLIF(sds.DSC_IDTR, '') AS "t:Sender", 
				NULLIF(sds.DSC_IDRP, '') AS "t:PersonLodging"
			FOR XML PATH('ns:MessageInformation'), TYPE),
			(SELECT
				(sds.DSC_NCMF + sds.DSC_NCMV) AS "ns:CustomsReferenceNumber",
				(SELECT					
					sds.DSC_IDRP AS "t:IdentificationNumber"					
				FOR XML PATH('ns:Declarant'), TYPE)		
			FOR XML PATH('ns:GeneralData'), TYPE),
			(SELECT
				(CASE lin.DSD_ESTI WHEN 1 THEN 'Update' WHEN 2 THEN 'Annul' ELSE 'Create' END) AS "ns:Action", 				
				sds.EAD_CODI AS "ns:CustomsOfficeOfPresentation", 
				(RIGHT(STR(sds.DSC_EANO, 4), 2) + NULLIF(sds.DSC_IDRP, '') + REPLICATE('0', (9 - LEN(CAST(lin.DSD_IDNN AS varchar(20))))) + CAST(lin.DSD_IDNN AS varchar(20))) AS "ns:LocalReferenceNumber", 
				(SELECT 
					41 AS "t:TypeOfIdentification", 
					NULLIF(sds.DSC_NVOO, '') AS "t:IdentificationNumber"					
				FOR XML PATH('ns:ArrivalTransportMeans'), TYPE), 
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DPRV), 120) AS "ns:EstimatedDateAndTimeOfArrivalAtThePlaceOfUnloading",
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), DATEADD(MINUTE, 10, sds.DSC_DEFT)), 120) AS "ns:DeclarationDate", 
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DEFT), 120) AS "ns:DateAndTimeOfPresentationOfTheGoods", 
				(SELECT
					'B' AS "t:TypeOfLocation", 
					'Y' AS "t:QualifierOfIdentification", 					
					(CASE sds.EAD_CODI WHEN 'PT000020' THEN @CodLocMercadoriaArmDTPOPO ELSE @CodLocMercadoriaArmDTPLIS END) AS "t:AuthorisationNumber"					
				FOR XML PATH('ns:LocationOfGoods'), TYPE), 
				NULLIF(sds.DSC_IDRP, '') AS "ns:PersonPresentingTheGoods", 
				(SELECT 		
					lin.DOC_CODI AS "t:Type", 
					NULLIF(lin.DSD_NRMH, '') AS "t:ReferenceNumber"										
				FOR XML PATH('ns:TransportDocument'), TYPE),
				(SELECT 
					'N830' AS "t:Type", 
					NULLIF(lin.DSD_NDPR, '') AS "t:ReferenceNumber", 
					1 AS "t:GoodsItemIdentifier"
				HAVING ISNULL(lin.DSD_NDPR, '') <> ''					
				FOR XML PATH('ns:PreviousDocument'), TYPE), 	
				lin.DSD_TCAR AS "ns:CargoType", 
				(SELECT 
					NULLIF(lin.TEM_CODI, '') AS "t:TypeOfPackages", 
					lin.DSD_VOLS AS "t:NumberOfPackages", 
					NULLIF(lin.DSD_MRNR, '') AS "t:ShippingMarks"
				FOR XML PATH('ns:Packaging'), TYPE),
				lin.DSD_PESO AS "ns:GrossMass", 				
				(CASE WHEN lin.PAE_CODI IN ('LIS', 'OPO') THEN 'No' ELSE 'Yes' END) AS "ns:IsTranshipment", 
				(CASE WHEN lin.PAE_CODI NOT IN ('LIS', 'OPO') THEN (lin.PAI_CODI + lin.PAE_CODI) ELSE NULL END) AS "ns:AirportOfDestination", 
				(CASE WHEN (lin.DSD_ESTI = 0) AND (lin.DSD_CAPO = 1) then 'CARGA EM EXCESSO' WHEN (lin.DSD_ESTI = 1) THEN 'Alteracao Volume/Peso.' WHEN (lin.DSD_ESTI = 2) THEN 'FALTA A DESCARGA' ELSE NULL END) AS "ns:Justification"
			FROM VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes AS lin WITH(NOLOCK) 		
				LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON duc.DUC_DUNO IN (1, 2) AND lin.DSD_NRMH = duc.DUC_CPRT AND lin.EAD_CODI = duc.ALF_CODI AND CAST(CONVERT(varchar(10), lin.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime)
				LEFT OUTER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI
			WHERE lin.DSC_EANO = sds.DSC_EANO AND lin.DSC_NPRO = sds.DSC_NPRO AND lin.DSC_TIPO = 0 AND lin.DSD_TCAR = ISNULL(NULLIF(@TipoCarga, ''), lin.DSD_TCAR) 
				AND ((@TipoCarga <> 'XXX') OR (@TipoCarga = 'XXX' AND lin.DSD_VOLS = duc.DUC_VSCA AND ((nat.NDE_FEDI = 1) OR (duc.DUC_ARTI IS NOT NULL))))
			FOR XML PATH('ns:UnloadReport'), TYPE), 
			(SELECT
				(CASE lin.DSD_ESTI WHEN 1 THEN 'Update' WHEN 2 THEN 'Annul' ELSE 'Create' END) AS "ns:Action", 				
				sds.EAD_CODI AS "ns:CustomsOfficeOfPresentation", 
				(RIGHT(STR(sds.DSC_EANO, 4), 2) + NULLIF(sds.DSC_IDRP, '') + REPLICATE('0', (9 - LEN(CAST(lin.DSD_IDNN AS varchar(20))))) + CAST(lin.DSD_IDNN AS varchar(20))) AS "ns:LocalReferenceNumber", 
				(SELECT 
					41 AS "t:TypeOfIdentification", 
					NULLIF(sds.DSC_NVOO, '') AS "t:IdentificationNumber"		
				FOR XML PATH('ns:DepartureTransportMeans'), TYPE),
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DPRV), 120) AS "ns:EstimatedDateAndTimeOfDeparture", 
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), DATEADD(MINUTE, 10, sds.DSC_DEFT)), 120) AS "ns:DeclarationDate", 
				CONVERT(varchar(19), DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), sds.DSC_DEFT), 120) AS "ns:DateAndTimeOfLoadingOfTheGoods", 
				(SELECT
					'B' AS "t:TypeOfLocation", 
					'Y' AS "t:QualifierOfIdentification", 					
					(CASE sds.EAD_CODI WHEN 'PT000020' THEN @CodLocMercadoriaArmDTPOPO ELSE @CodLocMercadoriaArmDTPLIS END) AS "t:AuthorisationNumber"	
				FOR XML PATH('ns:LocationOfGoods'), TYPE), 
				(SELECT 							
					lin.DOC_CODI AS "t:Type", 
					NULLIF(lin.DSD_NRMH, '') AS "t:ReferenceNumber"														
				FOR XML PATH('ns:TransportDocument'), TYPE), 
				(SELECT 
					'N830' AS "t:Type", 
					NULLIF(lin.DSD_NDPR, '') AS "t:ReferenceNumber", 
					1 AS "t:GoodsItemIdentifier", 
					'Total' AS "t:EmbarkmentSituation"	/*OBRIGATÓRIO*/				
				HAVING ISNULL(lin.DSD_NDPR, '') <> ''
				FOR XML PATH('ns:PreviousDocument'), TYPE), 	
				lin.DSD_TCAR AS "ns:CargoType",
				(SELECT 
					NULLIF(lin.TEM_CODI, '') AS "t:TypeOfPackages", 
					lin.DSD_VOLS AS "t:NumberOfPackages", 
					NULLIF(lin.DSD_MRNR, '') AS "t:ShippingMarks"
				FOR XML PATH('ns:Packaging'), TYPE),
				lin.DSD_PESO AS "ns:GrossMass", 				 				
				(CASE WHEN (lin.DSD_ESTI = 0) AND (lin.DSD_CAPO = 1) then 'CARGA EM EXCESSO' WHEN (lin.DSD_ESTI = 1) THEN 'Alteracao Volume/Peso.' WHEN (lin.DSD_ESTI = 2) THEN 'FALTA A CARGA' ELSE NULL END) AS "ns:Justification"							
			FROM VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes AS lin WITH(NOLOCK) 
				LEFT OUTER JOIN PRO_EXAD as adi WITH(NOLOCK) ON lin.EXA_CHVE = adi.EXA_CHVE
				LEFT OUTER JOIN PRO_EXML AS exm WITH(NOLOCK) ON adi.EXM_EANO = exm.EXM_EANO AND adi.EXM_CODI = exm.EXM_CODI AND adi.EXM_COPE = exm.DEC_CODI
				LEFT OUTER JOIN TAB_NDES AS nat WITH(NOLOCK) ON exm.NDE_CODI = nat.NDE_CODI
			WHERE lin.DSC_EANO = sds.DSC_EANO AND lin.DSC_NPRO = sds.DSC_NPRO AND lin.DSC_TIPO = 1 AND lin.DSD_TCAR = ISNULL(NULLIF(@TipoCarga, ''), lin.DSD_TCAR) 
				AND ((@TipoCarga <> 'XXX') OR (@TipoCarga = 'XXX' AND lin.DSD_VOLS = exm.EXM_VSCA AND ((nat.NDE_FEDI = 1) /*OR (exm.EXM_ARTI IS NOT NULL)*/)))
			FOR XML PATH('ns:LoadReport'), TYPE), 
			(SELECT
				NULLIF(sds.DSC_IDRP, '') AS "ns:PersonPresentingTheGoods", 
				CONVERT(varchar(19), @DataAtual, 120) AS "ns:DateAndTimeOfEndOfOperations"
			HAVING sds.DSC_TIPO = 0 AND @SoCriacao = 0
			FOR XML PATH('ns:UnloadEndOfOperations'), TYPE),
			(SELECT
				NULLIF(sds.DSC_IDRP, '') AS "ns:PersonPresentingTheGoods", 
				CONVERT(varchar(19), @DataAtual, 120) AS "ns:DateAndTimeOfEndOfOperations"
			HAVING sds.DSC_TIPO = 1 AND @SoCriacao = 0
			FOR XML PATH('ns:LoadEndOfOperations'), TYPE)			
		FROM PRO_SDSC AS sds WITH(NOLOCK) 			
		WHERE sds.DSC_EANO = @AnoManifesto AND sds.DSC_NPRO = @NumManifesto
		FOR XML PATH('ns:AirWarehouseKeepersReportInformation'), ELEMENTS)
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersReportInformation] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersReportInformation] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemIntegraAirManifestResponse]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemIntegraAirManifestResponse] @MensagemXML xml, @Utilizador varchar(30), @IdMensagem varchar(35) OUTPUT, @SucessoMensagem varchar(10) OUTPUT, 
	@ContramarcaMensagem varchar(14) OUTPUT, @AnoManifesto int OUTPUT, @NumManifesto int OUTPUT, @AWBIntegradasXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @IdUtilizador int, @ErroGeracao varchar(8000), @TotalLinhasAWBInvalidas int
	DECLARE @DataMsgXML datetime, @IdManifestoMsgXML varchar(35), @EstadoContramarcaMsgXML varchar(15), @DocsTransporteMsgXML xml, @ErrosMsgXML xml, @AlertasMsgXML xml
	DECLARE @TipoManifesto int, @DataVooManifesto datetime, @CodEstanciaManifesto varchar(8), @ErrosGerais varchar(MAX)
	DECLARE @AcaoAwbXML varchar(8), @EstadoAwbXML varchar(50), @SucessoAwbXML varchar(8), @NRLAwbXML varchar(22), @MRNAwbXML varchar(18), @NumDocumentoAwbXML varchar(24), 
		@ErrosAwbXML xml, @AlertasAwbXML xml, @NumDGAItemXML varchar(29), @ErrosItemXML xml, @AlertasItemXML xml
	DECLARE @EstadoLinhaAWB varchar(3), @IdLinhaAWB int, @NumAWBLinhaAWB varchar(30), @ErrosLinhaAWB varchar(MAX), @ErrosXLinhaAWB xml, @AlertasXLinhaAWB xml
	DECLARE @AnoProcesso int, @NumProcesso int, @ArtigoFranquia int, @ContextoIMP int, @IdDeclaracaoIMP bigint, @IdDeclaracaoDAR int
	DECLARE @NumAdicao int, @ProxNumeroDeclSumaria int, @DeclSumariaAuto int, @CodRelDeclSumaria varchar(20), @IDIntDeclSumaria varchar(20), @IDIntDeclSumaria1Adicao varchar(20)
	DECLARE @NumLinhaIncidencia int, @DataIncidencia datetime, @HoraIncidencia datetime
	DECLARE @TblTmpLinhasAWBIntegradas TABLE(MAN_ANO smallint NOT NULL, MAN_NUME int NOT NULL, MAN_TIPO tinyint NOT NULL, MAN_DVOO datetime NOT NULL, EAD_CODI varchar(8) NOT NULL, 
		MAN_NCTM varchar(14) NULL, MAN_ESTA varchar(15) NULL, MAN_SUCE varchar(10) NULL, MAN_ERRS xml NULL, MAN_ALRS xml NULL, AWB_NUME varchar(30) NULL, AWB_ACAO varchar(8) NULL, 
		AWB_SUCE varchar(8) NULL, AWB_NMRN varchar(18) NULL, AWB_IDGA varchar(29) NULL, AWB_ERRS xml NULL, AWB_ALRS xml NULL)
-- inicia transacção para integração da mensagem AirManifestResponse
	BEGIN TRANSACTION tSDSIntMsgAirManifestResponse
	BEGIN TRY	
		SET @NumErro = 0
		SET @TotalLinhasAWBInvalidas = 0	
-- obtem dados da mensagem XML	
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
		SELECT 			
			@IdMensagem = f.m.value('(ns2:MessageInformation/Identification)[1]', 'varchar(35)'), 
			@DataMsgXML = f.m.value('(ns2:MessageInformation/DateAndTime)[1]', 'datetime'), 
			@IdManifestoMsgXML = f.m.value('(ns2:MessageCorrelationInformation/Identification)[1]', 'varchar(35)'), 
			@SucessoMensagem = f.m.value('(ns2:MessageCorrelationInformation/Success)[1]', 'varchar(10)'), 
			@ContramarcaMensagem = f.m.value('(ns2:CustomsProcess/CustomsReferenceNumber)[1]', 'varchar(14)'), 
			@EstadoContramarcaMsgXML = f.m.value('(ns2:CustomsProcess/CurrentCustomsProcessState)[1]', 'varchar(15)'), 
			@DocsTransporteMsgXML = f.m.query('ns2:TransportDocuments'), 
			@ErrosMsgXML = f.m.query('ns2:Errors'), 
			@AlertasMsgXML = f.m.query('ns2:Warnings')
		FROM @MensagemXML.nodes('ns2:AirManifestResponse') AS f(m)
-- extrai ano e número de manifesto 
		IF ISNULL(@IdManifestoMsgXML, '') <> ''
		BEGIN
			SET @AnoManifesto = CAST(LEFT(@IdManifestoMsgXML, 4) AS int)
			SET @NumManifesto = CAST(SUBSTRING(@IdManifestoMsgXML, 6, LEN(@IdManifestoMsgXML) - 8 - 5) AS int)	
		END
		ELSE
		BEGIN
			SELECT TOP 1 @AnoManifesto = DSC_EANO, @NumManifesto = DSC_NPRO
			FROM PRO_SDSC WITH(NOLOCK) 				
			WHERE DSC_NCMF = LEFT(@ContramarcaMensagem, 8) AND DSC_NCMV = RIGHT(@ContramarcaMensagem, 6)
			ORDER BY DSC_TIPO, DSC_IDEN DESC
		END			
-- verifica se mensagem é válida para o manifesto SDS - Via Aérea
		IF NOT EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto)
			RAISERROR('Manifesto SDS - Via Aérea com ID "%s" e Contramarca "%s" inexistente.', 16, 1, @IdManifestoMsgXML, @ContramarcaMensagem)	
		ELSE
			IF EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSC_RESP LIKE '%' + @IdMensagem + '%' AND DSC_RESP LIKE '%' + CONVERT(varchar(23), @DataMsgXML, 121) + '%')
				RAISERROR('Mensagem XML AirManifestResponse com ID "%s" já integrada no Manifesto SDS - Via Aérea com ID "%s" e Contramarca "%s".', 16, 2, @IdMensagem, @IdManifestoMsgXML, @ContramarcaMensagem)	
-- obtem os erros gerais do manifesto da mensagem XML		
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
		SELECT @ErrosGerais = ISNULL(@ErrosGerais, ' #Erros Gerais: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
		FROM @ErrosMsgXML.nodes('ns2:Errors/Error') AS f(m)
-- obtem somente a lista de erros e warnings
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirTransportStatus' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
		SELECT @ErrosMsgXML = @ErrosMsgXML.query('ns2:Errors/Error'), @AlertasMsgXML = @AlertasMsgXML.query('ns2:Warnings/Warning')
-- obtem dados do Manifesto SDS - Via Aérea
		SELECT @TipoManifesto = DSC_TIPO, @CodEstanciaManifesto = EAD_CODI, @DataVooManifesto = DSC_DTVO
		FROM PRO_SDSC WITH(NOLOCK) 				
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- obtem o ID do utilizador
		SELECT @IdUtilizador = UTI_IDTY
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_UTIL = @Utilizador
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os documentos de transporte da mensagem XML
		DECLARE LinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
			SELECT f.m.value('@action[1]', 'varchar(8)'),
				f.m.value('ns2:LocalReferenceNumber[1]', 'varchar(22)'), 
				f.m.value('ns2:MovementReferenceNumber[1]', 'varchar(18)'), 
				f.m.value('ns2:DocumentNumber[1]', 'varchar(24)'), 
				f.m.value('ns2:TransportDocumentState[1]', 'varchar(50)'), 
				f.m.value('ns2:Success[1]', 'varchar(8)'), 
				f.m.query('ns2:Errors'), 
				f.m.query('ns2:Warnings'), 
				f.m.value('(ns2:GoodsItems/ns2:GoodsItem/ns2:CustomsItemNumber)[1]', 'varchar(29)'), 
				f.m.query('(ns2:GoodsItems/ns2:GoodsItem/ns2:Errors)[1]'), 
				f.m.query('(ns2:GoodsItems/ns2:GoodsItem/ns2:Warnings)[1]')
			FROM @DocsTransporteMsgXML.nodes('ns2:TransportDocuments/ns2:TransportDocument') AS f(m)	
		OPEN LinhasAWB
		FETCH NEXT FROM LinhasAWB INTO @AcaoAwbXML, @NRLAwbXML, @MRNAwbXML, @NumDocumentoAwbXML, @EstadoAwbXML, @SucessoAwbXML, @ErrosAwbXML, @AlertasAwbXML, @NumDGAItemXML, 
			@ErrosItemXML, @AlertasItemXML
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @NumAWBLinhaAWB = NULL	
			SET @ErrosLinhaAWB = NULL
			SET @ErrosXLinhaAWB = NULL
			SET @AlertasXLinhaAWB = NULL
-- obtem o ID da linha AWB a partir do NRL
			SET @IdLinhaAWB = CAST(RIGHT(@NRLAwbXML, 9)	AS int)
-- obtem número AWB da linha AWB do Manifesto SDS - Via Aérea
			SELECT @NumAWBLinhaAWB = DSD_NRMH
			FROM PRO_SDSD WITH(NOLOCK) 				
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_IDNN = @IdLinhaAWB
-- verifica se mensagem é válida para o manifesto SDS - Via Aérea
			IF (@IdLinhaAWB IS NOT NULL) AND (ISNULL(@NumAWBLinhaAWB, '') = '')
				RAISERROR('Linha AWB com ID "%s" inexistente no Manifesto SDS - Via Aérea com ID "%s" e Contramarca "%s".', 16, 3, @NRLAwbXML, @IdManifestoMsgXML, @ContramarcaMensagem)
			ELSE
				IF (@IdLinhaAWB IS NULL) AND (ISNULL(@NumAWBLinhaAWB, '') = '')
					SET @TotalLinhasAWBInvalidas = @TotalLinhasAWBInvalidas + 1
-- calcula o estado da operação da linha AWB do Manifesto SDS - Via Aérea
			IF ISNULL(@EstadoAwbXML, '') = 'Provisional'
				SET	@EstadoLinhaAWB = 'PRV' --Provisório
			ELSE
				IF ISNULL(@EstadoAwbXML, '') IN ('Conditional', 'Conditioned by Rejection', 'Conditioned by lack of response')
					SET	@EstadoLinhaAWB = 'PEN' --Pendente
				ELSE
					IF ISNULL(@EstadoAwbXML, '') = 'Active'
						SET	@EstadoLinhaAWB = 'ACT' --Ativo
					ELSE
						IF ISNULL(@EstadoAwbXML, '') = 'Unfolding'
							SET	@EstadoLinhaAWB = 'EMD' --Em Desdobramento
						ELSE 
							IF ISNULL(@EstadoAwbXML, '') = 'Unfold'
								SET	@EstadoLinhaAWB = 'DES' --Desdobrado
							ELSE
								IF ISNULL(@EstadoAwbXML, '') = 'Annul'
									SET	@EstadoLinhaAWB = 'ANU' --Anulado
								ELSE
									SET	@EstadoLinhaAWB = ''
-- obtem os erros da AWB e/ou do item da linha AWB
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
			SELECT @ErrosLinhaAWB = ISNULL(@ErrosLinhaAWB, '#ERROS:') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
			FROM @ErrosAwbXML.nodes('ns2:Errors/Error') AS f(m)
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
			SELECT @ErrosLinhaAWB = ISNULL(@ErrosLinhaAWB, '#ERROS:') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
			FROM @ErrosItemXML.nodes('ns2:Errors/Error') AS f(m)
-- atualiza dados da linha AWB
			UPDATE PRO_SDSD SET 
				DSD_ESTA = (CASE 
								WHEN (DSD_ESTA IN ('FIN', 'APU')) THEN DSD_ESTA
								WHEN (@AcaoAwbXML = 'Create') AND (@SucessoAwbXML = 'No') AND (ISNULL(DSD_ESTA, '') = '') THEN DSD_ESTA 
								WHEN (@SucessoAwbXML = 'Pending') AND (@EstadoLinhaAWB = '') THEN DSD_ESTA 
								ELSE NULLIF(@EstadoLinhaAWB, '')
							END),
				DSD_DERR = @ErrosLinhaAWB,
				DSD_STAT = (CASE @AcaoAwbXML 
								WHEN 'Create' THEN (CASE @SucessoAwbXML WHEN 'Yes' THEN 2 ELSE 3 END) 
								WHEN 'Update' THEN (CASE @SucessoAwbXML WHEN 'Yes' THEN 5 WHEN 'No' THEN 6 ELSE (CASE @EstadoLinhaAWB WHEN '' THEN 6 ELSE 5 END) END) 
								ELSE (CASE @SucessoAwbXML WHEN 'Yes' THEN 8 WHEN 'No' THEN 9 ELSE (CASE @EstadoLinhaAWB WHEN '' THEN 9 ELSE 8 END) END) 
							END),
				DSD_NDGA = @MRNAwbXML, 
				DSD_NDGI = @NumDGAItemXML, 
				DSD_ASAI = (CASE 
								WHEN (@AcaoAwbXML = 'Create') AND (@SucessoAwbXML = 'Yes') THEN 1 
								ELSE DSD_ASAI 
							END), 
				DSD_NDSC = @NumDocumentoAwbXML
			WHERE DSD_IDNN = @IdLinhaAWB	
-- obtem os erros da AWB e do item da linha AWB no formato XML
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
			SELECT @ErrosXLinhaAWB = CAST(NULLIF(ISNULL(CAST(a.e.query('Error') AS varchar(MAX)), '') + ISNULL(CAST(i.e.query('Error') AS varchar(MAX)), ''), '') AS  xml)
			FROM @ErrosAwbXML.nodes('ns2:Errors') AS a(e)
				FULL OUTER JOIN @ErrosItemXML.nodes('ns2:Errors') AS i(e) ON 1 = 1
-- obtem os alertas da AWB e do item da linha AWB no formato XML
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirManifestResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
			SELECT @AlertasXLinhaAWB = CAST(NULLIF(ISNULL(CAST(a.e.query('Warning') AS varchar(MAX)), '') + ISNULL(CAST(i.e.query('Warning') AS varchar(MAX)), ''), '') AS  xml)
			FROM @AlertasAwbXML.nodes('ns2:Warnings') AS a(e)
				FULL OUTER JOIN @AlertasItemXML.nodes('ns2:Warnings') AS i(e) ON 1 = 1
-- insere dados do manifesto e linha AWB na tabela tmp
			INSERT INTO @TblTmpLinhasAWBIntegradas(MAN_ANO, MAN_NUME, MAN_TIPO, MAN_DVOO, EAD_CODI, MAN_NCTM, MAN_ESTA, MAN_SUCE, MAN_ERRS, MAN_ALRS, AWB_NUME, AWB_ACAO, AWB_SUCE, AWB_NMRN, 
				AWB_IDGA, AWB_ERRS, AWB_ALRS)
			VALUES(@AnoManifesto, @NumManifesto, @TipoManifesto, @DataVooManifesto, @CodEstanciaManifesto, @ContramarcaMensagem, @EstadoContramarcaMsgXML, @SucessoMensagem, @ErrosMsgXML, @AlertasMsgXML, @NumAWBLinhaAWB, @AcaoAwbXML, @SucessoAwbXML, @MRNAwbXML, 
				@NumDGAItemXML, @ErrosXLinhaAWB, @AlertasXLinhaAWB)
-- se manifesto SDS - Via Aérea for de importação e linha AWB tiver "N.º DGA" atribuído, processa atualizações nas respetivas declarações de importação DUI2, IMP-CAU ou DAR
			IF (@TipoManifesto = 0) AND (ISNULL(@MRNAwbXML, '') <> '')
			BEGIN
				SET @NumProcesso = NULL
				SET @AnoProcesso = NULL
				SET @ArtigoFranquia = NULL
				SET @ContextoIMP = NULL
				SET @IdDeclaracaoIMP = NULL
-- obtem dados da Declaração de Importação se tiver "Artigo Franquia" definido
				SELECT @NumProcesso = DUC_PNUM, @AnoProcesso = DUC_EANO, @ArtigoFranquia = DUC_ARTI, @ContextoIMP = DUC_DUNO, @IdDeclaracaoIMP = DUC_IDTY			
				FROM PRO_DUCG WITH(NOLOCK) 								
				WHERE DUC_DUNO IN (1, 2) AND DUC_CPRT = @NumAWBLinhaAWB AND CAST(CONVERT(varchar(10), DUC_DTVO, 105) as datetime) = CAST(CONVERT(varchar(10), @DataVooManifesto, 105) as datetime)
					AND (SELECT COUNT(*) FROM PRO_DUOD WITH(NOLOCK) WHERE DUC_EANO = PRO_DUCG.DUC_EANO AND DUC_PNUM = PRO_DUCG.DUC_PNUM) > 0
-- verifica se se trata de uma Declaração de Importação
				IF @NumProcesso IS NOT NULL
				BEGIN
-- actualiza DU Importação relacionado com linha AWB
					UPDATE PRO_DUCG SET 
						DUC_LC27 = @MRNAwbXML, 
						DUC_ASAI = (CASE WHEN DUC_ARTI IS NOT NULL THEN 1 ELSE DUC_ASAI END),
						DUC_NORD = (CASE WHEN DUC_ARTI IS NOT NULL THEN @MRNAwbXML ELSE DUC_NORD END),
						DUC_NDAT = (CASE WHEN DUC_ARTI IS NOT NULL THEN CAST(CONVERT(varchar(10), @DataAtual, 105) as datetime) ELSE DUC_NDAT END)					
					WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso
-- actualiza adições do DU Importação relacionado com linha AWB
					UPDATE PRO_DUAD SET 
						DUA_QUAL = 'X', 
						DUA_DANO = CAST(SUBSTRING(@NumDocumentoAwbXML, 10, 4) AS int), 
						DUA_DNUM = SUBSTRING(@NumDocumentoAwbXML, 14, 6), 
						DOC_CODI = (CASE @ContextoIMP WHEN 2 THEN 'N337' ELSE '785' END), 
						EAD_CODI = ('PT000' + SUBSTRING(@NumDocumentoAwbXML, 6, 3)), 
						DUA_DDAT = @DataVooManifesto, 
						MTR_CODI = '4', 
						DUA_LINH = SUBSTRING(@NumDocumentoAwbXML, 20, 10)
					WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso	
-- processa atualizações especificas em função se DUI2 ou IMP-CAU
					IF @ContextoIMP = 1
					BEGIN								
-- obtem as adições da Declaração de Importação
						DECLARE LstAdicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
							SELECT DUA_CODI									
							FROM PRO_DUAD WITH(NOLOCK) 								
							WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso
							ORDER BY DUA_CODI
						OPEN LstAdicoes
						FETCH NEXT FROM LstAdicoes INTO @NumAdicao
						WHILE @@FETCH_STATUS = 0
						BEGIN
-- para cada adição, verifica se linha "Sumária" do anexo de Declaração Sumária já existe					
							IF EXISTS(SELECT DRA_CODI FROM PRO_DURA WITH(NOLOCK) WHERE DRA_QUAL = 'X' AND DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao)
							BEGIN
								IF @NumAdicao = 1
								BEGIN
									SELECT TOP 1 @IDIntDeclSumaria1Adicao = DRA_IDCR
									FROM PRO_DURA WITH(NOLOCK) 
									WHERE DRA_QUAL = 'X' AND DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao
								END
-- actualiza linha "Sumária" do anexo de Declaração Sumária							
								UPDATE PRO_DURA set 
									DOC_CODI = '785', 
									DRA_APDT = @DataVooManifesto, 
									DRA_APAN = CAST(SUBSTRING(@NumDGAItemXML, 10, 4) AS int)
								WHERE DRA_QUAL = 'X' AND DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao
							END
							ELSE
							BEGIN
								IF @NumAdicao = 1
								BEGIN
									SET @DeclSumariaAuto = 0
									SET @CodRelDeclSumaria = NULL
									SET @IDIntDeclSumaria = REPLACE(LTRIM(STR(CAST(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT() AS numeric(38,6)), 20, 6)), '.', ',')
									SET @IDIntDeclSumaria1Adicao = @IDIntDeclSumaria
								END
								ELSE
								BEGIN
									SET @DeclSumariaAuto = 1
									SET @CodRelDeclSumaria = @IDIntDeclSumaria1Adicao
									SET @IDIntDeclSumaria = REPLACE(LTRIM(STR(CAST(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT() AS numeric(38,6)), 20, 6)), '.', ',')							
								END
								SET @ProxNumeroDeclSumaria = (ISNULL((SELECT MAX(DRA_CODI) FROM PRO_DURA WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso AND DUA_CODI = @NumAdicao), 0) + 1)
-- insere linha "Sumária" do anexo de Declaração Sumária
								INSERT INTO PRO_DURA(DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DRA_APDT, DRA_QUAL, DRA_CODR, DRA_AUTO, DRA_IDCR)
								VALUES(@AnoProcesso, @NumProcesso, @NumAdicao, @ProxNumeroDeclSumaria, '785', CAST(SUBSTRING(@NumDGAItemXML, 10, 4) AS int), 
									SUBSTRING(@NumDGAItemXML, 14, 12), 'NP', @DataVooManifesto, 'X', @CodRelDeclSumaria, @DeclSumariaAuto, @IDIntDeclSumaria)
							END							
							FETCH NEXT FROM LstAdicoes INTO @NumAdicao
						END
						CLOSE LstAdicoes
						DEALLOCATE LstAdicoes					
					END
					ELSE --Declaração Importação IMP-CAU
					BEGIN							
-- procede à inserção/atualização do documento precedente c/ código "N337"						
						IF NOT EXISTS(SELECT id FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY WHERE dpr.id_declaracaoIMP = @IdDeclaracaoIMP AND doc.DOC_CODI = 'N337')
						BEGIN
							INSERT INTO tb_IMP_DeclaracoesPrecedentes(id_declaracaoIMP, id_documento, numero, dataContramarca, origem, id_utilizadorControlo, dataControlo)
							SELECT @IdDeclaracaoIMP, DOC_IDTY, @MRNAwbXML, @DataVooManifesto, 3, @IdUtilizador, @DataAtual
							FROM TAB_DOCU WITH(NOLOCK)
							WHERE DOC_CODI = 'N337'
						END
						ELSE
						BEGIN
							UPDATE tb_IMP_DeclaracoesPrecedentes SET 
								numero = @MRNAwbXML, 
								dataContramarca = @DataVooManifesto, 
								id_utilizadorControlo = @IdUtilizador, 
								dataControlo = @DataAtual								
							FROM tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) 									
								INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
							WHERE dpr.id_declaracaoIMP = @IdDeclaracaoIMP AND doc.DOC_CODI = 'N337'
						END
					END																										
-- se declaração tiver "Artigo Franquia" definido, processa a inserção da incidência "A00"
					IF @ArtigoFranquia IS NOT NULL
					BEGIN
-- obtem dados para registo de incidência
						SET @NumLinhaIncidencia = (ISNULL((SELECT MAX(DUI_CODI) FROM PRO_DUIN WHERE DUC_EANO = @AnoProcesso AND DUC_PNUM = @NumProcesso), 0) + 1)
						SET @DataIncidencia = CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)
						SET @HoraIncidencia = @DataAtual							
-- insere a incidência "A00"							
						INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM)
						SELECT @AnoProcesso, @NumProcesso, @NumLinhaIncidencia, SIN_CODI, SIN_DESP, @DataIncidencia, @HoraIncidencia, @DataIncidencia, @HoraIncidencia
						FROM TAB_SINC WITH(NOLOCK) 
						WHERE SIN_CODI = 'A00'							
					END
				END
				ELSE
				BEGIN
					SET @IdDeclaracaoDAR = NULL					
-- verifica se se trata de uma Declaração DAR
					SELECT TOP 1 @IdDeclaracaoDAR = dar.id 
					FROM tb_DeclaracoesDAR AS dar WITH(NOLOCK) 							
					WHERE dar.documentoTransporte = @NumAWBLinhaAWB AND CAST(CONVERT(varchar(10), dar.dataVoo, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataVooManifesto, 105) AS datetime)
						AND EXISTS(SELECT id FROM tb_DeclaracoesDARManifestos WITH(NOLOCK) WHERE id_declaracaoDAR = dar.id)
-- se for Declaração DAR, procede à inserção/atualização do documento precedente c/ código "N337"
					IF @IdDeclaracaoDAR IS NOT NULL
					BEGIN							
-- obtem o ID do utilizador
						SELECT @IdUtilizador = UTI_IDTY
						FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
						WHERE UTI_UTIL = @Utilizador
-- procede à inserção/atualização do documento precedente c/ código "N337"						
						IF NOT EXISTS(SELECT id FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY WHERE dpr.id_declaracaoDAR = @IdDeclaracaoDAR AND doc.DOC_CODI = 'N337')
						BEGIN
							INSERT INTO tb_DeclaracoesDARPrecedentes(id_declaracaoDAR, id_documento, numero, id_utilizadorControlo, dataControlo, origem, dataContramarca)
							SELECT @IdDeclaracaoDAR, DOC_IDTY, @MRNAwbXML, @IdUtilizador, @DataAtual, 2, @DataVooManifesto
							FROM TAB_DOCU WITH(NOLOCK) 
							WHERE DOC_CODI = 'N337'
						END
						ELSE
						BEGIN
							UPDATE tb_DeclaracoesDARPrecedentes SET 
								numero = @MRNAwbXML, 
								id_utilizadorControlo = @IdUtilizador, 
								dataControlo = @DataAtual, 
								dataContramarca = @DataVooManifesto
							FROM tb_DeclaracoesDARPrecedentes AS dpr WITH(NOLOCK) 									
								INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY
							WHERE dpr.id_declaracaoDAR = @IdDeclaracaoDAR AND doc.DOC_CODI = 'N337'
						END
					END
				END				
			END
			ELSE
-- se linha AWB tem "Aut. Saída" e pertence a um SDS do tipo "Exportação", insere ou edita registo de Saida AEX correspondente
				IF (@TipoManifesto = 1) AND (ISNULL(@MRNAwbXML, '') <> '') AND (EXISTS(SELECT 1 FROM PRO_SDSD WITH(NOLOCK) WHERE DSD_ASAI = 1 AND DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_NRMH = @NumAWBLinhaAWB))
					EXEC SP_SaidasAEX_InsereOuEditaViaExportacaoXMLouSDSViaAerea 0, @AnoManifesto, @NumManifesto, NULL, @NumAWBLinhaAWB, @Utilizador, @ErroGeracao OUTPUT															
			FETCH NEXT FROM LinhasAWB INTO @AcaoAwbXML, @NRLAwbXML, @MRNAwbXML, @NumDocumentoAwbXML, @EstadoAwbXML, @SucessoAwbXML, @ErrosAwbXML, @AlertasAwbXML, @NumDGAItemXML, 
				@ErrosItemXML, @AlertasItemXML
		END
		CLOSE LinhasAWB
		DEALLOCATE LinhasAWB
-- actualiza dados do manifesto SDS
		UPDATE PRO_SDSC SET 							
			DSC_NRRR = DSC_NRRR + 1, 
			DSC_UDRR = @DataAtual, 
			DSC_RESP = '-> AIR MANIFEST RESPONSE: ' + CHAR(13) + CHAR(10) 
						+ '	#Data Integração: ' + CONVERT(varchar(23), @DataAtual, 121) + CHAR(13) + CHAR(10) 
						+ '	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) 
						+ '	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) 
						+ '	#MessageDate: ' + CONVERT(varchar(23), @DataMsgXML, 121) + CHAR(13) + CHAR(10) 
						+ '	#Sucess: ' + ISNULL(@SucessoMensagem, '<n.d.>') + CHAR(13) + CHAR(10) 
						+ ISNULL(@ErrosGerais + CHAR(13) + CHAR(10), '') 
						+ (CASE WHEN (ISNULL(@SucessoMensagem, '<n.d.>') = 'No') AND (ISNULL(@ErrosGerais, '') = '') THEN ' #Erros Linhas: ' + CHAR(13) + CHAR(10) + '		. «Verificar erros nas linhas AWB»' + CHAR(13) + CHAR(10) ELSE '' END) 
						+ '===============================================================================================================================' + CHAR(13) + CHAR(10) 
						+ ISNULL(CAST(DSC_RESP AS varchar(max)), '')
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- atualiza status das linhas AWB para "Respondido Create/Update/Delete NOK" quando tem respetivamente o status como "Enviado Create/Update/Delete" e não houve sucesso nas linhas AWB integradas (normalmente devido à ocorrencia de erros gerais e/ou erros de schema [que vem descriminados nas linhas AWB mas sem quaisquer informação da AWB])
		IF (@TotalLinhasAWBInvalidas > 0) OR ((@TotalLinhasAWBInvalidas = 0) AND (NOT EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas)))
		BEGIN
			UPDATE PRO_SDSD SET 
				DSD_STAT = (CASE DSD_STAT WHEN 1 THEN 3 WHEN 4 THEN 6 WHEN 7 THEN 9 ELSE DSD_STAT END)				
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_STAT IN (1, 4, 7)
		END
-- constroi XML com as linhas AWB integradas no MAnifesto SDS - Via Aérea
		SET @AWBIntegradasXML = 
			(SELECT 				
				MAN_ANO AS "AnoManifesto",		
				MAN_NUME AS "NumManifesto", 
				MAN_TIPO AS "TipoManifesto",
				MAN_DVOO AS "DataVooManifesto",
				EAD_CODI AS "EstanciaManifesto", 
				MAN_NCTM AS "ContramarcaManifesto", 
				MAN_ESTA AS "EstadoManifesto",
				MAN_SUCE AS "SucessoManifesto", 
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(MAN_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosManifesto",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(MAN_ALRS AS varchar(MAX)), '') AS xml)) AS "AlertasManifesto",
				AWB_NUME AS "NumeroAWB",
				AWB_ACAO AS "AcaoAWB",
				AWB_SUCE AS "SucessoAWB",
				AWB_NMRN AS "NumMRNAWB",
				AWB_IDGA AS "NumDGAAWB",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(AWB_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosAWB",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(AWB_ALRS AS varchar(MAX)), '') AS xml)) AS "AlertasAWB"
			FROM @TblTmpLinhasAWBIntegradas	
			FOR XML PATH('AWB'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION tSDSIntMsgAirManifestResponse
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION tSDSIntMsgAirManifestResponse
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirManifestResponse] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirManifestResponse] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemIntegraAirTransportStatus]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemIntegraAirTransportStatus] @MensagemXML xml, @Utilizador varchar(30), @IdMensagem varchar(35) OUTPUT, @SucessoMensagem varchar(10) OUTPUT, 
	@ContramarcaMensagem varchar(14) OUTPUT, @AnoManifesto int OUTPUT, @NumManifesto int OUTPUT, @AWBIntegradasXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime
	DECLARE @DataMsgXML datetime, @IdManifestoMsgXML varchar(35), @EstadoContramarcaMsgXML varchar(15), @ErrosMsgXML xml, @AlertasMsgXML xml
	DECLARE @EstadoManifesto varchar(3), @ErrosManifesto varchar(MAX)		
-- inicia transacção para integração da mensagem AirManifestResponse
	BEGIN TRANSACTION tSDSIntMsgAirTransportStatus
	BEGIN TRY	
		SET @NumErro = 0	
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem dados da mensagem XML	
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirTransportStatus' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
		SELECT 			
			@IdMensagem = f.m.value('(ns2:MessageInformation/Identification)[1]', 'varchar(35)'), 
			@DataMsgXML = f.m.value('(ns2:MessageInformation/DateAndTime)[1]', 'datetime'), 
			@IdManifestoMsgXML = f.m.value('(ns2:MessageCorrelationInformation/Identification)[1]', 'varchar(35)'), 
			@SucessoMensagem = f.m.value('(ns2:MessageCorrelationInformation/Success)[1]', 'varchar(10)'), 
			@ContramarcaMensagem = f.m.value('(ns2:CustomsProcess/CustomsReferenceNumber)[1]', 'varchar(14)'), 
			@EstadoContramarcaMsgXML = f.m.value('(ns2:CustomsProcess/CurrentCustomsProcessState)[1]', 'varchar(15)'), 			
			@ErrosMsgXML = f.m.query('ns2:Errors'), 
			@AlertasMsgXML = f.m.query('ns2:Warnings')
		FROM @MensagemXML.nodes('ns2:AirTransportStatus') AS f(m)		
-- extrai ano e número de manifesto 
		IF ISNULL(@IdManifestoMsgXML, '') <> ''
		BEGIN
			SET @AnoManifesto = CAST(LEFT(@IdManifestoMsgXML, 4) AS int)
			SET @NumManifesto = CAST(SUBSTRING(@IdManifestoMsgXML, 6, LEN(@IdManifestoMsgXML) - 8 - 5) AS int)
		END
		ELSE
		BEGIN
			SELECT TOP 1 @AnoManifesto = DSC_EANO, @NumManifesto = DSC_NPRO
			FROM PRO_SDSC WITH(NOLOCK) 				
			WHERE DSC_NCMF = LEFT(@ContramarcaMensagem, 8) AND DSC_NCMV = RIGHT(@ContramarcaMensagem, 6)
			ORDER BY DSC_TIPO, DSC_IDEN DESC
		END
-- verifica se mensagem é válida para o manifesto SDS - Via Aérea
		IF NOT EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto)
			RAISERROR('Manifesto SDS - Via Aérea com ID "%s" e Contramarca "%s" inexistente.', 16, 1, @IdManifestoMsgXML, @ContramarcaMensagem)	
		ELSE
			IF EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSC_RESP LIKE '%' + @IdMensagem + '%' AND DSC_RESP LIKE '%' + CONVERT(varchar(23), @DataMsgXML, 121) + '%')
				RAISERROR('Mensagem XML AirTransportStatus com ID "%s" já integrada no Manifesto SDS - Via Aérea com ID "%s" e Contramarca "%s".', 16, 2, @IdMensagem, @IdManifestoMsgXML, @ContramarcaMensagem)
-- calcula o estado da operação da contramarca do Manifesto SDS - Via Aérea
		IF ISNULL(@EstadoContramarcaMsgXML, '') IN ('PreActive', 'Provisional')
			SET	@EstadoManifesto = 'PRV' --Provisório
		ELSE
			IF ISNULL(@EstadoContramarcaMsgXML, '') IN ('Closed', 'Ultimate')
				SET	@EstadoManifesto = 'FIN' --Finalizado
			ELSE
				IF ISNULL(@EstadoContramarcaMsgXML, '') = 'Active'
					SET	@EstadoManifesto = 'ACT' --Ativo
				ELSE
					IF ISNULL(@EstadoContramarcaMsgXML, '') = 'Annul'
						SET	@EstadoManifesto = 'ANU' --Anulado
					ELSE
						SET	@EstadoManifesto = ''	
-- obtem os erros gerais do manifesto da mensagem XML		
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirTransportStatus' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
		SELECT @ErrosManifesto = ISNULL(@ErrosManifesto, ' #Erros Gerais: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
		FROM @ErrosMsgXML.nodes('ns2:Errors/Error') AS f(m)
-- obtem somente a lista de erros e warnings
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirTransportStatus' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirTypes')
		SELECT @ErrosMsgXML = @ErrosMsgXML.query('ns2:Errors/Error'), @AlertasMsgXML = @AlertasMsgXML.query('ns2:Warnings/Warning')
-- actualiza dados do manifesto SDS
		UPDATE PRO_SDSC SET 			
			DSC_NCMF = (CASE WHEN (ISNULL(@ContramarcaMensagem, '') <> '') AND (DSC_NCMF <> LEFT(@ContramarcaMensagem, 8)) THEN LEFT(@ContramarcaMensagem, 8) ELSE DSC_NCMF END), 
			DSC_NCMV = (CASE WHEN (ISNULL(@ContramarcaMensagem, '') <> '') AND (DSC_NCMV <> RIGHT(@ContramarcaMensagem, 6)) THEN RIGHT(@ContramarcaMensagem, 6) ELSE DSC_NCMV END),
			DSC_STCM = (CASE ISNULL(@SucessoMensagem, '') 
							WHEN 'No' THEN (CASE WHEN DSC_STCM IN (1, 10) THEN 0 ELSE (CASE WHEN DSC_DUCR IS NULL THEN 1 ELSE 2 END) END) 
							WHEN 'Yes' THEN (DSC_STCM / (CASE WHEN DSC_STCM >= 10 THEN 10 ELSE 1 END)) 
							ELSE DSC_STCM 
						END), 
			DSC_UCCR = (CASE WHEN (ISNULL(@SucessoMensagem, '') = 'Yes') AND (DSC_STCM IN (1, 10)) THEN @Utilizador ELSE DSC_UCCR END), 
			DSC_DCCR = (CASE WHEN (ISNULL(@SucessoMensagem, '') = 'Yes') AND (DSC_STCM IN (1, 10)) THEN @DataAtual ELSE DSC_DCCR END),
			DSC_UUCR = (CASE WHEN (ISNULL(@SucessoMensagem, '') = 'Yes') AND (DSC_STCM IN (2, 20)) THEN @Utilizador ELSE DSC_UUCR END), 
			DSC_DUCR = (CASE WHEN (ISNULL(@SucessoMensagem, '') = 'Yes') AND (DSC_STCM IN (2, 20)) THEN @DataAtual ELSE DSC_DUCR END),
			DSC_UACR = (CASE WHEN (ISNULL(@SucessoMensagem, '') = 'Yes') AND (DSC_STCM IN (3, 30)) THEN @Utilizador ELSE DSC_UACR END), 
			DSC_DACR = (CASE WHEN (ISNULL(@SucessoMensagem, '') = 'Yes') AND (DSC_STCM IN (3, 30)) THEN @DataAtual ELSE DSC_DACR END),		
			DSC_ESTA = @EstadoManifesto, 
			DSC_RESP = '-> AIR TRANSPORT STATUS: ' + CHAR(13) + CHAR(10) 
						+ '	#Data Integração: ' + CONVERT(varchar(23), @DataAtual, 121) + CHAR(13) + CHAR(10) 
						+ '	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) 
						+ '	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) 
						+ '	#MessageDate: ' + CONVERT(varchar(23), @DataMsgXML, 121) + CHAR(13) + CHAR(10) 
						+ '	#Sucess: ' + ISNULL(@SucessoMensagem, '<n.d.>') + CHAR(13) + CHAR(10) 
						+ ISNULL(@ErrosManifesto + CHAR(13) + CHAR(10), '') 						
						+ '===============================================================================================================================' + CHAR(13) + CHAR(10) 
						+ ISNULL(CAST(DSC_RESP AS varchar(MAX)), '')
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto		
-- constroi XML com as linhas AWB integradas no MAnifesto SDS - Via Aérea
		SET @AWBIntegradasXML = 
			(SELECT 				
				DSC_EANO AS "AnoManifesto",		
				DSC_NPRO AS "NumManifesto", 
				DSC_TIPO AS "TipoManifesto",
				DSC_DTVO AS "DataVooManifesto",
				EAD_CODI AS "EstanciaManifesto", 
				@ContramarcaMensagem AS "ContramarcaManifesto", 
				@EstadoContramarcaMsgXML AS "EstadoManifesto",
				@SucessoMensagem AS "SucessoManifesto", 
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(@ErrosMsgXML AS varchar(MAX)), '') AS xml)) AS "ErrosManifesto",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(@AlertasMsgXML AS varchar(MAX)), '') AS xml)) AS "AlertasManifesto"
			FROM PRO_SDSC WITH(NOLOCK) 				
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
			FOR XML PATH('AWB'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION tSDSIntMsgAirTransportStatus
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION tSDSIntMsgAirTransportStatus
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirTransportStatus] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirTransportStatus] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersMovementResponse]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersMovementResponse] @MensagemXML xml, @Utilizador varchar(30), @IdMensagem varchar(35) OUTPUT, @SucessoMensagem varchar(10) OUTPUT, 
	@ContramarcaMensagem varchar(14) OUTPUT, @AnoManifesto int OUTPUT, @NumManifesto int OUTPUT, @AWBIntegradasXML xml OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @TotalLinhasAWBInvalidas int
	DECLARE @DataMsgXML datetime, @IdManifestoMsgXML varchar(35), @DadosEntradaMsgXML xml, @ErrosMsgXML xml, @AlertasMsgXML xml
	DECLARE @TipoManifesto int, @DataVooManifesto datetime, @CodEstanciaManifesto varchar(8), @ErrosGerais varchar(MAX), @AlertasGerais varchar(MAX)		
	DECLARE @AcaoAwbXML varchar(8), @SucessoAwbXML varchar(8), @NRLAwbXML varchar(22), @ErrosAwbXML xml, @AlertasAwbXML xml, @JustificacaoAwbXML varchar(512)		
	DECLARE @IdLinhaAWB int, @NumAWBLinhaAWB varchar(30), @ErrosLinhaAWB varchar(MAX), @AlertasLinhaAWB varchar(MAX)
	DECLARE @TblTmpLinhasAWBIntegradas TABLE(MAN_ANO smallint NULL, MAN_NUME int NULL, MAN_TIPO tinyint NULL, MAN_DVOO datetime NULL, EAD_CODI varchar(8) NULL, 
		MAN_NCTM varchar(14) NULL, MAN_SUCE varchar(10) NULL, MAN_ERRS xml NULL, MAN_ALRS xml NULL, AWB_NUME varchar(30) NULL, AWB_ACAO varchar(8) NULL, AWB_SUCE varchar(8) NULL, 
		AWB_ERRS xml NULL, AWB_ALRS xml NULL)
-- inicia transacção para integração da mensagem AirWarehouseKeepersMovementResponse
	BEGIN TRANSACTION tSDSIntMsgAirMovementResponse
	BEGIN TRY	
		SET @NumErro = 0
		SET @TotalLinhasAWBInvalidas = 0	
-- obtem dados da mensagem XML	
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT 			
			@IdMensagem = f.m.value('(ns2:MessageInformation/Identification)[1]', 'varchar(35)'), 
			@DataMsgXML = f.m.value('(ns2:MessageInformation/DateAndTime)[1]', 'datetime'), 
			@IdManifestoMsgXML = f.m.value('(ns2:MessageCorrelationInformation/Identification)[1]', 'varchar(35)'), 
			@SucessoMensagem = f.m.value('(ns2:MessageCorrelationInformation/Success)[1]', 'varchar(10)'), 			
			@DadosEntradaMsgXML = f.m.query('ns2:EntryMovementResponse'), 			
			@AlertasMsgXML = f.m.query('ns2:Warnings'), 
			@ErrosMsgXML = f.m.query('ns2:Errors')		
		FROM @MensagemXML.nodes('ns2:AirWarehouseKeepersMovementResponse') AS f(m)
-- extrai ano e número do Movimento de Saída
		IF ISNULL(@IdManifestoMsgXML, '') <> ''
		BEGIN
			SET @AnoManifesto = CAST(LEFT(@IdManifestoMsgXML, 4) AS int)
			SET @NumManifesto = CAST(SUBSTRING(@IdManifestoMsgXML, 6, LEN(@IdManifestoMsgXML) - 8 - 5) AS int)	
		END			
-- verifica se mensagem é válida para o Movimento de Saída SDS - Via Aérea
		IF (@AnoManifesto IS NOT NULL) AND (@NumManifesto IS NOT NULL) AND (NOT EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto))
			RAISERROR('Movimento de Saída SDS - Via Aérea com ID "%s" e Contramarca "%s" inexistente.', 16, 1, @IdManifestoMsgXML, @ContramarcaMensagem)	
		ELSE
			IF (@AnoManifesto IS NOT NULL) AND (@NumManifesto IS NOT NULL) AND (EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSC_RPMS LIKE '%' + @IdMensagem + '%' AND DSC_RPMS LIKE '%' + CONVERT(varchar(23), @DataMsgXML, 121) + '%'))
				RAISERROR('Mensagem XML AirWarehouseKeepersMovementResponse com ID "%s" já integrada no Movimento de Saída SDS - Via Aérea com ID "%s" e Contramarca "%s".', 16, 2, @IdMensagem, @IdManifestoMsgXML, @ContramarcaMensagem)			
-- obtem os erros gerais do Movimento de Saída da mensagem XML		
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @ErrosGerais = ISNULL(@ErrosGerais, ' #Erros Gerais: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
		FROM @ErrosMsgXML.nodes('ns2:Errors/Error') AS f(m)
-- obtem os alertas gerais do Movimento de Saída da mensagem XML		
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @AlertasGerais = ISNULL(@AlertasGerais, ' #Alertas Gerais: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('WarningDescription[1]', 'varchar(250)')
		FROM @AlertasMsgXML.nodes('ns2:Warnings/Warning') AS f(m)
-- obtem somente a lista de erros e warnings gerais
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @ErrosMsgXML = @ErrosMsgXML.query('ns2:Errors/Error'), @AlertasMsgXML = @AlertasMsgXML.query('ns2:Warnings/Warning')
-- obtem dados do Movimento de Saída SDS - Via Aérea
		SELECT @TipoManifesto = DSC_TIPO, @CodEstanciaManifesto = EAD_CODI, @DataVooManifesto = DSC_DTVO, @ContramarcaMensagem = (DSC_NCMF + DSC_NCMV)
		FROM PRO_SDSC WITH(NOLOCK) 				
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os documentos de transporte da mensagem XML
		DECLARE LinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT f.m.value('ns2:Action[1]', 'varchar(8)'),
				f.m.value('ns2:Success[1]', 'varchar(8)'), 
				f.m.value('ns2:LocalReferenceNumber[1]', 'varchar(22)'), 								
				f.m.query('ns2:Warnings'), 
				f.m.query('ns2:Errors'), 
				f.m.value('ns2:Justification[1]', 'varchar(512)')
			FROM @DadosEntradaMsgXML.nodes('ns2:EntryMovementResponse') AS f(m)	
		OPEN LinhasAWB
		FETCH NEXT FROM LinhasAWB INTO @AcaoAwbXML, @SucessoAwbXML, @NRLAwbXML, @AlertasAwbXML, @ErrosAwbXML, @JustificacaoAwbXML
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @NumAWBLinhaAWB = NULL	
			SET @ErrosLinhaAWB = NULL		
			SET @AlertasLinhaAWB = NULL	
-- obtem o ID da linha AWB a partir do NRL
			SET @IdLinhaAWB = CAST(RIGHT(@NRLAwbXML, 9)	AS int)
-- obtem número AWB da linha AWB do Movimento de Saída SDS - Via Aérea
			SELECT @NumAWBLinhaAWB = dsd.DSD_NRMH, @AnoManifesto = ISNULL(@AnoManifesto, dsd.DSC_EANO), @NumManifesto = ISNULL(@NumManifesto, dsd.DSC_NPRO), 
				@TipoManifesto = ISNULL(@TipoManifesto, dsc.DSC_TIPO), @CodEstanciaManifesto = ISNULL(@CodEstanciaManifesto, dsc.EAD_CODI), 
				@DataVooManifesto = ISNULL(@DataVooManifesto, dsc.DSC_DTVO), @ContramarcaMensagem = ISNULL(@ContramarcaMensagem, (dsc.DSC_NCMF + dsc.DSC_NCMV))
			FROM PRO_SDSD AS dsd WITH(NOLOCK) 	
				INNER JOIN PRO_SDSC AS dsc WITH(NOLOCK) ON dsd.DSC_EANO = dsc.DSC_EANO AND dsd.DSC_NPRO = dsc.DSC_NPRO 			
			WHERE dsd.DSC_EANO = ISNULL(@AnoManifesto, dsd.DSC_EANO) AND dsd.DSC_NPRO = ISNULL(@NumManifesto, dsd.DSC_NPRO) AND dsd.DSD_IDNN = @IdLinhaAWB
-- verifica se mensagem é válida para o Movimento de Saída SDS - Via Aérea
			IF (@IdLinhaAWB IS NOT NULL) AND (ISNULL(@NumAWBLinhaAWB, '') = '')
				RAISERROR('Linha AWB com ID "%s" inexistente no Movimento de Saída SDS - Via Aérea com ID "%s" e Contramarca "%s".', 16, 3, @NRLAwbXML, @IdManifestoMsgXML, @ContramarcaMensagem)
			ELSE
				IF (@IdLinhaAWB IS NULL) AND (ISNULL(@NumAWBLinhaAWB, '') = '')
					SET @TotalLinhasAWBInvalidas = @TotalLinhasAWBInvalidas + 1
-- obtem os erros da linha AWB
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT @ErrosLinhaAWB = ISNULL(@ErrosLinhaAWB, '#ERROS:') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
			FROM @ErrosAwbXML.nodes('ns2:Errors/Error') AS f(m)		
-- obtem os alertas da linha AWB
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT @AlertasLinhaAWB = ISNULL(@AlertasLinhaAWB, '#ALERTAS:') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('WarningDescription[1]', 'varchar(250)')
			FROM @AlertasAwbXML.nodes('ns2:Warnings/Warning') AS f(m)							
-- atualiza dados da linha AWB
			UPDATE PRO_SDSD SET 
				DSD_STMS = (CASE @SucessoAwbXML WHEN 'No' THEN 0 ELSE DSD_STMS END), 
				DSD_SIMS = 1, 
				DSD_DIMS = @DataAtual, 
				DSD_RIMS = (CASE @SucessoAwbXML WHEN 'No' THEN 2 WHEN 'Pending' THEN 3 ELSE 1 END), 
				DSD_EIMS = NULLIF(ISNULL(@ErrosLinhaAWB + CHAR(13) + CHAR(10), '') + ISNULL(@AlertasLinhaAWB + CHAR(13) + CHAR(10), '') + ISNULL('#JUSTIFICACAO: ' + NULLIF(@JustificacaoAwbXML, ''), ''), '')			
			WHERE DSD_IDNN = @IdLinhaAWB
-- obtem somente a lista de erros e warnings
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersMovementResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT @ErrosAwbXML = @ErrosAwbXML.query('ns2:Errors/Error'), @AlertasAwbXML = @AlertasAwbXML.query('ns2:Warnings/Warning')
-- insere dados do Movimento de Saída e linha AWB na tabela tmp
			INSERT INTO @TblTmpLinhasAWBIntegradas(MAN_ANO, MAN_NUME, MAN_TIPO, MAN_DVOO, EAD_CODI, MAN_NCTM, MAN_SUCE, MAN_ERRS, MAN_ALRS, AWB_NUME, AWB_ACAO, AWB_SUCE, AWB_ERRS, AWB_ALRS)
			VALUES(@AnoManifesto, @NumManifesto, @TipoManifesto, @DataVooManifesto, @CodEstanciaManifesto, @ContramarcaMensagem, @SucessoMensagem, @ErrosMsgXML, @AlertasMsgXML, @NumAWBLinhaAWB, @AcaoAwbXML, @SucessoAwbXML, @ErrosAwbXML, @AlertasAwbXML)
			FETCH NEXT FROM LinhasAWB INTO  @AcaoAwbXML, @SucessoAwbXML, @NRLAwbXML, @AlertasAwbXML, @ErrosAwbXML, @JustificacaoAwbXML
		END
		CLOSE LinhasAWB
		DEALLOCATE LinhasAWB
-- actualiza dados do Movimento de Saída SDS
		UPDATE PRO_SDSC SET 
			DSC_STMS = 2, 
			DSC_NRMS = DSC_NRMS + 1, 
			DSC_URMS = @Utilizador, 
			DSC_DRMS = @DataAtual, 
			DSC_RPMS = '-> AIR WAREHOUSEKEEPERS MOVEMENT RESPONSE: ' + CHAR(13) + CHAR(10) 
						+ '	#Data Integração: ' + CONVERT(varchar(23), @DataAtual, 121) + CHAR(13) + CHAR(10) 
						+ '	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) 
						+ '	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) 
						+ '	#MessageDate: ' + CONVERT(varchar(23), @DataMsgXML, 121) + CHAR(13) + CHAR(10) 
						+ '	#Sucess: ' + ISNULL(@SucessoMensagem, '<n.d.>') + CHAR(13) + CHAR(10) 
						+ ISNULL(@ErrosGerais + CHAR(13) + CHAR(10), '') 
						+ ISNULL(@AlertasGerais + CHAR(13) + CHAR(10), '') 
						+ (CASE WHEN (ISNULL(@SucessoMensagem, '<n.d.>') = 'No') AND (ISNULL(@ErrosGerais, '') = '') THEN ' #Erros Linhas: ' + CHAR(13) + CHAR(10) + '		. «Verificar erros nas linhas AWB»' + CHAR(13) + CHAR(10) ELSE '' END) 						
						+ '===============================================================================================================================' + CHAR(13) + CHAR(10) 
						+ ISNULL(CAST(DSC_RPMS AS varchar(MAX)), '')											
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto		
-- atualiza status das linhas AWB para "Respondido Create" quando tem respetivamente o status como "Enviado Create" e não houve sucesso nas linhas AWB integradas (normalmente devido à ocorrencia de erros gerais e/ou erros de schema [que vem descriminados nas linhas AWB mas sem quaisquer informação da AWB])
		IF (@TotalLinhasAWBInvalidas > 0) OR ((@TotalLinhasAWBInvalidas = 0) AND (NOT EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas)))
		BEGIN
			UPDATE PRO_SDSD SET DSD_STMS = 0	
			FROM PRO_SDSD AS dsd WITH(NOLOCK)
				INNER JOIN PRO_SDSC AS dsc WITH(NOLOCK) ON dsd.DSC_EANO = dsc.DSC_EANO AND dsd.DSC_NPRO = dsc.DSC_NPRO 
				INNER JOIN (SELECT duc.DUC_CPRT, duc.DUC_DTVO, MIN(dui.SIN_CODI) AS SIN_CODI
					FROM PRO_DUCG AS duc WITH(NOLOCK) 
						LEFT OUTER JOIN PRO_DUIN AS dui WITH(NOLOCK) ON duc.DUC_EANO = dui.DUC_EANO AND duc.DUC_PNUM = dui.DUC_PNUM AND (dui.SIN_CODI IN ('A00', 'A13') OR dui.DUI_REHO = 0)
					WHERE ISNULL(dui.SIN_CODI, '') <> ''
					GROUP BY duc.DUC_CPRT, duc.DUC_DTVO) AS t ON dsd.DSD_NRMH = t.DUC_CPRT AND CAST(CONVERT(varchar(10), dsc.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), t.DUC_DTVO, 105) AS datetime)
			WHERE dsd.DSD_STRD > 0 AND dsd.DSD_STMS = 1 AND dsd.DSD_SIMS = 0 AND dsd.DSD_RIMS IS NULL AND dsc.DSC_TIPO = 0 AND dsc.DSC_STRD > 1 
				AND ISNULL(dsd.DSD_DNRD, '') <> '' AND ISNULL(t.SIN_CODI, '') <> ''
			
		END
-- insere dados do Movimento de Saída na tabela tmp
		IF (@TotalLinhasAWBInvalidas = 0) AND (NOT EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas))
		BEGIN
			INSERT INTO @TblTmpLinhasAWBIntegradas(MAN_ANO, MAN_NUME, MAN_TIPO, MAN_DVOO, EAD_CODI, MAN_NCTM, MAN_SUCE, MAN_ERRS, MAN_ALRS, AWB_NUME, AWB_ACAO, AWB_SUCE, AWB_ERRS, AWB_ALRS)
			VALUES(@AnoManifesto, @NumManifesto, @TipoManifesto, @DataVooManifesto, @CodEstanciaManifesto, @ContramarcaMensagem, @SucessoMensagem, @ErrosMsgXML, @AlertasMsgXML, NULL, NULL, NULL, NULL, NULL)
		END
-- constroi XML com as linhas AWB integradas no Movimento de Saída SDS - Via Aérea
		SET @AWBIntegradasXML = 
			(SELECT 				
				MAN_ANO AS "AnoManifesto",		
				MAN_NUME AS "NumManifesto", 
				MAN_TIPO AS "TipoManifesto",
				MAN_DVOO AS "DataVooManifesto",
				EAD_CODI AS "EstanciaManifesto", 
				MAN_NCTM AS "ContramarcaManifesto", 				
				MAN_SUCE AS "SucessoManifesto", 
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(MAN_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosManifesto",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(MAN_ALRS AS varchar(MAX)), '') AS xml)) AS "AlertasManifesto",
				AWB_NUME AS "NumeroAWB",
				AWB_ACAO AS "AcaoAWB",
				AWB_SUCE AS "SucessoAWB",				
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(AWB_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosAWB",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(AWB_ALRS AS varchar(MAX)), '') AS xml)) AS "AlertasAWB"
			FROM @TblTmpLinhasAWBIntegradas	
			FOR XML PATH('AWB'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION tSDSIntMsgAirMovementResponse
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION tSDSIntMsgAirMovementResponse
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersMovementResponse] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersMovementResponse] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersNotification]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersNotification] @MensagemXML xml, @Utilizador varchar(30), @TipoNotificacaoMensagem int OUTPUT, 
	@IdMensagem varchar(35) OUTPUT, @SucessoMensagem varchar(10) OUTPUT, @ContramarcaMensagem varchar(14) OUTPUT, @AnoManifesto int OUTPUT, @NumManifesto int OUTPUT, @AWBIntegradasXML xml OUTPUT, 
	@Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime
	DECLARE @DataMsgXML datetime, @DocsTransporteMsgXML xml
	DECLARE @TipoManifesto int, @DataVooManifesto datetime, @CodEstanciaManifesto varchar(8), @ErrosGeraisXML xml, @ErrosGerais varchar(MAX), @TotalDocsTransporte int
	DECLARE @NumeroAWBXML varchar(30), @TipoControloXML varchar(10), @DescricaoControloXML varchar(256), @DataAutorizacaoXML datetime, @TipoAutorizacaoXML varchar(30), 
		@DescricaoAutorizacaoXML varchar(256), @TipoAWBAutorizacaoXML varchar(4), @NumeroAWBAutorizacaoXML varchar(30)
	DECLARE @IdLinhaAWB int, @AcaoLinhaAWB varchar(8), @SucessoLinhaAWB varchar(8), @ErrosLinhaAWB xml
	DECLARE @TblTmpLinhasAWBIntegradas TABLE(MAN_ANO smallint NOT NULL, MAN_NUME int NOT NULL, MAN_TIPO tinyint NOT NULL, MAN_DVOO datetime NOT NULL, EAD_CODI varchar(8) NOT NULL, 
		MAN_NCTM varchar(14) NULL, MAN_SUCE varchar(10) NULL, MAN_ERRS xml NULL, AWB_NUME varchar(30) NULL, AWB_ACAO varchar(8) NULL, AWB_SUCE varchar(8) NULL, AWB_ERRS xml NULL)
-- inicia transacção para integração da mensagem AirWarehouseKeepersNotification
	BEGIN TRANSACTION tSDSIntMsgAirWarehouseNotify
	BEGIN TRY	
		SET @NumErro = 0		
		SET @TotalDocsTransporte = 0
		SET @SucessoMensagem = 'Yes'
-- obtem dados da mensagem XML	
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersNotification' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT 			
			@IdMensagem = f.m.value('(ns2:MessageInformation/Identification)[1]', 'varchar(35)'), 
			@DataMsgXML = f.m.value('(ns2:MessageInformation/DateAndTime)[1]', 'datetime'), 			
			@ContramarcaMensagem = f.m.value('ns2:CustomsReferenceNumber[1]', 'varchar(14)'), 			
			@DocsTransporteMsgXML = f.m.query('ns2:Cargos')
		FROM @MensagemXML.nodes('ns2:AirWarehouseKeepersNotification') AS f(m)
-- verifica se mensagem é válida para o Relatório de Descarga SDS - Via Aérea
		IF NOT EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_TIPO = 0 AND DSC_NCMF = LEFT(@ContramarcaMensagem, 8) AND DSC_NCMV = RIGHT(@ContramarcaMensagem, 6))
			RAISERROR('Relatório de Descarga SDS - Via Aérea com Contramarca "%s" inexistente.', 16, 1, @ContramarcaMensagem)	
		ELSE
			IF EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_TIPO = 0 AND DSC_NCMF = LEFT(@ContramarcaMensagem, 8) AND DSC_NCMV = RIGHT(@ContramarcaMensagem, 6) AND DSC_RPRD LIKE '%' + @IdMensagem + '%' AND DSC_RPRD LIKE '%' + CONVERT(varchar(23), @DataMsgXML, 121) + '%')
				RAISERROR('Mensagem XML AirWarehouseKeepersNotification com ID "%s" já integrada no Relatório de Descarga SDS - Via Aérea com Contramarca "%s".', 16, 2, @IdMensagem, @ContramarcaMensagem)	
-- verifica a existência de documentos de transporte 
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersNotification' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @TotalDocsTransporte = COUNT(*) 
		FROM @DocsTransporteMsgXML.nodes('ns2:Cargos/ns2:Cargo') AS f(m)
		IF @TotalDocsTransporte = 0
		BEGIN
			SET @ErrosGeraisXML = 
				(SELECT 
					'S/ DADOS DE DOCUMENTOS DE TRANSPORTE ESPECIFICADOS' AS "ErrorDescription"
				FOR XML PATH('Error'), ELEMENTS)
		END
		ELSE 
			SET @ErrosGeraisXML = NULL
-- obtem os erros gerais do Relatório de Descarga da mensagem XML				
		SELECT @ErrosGerais = ISNULL(@ErrosGerais, ' #Erros Gerais: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
		FROM @ErrosGeraisXML.nodes('Error') AS f(m)
-- obtem dados do Relatório de Descarga SDS - Via Aérea
		SELECT TOP 1 @AnoManifesto = DSC_EANO, @NumManifesto = DSC_NPRO, @TipoManifesto = DSC_TIPO, @CodEstanciaManifesto = EAD_CODI, @DataVooManifesto = DSC_DTVO
		FROM PRO_SDSC WITH(NOLOCK) 				
		WHERE DSC_TIPO = 0 AND DSC_NCMF = LEFT(@ContramarcaMensagem, 8) AND DSC_NCMV = RIGHT(@ContramarcaMensagem, 6)
		ORDER BY DSC_IDEN DESC
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os documentos de transporte da mensagem XML
		DECLARE LinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersNotification' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT f.m.value('(ns2:TransportDocument/ReferenceNumber)[1]', 'varchar(30)'), 								
				f.m.value('(ns2:Control/ns2:Type)[1]', 'varchar(10)'),
				f.m.value('(ns2:Control/ns2:Description)[1]', 'varchar(256)'),
				f.m.value('(ns2:Authorization/ns2:AuthorizationDate)[1]', 'datetime'),
				f.m.value('(ns2:Authorization/ns2:AuthorizationType)[1]', 'varchar(30)'), 
				f.m.value('(ns2:Authorization/ns2:AuthorizationDescription)[1]', 'varchar(256)'),
				f.m.value('(ns2:Authorization/ns2:Document/Type)[1]', 'varchar(4)'), 
				f.m.value('(ns2:Authorization/ns2:Document/ReferenceNumber)[1]', 'varchar(30)')
			FROM @DocsTransporteMsgXML.nodes('ns2:Cargos/ns2:Cargo') AS f(m)	
		OPEN LinhasAWB
		FETCH NEXT FROM LinhasAWB INTO @NumeroAWBXML, @TipoControloXML, @DescricaoControloXML, @DataAutorizacaoXML, @TipoAutorizacaoXML, @DescricaoAutorizacaoXML, @TipoAWBAutorizacaoXML, 
			@NumeroAWBAutorizacaoXML
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @IdLinhaAWB = NULL	
			SET @AcaoLinhaAWB = NULL
			SET @SucessoLinhaAWB = NULL
			SET @ErrosLinhaAWB = NULL			
-- obtem ID da linha AWB do Relatório de Descarga SDS - Via Aérea
			SELECT @IdLinhaAWB = DSD_IDNN
			FROM PRO_SDSD WITH(NOLOCK) 				
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_NRMH = @NumeroAWBXML
-- verifica se linha AWB é válida para o Relatório de Descarga SDS - Via Aérea
			IF @IdLinhaAWB IS NULL
				RAISERROR('Linha AWB com Número Documento "%s" inexistente no Relatórios de Descarga SDS - Via Aérea com Contramarca "%s".', 16, 3, @NumeroAWBXML, @ContramarcaMensagem)
-- atualiza dados de controlo da linha AWB			
			IF ISNULL(@TipoControloXML, '') <> ''
			BEGIN
				UPDATE PRO_SDSD SET 
					DSD_SIRD = 4, 
					DSD_DIRD = @DataAtual, 					
					DSD_CTRD = @TipoControloXML
				WHERE DSD_IDNN = @IdLinhaAWB
			END
-- atualiza dados de autorização da linha AWB			
			IF ISNULL(@TipoAutorizacaoXML, '') <> ''
			BEGIN
				UPDATE PRO_SDSD SET 
					DSD_SIRD = 5, 
					DSD_DIRD = @DataAtual, 
					DSD_ADRD = @DataAutorizacaoXML, 
					DSD_ATRD = @TipoAutorizacaoXML, 
					DSD_DTRD = @TipoAWBAutorizacaoXML, 
					DSD_DNRD = @NumeroAWBAutorizacaoXML					
				WHERE DSD_IDNN = @IdLinhaAWB
			END				
-- calcula valores em função do tipo de notificações existentes
			IF (ISNULL(@TipoControloXML, '') <> '') AND (ISNULL(@TipoAutorizacaoXML, '') = '')
			BEGIN
				SET @AcaoLinhaAWB = 'NotifyCA'
				SET @SucessoLinhaAWB = 'Yes'
			END
			ELSE
				IF (ISNULL(@TipoControloXML, '') = '') AND (ISNULL(@TipoAutorizacaoXML, '') <> '')
				BEGIN
					SET @AcaoLinhaAWB = 'NotifyAS'
					SET @SucessoLinhaAWB = 'Yes'
				END
				ELSE
					IF (ISNULL(@TipoControloXML, '') <> '') AND (ISNULL(@TipoAutorizacaoXML, '') <> '')
					BEGIN
						SET @AcaoLinhaAWB = 'NotifyBO'
						SET @SucessoLinhaAWB = 'Yes'
					END
					ELSE
						IF (ISNULL(@TipoControloXML, '') = '') AND (ISNULL(@TipoAutorizacaoXML, '') = '')
						BEGIN		
							SET @AcaoLinhaAWB = NULL				
							SET @SucessoLinhaAWB = 'No'				
							SET @ErrosLinhaAWB = 
								(SELECT 
									'S/ DADOS DE NOTIFICAÇÃO DE CONTROLO OU NOTIFICAÇÃO DE AUTORIZAÇÃO ESPECIFICADOS' AS "ErrorDescription"
								FOR XML PATH('Error'), ELEMENTS)
						END							
-- insere dados do Relatório de Descarga e linha AWB na tabela tmp
			INSERT INTO @TblTmpLinhasAWBIntegradas(MAN_ANO, MAN_NUME, MAN_TIPO, MAN_DVOO, EAD_CODI, MAN_NCTM, MAN_SUCE, MAN_ERRS, AWB_NUME, AWB_ACAO, AWB_SUCE, AWB_ERRS)
			VALUES(@AnoManifesto, @NumManifesto, @TipoManifesto, @DataVooManifesto, @CodEstanciaManifesto, @ContramarcaMensagem, @SucessoMensagem, @ErrosGeraisXML, @NumeroAWBXML, @AcaoLinhaAWB, @SucessoLinhaAWB, @ErrosLinhaAWB)
			FETCH NEXT FROM LinhasAWB INTO @NumeroAWBXML, @TipoControloXML, @DescricaoControloXML, @DataAutorizacaoXML, @TipoAutorizacaoXML, @DescricaoAutorizacaoXML, @TipoAWBAutorizacaoXML, 
				@NumeroAWBAutorizacaoXML
		END
		CLOSE LinhasAWB
		DEALLOCATE LinhasAWB
-- atualiza sucesso da mensagem quando existem linhas AWB com sucesso "No"
		IF EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas WHERE AWB_SUCE = 'No')
		BEGIN
			SET @SucessoMensagem = 'No'
			UPDATE @TblTmpLinhasAWBIntegradas SET MAN_SUCE = @SucessoMensagem
		END		
		ELSE
			IF NOT EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas)
			BEGIN
				SET @SucessoMensagem = 'No'
				INSERT INTO @TblTmpLinhasAWBIntegradas(MAN_ANO, MAN_NUME, MAN_TIPO, MAN_DVOO, EAD_CODI, MAN_NCTM, MAN_SUCE, MAN_ERRS)
				VALUES(@AnoManifesto, @NumManifesto, @TipoManifesto, @DataVooManifesto, @CodEstanciaManifesto, @ContramarcaMensagem, @SucessoMensagem, @ErrosGeraisXML)	
			END	
-- calcula tipo de notificação que da mensagem XML integrada
		IF EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas WHERE AWB_ACAO IN ('NotifyAS', 'NotifyBO'))
			SET @TipoNotificacaoMensagem = 2
		ELSE
			SET @TipoNotificacaoMensagem = 3				
-- actualiza dados do Relatório de Descarga SDS
		UPDATE PRO_SDSC SET 
			DSC_STRD = (CASE @TipoNotificacaoMensagem WHEN 2 THEN 5 ELSE 4 END), 
			DSC_NRRD = DSC_NRRD + 1, 
			DSC_URRD = @Utilizador, 
			DSC_DRRD = @DataAtual, 
			DSC_RPRD = '-> AIR WAREHOUSEKEEPERS NOTIFICATION: ' + CHAR(13) + CHAR(10) 
						+ '	#Data Integração: ' + CONVERT(varchar(23), @DataAtual, 121) + CHAR(13) + CHAR(10) 
						+ '	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) 
						+ '	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) 
						+ '	#MessageDate: ' + CONVERT(varchar(23), @DataMsgXML, 121) + CHAR(13) + CHAR(10) 
						+ '	#Sucess: ' + ISNULL(@SucessoMensagem, '<n.d.>') + CHAR(13) + CHAR(10) 
						+ '	#NotificationType: ' + ISNULL((CASE WHEN EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas WHERE AWB_ACAO = 'NotifyBO') THEN 'Control Notification & Authorization Notification' WHEN EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas WHERE AWB_ACAO = 'NotifyAS') THEN 'Authorization Notification' WHEN EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas WHERE AWB_ACAO = 'NotifyCA') THEN 'Control Notification' ELSE NULL END), '<n.d.>') + CHAR(13) + CHAR(10) 
						+ ISNULL(@ErrosGerais + CHAR(13) + CHAR(10), '')  
						+ (CASE WHEN (ISNULL(@SucessoMensagem, '<n.d.>') = 'No') AND (ISNULL(@ErrosGerais, '') = '') THEN ' #Erros Linhas: ' + CHAR(13) + CHAR(10) + '		. «Verificar erros nas linhas AWB»' + CHAR(13) + CHAR(10) ELSE '' END) 											
						+ '===============================================================================================================================' + CHAR(13) + CHAR(10) 
						+ ISNULL(CAST(DSC_RPRD AS varchar(max)), '')						
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto		
-- constroi XML com as linhas AWB integradas no Relatório de Descarga SDS - Via Aérea
		SET @AWBIntegradasXML = 
			(SELECT 				
				MAN_ANO AS "AnoManifesto",		
				MAN_NUME AS "NumManifesto", 
				MAN_TIPO AS "TipoManifesto",
				MAN_DVOO AS "DataVooManifesto",
				EAD_CODI AS "EstanciaManifesto", 
				MAN_NCTM AS "ContramarcaManifesto", 				
				MAN_SUCE AS "SucessoManifesto", 
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(MAN_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosManifesto",				
				AWB_NUME AS "NumeroAWB",
				AWB_ACAO AS "AcaoAWB",
				AWB_SUCE AS "SucessoAWB",				
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(AWB_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosAWB"				
			FROM @TblTmpLinhasAWBIntegradas	
			FOR XML PATH('AWB'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION tSDSIntMsgAirWarehouseNotify
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION tSDSIntMsgAirWarehouseNotify
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersNotification] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersNotification] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersReportResponse]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersReportResponse] @MensagemXML xml, @Utilizador varchar(30), @IdMensagem varchar(35) OUTPUT, 
	@SucessoMensagem varchar(10) OUTPUT, @ContramarcaMensagem varchar(14) OUTPUT, @AnoManifesto int OUTPUT, @NumManifesto int OUTPUT, @AWBIntegradasXML xml OUTPUT, 
	@Erro varchar(MAX) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @TotalLinhasAWBInvalidas int
	DECLARE @DataMsgXML datetime, @IdManifestoMsgXML varchar(35), @DadosDescargaMsgXML xml, @SucessoFimOpXML varchar(8), @ErrosFimOpXML xml, @AlertasFimOpXML xml, 
		@JustificacaoFimOpXML varchar(512), @ErrosMsgXML xml, @AlertasMsgXML xml
	DECLARE @TipoManifesto int, @DataVooManifesto datetime, @CodEstanciaManifesto varchar(8), @IdDepositarioManifesto varchar(20), @ErrosGerais varchar(MAX), @AlertasGerais varchar(MAX), 
		@ErrosFimOp varchar(MAX), @AlertasFimOp varchar(MAX)
	DECLARE @AcaoAwbXML varchar(8), @SucessoAwbXML varchar(8), @NRLAwbXML varchar(22), @ErrosAwbXML xml, @AlertasAwbXML xml, @JustificacaoAwbXML varchar(512)		
	DECLARE @IdLinhaAWB int, @NumAWBLinhaAWB varchar(30), @ErrosLinhaAWB varchar(MAX), @AlertasLinhaAWB varchar(MAX)
	DECLARE @TblTmpLinhasAWBIntegradas TABLE(MAN_ANO smallint NOT NULL, MAN_NUME int NOT NULL, MAN_TIPO tinyint NOT NULL, MAN_DVOO datetime NOT NULL, EAD_CODI varchar(8) NOT NULL, 
		MAN_NCTM varchar(14) NULL, MAN_SUCE varchar(10) NULL, MAN_ERRS xml NULL, MAN_ALRS xml NULL, AWB_NUME varchar(30) NULL, AWB_ACAO varchar(8) NULL, AWB_SUCE varchar(8) NULL, 
		AWB_ERRS xml NULL, AWB_ALRS xml NULL)
-- inicia transacção para integração da mensagem AirWarehouseKeepersReportResponse
	BEGIN TRANSACTION tSDSIntMsgAirWarehouseResponse
	BEGIN TRY	
		SET @NumErro = 0
		SET @TotalLinhasAWBInvalidas = 0	
-- obtem dados da mensagem XML	
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT 			
			@IdMensagem = f.m.value('(ns2:MessageInformation/Identification)[1]', 'varchar(35)'), 
			@DataMsgXML = f.m.value('(ns2:MessageInformation/DateAndTime)[1]', 'datetime'), 
			@IdManifestoMsgXML = f.m.value('(ns2:MessageCorrelationInformation/Identification)[1]', 'varchar(35)'), 
			@SucessoMensagem = f.m.value('(ns2:MessageCorrelationInformation/Success)[1]', 'varchar(10)'), 
			@ContramarcaMensagem = f.m.value('ns2:CustomsReferenceNumber[1]', 'varchar(14)'), 			
			@DadosDescargaMsgXML = f.m.query('ns2:UnloadReportResponse'), 
			@SucessoFimOpXML = f.m.value('(ns2:UnloadEndOfOperationsResponse/ns2:Success)[1]', 'varchar(10)'), 
			@AlertasFimOpXML = f.m.query('(ns2:UnloadEndOfOperationsResponse/ns2:Warnings)'), 
			@ErrosFimOpXML = f.m.query('(ns2:UnloadEndOfOperationsResponse/ns2:Errors)'), 			
			@JustificacaoFimOpXML = f.m.value('(ns2:UnloadEndOfOperationsResponse/ns2:Justification)[1]', 'varchar(512)'), 
			@AlertasMsgXML = f.m.query('ns2:Warnings'), 
			@ErrosMsgXML = f.m.query('ns2:Errors')		
		FROM @MensagemXML.nodes('ns2:AirWarehouseKeepersReportResponse') AS f(m)
-- extrai ano e número do Relatório de Descarga 
		IF ISNULL(@IdManifestoMsgXML, '') <> ''
		BEGIN
			SET @AnoManifesto = CAST(LEFT(@IdManifestoMsgXML, 4) AS int)
			SET @NumManifesto = CAST(SUBSTRING(@IdManifestoMsgXML, 6, LEN(@IdManifestoMsgXML) - 8 - 5) AS int)	
		END
		ELSE
		BEGIN
			SELECT TOP 1 @AnoManifesto = DSC_EANO, @NumManifesto = DSC_NPRO
			FROM PRO_SDSC WITH(NOLOCK) 				
			WHERE DSC_NCMF = LEFT(@ContramarcaMensagem, 8) AND DSC_NCMV = RIGHT(@ContramarcaMensagem, 6)
			ORDER BY DSC_TIPO, DSC_IDEN DESC
		END			
-- verifica se mensagem é válida para o Relatório de Descarga SDS - Via Aérea
		IF NOT EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto)
			RAISERROR('Relatório de Descarga SDS - Via Aérea com ID "%s" e Contramarca "%s" inexistente.', 16, 1, @IdManifestoMsgXML, @ContramarcaMensagem)	
		ELSE
			IF EXISTS(SELECT 1 FROM PRO_SDSC WITH(NOLOCK) WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSC_RPRD LIKE '%' + @IdMensagem + '%' AND DSC_RPRD LIKE '%' + CONVERT(varchar(23), @DataMsgXML, 121) + '%')
				RAISERROR('Mensagem XML AirWarehouseKeepersReportResponse com ID "%s" já integrada no Relatório de Descarga SDS - Via Aérea com ID "%s" e Contramarca "%s".', 16, 2, @IdMensagem, @IdManifestoMsgXML, @ContramarcaMensagem)	
-- obtem os erros gerais do Relatório de Descarga da mensagem XML		
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @ErrosGerais = ISNULL(@ErrosGerais, ' #Erros Gerais: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
		FROM @ErrosMsgXML.nodes('ns2:Errors/Error') AS f(m)
-- obtem os alertas gerais do Relatório de Descarga da mensagem XML		
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @AlertasGerais = ISNULL(@AlertasGerais, ' #Alertas Gerais: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('WarningDescription[1]', 'varchar(250)')
		FROM @AlertasMsgXML.nodes('ns2:Warnings/Warning') AS f(m)
-- obtem somente a lista de erros e warnings gerais
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @ErrosMsgXML = @ErrosMsgXML.query('ns2:Errors/Error'), @AlertasMsgXML = @AlertasMsgXML.query('ns2:Warnings/Warning')
-- obtem os erros do fim de operação
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @ErrosFimOp = ISNULL(@ErrosFimOp, ' #Erros Fim Operação: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
		FROM @ErrosFimOpXML.nodes('ns2:Errors/Error') AS f(m)		
-- obtem os alertas do fim de operação
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @AlertasFimOp = ISNULL(@AlertasFimOp, ' #Alertas Fim Operação: ') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('WarningDescription[1]', 'varchar(250)')
		FROM @AlertasFimOpXML.nodes('ns2:Warnings/Warning') AS f(m)
-- obtem somente a lista de erros e warnings de fim de operação
		;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
		SELECT @ErrosFimOpXML = @ErrosFimOpXML.query('ns2:Errors/Error'), @AlertasFimOpXML = @AlertasFimOpXML.query('ns2:Warnings/Warning')
-- obtem dados do Relatório de Descarga SDS - Via Aérea
		SELECT @TipoManifesto = DSC_TIPO, @CodEstanciaManifesto = EAD_CODI, @DataVooManifesto = DSC_DTVO, @IdDepositarioManifesto = DSC_IDDP
		FROM PRO_SDSC WITH(NOLOCK) 				
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os documentos de transporte da mensagem XML
		DECLARE LinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT f.m.value('ns2:Action[1]', 'varchar(8)'),
				f.m.value('ns2:Success[1]', 'varchar(8)'), 
				f.m.value('ns2:LocalReferenceNumber[1]', 'varchar(22)'), 								
				f.m.query('ns2:Warnings'), 
				f.m.query('ns2:Errors'), 
				f.m.value('ns2:Justification[1]', 'varchar(512)')
			FROM @DadosDescargaMsgXML.nodes('ns2:UnloadReportResponse') AS f(m)	
		OPEN LinhasAWB
		FETCH NEXT FROM LinhasAWB INTO @AcaoAwbXML, @SucessoAwbXML, @NRLAwbXML, @AlertasAwbXML, @ErrosAwbXML, @JustificacaoAwbXML
		WHILE @@FETCH_STATUS = 0
		BEGIN		
			SET @NumAWBLinhaAWB = NULL	
			SET @ErrosLinhaAWB = NULL		
			SET @AlertasLinhaAWB = NULL	
-- obtem o ID da linha AWB a partir do NRL
			SET @IdLinhaAWB = CAST(RIGHT(@NRLAwbXML, 9)	AS int)
-- obtem número AWB da linha AWB do Relatório de Descarga SDS - Via Aérea
			SELECT @NumAWBLinhaAWB = DSD_NRMH
			FROM PRO_SDSD WITH(NOLOCK) 				
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_IDNN = @IdLinhaAWB
-- verifica se mensagem é válida para o Relatório de Descarga SDS - Via Aérea
			IF (@IdLinhaAWB IS NOT NULL) AND (ISNULL(@NumAWBLinhaAWB, '') = '')
				RAISERROR('Linha AWB com ID "%s" inexistente no Relatórios de Descarga SDS - Via Aérea com ID "%s" e Contramarca "%s".', 16, 3, @NRLAwbXML, @IdManifestoMsgXML, @ContramarcaMensagem)
			ELSE
				IF (@IdLinhaAWB IS NULL) AND (ISNULL(@NumAWBLinhaAWB, '') = '')
					SET @TotalLinhasAWBInvalidas = @TotalLinhasAWBInvalidas + 1
-- obtem os erros da linha AWB
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT @ErrosLinhaAWB = ISNULL(@ErrosLinhaAWB, '#ERROS:') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('ErrorDescription[1]', 'varchar(250)')
			FROM @ErrosAwbXML.nodes('ns2:Errors/Error') AS f(m)		
-- obtem os alertas da linha AWB
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT @AlertasLinhaAWB = ISNULL(@AlertasLinhaAWB, '#ALERTAS:') + CHAR(13) + CHAR(10) + '		. ' + f.m.value('WarningDescription[1]', 'varchar(250)')
			FROM @AlertasAwbXML.nodes('ns2:Warnings/Warning') AS f(m)							
-- atualiza dados da linha AWB
			UPDATE PRO_SDSD SET 
				DSD_SIRD = (CASE @AcaoAwbXML WHEN 'Update' THEN 2 ELSE 1 END),
				DSD_DIRD = @DataAtual, 
				DSD_RIRD = (CASE @SucessoAwbXML WHEN 'No' THEN 2 WHEN 'Pending' THEN 3 ELSE 1 END), 
				DSD_EIRD = NULLIF(ISNULL(@ErrosLinhaAWB + CHAR(13) + CHAR(10), '') + ISNULL(@AlertasLinhaAWB + CHAR(13) + CHAR(10), '') + ISNULL('#JUSTIFICACAO: ' + NULLIF(@JustificacaoAwbXML, ''), ''), '')					
			WHERE DSD_IDNN = @IdLinhaAWB					
-- obtem somente a lista de erros e warnings
			;WITH XMLNAMESPACES ('http://simtem.at.gov.pt/WS/AirWarehouseKeepersReportResponse' AS ns2, DEFAULT 'http://simtem.at.gov.pt/WS/AirWarehouseKeepersTypes')
			SELECT @ErrosAwbXML = @ErrosAwbXML.query('ns2:Errors/Error'), @AlertasAwbXML = @AlertasAwbXML.query('ns2:Warnings/Warning')
-- insere dados do Relatório de Descarga e linha AWB na tabela tmp
			INSERT INTO @TblTmpLinhasAWBIntegradas(MAN_ANO, MAN_NUME, MAN_TIPO, MAN_DVOO, EAD_CODI, MAN_NCTM, MAN_SUCE, MAN_ERRS, MAN_ALRS, AWB_NUME, AWB_ACAO, AWB_SUCE, AWB_ERRS, AWB_ALRS)
			VALUES(@AnoManifesto, @NumManifesto, @TipoManifesto, @DataVooManifesto, @CodEstanciaManifesto, @ContramarcaMensagem, @SucessoMensagem, @ErrosMsgXML, @AlertasMsgXML, @NumAWBLinhaAWB, @AcaoAwbXML, @SucessoAwbXML, @ErrosAwbXML, @AlertasAwbXML)
			FETCH NEXT FROM LinhasAWB INTO  @AcaoAwbXML, @SucessoAwbXML, @NRLAwbXML, @AlertasAwbXML, @ErrosAwbXML, @JustificacaoAwbXML
		END
		CLOSE LinhasAWB
		DEALLOCATE LinhasAWB
-- actualiza dados do Relatório de Descarga SDS
		UPDATE PRO_SDSC SET 
			DSC_STRD = 3, 	
			DSC_UERF = (CASE ISNULL(@SucessoFimOpXML, '') WHEN 'No' THEN NULL ELSE DSC_UERF END), 
			DSC_DERF = (CASE ISNULL(@SucessoFimOpXML, '') WHEN 'No' THEN NULL ELSE DSC_DERF END), 
			DSC_NRRD = DSC_NRRD + 1, 
			DSC_URRD = @Utilizador, 
			DSC_DRRD = @DataAtual, 
			DSC_RPRD = '-> AIR WAREHOUSEKEEPERS REPORT RESPONSE: ' + CHAR(13) + CHAR(10) 
						+ '	#Data Integração: ' + CONVERT(varchar(23), @DataAtual, 121) + CHAR(13) + CHAR(10) 
						+ '	#Utilizador Integração: ' + @Utilizador + CHAR(13) + CHAR(10) 
						+ '	#MessageIdentification: ' + @IdMensagem + CHAR(13) + CHAR(10) 
						+ '	#MessageDate: ' + CONVERT(varchar(23), @DataMsgXML, 121) + CHAR(13) + CHAR(10) 
						+ '	#Sucess: ' + ISNULL(@SucessoMensagem, '<n.d.>') + CHAR(13) + CHAR(10) 
						+ ISNULL(@ErrosGerais + CHAR(13) + CHAR(10), '') 
						+ ISNULL(@AlertasGerais + CHAR(13) + CHAR(10), '') 
						+ (CASE WHEN (ISNULL(@SucessoMensagem, '<n.d.>') = 'No') AND (ISNULL(@ErrosGerais, '') = '') AND (ISNULL(@ErrosFimOp, '') = '') THEN ' #Erros Linhas: ' + CHAR(13) + CHAR(10) + '		. «Verificar erros nas linhas AWB»' + CHAR(13) + CHAR(10) ELSE '' END) 
						+ ISNULL(' #Sucess Fim Operação: ' + NULLIF(@SucessoFimOpXML, '') + CHAR(13) + CHAR(10), '')
						+ ISNULL(' #Justification Fim Operação: ' + NULLIF(@JustificacaoFimOpXML, '') + CHAR(13) + CHAR(10), '') 
						+ ISNULL(@ErrosFimOp + CHAR(13) + CHAR(10), '') 
						+ ISNULL(@AlertasFimOp + CHAR(13) + CHAR(10), '') 						
						+ '===============================================================================================================================' + CHAR(13) + CHAR(10) 
						+ ISNULL(CAST(DSC_RPRD AS varchar(max)), '')						
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- processo atualizações de fim de operação
		IF ISNULL(@SucessoFimOpXML, '') = 'Yes'
		BEGIN
-- atualiza status das linhas AWB para "Respondido Finalize" e atribui estado "FIN" (Finalizado) quando tem respetivamente o status como "Enviado Create/Update/Delete" e a integração diferente de "Não respondido" com resultado de integração atribuído
			UPDATE PRO_SDSD SET 
				DSD_SIRD = 3,
				DSD_ESTA = (CASE DSD_RIRD WHEN 1 THEN 'FIN' ELSE DSD_ESTA END)
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_EADC <> 'C' AND DSD_TIPO <> 'TR' AND DSD_DEPO = @IdDepositarioManifesto AND DSD_ENVI = 1 
				AND DSD_STRD > 0 AND DSD_SIRD > 0 AND DSD_RIRD IS NOT NULL
		END
		ELSE
-- atualiza status das linhas AWB para "Respondido Create/Update" quando tem respetivamente o status como "Enviado Create/Update/Delete" e não houve sucesso nas linhas AWB integradas (normalmente devido à ocorrencia de erros gerais e/ou erros de schema [que vem descriminados nas linhas AWB mas sem quaisquer informação da AWB])
			IF (ISNULL(@SucessoFimOpXML, '') = '') AND ((@TotalLinhasAWBInvalidas > 0) OR ((@TotalLinhasAWBInvalidas = 0) AND (NOT EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas))))
			BEGIN
				UPDATE PRO_SDSD SET 
					DSD_SIRD = (CASE DSD_STRD WHEN 1 THEN 1 ELSE 2 END), 					
					DSD_RIRD = 2					
				WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto AND DSD_EADC <> 'C' AND DSD_TIPO <> 'TR' AND DSD_DEPO = @IdDepositarioManifesto AND DSD_ENVI = 1 
					AND DSD_STRD > 0 AND DSD_SIRD = 0 AND DSD_RIRD IS NULL
			END
-- insere dados do Relatório de Descarga e fim de operação na tabela tmp
		IF (ISNULL(@SucessoFimOpXML, '') <> '') OR ((@TotalLinhasAWBInvalidas = 0) AND (NOT EXISTS(SELECT 1 FROM @TblTmpLinhasAWBIntegradas)))
		BEGIN
			INSERT INTO @TblTmpLinhasAWBIntegradas(MAN_ANO, MAN_NUME, MAN_TIPO, MAN_DVOO, EAD_CODI, MAN_NCTM, MAN_SUCE, MAN_ERRS, MAN_ALRS, AWB_NUME, AWB_ACAO, AWB_SUCE, AWB_ERRS, AWB_ALRS)
			VALUES(@AnoManifesto, @NumManifesto, @TipoManifesto, @DataVooManifesto, @CodEstanciaManifesto, @ContramarcaMensagem, @SucessoMensagem, @ErrosMsgXML, @AlertasMsgXML, NULL, (CASE WHEN ISNULL(@SucessoFimOpXML, '') <> '' THEN 'Finalize' ELSE NULL END), @SucessoFimOpXML, @ErrosFimOpXML, @AlertasFimOpXML)
		END
-- constroi XML com as linhas AWB integradas no Relatório de Descarga SDS - Via Aérea
		SET @AWBIntegradasXML = 
			(SELECT 				
				MAN_ANO AS "AnoManifesto",		
				MAN_NUME AS "NumManifesto", 
				MAN_TIPO AS "TipoManifesto",
				MAN_DVOO AS "DataVooManifesto",
				EAD_CODI AS "EstanciaManifesto", 
				MAN_NCTM AS "ContramarcaManifesto", 				
				MAN_SUCE AS "SucessoManifesto", 
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(MAN_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosManifesto",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(MAN_ALRS AS varchar(MAX)), '') AS xml)) AS "AlertasManifesto",
				AWB_NUME AS "NumeroAWB",
				AWB_ACAO AS "AcaoAWB",
				AWB_SUCE AS "SucessoAWB",				
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(AWB_ERRS AS varchar(MAX)), '') AS xml)) AS "ErrosAWB",
				CONVERT(varbinary(MAX), CAST(NULLIF(CAST(AWB_ALRS AS varchar(MAX)), '') AS xml)) AS "AlertasAWB"
			FROM @TblTmpLinhasAWBIntegradas	
			FOR XML PATH('AWB'), ELEMENTS)
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION tSDSIntMsgAirWarehouseResponse
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION tSDSIntMsgAirWarehouseResponse
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersReportResponse] TO  SCHEMA OWNER 
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagensObtemEstadoAtual]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagensObtemEstadoAtual] @AnoManifesto int, @NumManifesto int, @IdUtilizador int, @MsgEstado varchar(MAX) OUTPUT, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), 
		@ProxyPassword varchar(100), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), @IdTransitario varchar(20), @PathCertificado varchar(250), @PwdCertificado varchar(100), 
		@IdRepresentante varchar(20), @NumContramarca varchar(14), @MensagemSoapAction varchar(250), @PublicKeyCertificadoAT nvarchar(4000), @PwdWSEncriptada nvarchar(4000), 
		@PwdDigestWSEncriptada nvarchar(4000), @DataSistema nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), @RequestXML xml, @Resultado int, @ResponseXML xml, @FaultCode varchar(100), 
		@FaultMessage varchar(MAX), @CodigoEstado varchar(3)
-- inicia processo de obtenção de respostas da declaração
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações do Proxy Authentication nos Parâmetros da Aplicação
		SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), @ProxyPassword = ISNULL(PAP_PPWD, '')		
		FROM TAB_PAPL WITH(NOLOCK)
-- obtem configurações do Webservice nos Parâmetros de SDS - Via Aérea
		SELECT @IdTransitario = PSD_ITSP, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC, @EnderecoWS = PSD_WSTR, @LoginWS = PSD_UTTR, @PwdWS = PSD_PWTR			      
		FROM TAB_PSDS WITH(NOLOCK) 	
-- obtem a chave pública do sistema de autenticação na AT em função se o request é para ambiente de testes ou não (porta 821 = Ambiente de Testes)
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT((CASE WHEN CHARINDEX(':821', @EnderecoWS) > 0 THEN 1 ELSE 0 END))				
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- obtem dados do manifesto
		SELECT @IdRepresentante = DSC_IDRP, @NumContramarca = (DSC_NCMF + DSC_NCMV)
		FROM PRO_SDSC WITH(NOLOCK)
		WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- valida dados do manifesto		
		IF (ISNULL(@IdRepresentante, '') = '') OR (ISNULL(@NumContramarca, '') = '')
			RAISERROR('Manifesto SDS - Via Aérea "%d"/"%d" inválido.', 16, 2, @AnoManifesto, @NumManifesto)								
-- define o SoapAction
		SET @MensagemSoapAction = ''
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
		EXEC GIDWIN.dbo.SP_Externo_GerarDigestSecurityHeader @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @PwdDigestWSEncriptada OUTPUT, @DataSistema OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido ao metodo para enviar mensagem à AT
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://simtem.at.gov.pt/WS/AirTraders' AS air, 'http://www.w3.org/2003/05/soap-envelope' AS soap)		
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT
						(SELECT 
							@LoginWS AS "wss:Username", 
							@ChvSimetricaEncriptada AS "wss:Nonce",
							(SELECT @PwdDigestWSEncriptada AS "@Digest", 
								@PwdWSEncriptada	
							FOR XML PATH('wss:Password'), ELEMENTS, TYPE),							 							
							@DataSistema AS "wss:Created"
						FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soap:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT 
						@IdRepresentante AS "air:requester", 
						@NumContramarca AS "air:customsReferenceNumber"						
					FOR XML PATH('air:getMeansOfTransportProcessStateRequest'), TYPE)
				FOR XML PATH('soap:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soap:Envelope'), ELEMENTS)		
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT		
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)				
-- obtem o resultado "OK"/"NOK" retornados do WS
		;WITH XMLNAMESPACES ('http://www.w3.org/2003/05/soap-envelope' AS env, 'http://simtem.at.gov.pt/WS/AirTraders' AS ns2)		
		SELECT 
			@CodigoEstado = t.c.value('ns2:state[1]', 'nvarchar(3)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/ns2:getMeansOfTransportProcessStateResponse') AS t(c)				
-- se resultado não for de sucesso, manda erro
		IF ISNULL(@CodigoEstado, '') = ''
			RAISERROR('Não foi possível obter o estado atual da contramarca "%s".', 16, 4, @NumContramarca)	
-- Constroi a mensagem do estado atual da contramarca
		SET @MsgEstado = 'ESTADO DA CONTRAMARCA:' + CHAR(13) + CHAR(10)		
        SET @MsgEstado = @MsgEstado + '   .Código do Estado Atual:    ' + ISNULL(NULLIF(@CodigoEstado, ''), 'n.d.') + CHAR(13) + CHAR(10)        
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagensObtemEstadoAtual] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagensObtemEstadoAtual] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagensObtemRespostas]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagensObtemRespostas] @Depositarios bit, @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @Resultado int, @IdIntegracao int
	DECLARE @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), @ProxyPassword varchar(100)
	DECLARE @IdTransitario varchar(20), @PathCertificado varchar(250), @PwdCertificado varchar(100), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100)
	DECLARE @PublicKeyCertificadoAT nvarchar(4000), @MensagemSoapAction varchar(250), @PwdWSEncriptada nvarchar(4000), @PwdDigestWSEncriptada nvarchar(4000), @DataSistema nvarchar(4000), 
		@ChvSimetricaEncriptada nvarchar(4000)
	DECLARE @RequestXML xml, @ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX), @IdsRequestXML xml, @MensagensXML xml, @MensagemXMLBase64 varchar(MAX), @MensagemXML xml, 
		@RootMensagemXML varchar(50), @IdMensagemXML varchar(50), @SucessoMensagemXML varchar(10), @ContramarcaMensagemXML varchar(14), @TipoNotificacaoMensagemXML int, @AWBIntegradasXML xml, 
		@ErroIntegracao varchar(MAX), @AnoManifesto int, @NumeroManifesto int	
	DECLARE @TblTmpResumoIntegracao TABLE(id int NOT NULL IDENTITY(1, 1), idMensagemXML varchar(50) NOT NULL, tipoMensagemXML varchar(50) NOT NULL, integracaoXML xml NOT NULL)
-- inicia processo de obtenção de respostas do webservice SiMTeM
	BEGIN TRY	
		SET @NumErro = 0	
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações do Proxy Authentication nos Parâmetros da Aplicação
		SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), @ProxyPassword = ISNULL(PAP_PPWD, '')		
		FROM TAB_PAPL WITH(NOLOCK)
-- obtem configurações do Webservice nos Parâmetros de SDS - Via Aérea
		SELECT @IdTransitario = PSD_ITSP, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC, 
			@EnderecoWS = (CASE @Depositarios WHEN 0 THEN PSD_WSTR ELSE PSD_WEBS END), 
			@LoginWS = (CASE @Depositarios WHEN 0 THEN PSD_UTTR ELSE PSD_UTIL END), 
			@PwdWS = (CASE @Depositarios WHEN 0 THEN PSD_PWTR ELSE PSD_PASS END)			      
		FROM TAB_PSDS WITH(NOLOCK) 	
-- obtem a chave pública do sistema de autenticação na AT em função se o request é para ambiente de testes ou não (porta 821 = Ambiente de Testes)
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT((CASE WHEN CHARINDEX(':821', @EnderecoWS) > 0 THEN 1 ELSE 0 END))
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- assume o soap action
		SET @MensagemSoapAction = ''
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS		
		EXEC GIDWIN.dbo.SP_Externo_GerarDigestSecurityHeader @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @PwdDigestWSEncriptada OUTPUT, @DataSistema OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido ao metodo para enviar mensagem à AT		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://simtem.at.gov.pt/WS/AirTraders' AS air, 'http://www.w3.org/2003/05/soap-envelope' AS soap)	
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT
						(SELECT 
							@LoginWS AS "wss:Username", 
							@ChvSimetricaEncriptada AS "wss:Nonce",
							(SELECT @PwdDigestWSEncriptada AS "@Digest", 
								@PwdWSEncriptada	
							FOR XML PATH('wss:Password'), ELEMENTS, TYPE),							 							
							@DataSistema AS "wss:Created"
						FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soap:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT 
						@IdTransitario AS "air:receiver"						
					FOR XML PATH('air:retrieveNewOutputMessagesIdsRequest'), TYPE)
				FOR XML PATH('soap:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soap:Envelope'), ELEMENTS)				
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)	
-- obtem o resultado com a lista de IDs Request
		;WITH XMLNAMESPACES ('http://www.w3.org/2003/05/soap-envelope' AS env, 'http://simtem.at.gov.pt/WS/AirTraders' AS ns2)		
		SELECT 
			@IdsRequestXML = t.c.query('ns2:return')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/ns2:retrieveNewOutputMessagesIdsResponse') AS t(c)	
-- remove referência ao namespace ns2 existente
		SET @IdsRequestXML = CAST(REPLACE(REPLACE(CAST(@IdsRequestXML AS varchar(MAX)), 'ns2:', ''), ' xmlns:ns2="http://simtem.at.gov.pt/WS/AirTraders"', '') AS xml)						
-- processa obtenção das mensagens XML para os IDs Request de resposta obtidos
		IF EXISTS(SELECT 1 FROM @IdsRequestXML.nodes('return') AS t(c))
		BEGIN
			SET @ResponseXML = NULL
-- obtem data atual GMT
			SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- insere os IDs Request na tabela de Histórico de Integrações WS SDS - Via Aérea			
			SET @IdIntegracao = (ISNULL((SELECT MAX(DSI_CODI) FROM HST_SDSI), 0) + 1)		
			INSERT INTO HST_SDSI(DSI_CODI, DSI_DATA, DSI_MSGI, DSI_MSGD, DSI_STAT, DSI_DTST)
			SELECT @IdIntegracao, @DataAtual, t.c.value('.[1]', 'varchar(100)'), t.c.query('.'), 0, @DataAtual
			FROM @IdsRequestXML.nodes('return') AS t(c)	
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
			EXEC GIDWIN.dbo.SP_Externo_GerarDigestSecurityHeader @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @PwdDigestWSEncriptada OUTPUT, @DataSistema OUTPUT, @ChvSimetricaEncriptada OUTPUT			
-- constroi estrutura XML com os dados do pedido ao metodo para enviar mensagem à AT
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://simtem.at.gov.pt/WS/AirTraders' AS air, 'http://www.w3.org/2003/05/soap-envelope' AS soap)				
			SELECT @RequestXML = 
				(SELECT 
					(SELECT 
						(SELECT
							(SELECT 
								@LoginWS AS "wss:Username", 
								@ChvSimetricaEncriptada AS "wss:Nonce",
								(SELECT @PwdDigestWSEncriptada AS "@Digest", 
									@PwdWSEncriptada	
								FOR XML PATH('wss:Password'), ELEMENTS, TYPE),							 							
								@DataSistema AS "wss:Created"
							FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
						FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
					FOR XML PATH('soap:Header'), ELEMENTS, TYPE),
					(SELECT
						(SELECT 
							@IdTransitario AS "air:receiver",
							(SELECT 
								t.c.value('.[1]', 'varchar(100)')				
							FROM @IdsRequestXML.nodes('return') AS t(c)			
							FOR XML PATH('air:outputMessagesIds'), TYPE)
						FOR XML PATH('air:retrieveOutputMessagesByIdsRequest'), TYPE)
					FOR XML PATH('soap:Body'), ELEMENTS, TYPE)
				FOR XML PATH('soap:Envelope'), ELEMENTS)				
-- processa envio do XML para o WebService da AT	
			EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 4, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
			;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
			SELECT 
				@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
				@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
			IF ISNULL(@FaultMessage, '') <> ''
				RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 5, @FaultMessage)	
-- obtem o resultado com a lista de mensagens XML
			;WITH XMLNAMESPACES ('http://www.w3.org/2003/05/soap-envelope' AS env, 'http://simtem.at.gov.pt/WS/AirTraders' AS ns2)		
			SELECT 
				@MensagensXML = t.c.query('ns2:return')
			FROM @ResponseXML.nodes('env:Envelope/env:Body/ns2:retrieveOutputMessagesByIdsResponse') AS t(c)
-- remove referência ao namespace ns2 existente
			SET @MensagensXML = CAST(REPLACE(REPLACE(CAST(@MensagensXML AS varchar(MAX)), 'ns2:', ''), ' xmlns:ns2="http://simtem.at.gov.pt/WS/AirTraders"', '') AS xml)				
-- obtem todos as mensagens XML de resposta
			DECLARE MensagensXML CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
				SELECT 					
					t.c.value('.[1]', 'varchar(MAX)')
				FROM @MensagensXML.nodes('return') AS t(c)
			OPEN MensagensXML
			FETCH NEXT FROM MensagensXML INTO @MensagemXMLBase64
			WHILE @@FETCH_STATUS = 0
			BEGIN  
				SET @RootMensagemXML = NULL
				SET @IdMensagemXML = NULL
				SET @SucessoMensagemXML = NULL
				SET @ContramarcaMensagemXML = NULL
				SET @AnoManifesto = NULL
				SET @NumeroManifesto = NULL
				SET @AWBIntegradasXML = NULL 
				SET @ErroIntegracao = NULL
				SET @Resultado = 0				
-- converte o Base64 para varbinary e depois para xml
				SET @MensagemXML = CAST('' AS XML).value('xs:base64Binary(sql:variable("@MensagemXMLBase64"))', 'varbinary(max)')
-- obtem da mensagem xml o nome do elemento root como tipo da mensagem obtida
				SELECT @RootMensagemXML = t.c.value('local-name(.)', 'varchar(50)')
				FROM @MensagemXML.nodes('*') AS t(c)					
-- atualiza manifesto em função da mensagem de resposta obtida								
				IF @RootMensagemXML = 'AirTransportStatus'
					EXEC @Resultado = sp_SDSViaAerea_Manifestos_MensagemIntegraAirTransportStatus @MensagemXML, @CodUtilizador, @IdMensagemXML OUTPUT, @SucessoMensagemXML OUTPUT, @ContramarcaMensagemXML OUTPUT, @AnoManifesto OUTPUT, @NumeroManifesto OUTPUT, @AWBIntegradasXML OUTPUT, @ErroIntegracao OUTPUT				
				ELSE
				IF @RootMensagemXML = 'AirManifestResponse'
					EXEC @Resultado = sp_SDSViaAerea_Manifestos_MensagemIntegraAirManifestResponse @MensagemXML, @CodUtilizador, @IdMensagemXML OUTPUT, @SucessoMensagemXML OUTPUT, @ContramarcaMensagemXML OUTPUT, @AnoManifesto OUTPUT, @NumeroManifesto OUTPUT, @AWBIntegradasXML OUTPUT, @ErroIntegracao OUTPUT					
				ELSE				
				IF @RootMensagemXML = 'AirWarehouseKeepersReportResponse'
					EXEC @Resultado = sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersReportResponse @MensagemXML, @CodUtilizador, @IdMensagemXML OUTPUT, @SucessoMensagemXML OUTPUT, @ContramarcaMensagemXML OUTPUT, @AnoManifesto OUTPUT, @NumeroManifesto OUTPUT, @AWBIntegradasXML OUTPUT, @ErroIntegracao OUTPUT				
				ELSE				
				IF @RootMensagemXML = 'AirWarehouseKeepersNotification'
					EXEC @Resultado = sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersNotification @MensagemXML, @CodUtilizador, @TipoNotificacaoMensagemXML OUTPUT, @IdMensagemXML OUTPUT, @SucessoMensagemXML OUTPUT, @ContramarcaMensagemXML OUTPUT, @AnoManifesto OUTPUT, @NumeroManifesto OUTPUT, @AWBIntegradasXML OUTPUT, @ErroIntegracao OUTPUT
				ELSE
				IF @RootMensagemXML = 'AirWarehouseKeepersMovementResponse'
					EXEC @Resultado = sp_SDSViaAerea_Manifestos_MensagemIntegraAirWarehouseKeepersMovementResponse @MensagemXML, @CodUtilizador, @IdMensagemXML OUTPUT, @SucessoMensagemXML OUTPUT, @ContramarcaMensagemXML OUTPUT, @AnoManifesto OUTPUT, @NumeroManifesto OUTPUT, @AWBIntegradasXML OUTPUT, @ErroIntegracao OUTPUT				
				ELSE
				BEGIN
					SET @Resultado = 9999
					SET @ErroIntegracao = ('Mensagem XML "' + @RootMensagemXML + '" desconhecida.')
				END
-- atualiza dados do ID Request na tabela de Histórico de Integrações WS SDS - Via Aérea	
				UPDATE HST_SDSI SET 
					DSI_MSGD = @MensagemXML, 
					DSI_STAT = (CASE WHEN (@Resultado <> 0) THEN 2 ELSE 1 END), 
					DSI_DTST = @DataAtual, 
					DSI_TMSG = (CASE @RootMensagemXML 
									WHEN 'AirManifestResponse' THEN 4 
									WHEN 'AirTransportStatus' THEN 5 
									WHEN 'AirWarehouseKeepersReportResponse' THEN 1 
									WHEN 'AirWarehouseKeepersNotification' THEN @TipoNotificacaoMensagemXML
									WHEN 'AirWarehouseKeepersMovementResponse' THEN 1
									ELSE NULL 								
							END), 
					DSI_RDES = (CASE @RootMensagemXML WHEN 'AirWarehouseKeepersReportResponse' THEN 1 ELSE 0 END),
					DSI_NCTM = @ContramarcaMensagemXML, 
					DSI_RESG = @SucessoMensagemXML, 
					DSC_EANO = @AnoManifesto, 
					DSC_NPRO = @NumeroManifesto
				WHERE DSI_CODI = @IdIntegracao AND DSI_MSGI = @IdMensagemXML		
-- insere dados da integração da mensagem XML na tabela tmp
				IF @AWBIntegradasXML IS NOT NULL
				BEGIN
					INSERT INTO @TblTmpResumoIntegracao(idMensagemXML, tipoMensagemXML, integracaoXML)
					VALUES(@IdMensagemXML, @RootMensagemXML, @AWBIntegradasXML)
				END
-- valida a integração da mensagem XML 
				IF @Resultado <> 0
					RAISERROR('Mensagem XML relativa ao ID "%s" gerou o seguinte erro "%s".', 16, 6, @IdMensagemXML, @ErroIntegracao)	
				FETCH NEXT FROM MensagensXML INTO @MensagemXMLBase64
			END
			CLOSE MensagensXML
			DEALLOCATE MensagensXML		
		END
	END TRY
	BEGIN CATCH		
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH	
-- devolve todos os dados das AWB integradas de todas as mensagens XML obtidas
	SELECT ROW_NUMBER() OVER(ORDER BY tri.id) AS id, tri.idMensagemXML, tri.tipoMensagemXML, 
		i.a.value('AnoManifesto[1]', 'smallint') AS anoManifesto, 
		i.a.value('NumManifesto[1]', 'int') AS numManifesto, 
		i.a.value('TipoManifesto[1]', 'tinyint') AS tipoManifesto, 
		i.a.value('DataVooManifesto[1]', 'datetime') AS dataVooManifesto, 
		i.a.value('EstanciaManifesto[1]', 'varchar(8)') AS estanciaManifesto, 
		i.a.value('ContramarcaManifesto[1]', 'varchar(14)') AS contramarcaManifesto, 
		i.a.value('EstadoManifesto[1]', 'varchar(15)') AS estadoManifesto, 
		i.a.value('SucessoManifesto[1]', 'varchar(10)') AS sucessoManifesto, 
		CAST(i.a.value('ErrosManifesto[1]', 'varbinary(MAX)') AS xml) AS errosManifesto, 
		CAST(i.a.value('AlertasManifesto[1]', 'varbinary(MAX)') AS xml) AS alertasManifesto,
		i.a.value('NumeroAWB[1]', 'varchar(30)') AS numeroAWB, 
		i.a.value('AcaoAWB[1]', 'varchar(8)') AS acaoAWB, 
		i.a.value('SucessoAWB[1]', 'varchar(8)') AS sucessoAWB, 
		i.a.value('NumMRNAWB[1]', 'varchar(18)') AS numMRNAWB, 
		i.a.value('NumDGAAWB[1]', 'varchar(29)') AS numDGAAWB, 
		CAST(i.a.value('ErrosAWB[1]', 'varbinary(MAX)') AS xml) AS errosAWB, 
		CAST(i.a.value('AlertasAWB[1]', 'varbinary(MAX)') AS xml) AS alertasAWB	
	FROM @TblTmpResumoIntegracao AS tri
		CROSS APPLY tri.integracaoXML.nodes('AWB') AS i(a)
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagensObtemRespostas] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagensObtemRespostas] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_MensagensSubmetePedido]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_MensagensSubmetePedido] @TipoMensagem varchar(50), @AcaoMensagem varchar(10), @AnoManifesto int, @NumManifesto int, @SoFranquias bit, 
	@SoCriacao bit, @TipoCarga varchar(3), @CodEstancia varchar(8), @IdUtilizador int, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int, @DataAtual datetime, @CodUtilizador varchar(30), @ProxyAuthentication bit, @ProxyServer varchar(100), @ProxyPort int, @ProxyUser varchar(100), 
		@ProxyPassword varchar(100), @EnderecoWS varchar(250), @LoginWS varchar(50), @PwdWS varchar(100), @IdTransitario varchar(20), @PathCertificado varchar(250), @PwdCertificado varchar(100), 
		@MensagemSoapAction varchar(250), @MensagemXML xml, @MensagemTXT varchar(MAX), @MensagemXMLBinario varbinary(MAX), @MensagemXMLBase64 varchar(MAX), @PublicKeyCertificadoAT nvarchar(4000), 
		@PwdWSEncriptada nvarchar(4000), @PwdDigestWSEncriptada nvarchar(4000), @DataSistema nvarchar(4000), @ChvSimetricaEncriptada nvarchar(4000), @RequestXML xml, @Resultado int, 
		@ResponseXML xml, @FaultCode varchar(100), @FaultMessage varchar(MAX)
-- inicia processo de submissão de pedido da declaração
	BEGIN TRY	
		SET @NumErro = 0
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem utilizador
		SELECT @CodUtilizador = UTI_UTIL
		FROM GIDWIN.dbo.FAP_UTIL WITH(NOLOCK)
		WHERE UTI_IDTY = @IdUtilizador
-- obtem configurações do Proxy Authentication nos Parâmetros da Aplicação
		SELECT @ProxyAuthentication = PAP_PAUT, @ProxyServer = ISNULL(PAP_PSRV, ''), @ProxyPort = ISNULL(PAP_PPRT, 0), @ProxyUser = ISNULL(PAP_PUSE, ''), @ProxyPassword = ISNULL(PAP_PPWD, '')		
		FROM TAB_PAPL WITH(NOLOCK)
-- obtem configurações do Webservice nos Parâmetros de SDS - Via Aérea
		SELECT @IdTransitario = PSD_ITSP, @PathCertificado = PSD_PATC, @PwdCertificado = PSD_PWDC, 
			@EnderecoWS = (CASE WHEN @TipoMensagem IN ('AirManifestInformation', 'AirTransportInformation') THEN PSD_WSTR ELSE PSD_WEBS END), 
			@LoginWS = (CASE WHEN @TipoMensagem IN ('AirManifestInformation', 'AirTransportInformation') THEN PSD_UTTR ELSE PSD_UTIL END), 
			@PwdWS = (CASE WHEN @TipoMensagem IN ('AirManifestInformation', 'AirTransportInformation') THEN PSD_PWTR ELSE PSD_PASS END)			      
		FROM TAB_PSDS WITH(NOLOCK) 	
-- obtem a chave pública do sistema de autenticação na AT em função se o request é para ambiente de testes ou não (porta 821 = Ambiente de Testes)
		SET @PublicKeyCertificadoAT = GIDWIN.dbo.fn_Geral_ChavePublicaRSAWebservicesAT((CASE WHEN CHARINDEX(':821', @EnderecoWS) > 0 THEN 1 ELSE 0 END))				
-- valida se o path p/ o certificado é válido
		EXEC master.dbo.xp_fileexist @PathCertificado, @Resultado OUTPUT
		IF @Resultado = 0
			RAISERROR('Ficheiro do certificado não encontrado em "%s".', 16, 1, @PathCertificado)	
-- constroi o XML de acordo com o tipo de mensagem
		SET @MensagemSoapAction = ''
		IF @TipoMensagem = 'AirTransportInformation' -- Criação/Alteração/Anulação da contramarca SDS-Via Aérea
			EXEC sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirTransportInformation @AnoManifesto, @NumManifesto, @AcaoMensagem, @MensagemXML OUTPUT
		ELSE
		IF @TipoMensagem = 'AirManifestInformation' -- Criação do manifesto SDS-Via Aérea
			EXEC sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirManifestInformation @AnoManifesto, @NumManifesto, @SoFranquias, @MensagemXML OUTPUT		
		ELSE
		IF @TipoMensagem = 'AirWarehouseKeepersReportInformation' -- Criação do relatório descarga SDS-Via Aérea
			EXEC sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersReportInformation @AnoManifesto, @NumManifesto, @SoCriacao, @TipoCarga, @MensagemXML OUTPUT
		ELSE
		IF @TipoMensagem = 'AirWarehouseKeepersMovementInformation' -- Criação do movimento de saída SDS-Via Aérea
			EXEC sp_SDSViaAerea_Manifestos_MensagemGeraXMLAirWarehouseKeepersMovementInformation @CodEstancia, @MensagemXML OUTPUT
-- converte o XML gerado para varbinary e depois para Base64
		SET @MensagemTXT = '<?xml version="1.0" encoding="UTF-8"?>' + CAST(@MensagemXML AS varchar(MAX))
		SET @MensagemXMLBinario = CONVERT(varbinary(MAX), @MensagemTXT)
		/* POR ENQUANTO A COMPRESSÃO ZIP DAS MENSAGENS XML FICA EM STAND-BY
		IF @TipoMensagem = 'AirTransportInformation' -- Criação/Alteração/Anulação da contramarca SDS-Via Aérea
			SET @MensagemXMLBinario = CONVERT(varbinary(MAX), @MensagemTXT) 		
		ELSE
			EXEC GIDWIN.dbo.SP_Externo_ComprimirXMLEmBinario @MensagemTXT, @MensagemXMLBinario OUTPUT*/
		SET @MensagemXMLBase64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@MensagemXMLBinario"))', 'varchar(MAX)') 
-- encripta password acesso à AT, Nounce e Data de Criação de acordo com o standard WS-Security da OASIS
		EXEC GIDWIN.dbo.SP_Externo_GerarDigestSecurityHeader @PwdWS, @PublicKeyCertificadoAT, @PwdWSEncriptada OUTPUT, @PwdDigestWSEncriptada OUTPUT, @DataSistema OUTPUT, @ChvSimetricaEncriptada OUTPUT
-- constroi estrutura XML com os dados do pedido ao metodo para enviar mensagem à AT
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/ws/2002/12/secext' AS wss, 'http://simtem.at.gov.pt/WS/AirTraders' AS air, 'http://www.w3.org/2003/05/soap-envelope' AS soap)		
		SELECT @RequestXML = 
			(SELECT 
				(SELECT 
					(SELECT
						(SELECT 
							@LoginWS AS "wss:Username", 
							@ChvSimetricaEncriptada AS "wss:Nonce",
							(SELECT @PwdDigestWSEncriptada AS "@Digest", 
								@PwdWSEncriptada	
							FOR XML PATH('wss:Password'), ELEMENTS, TYPE),							 							
							@DataSistema AS "wss:Created"
						FOR XML PATH('wss:UsernameToken'), ELEMENTS, TYPE)
					FOR XML PATH('wss:Security'), ELEMENTS, TYPE)
				FOR XML PATH('soap:Header'), ELEMENTS, TYPE),
				(SELECT
					(SELECT 
						@IdTransitario AS "air:sender", 
						@MensagemXMLBase64 AS "air:messages"						
					FOR XML PATH('air:submitMessagesRequest'), TYPE)
				FOR XML PATH('soap:Body'), ELEMENTS, TYPE)
			FOR XML PATH('soap:Envelope'), ELEMENTS)		
-- processa envio do XML para o WebService da AT	
		EXEC GIDWIN.dbo.SP_Externo_EnviarDadosWS @RequestXML, @EnderecoWS, @MensagemSoapAction, @PathCertificado, @PwdCertificado, @ProxyAuthentication, @ProxyServer, @ProxyPort, @ProxyUser, @ProxyPassword, @ResponseXML OUTPUT
-- valida se ocorreu erro na invocação do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS "SOAP-ENV")
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('Comunicação ao webservice falhou c/ erro "%s".', 16, 2, @FaultMessage)	
-- valida se ocorreu erro na autenticação/autorização do webservice		
		;WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' AS env)
		SELECT 
			@FaultCode = t.c.value('faultcode[1]', 'nvarchar(100)'), 
			@FaultMessage = t.c.value('faultstring[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/env:Fault') AS t(c)
		IF ISNULL(@FaultMessage, '') <> ''
			RAISERROR('A autenticação/autorização ao webservice gerou o erro "%s".', 16, 3, @FaultMessage)				
-- obtem o resultado "OK"/"NOK" retornados do WS
		;WITH XMLNAMESPACES ('http://www.w3.org/2003/05/soap-envelope' AS env, 'http://simtem.at.gov.pt/WS/AirTraders' AS ns2)		
		SELECT TOP 1 			
			@FaultMessage = t.c.value('.[1]', 'nvarchar(MAX)')
		FROM @ResponseXML.nodes('env:Envelope/env:Body/ns2:submitMessagesResponse/ns2:return') AS t(c)				
-- se resultado não for de sucesso, manda erro
		IF @FaultMessage <> 'OK'
			RAISERROR('O envio da mensagem gerou o erro "%s".', 16, 4, @FaultMessage)	
-- processa atualizações no manifesto e linhas AWB conforme tipo de mensagem
		IF @TipoMensagem = 'AirTransportInformation' -- Criação/Alteração/Anulação da contramarca SDS-Via Aérea
		BEGIN
			UPDATE PRO_SDSC SET 
				DSC_STCM = (CASE @AcaoMensagem WHEN 'Create' THEN 10 WHEN 'Update' THEN 20 WHEN 'Annul' THEN 30 ELSE 0 END),
				DSC_UCCM = (CASE @AcaoMensagem WHEN 'Create' THEN @CodUtilizador ELSE DSC_UCCM END),
				DSC_DCCM = (CASE @AcaoMensagem WHEN 'Create' THEN @DataAtual ELSE DSC_DCCM END),
				DSC_UUCM = (CASE @AcaoMensagem WHEN 'Update' THEN @CodUtilizador ELSE DSC_UUCM END),
				DSC_DUCM = (CASE @AcaoMensagem WHEN 'Update' THEN @DataAtual ELSE DSC_DUCM END),
				DSC_UACM = (CASE @AcaoMensagem WHEN 'Annul' THEN @CodUtilizador ELSE DSC_UACM END),
				DSC_DACM = (CASE @AcaoMensagem WHEN 'Annul' THEN @DataAtual ELSE DSC_DACM END), 
				DSC_UALT = @CodUtilizador,
				DSC_DALT = @DataAtual
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto			
		END
		ELSE
		IF @TipoMensagem = 'AirManifestInformation' -- Criação do manifesto SDS-Via Aérea
		BEGIN
-- atualiza estado interno de envio conforme acção de cada linha AWB
			UPDATE PRO_SDSD SET 
				DSD_STAT = (CASE DSD_ESTI WHEN 1 THEN 1 WHEN 2 THEN 4 WHEN 3 THEN 7 ELSE 0 END),
				DSD_DERR = NULL, 
				DSD_JUST = NULL, 
				DSD_EFRQ = (CASE @SoFranquias WHEN 1 THEN 1 ELSE DSD_EFRQ END)					
			FROM VW_SDSViaAerea_EnvioManifestoDadosAWBPendentes AS SDSVA_EMDAWBP
			WHERE PRO_SDSD.DSC_EANO = SDSVA_EMDAWBP.DSC_EANO AND PRO_SDSD.DSC_NPRO = SDSVA_EMDAWBP.DSC_NPRO AND PRO_SDSD.DSD_NUME = SDSVA_EMDAWBP.DSD_NUME AND PRO_SDSD.DSC_EANO = @AnoManifesto 
				AND PRO_SDSD.DSC_NPRO = @NumManifesto AND (CASE @SoFranquias WHEN 1 THEN ISNULL(SDSVA_EMDAWBP.DSD_AFRQ, -1) ELSE 0 END) <> -1					
-- atualiza manifesto SDS - Via Aérea p/ incremento do n.º submissões e utilizador/data
			IF @SoFranquias = 0
			BEGIN
				UPDATE PRO_SDSC SET 
					DSC_NREM = DSC_NREM + 1,
					DSC_UDEM = @DataAtual, 
					DSC_UALT = @CodUtilizador,
					DSC_DALT = @DataAtual
				WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
			END		
		END
		ELSE
		IF @TipoMensagem = 'AirWarehouseKeepersReportInformation' -- Criação do relatório descarga SDS-Via Aérea
		BEGIN
-- atualiza processo SDS - Via Aérea p/ alteração do status e utilizador/data
			UPDATE PRO_SDSC SET 
				DSC_STRD = (CASE @SoCriacao WHEN 1 THEN 1 ELSE 2 END), 
				DSC_NRER = DSC_NRER + 1,
				DSC_UERC = (CASE @SoCriacao WHEN 1 THEN @CodUtilizador ELSE DSC_UERC END), 
				DSC_DERC = (CASE @SoCriacao WHEN 1 THEN @DataAtual ELSE DSC_DERC END),
				DSC_UERF = (CASE @SoCriacao WHEN 1 THEN DSC_UERF ELSE @CodUtilizador END), 
				DSC_DERF = (CASE @SoCriacao WHEN 1 THEN DSC_DERF ELSE @DataAtual END)	
			WHERE DSC_EANO = @AnoManifesto AND DSC_NPRO = @NumManifesto
-- atualiza linhas AWB do processo SDS - Via Aérea p/ alteração do status e data de envio do relatório de descarga
			UPDATE PRO_SDSD SET 
				DSD_STRD = (CASE dsp.DSD_ESTI WHEN 1 THEN 2 WHEN 2 THEN 3 ELSE 1 END), 
				DSD_DERD = @DataAtual
			FROM PRO_SDSD AS dsd WITH(NOLOCK) 
				INNER JOIN VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes AS dsp ON dsd.DSD_IDNN = dsp.DSD_IDNN
				LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON duc.DUC_DUNO IN (1, 2) AND dsp.DSD_NRMH = duc.DUC_CPRT AND dsp.EAD_CODI = duc.ALF_CODI AND CAST(CONVERT(varchar(10), dsp.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime)
				LEFT OUTER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI
			WHERE dsd.DSC_EANO = @AnoManifesto AND dsd.DSC_NPRO = @NumManifesto AND dsd.DSD_TCAR = ISNULL(NULLIF(@TipoCarga, ''), dsd.DSD_TCAR) 
				AND ((@TipoCarga <> 'XXX') OR (@TipoCarga = 'XXX' AND dsd.DSD_VOLS = duc.DUC_VSCA AND ((nat.NDE_FEDI = 1) OR (duc.DUC_ARTI IS NOT NULL))))
		END
		ELSE
		IF @TipoMensagem = 'AirWarehouseKeepersMovementInformation' -- Criação do movimento de saída SDS-Via Aérea
		BEGIN
-- atualiza processo SDS - Via Aérea p/ alteração do status e utilizador/data
			UPDATE PRO_SDSC SET 
				DSC_STMS = 1, 
				DSC_NRES = DSC_NRES + 1, 
				DSC_UEMS = @CodUtilizador, 
				DSC_DEMS = @DataAtual 
			FROM PRO_SDSC AS sds WITH(NOLOCK)
				INNER JOIN (SELECT DSC_EANO, DSC_NPRO 
					FROM VW_SDSViaAerea_MovimentoSaidaDadosAWB 
					WHERE ISNULL(DSD_DNRD, '') <> '' AND ISNULL(SIN_CODI, '') <> '' AND EAD_CODI = @CodEstancia
					GROUP BY DSC_EANO, DSC_NPRO) AS t ON sds.DSC_EANO = t.DSC_EANO AND sds.DSC_NPRO = t.DSC_NPRO			
-- atualiza linhas AWB do processo SDS - Via Aérea p/ alteração do status e data de envio do movimento de saída
			UPDATE PRO_SDSD SET 
				DSD_STMS = 1, 
				DSD_DEMS = @DataAtual
			FROM PRO_SDSD AS dsd WITH(NOLOCK) 
				INNER JOIN VW_SDSViaAerea_MovimentoSaidaDadosAWB AS mvs ON dsd.DSD_IDNN = mvs.DSD_IDNN
			WHERE ISNULL(mvs.DSD_DNRD, '') <> '' AND ISNULL(mvs.SIN_CODI, '') <> '' AND mvs.EAD_CODI = @CodEstancia
		END
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'		
	END CATCH	
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_MensagensSubmetePedido] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_MensagensSubmetePedido] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_SDSViaAerea_Manifestos_ProcessaMensagensSubmissaoAutomatica]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_SDSViaAerea_Manifestos_ProcessaMensagensSubmissaoAutomatica] @TipoMensagem varchar(50), @DataVoo datetime, @SoFranquias bit, @SoCriacao bit, @TipoCarga varchar(3), 
	@CodEstancia varchar(8), @IdUtilizador int, @Erros varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE	@NumErro int, @AnoManifesto int, @NumManifesto int, @Erro varchar(MAX)
-- inicia variáveis
	SET @Erros = ''
-- obtem manifestos, relatórios de descarga ou movimentos de saída SDS - Via Aérea em situação de submissão ao webservice
	DECLARE Manifestos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR		
		SELECT lin.DSC_EANO, lin.DSC_NPRO
		FROM VW_SDSViaAerea_EnvioManifestoDadosAWBPendentes AS lin WITH(NOLOCK) 		
		WHERE @TipoMensagem = 'AirManifestInformation' AND lin.DSC_DTVO = CAST(CONVERT(varchar(10), @DataVoo, 105) AS datetime) 
			AND (CASE @SoFranquias WHEN 0 THEN 1 ELSE ISNULL(lin.DSD_AFRQ, 0) END) > 0		
		GROUP BY lin.DSC_EANO, lin.DSC_NPRO
		UNION 
		SELECT lin.DSC_EANO, lin.DSC_NPRO
		FROM VW_SDSViaAerea_EnvioRelatorioDescargaDadosAWBPendentes AS lin WITH(NOLOCK) 		
			LEFT OUTER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON duc.DUC_DUNO IN (1, 2) AND lin.DSD_NRMH = duc.DUC_CPRT AND lin.EAD_CODI = duc.ALF_CODI AND CAST(CONVERT(varchar(10), lin.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), duc.DUC_DTVO, 105) AS datetime)
			LEFT OUTER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI
		WHERE @TipoMensagem = 'AirWarehouseKeepersReportInformation' AND lin.DSC_DTVO = CAST(CONVERT(varchar(10), @DataVoo, 105) AS datetime) 
			AND lin.DSD_TCAR = ISNULL(NULLIF(@TipoCarga, ''), lin.DSD_TCAR) 
			AND ((@TipoCarga <> 'XXX') OR (@TipoCarga = 'XXX' AND lin.DSD_VOLS = duc.DUC_VSCA AND ((nat.NDE_FEDI = 1) OR (duc.DUC_ARTI IS NOT NULL))))
		GROUP BY lin.DSC_EANO, lin.DSC_NPRO		
		UNION 
		SELECT TOP 1 lin.DSC_EANO, lin.DSC_NPRO
		FROM VW_SDSViaAerea_MovimentoSaidaDadosAWB AS lin WITH(NOLOCK) 					
		WHERE @TipoMensagem = 'AirWarehouseKeepersMovementInformation' AND ISNULL(lin.DSD_DNRD, '') <> '' AND ISNULL(lin.SIN_CODI, '') <> '' AND lin.EAD_CODI = @CodEstancia
		GROUP BY lin.DSC_EANO, lin.DSC_NPRO		
	OPEN Manifestos
	FETCH NEXT FROM Manifestos INTO @AnoManifesto, @NumManifesto
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		SET @Erro = NULL
-- processa a submissão da mensagem XML do manifesto ou relatório de descarga SDS - Via Aérea
		EXEC @NumErro = sp_SDSViaAerea_Manifestos_MensagensSubmetePedido @TipoMensagem, 'Create', @AnoManifesto, @NumManifesto, @SoFranquias, @SoCriacao, @TipoCarga, @CodEstancia, @IdUtilizador, @Erro OUTPUT
-- se resultado não for de sucesso, guarda erro
		IF @NumErro > 0
			SET @Erros = @Erros + '-> A submissão da mensagem "' + @TipoMensagem + '" do manifesto/relatório descarga SDS-Via Aérea N.º ' + CAST(@NumManifesto AS varchar(10)) + ' gerou o erro "' + @Erro + '".' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
		FETCH NEXT FROM Manifestos INTO @AnoManifesto, @NumManifesto
	END
	CLOSE Manifestos
	DEALLOCATE Manifestos
-- devolve resultado (0: Sucesso; 1: Erro)
	IF @Erros = ''
		RETURN 0
	ELSE
		RETURN 1
END

ALTER AUTHORIZATION ON [sp_SDSViaAerea_Manifestos_ProcessaMensagensSubmissaoAutomatica] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_SDSViaAerea_Manifestos_ProcessaMensagensSubmissaoAutomatica] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_SDSViaAerea_RemoveLinhasAWB]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROC [SP_SDSViaAerea_RemoveLinhasAWB] @AnoSDS int, @NumeroSDS int, @LstLinhasAWB xml, @Utilizador varchar(30), @MensagemErro varchar(8000) OUTPUT AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON
	SET DATEFORMAT DMY
-- declaração de variaveis
	DECLARE @NumLinhaAWB int, @IDLinhaAWB varchar(20), @PrimeiroNumLinhaAWBRemovido int, @Erro int
-- inicia variaveis
	SET @Erro = 0
	SET @PrimeiroNumLinhaAWBRemovido = 0			
-- inicia transacção para remoção das linhas AWB do SDS - Via Aérea
	BEGIN TRANSACTION		
	BEGIN TRY
-- obtem lista de linhas AWB selecionadas
		DECLARE LstLinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dsd.DSD_NUME, dsd.DSD_IDCR 
			FROM @LstLinhasAWB.nodes('LstLinhasAWB/LinhaAWB') as XML_LINS(LIN_LIST) INNER JOIN PRO_SDSD as dsd ON @AnoSDS = dsd.DSC_EANO and @NumeroSDS = dsd.DSC_NPRO and XML_LINS.LIN_LIST.value('DSD_NUME[1]', 'int') = dsd.DSD_NUME
			ORDER BY dsd.DSD_NUME
		OPEN LstLinhasAWB
		FETCH NEXT FROM LstLinhasAWB INTO @NumLinhaAWB, @IDLinhaAWB
		WHILE @@FETCH_STATUS = 0
		BEGIN					
-- guarda o primeiro nº. de linha AWB a remover
			IF @PrimeiroNumLinhaAWBRemovido = 0
				SET @PrimeiroNumLinhaAWBRemovido = @NumLinhaAWB		
-- remove os documentos das linhas AWB filhas da linha AWB "Master"
			DELETE FROM PRO_SSDD
			WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME in (SELECT DSD_NUME 
				FROM PRO_SDSD 
				WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_CODR = @IDLinhaAWB)
-- remove as linhas AWB filhas da linha AWB "Master"
			DELETE FROM PRO_SDSD
			WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_CODR = @IDLinhaAWB
-- remove os documentos da linha AWB
			DELETE FROM PRO_SSDD
			WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB			
-- remove a linha AWB
			DELETE FROM PRO_SDSD
			WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB			
									
			FETCH NEXT FROM LstLinhasAWB INTO @NumLinhaAWB, @IDLinhaAWB
		END
		CLOSE LstLinhasAWB
		DEALLOCATE LstLinhasAWB
-- obtem lista de linhas AWB cujo nº. seja superior à 1ª linha AWB removida
		DECLARE LstLinhasAWB CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DSD_NUME
			FROM PRO_SDSD
			WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME >= @PrimeiroNumLinhaAWBRemovido
			ORDER BY DSD_NUME
		OPEN LstLinhasAWB
		FETCH NEXT FROM LstLinhasAWB INTO @NumLinhaAWB
		WHILE @@FETCH_STATUS = 0
		BEGIN					
-- atualiza o nº. linha nos documentos da linha AWB
			UPDATE PRO_SSDD SET DSD_NUME = @PrimeiroNumLinhaAWBRemovido
			WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB
-- atualiza o nº. linha na linha AWB
			UPDATE PRO_SDSD SET DSD_NUME = @PrimeiroNumLinhaAWBRemovido
			WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS and DSD_NUME = @NumLinhaAWB
-- incrementa variavel												
			SET @PrimeiroNumLinhaAWBRemovido = @PrimeiroNumLinhaAWBRemovido + 1
			
			FETCH NEXT FROM LstLinhasAWB INTO @NumLinhaAWB
		END	
		CLOSE LstLinhasAWB
		DEALLOCATE LstLinhasAWB
-- atualiza dados SDS - Via Aérea
		UPDATE PRO_SDSC SET DSC_UALT = @Utilizador, DSC_DALT = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
		WHERE DSC_EANO = @AnoSDS and DSC_NPRO = @NumeroSDS 
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SELECT @Erro = 1, @MensagemErro = 'Erro N.º: ' + CAST(ERROR_NUMBER() as varchar(50)) + ', Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ ', Estado: ' + CAST(ERROR_STATE() as varchar(5)) + ', Objeto: ' + ERROR_PROCEDURE() + ', Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ ', Mensagem: ' + ERROR_MESSAGE()
-- em caso de erro faz rollback da transacção iniciada						           
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION
	END CATCH			
-- se sucesso faz commit da transacção iniciada
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @Erro	
END

ALTER AUTHORIZATION ON [SP_SDSViaAerea_RemoveLinhasAWB] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_SDSViaAerea_RemoveLinhasAWB] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_AgentesTrafego_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_AgentesTrafego_Migracao_ObtemDados] @IncluiInativos bit, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos agentes de tráfego para migração de dados no novo sistema GIDWin
		SELECT AGE_CODI, AGE_INAC, AGE_NOME, AGE_MORA, AGE_LOCA, AGE_CPOS, AGE_NIF, PAI_CODI
		FROM TAB_AGEN WITH(NOLOCK)
		WHERE AGE_INAC = (CASE @IncluiInativos WHEN 1 THEN AGE_INAC ELSE 0 END)
		ORDER BY AGE_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_AgentesTrafego_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_AgentesTrafego_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Armazens_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Armazens_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos armazéns para migração de dados no novo sistema GIDWin
		SELECT ARM_CODI, ARM_NOME, TAR_CODI, EAD_CODI, DOC_CODI, ARM_NAUT, ARM_DATA, ARM_EORI
		FROM TAB_ARMZ WITH(NOLOCK)		
		ORDER BY ARM_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Armazens_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Armazens_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Artigos_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Artigos_Migracao_ObtemDados] @IncluiInativos bit, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos artigos pautais para migração de dados no novo sistema GIDWin
		SELECT APA_CODI, APA_CEAN, APA_INAC, APA_CPAU, APA_DESG, APA_DCOM, APA_EUR1, APA_ATR, APA_AGRX, APA_LIMP, USU_CODI, APA_TRIB, APA_OBSR, APA_TPT, APA_TPMN, APA_TPMX, 
			APA_EFTA, APA_EFMN, APA_EFMX, APA_SPG, APA_SPMN, APA_SPMX, APA_TIVA, APA_CIEC, APA_ATAR, APA_AIVA, APA_AIC1, APA_AIC2, APA_AIC3, APA_FLUX, APA_EDAR, APA_CCUS, 
			APA_AIC4, APA_AIC5, 
			(SELECT
				(SELECT t.ACO_TIPO, t.PAI_CODI, t.ACO_TAXA, t.ACO_VLMN, t.ACO_VLMX
				FROM 
					(SELECT 0 AS ACO_TIPO, PAI_CODI, ISNULL(APT_TFT, 0) AS ACO_TAXA, 0 AS ACO_VLMN, 0 AS ACO_VLMX
					FROM TAB_APTF
					WHERE APA_CHVE = TAB_APAU.APA_CHVE
					UNION
					SELECT 1 AS ACO_TIPO, PAI_CODI, ISNULL(APS_SPG, 0) AS ACO_TAXA, ISNULL(APS_SPMN, 0) AS ACO_VLMN, ISNULL(APS_SPMX, 0) AS ACO_VLMX
					FROM TAB_APSP
					WHERE APA_CHVE = TAB_APAU.APA_CHVE
					UNION
					SELECT 2 AS ACO_TIPO, PAI_CODI, ISNULL(APE_EFTA, 0) AS ACO_TAXA, ISNULL(APE_EFMN, 0) AS ACO_VLMN, ISNULL(APE_EFMX, 0) AS ACO_VLMX
					FROM TAB_APEF
					WHERE APA_CHVE = TAB_APAU.APA_CHVE) AS t
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_ACOR,
			(SELECT
				(SELECT AET_CODI, UME_COD2, AET_ORIG, RRE_CODI, AET_TAXA, AET_TXVL
				FROM TAB_AETR
				WHERE APA_CHVE = TAB_APAU.APA_CHVE 
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_ETRI, 
			(SELECT
				(SELECT ADC_CODI, DOC_CODI
				FROM TAB_ADOC WITH(NOLOCK)
				WHERE APA_CHVE = TAB_APAU.APA_CHVE
				ORDER BY ADC_CODI
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_DOCU, 			
			(SELECT
				(SELECT AIE_CODI, TEM_CODI, ISNULL(AIE_TEOR, 0) AS AIE_TEOR, ISNULL(AIE_CAPA, 0) AS AIE_CAPA, MIE_CODI, UME_CODI
				FROM TAB_AIEC
				WHERE APA_CHVE = TAB_APAU.APA_CHVE
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_IECS
		FROM TAB_APAU WITH(NOLOCK)	
		WHERE APA_INAC = (CASE @IncluiInativos WHEN 1 THEN APA_INAC ELSE 0 END)		
		ORDER BY APA_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Artigos_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Artigos_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Artigos_ValidaRestricoesDumpingFicheiroDHL]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Artigos_ValidaRestricoesDumpingFicheiroDHL] @AdicoesXML xml, @FlexFieldsMSC varchar(255), @BusinessType varchar(4), @TipoDeclaracao varchar(3) OUTPUT, 
	@XMLDadosRestricao xml OUTPUT, @Erro varchar(MAX) OUTPUT AS 
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @NumErro int
-- inicia 
	BEGIN TRY	
		SET @NumErro = 0
-- Verifica se existem artigos pautais configurados com a restrição "Prohibited"
		IF (ISNULL(@FlexFieldsMSC, '') <> 'HVRD') AND (EXISTS(SELECT 1 FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
																		INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
															WHERE apa.APA_RTRC = 1)) --Prohibited
		BEGIN
			SET @TipoDeclaracao = 'IMP'			
			SET @XMLDadosRestricao = 
				(SELECT
					'PRD' AS "natureza", 					
					NULLIF(APA_CPAU, '') AS "artigoPautal", 
					NULLIF(APA_DESG, '') AS "designacaoPautal", 
					(SELECT
						t.c.value('GoodsItemNo[1]', 'int') AS "numero"
					FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
						INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
					WHERE apa.APA_RTRC = 1
					FOR XML PATH('AdicaoRestrita'), TYPE)		
				FROM TAB_APAU WITH(NOLOCK)
				WHERE APA_CODI = '9999999999'
				FOR XML PATH('DadosRestricao'), ELEMENTS)
		END
		ELSE
-- Verifica se existem artigos pautais configurados com a restrição "Restricted+"
		IF (ISNULL(@FlexFieldsMSC, '') <> 'HVRD') AND (EXISTS(SELECT 1 FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
																		INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
															WHERE apa.APA_RTRC = 2)) --Restricted+
		BEGIN
			SET @TipoDeclaracao = 'IMP'			
			SET @XMLDadosRestricao = 
				(SELECT
					'PRD' AS "natureza", 					
					NULLIF(APA_CPAU, '') AS "artigoPautal", 
					NULLIF(APA_DESG, '') AS "designacaoPautal", 					
					(SELECT
						t.c.value('GoodsItemNo[1]', 'int') AS "numero"
					FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
						INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
					WHERE apa.APA_RTRC = 2
					FOR XML PATH('AdicaoRestrita'), TYPE)
				FROM TAB_APAU WITH(NOLOCK)
				WHERE APA_CODI = '9999999998'
				FOR XML PATH('DadosRestricao'), ELEMENTS)
		END
		ELSE
-- Verifica se existem artigos pautais configurados com a restrição "Restricted B2B Only" apenas quando o destinatário é "B2B"
		IF (ISNULL(@FlexFieldsMSC, '') <> 'HVRD') AND (ISNULL(@BusinessType, '') NOT IN ('B2C', 'C2C')) AND (EXISTS(SELECT 1 FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
																																INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
																												WHERE apa.APA_RTRC = 3)) --Restricted B2B Only
		BEGIN
			SET @TipoDeclaracao = NULL						
			SET @XMLDadosRestricao = 
				(SELECT
					'PRD' AS "natureza", 					
					NULLIF(APA_CPAU, '') AS "artigoPautal", 
					NULLIF(APA_DESG, '') AS "designacaoPautal", 					 
					(SELECT
						t.c.value('GoodsItemNo[1]', 'int') AS "numero"
					FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
						INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
					WHERE apa.APA_RTRC = 3
					FOR XML PATH('AdicaoRestrita'), TYPE)
				FROM TAB_APAU WITH(NOLOCK)
				WHERE APA_CODI = '9999999997'
				FOR XML PATH('DadosRestricao'), ELEMENTS)				
		END
		ELSE
-- Verifica se existem artigos pautais configurados com a restrição "Anti-Dumping" e cujo país de origem pertence ao detalhe de dumping
		IF EXISTS(SELECT 1 FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
							INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
							INNER JOIN TAB_ADUM AS adu WITH(NOLOCK) ON apa.APA_CHVE = adu.APA_CHVE 
				WHERE apa.APA_RTRC = 4 AND NULLIF(t.c.value('CtryOrgnCd[1]', 'varchar(2)'), '') = adu.PAI_CODI) --Anti-Dumping
		BEGIN
			SET @TipoDeclaracao = 'IMP'						
			SET @XMLDadosRestricao = 
				(SELECT
					'PRD' AS "natureza", 					
					NULLIF(APA_CPAU, '') AS "artigoPautal", 
					NULLIF(APA_DESG, '') AS "designacaoPautal", 
					(SELECT
						t.c.value('GoodsItemNo[1]', 'int') AS "numero"
					FROM @AdicoesXML.nodes('LineItem/.') AS t(c) 
						INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON LEFT(NULLIF(t.c.value('TariffCdNo[1]', 'varchar(18)'), ''), 6) = apa.APA_CPAU 
						INNER JOIN TAB_ADUM AS adu WITH(NOLOCK) ON apa.APA_CHVE = adu.APA_CHVE 
					WHERE apa.APA_RTRC = 4 AND NULLIF(t.c.value('CtryOrgnCd[1]', 'varchar(2)'), '') = adu.PAI_CODI
					FOR XML PATH('AdicaoRestrita'), TYPE)
				FROM TAB_APAU WITH(NOLOCK)
				WHERE APA_CODI = '9999999996'
				FOR XML PATH('DadosRestricao'), ELEMENTS)
		END		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = 'Detalhes do Erro: ' + CHAR(13) + ' » Número: ' + CAST(ERROR_NUMBER() as varchar(50)) + CHAR(13) + ' » Nível: ' + CAST(ERROR_SEVERITY() as varchar(5)) 
			+ CHAR(13) + ' » Estado: ' + CAST(ERROR_STATE() as varchar(5)) + CHAR(13) + ' » Objeto: ' + ERROR_PROCEDURE() + CHAR(13) + ' » Linha N.º: ' + CAST(ERROR_LINE() as varchar(5)) 
			+ CHAR(13) + ' » Mensagem: ' + ERROR_MESSAGE()
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Artigos_ValidaRestricoesDumpingFicheiroDHL] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Artigos_ValidaRestricoesDumpingFicheiroDHL] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_ChargeCodes_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_ChargeCodes_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos Charge Codes DHL para migração de dados no novo sistema GIDWin
		SELECT CCO_CODI, CCO_DESC
		FROM DHL_CCOD WITH(NOLOCK)			
		ORDER BY CCO_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_ChargeCodes_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_ChargeCodes_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Clientes_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Clientes_Migracao_ObtemDados] @IncluiInativos bit, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos clientes para migração de dados no novo sistema GIDWin
		SELECT CLI_CODI, CLI_CEAN, CLI_INAC, CLI_DESP, CLI_NOME, CLI_MORA, CLI_LOCA, CLI_CPOS, CLI_LPOS, CLI_TELF, CLI_EMAI, CLI_WEB, CLI_NIF, CLI_TNIF, PAI_CODI, RES_CODI, CLI_NCA1, 
			CLI_ANO1, CLI_TCA1, CLI_INA1, CLI_NCA2, CLI_ANO2, CLI_TCA2, CLI_INA2, CLI_CCOR, CLI_CPOC, CLI_SUCA, CLI_INFO, CLI_CODC, CLI_CPAG, DIN_CODI, CLI_SENT, CLI_VCIL, CLI_CACC, 
			CLI_CEXB, CLI_CDAS, CLI_AURS, CLI_DTRS, DOC_CODI, CLI_NAOE, CLI_DTOE, DOC_CDOE, CLI_FXOE, COS_CDLS, COS_CDPO, CLI_VEVD, CLI_AIVA, CLI_INTR, CLI_IEEN, CLI_IESA, CLI_INDI, 
			CLI_ITFT, CLI_IVLF, DEC_CODI, CLI_TDEC, CLI_DPRO, CLI_CTRO, CLI_DPNM, CLI_DPCT, CLI_DPTL, CLI_DPEM, CLI_IESE, CLI_SYNC, CLI_PLET, CLI_BIVA, CLI_CGLO, CLI_DIBI, CLI_DCON, 
			CLI_DCUT, CLI_DCDT, CLI_DCOB, CLI_DESQ, CLI_DETP, CLI_DEUT, CLI_DEDT, CLI_DEOB, CLI_FETE, CLI_FEEP, CLI_FEEC, CLI_IEDA, CLI_CNIF, ALF_CODI1, CLI_CCA1, CLI_OCA1, ALF_CODI2, 
			CLI_CCA2, CLI_OCA2, 			
			(SELECT
				(SELECT DOC_CODI, CLD_NDOC, CLD_DDOC
				FROM TAB_CLDO WITH(NOLOCK)
				WHERE CLI_CODI = TAB_CLIE.CLI_CODI
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_DOCU
		FROM TAB_CLIE WITH(NOLOCK)	
		WHERE CLI_INAC = (CASE @IncluiInativos WHEN 1 THEN CLI_INAC ELSE 0 END)		
		ORDER BY CLI_CCOR, CLI_SENT, CLI_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Clientes_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Clientes_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_CodigosOperacao_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_CodigosOperacao_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos códigos de operação para migração de dados no novo sistema GIDWin
		SELECT COP_CODI, COP_DESG
		FROM TAB_COPE WITH(NOLOCK)		
		ORDER BY COP_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_CodigosOperacao_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_CodigosOperacao_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_DespesasDocumentadas_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_DespesasDocumentadas_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das despesas documentadas para migração de dados no novo sistema GIDWin
		SELECT DDO_CODI, DDO_NOME, DDO_POCC, DDO_POCS, DDO_PCDO, DDO_SPCD, DDO_SPSC, CCO_CODI, DDO_CREC
		FROM TAB_DDOC WITH(NOLOCK)		
		ORDER BY DDO_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_DespesasDocumentadas_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_DespesasDocumentadas_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_DespesasInerentes_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_DespesasInerentes_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das despesas inerentes para migração de dados no novo sistema GIDWin
		SELECT DIN_CODI, DIN_NOME, DIN_POCC, DIN_POCS, DIN_PCDO, DIN_SPCD, DIN_SPSC, CCO_CODI, DIN_ISEN, IIV_CODI
		FROM TAB_DINE WITH(NOLOCK)		
		ORDER BY DIN_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_DespesasInerentes_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_DespesasInerentes_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Documentos_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Documentos_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos documentos para migração de dados no novo sistema GIDWin
		SELECT DOC_CODI, DOC_NOME, DOC_RSDA, DOC_IOBC, DOC_TRAN, DOC_DESP, DOC_EXPT, DOC_CA40, DOC_TDNU, DOC_TDDT, DOC_DTRA
		FROM TAB_DOCU WITH(NOLOCK)		
		ORDER BY DOC_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Documentos_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Documentos_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_EANCodes_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_EANCodes_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos EAN Codes DHL para migração de dados no novo sistema GIDWin
		SELECT DHL_ACCT, DHL_NOME
		FROM DHL_CEAN WITH(NOLOCK)	
		ORDER BY DHL_ACCT
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_EANCodes_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_EANCodes_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Estancias_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Estancias_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das estâncias aduaneiras para migração de dados no novo sistema GIDWin
		SELECT est.EAD_CODI, est.EAD_NOME, 
			alf.MTR_CODI AS MTR_CIMP, alf.ALF_CONT AS EAD_CIMP, alf.ALF_TLOC AS EAD_TIMP, alf.LME_CODI AS LME_CIMP, 
			est.MTR_CODI AS MTR_CEXP, est.EAD_CONT AS EAD_CEXP, est.PAI_CODI AS PAI_CEXP, est.LME_CODI AS LME_CEXP, est.EAD_CODI1 AS EAD_EEXP, 
			(SELECT
				(SELECT ADD_CODI, DOC_CODI
				FROM TAB_EADD WITH(NOLOCK)
				WHERE EAD_CODI = est.EAD_CODI
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_DOCU
		FROM TAB_EADU AS est WITH(NOLOCK)
			LEFT OUTER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON est.EAD_CODI = alf.ALF_CODI
		UNION
		SELECT alf.ALF_CODI, alf.ALF_NOME, 
			alf.MTR_CODI AS MTR_CIMP, alf.ALF_CONT AS EAD_CIMP, alf.ALF_TLOC AS EAD_TIMP, alf.LME_CODI AS LME_CIMP, 
			NULL AS MTR_CEXP, NULL AS EAD_CEXP, NULL AS PAI_CEXP, NULL AS LME_CEXP, NULL AS EAD_EEXP, 
			(SELECT
				(SELECT AFD_CODI AS ADD_CODI, DOC_CODI
				FROM TAB_ALFD WITH(NOLOCK)
				WHERE ALF_CODI = alf.ALF_CODI
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_DOCU
		FROM TAB_ALFA AS alf WITH(NOLOCK)
			LEFT OUTER JOIN TAB_EADU AS est WITH(NOLOCK) ON alf.ALF_CODI = est.EAD_CODI		
		WHERE est.EAD_IDTY IS NULL
		ORDER BY EAD_EEXP, EAD_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Estancias_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Estancias_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Fornecedores_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Fornecedores_Migracao_ObtemDados] @IncluiInativos bit, @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos fornecedores para migração de dados no novo sistema GIDWin
		SELECT FOR_CODI, FOR_INAC, FOR_DESP, FOR_NOME, FOR_MORA, FOR_LOCA, FOR_CPOS, FOR_LPOS, FOR_TELF, FOR_EMAI, FOR_WEB, FOR_NIF, FOR_TNIF, PAI_CODI, FOR_INFO, CLI_CODI, ALF_CODI, TDE_CODI, 
			CEN_CODI, PAI_CODI1
		FROM TAB_FORN WITH(NOLOCK)	
		WHERE FOR_INAC = (CASE @IncluiInativos WHEN 1 THEN FOR_INAC ELSE 0 END)		
		ORDER BY FOR_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Fornecedores_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Fornecedores_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Fretes_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Fretes_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos fretes acordados para migração de dados no novo sistema GIDWin
		SELECT FTA_CODI, FTA_DESC, FTA_LIMI, FTA_VLIM, FTA_VADI, 
			(SELECT
				(SELECT FAL_CODI, ISNULL(FAL_LIMD, 0) AS FAL_LIMD, ISNULL(FAL_LIMA, 0) AS FAL_LIMA, ISNULL(FAL_VALO, 0) AS FAL_VALO
				FROM TAB_FALM WITH(NOLOCK)
				WHERE FTA_CODI = TAB_FTAC.FTA_CODI
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_PESO
		FROM TAB_FTAC WITH(NOLOCK)		
		ORDER BY FTA_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Fretes_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Fretes_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Homologacoes_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Homologacoes_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das homologações técnicas para migração de dados no novo sistema GIDWin
		SELECT HTE_HOMO, MAR_CODI, HTE_MODE, CAT_CODI, TVE_CODI, HTE_CILI, TCO_CODI, HTE_ECO2, HTE_VISV, HTE_TABE, HTE_TCO2, HTE_AUTO, HTE_QUAL
		FROM TAB_HTEC WITH(NOLOCK)		
		WHERE HTE_CODI IN (
			SELECT MIN(HTE_CODI)
			FROM TAB_HTEC WITH(NOLOCK)
			WHERE ISNULL(HTE_HOMO, '') <> ''
			GROUP BY HTE_HOMO)
		ORDER BY HTE_HOMO		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Homologacoes_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Homologacoes_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_LocaisAutorizados_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_LocaisAutorizados_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos locais de autorizados para migração de dados no novo sistema GIDWin
		SELECT LME_CODI, LME_NOME, LME_FLUX, LME_GAEX, LME_PNRE, LME_PNRS, LME_IMPR
		FROM TAB_LMER WITH(NOLOCK)		
		ORDER BY LME_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_LocaisAutorizados_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_LocaisAutorizados_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_LocaisEmbarque_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_LocaisEmbarque_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos locais de embarque para migração de dados no novo sistema GIDWin
		SELECT LEM_CODI, PAI_CODI, PAE_CODI, LEM_CCOD, LEM_DESC, EAD_CODI
		FROM TAB_LEMB WITH(NOLOCK)		
		ORDER BY LEM_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_LocaisEmbarque_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_LocaisEmbarque_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Marcas_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Marcas_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das marcas auto para migração de dados no novo sistema GIDWin
		SELECT MAR_CODI, MAR_NOME
		FROM TAB_MARC WITH(NOLOCK)		
		ORDER BY MAR_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Marcas_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Marcas_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_MarcasIEC_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_MarcasIEC_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das marcas IEC para migração de dados no novo sistema GIDWin
		SELECT MIE_CODI, MIE_DESC, MIE_CODE
		FROM TAB_MIEC WITH(NOLOCK)		
		ORDER BY MIE_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_MarcasIEC_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_MarcasIEC_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Mencoes_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Mencoes_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das menções especiais para migração de dados no novo sistema GIDWin
		SELECT INF_CODI, INF_DESI, INF_EXPT, INF_NSTI, INF_IMPC
		FROM TAB_INFC WITH(NOLOCK)		
		ORDER BY INF_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Mencoes_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Mencoes_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_MotivosCredito_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_MotivosCredito_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos motivos de crédito para migração de dados no novo sistema GIDWin
		SELECT MCR_CODI, MCR_DESC
		FROM TAB_MCRE WITH(NOLOCK)		
		ORDER BY MCR_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_MotivosCredito_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_MotivosCredito_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_Naturezas_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_Naturezas_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das naturezas de despacho para migração de dados no novo sistema GIDWin
		SELECT NDE_CODI, NDE_NOME, NDE_TIVA, NDE_STCK, NDE_FEDI, IIV_CODI, SIN_CODI, FUP_CODI, NDE_DRDR, NDE_GADT, NDE_IDDP, NDE_VDAR, NDE_CODI2, NDE_CODI3, NDE_RETO
		FROM TAB_NDES WITH(NOLOCK)		
		ORDER BY NDE_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_Naturezas_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_Naturezas_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_PedidosEletronicos_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_PedidosEletronicos_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos pedidos eletrónicos para migração de dados no novo sistema GIDWin
		SELECT TXM_CODI, TXM_DESC, TXM_TEXT, DOC_CODI, TXM_TXT2, TXM_TXT3
		FROM TAB_TXML WITH(NOLOCK)		
		ORDER BY TXM_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_PedidosEletronicos_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_PedidosEletronicos_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_PortosAeroportos_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_PortosAeroportos_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos portos e aeroportos para migração de dados no novo sistema GIDWin
		SELECT PAE_CODI, PAE_NOME, PAI_CODI, PAE_TIPO
		FROM TAB_PAER WITH(NOLOCK)		
		ORDER BY PAE_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_PortosAeroportos_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_PortosAeroportos_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_RubricasFaturacao_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_RubricasFaturacao_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das rubricas de faturação para migração de dados no novo sistema GIDWin
		SELECT RFC_CODI, RFC_NOME, RFC_IVA, RFC_PVP, RFC_CPOC, RFC_TIPO, RFC_VLNC, RFC_VLNS, IIV_CODI, CCO_CODI
		FROM TAB_RFCT WITH(NOLOCK)		
		ORDER BY RFC_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_RubricasFaturacao_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_RubricasFaturacao_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_RubricasReceita_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_RubricasReceita_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das rubricas de receita para migração de dados no novo sistema GIDWin
		SELECT RRE_CODI, RRE_NOME, RRE_IVA, RRE_VERB, COP_CODI, RRE_VALO, RRE_UVAL, RRE_IMPO, RRE_TIEC, RRE_DUMP
		FROM TAB_RREC WITH(NOLOCK)		
		ORDER BY RRE_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_RubricasReceita_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_RubricasReceita_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_StatusIncidencia_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_StatusIncidencia_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos status de incidência e cosmos code para migração de dados no novo sistema GIDWin
		SELECT COS_CODE, COS_POST, COS_SCAN, COS_FDES, COS_RELI, COS_HOLD, NDE_CODI, NDE_CDPO
		FROM TAB_COSM WITH(NOLOCK)
		UNION ALL
		SELECT SIN_CODI, NULL, NULL, SIN_DESP, 0, 0, NDE_CODI, NDE_CODI
		FROM TAB_SINC WITH(NOLOCK)		
		WHERE NOT EXISTS(SELECT COS_IDTY FROM TAB_COSM WITH(NOLOCK) WHERE COS_CODE = TAB_SINC.SIN_CODI)
		ORDER BY COS_CODE
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_StatusIncidencia_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_StatusIncidencia_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_TiposCombustivel_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_TiposCombustivel_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos tipos de combustível para migração de dados no novo sistema GIDWin
		SELECT TCO_CODI, TCO_NOME
		FROM TAB_TCOM WITH(NOLOCK)		
		ORDER BY TCO_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_TiposCombustivel_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_TiposCombustivel_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_TiposDeclaracao_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_TiposDeclaracao_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos tipos de declaração para migração de dados no novo sistema GIDWin
		SELECT TDE_CODI, TDE_NOME, TDE_1CAS, TDE_2CAS, TDE_3CAS, TDE_NATU, PRE_CODI, TDE_REGI, TDE_TPCG, TDE_DESD, 
			(SELECT
				(SELECT TDD_CODI, DOC_CODI
				FROM TAB_TDED WITH(NOLOCK)
				WHERE TDE_CODI = TAB_TDEC.TDE_CODI
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_DOCU, 			
			(SELECT
				(SELECT TDP_CODI, TXM_CODI
				FROM TAB_TDEP WITH(NOLOCK)
				WHERE TDE_CODI = TAB_TDEC.TDE_CODI
				FOR XML PATH('row'), TYPE)
			FOR XML PATH('dataset'), ELEMENTS) AS XML_PEDI
		FROM TAB_TDEC WITH(NOLOCK)		
		ORDER BY TDE_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_TiposDeclaracao_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_TiposDeclaracao_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_TiposDesalfandegamento_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_TiposDesalfandegamento_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos tipos de desalfândegamento para migração de dados no novo sistema GIDWin
		SELECT DES_CODI, DES_DESC
		FROM TAB_DESA WITH(NOLOCK)		
		ORDER BY DES_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_TiposDesalfandegamento_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_TiposDesalfandegamento_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_TiposEmbalagem_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_TiposEmbalagem_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos tipos de embalagem para migração de dados no novo sistema GIDWin
		SELECT TEM_CODI, TEM_NOME, TEM_PVOL, TEM_PUNI, TEM_TVOL, TEM_EXPT, TEM_NSTI, TEM_DEXT
		FROM TAB_TEMB WITH(NOLOCK)		
		ORDER BY TEM_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_TiposEmbalagem_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_TiposEmbalagem_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_TiposVeiculo_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_TiposVeiculo_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados dos tipos de veículo para migração de dados no novo sistema GIDWin
		SELECT TVE_CODI, TVE_NOME
		FROM TAB_TVEI WITH(NOLOCK)		
		ORDER BY TVE_CODI		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_TiposVeiculo_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_TiposVeiculo_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [sp_TAB_UnidadesTributacao_Migracao_ObtemDados]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [sp_TAB_UnidadesTributacao_Migracao_ObtemDados] @Erro varchar(MAX) OUTPUT AS
BEGIN	
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis	
	DECLARE @NumErro int
	BEGIN TRY	
		SET @NumErro = 0
-- obtem os dados das unidades de tributação para migração de dados no novo sistema GIDWin
		SELECT UME_COD2, MAX(UME_NOME) AS UME_NOME, MAX(UME_FACT) AS UME_FACT, CAST(MAX(CAST(UME_IMPT AS int)) AS bit) AS UME_IMPT, CAST(MAX(CAST(UME_EXPT AS int)) AS bit) AS UME_EXPT
		FROM TAB_UMED WITH(NOLOCK)		
		WHERE ISNULL(UME_COD2, '') <> ''
		GROUP BY UME_COD2
		ORDER BY UME_COD2		
	END TRY
	BEGIN CATCH
-- constroi mensagem de erro detalhada
		SET @NumErro = 1 
		SET @Erro = ERROR_MESSAGE() + CHAR(13) + '{Detalhe: Número=' + CAST(ERROR_NUMBER() as varchar(50)) + ',Nível=' + CAST(ERROR_SEVERITY() as varchar(5)) + ',Estado=' + CAST(ERROR_STATE() as varchar(5)) + ',Objeto=' + ISNULL(ERROR_PROCEDURE(), '') + ',Linha=' + CAST(ERROR_LINE() as varchar(5)) + '}'
	END CATCH			
-- devolve resultado (0: Sucesso; 1: Erro)
	RETURN @NumErro	
END

ALTER AUTHORIZATION ON [sp_TAB_UnidadesTributacao_Migracao_ObtemDados] TO  SCHEMA OWNER 
GRANT EXECUTE ON [sp_TAB_UnidadesTributacao_Migracao_ObtemDados] TO [public] AS [dbo]
/****** Object:  StoredProcedure [SP_Vendas_ImportaFicheirosXML]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [SP_Vendas_ImportaFicheirosXML] @DirOrigemFicheiros varchar(500), @DirDestinoFicheiros varchar(500), @DirDestinoFicheiroErros varchar(500), @DirFicheirosPDF varchar(250), 
	@PathReportAImprimir varchar(250), @PathGIDWinPDFExportTool varchar(250), @Utilizador varchar(30), @PwLoginGIDWin varchar(30) AS
BEGIN
	SET NOCOUNT ON	
	SET ARITHABORT ON	
	SET DATEFORMAT DMY
-- declaração de variáveis
	DECLARE @PathFicheiro varchar(500), @NomeFicheiro varchar(500), @ComandoSQL varchar(1500), @FicheiroXML xml(XMLSC_DocsVendaToGIDWin), @ListaErros varchar(MAX), @i int, 
		@NumErro int, @Erros varchar(MAX), @PathFicheiroErro varchar(500), @Linha varchar(MAX), @NomeFicheiroPDF varchar(100), @PathFicheiroPDF varchar(500), 
		@ArgsGIDWinPDFExportTool varchar(2000)
	DECLARE @CodTipoDoc varchar(4), @Data datetime, @IDExterno varchar(50), @Observacoes varchar(MAX), @DocumentoOrigem varchar(50), @CodCliente varchar(18), 
		@NomeCliente varchar(70), @MoradaCliente varchar(70), @LocalidadeCliente varchar(35), @CodigoPostalCliente varchar(12), @LocalidadePostalCliente varchar(35), 
		@CodRegiaoCliente int, @CodPaisCliente varchar(2), @NIFCliente varchar(18), @Linhas xml, @CodRubrica int, @DescricaoLinha varchar(500), @Qtd decimal(18, 2), 
		@ValorUnitario decimal(18, 2), @TaxaIVA decimal(18, 2), @CodIsencaoIVA varchar(3), @TxIVAIsenta numeric(38, 6), @TxIVAReduzida numeric(38, 6), 
		@TxIVAIntermedia numeric(38, 6), @TxIVANormal numeric(38, 6), @NumeroDoc int, @IVALinha numeric(38, 6), @TotalLiquido numeric(38, 6), @TotalIVA numeric(38, 6), 
		@IncidenciaTxIVA01 numeric(38, 6), @IncidenciaTxIVA02 numeric(38, 6), @IncidenciaTxIVA03 numeric(38, 6), @IncidenciaTxIVA04 numeric(38, 6), @ValorTxIVA01 numeric(38, 6), 
		@ValorTxIVA02 numeric(38, 6), @ValorTxIVA03 numeric(38, 6), @ValorTxIVA04 numeric(38, 6), @NumeroLinha int, @NumeroRefDocOrigem varchar(60), @Serie varchar(20)
-- coloca caracter '"' na path
	SET @PathReportAImprimir = QUOTENAME(@PathReportAImprimir, '"')
	SET @PathGIDWinPDFExportTool = QUOTENAME(@PathGIDWinPDFExportTool, '"')			
-- verfica se diretorias tem backslash no final
	IF SUBSTRING(REVERSE(@DirOrigemFicheiros), 1, 1) <> '\'
		SET @DirOrigemFicheiros = @DirOrigemFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiros), 1, 1) <> '\'
		SET @DirDestinoFicheiros = @DirDestinoFicheiros + '\'
	IF SUBSTRING(REVERSE(@DirDestinoFicheiroErros), 1, 1) <> '\'
		SET @DirDestinoFicheiroErros = @DirDestinoFicheiroErros + '\'
	IF SUBSTRING(REVERSE(@DirFicheirosPDF), 1, 1) <> '\'
		SET @DirFicheirosPDF = @DirFicheirosPDF + '\'			
-- cria tabela temporária p/ conteudo de cada ficheiro xml	
	CREATE TABLE #ConteudoFicheiro(CONTEUDO xml)
-- obtem lista de ficheiros a importar (considera apenas ficheiros cuja extensão é .xml)
	DECLARE Ficheiros CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	 
		SELECT [fullName], [fileName]
		FROM GIDWIN.dbo.FNT_Externo_ObtemListaFicheiros(@DirOrigemFicheiros, '*.xml')
		ORDER BY [lastWriteTime]		
	OPEN Ficheiros
	FETCH NEXT FROM Ficheiros INTO @PathFicheiro, @NomeFicheiro
	WHILE @@FETCH_STATUS = 0
	BEGIN		
		SET @ListaErros = ''				
		BEGIN TRY	
-- remove tabela de conteudos de cada ficheiro
			DELETE FROM #ConteudoFicheiro
-- processa a importação dos dados do ficheiro na tabela temporária			
			SET @ComandoSQL = 'INSERT INTO #ConteudoFicheiro(CONTEUDO) SELECT CONVERT(XML, BulkColumn) AS BulkColumn FROM OPENROWSET(BULK ''' + @PathFicheiro + ''', SINGLE_BLOB) AS x'
			EXEC (@ComandoSQL)
-- move o ficheiro importado
			EXEC GIDWIN.dbo.SP_Externo_MoveFicheiro @PathFicheiro, @DirDestinoFicheiros, @Erros OUTPUT
			IF ISNULL(@Erros, '') <> ''
				RAISERROR ('Não foi possível mover o ficheiro "%s"! ERRO: "%s".', 16, 1, @PathFicheiro, @Erros)			
-- obtem o xml do ficheiro xml importado						
			SELECT @FicheiroXML = CONTEUDO
			FROM #ConteudoFicheiro
-- obtem taxas de IVA configuradas
			SELECT @TxIVAIsenta = PAP_TXIS, @TxIVAReduzida = PAP_TXRD, @TxIVAIntermedia = PAP_TXIN, @TxIVANormal = PAP_TXNR
			FROM TAB_PAPL WITH(NOLOCK)
-- obtem os dados dos documentos de cada ficheiro xml
			DECLARE DocsVenda CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
				SELECT XML_DOCV.DOC_DATA.value('tipoDocumento[1]', 'varchar(4)'), XML_DOCV.DOC_DATA.value('data[1]', 'datetime'), 
					XML_DOCV.DOC_DATA.value('idExterno[1]', 'varchar(50)'), NULLIF(XML_DOCV.DOC_DATA.value('observacoes[1]', 'varchar(MAX)'), ''), 
					NULLIF(XML_DOCV.DOC_DATA.value('documentoOrigem[1]', 'varchar(50)'), ''), XML_DOCV.DOC_DATA.value('cliente/codigoCliente[1]', 'varchar(18)'), 
					NULLIF(XML_DOCV.DOC_DATA.value('cliente/infoCliente/nome[1]', 'varchar(70)'), ''), NULLIF(XML_DOCV.DOC_DATA.value('cliente/infoCliente/morada[1]', 'varchar(70)'), ''), 
					NULLIF(XML_DOCV.DOC_DATA.value('cliente/infoCliente/localidade[1]', 'varchar(35)'), ''), NULLIF(XML_DOCV.DOC_DATA.value('cliente/infoCliente/codigoPostal[1]', 'varchar(12)'), ''), 
					NULLIF(XML_DOCV.DOC_DATA.value('cliente/infoCliente/localidadePostal[1]', 'varchar(35)'), ''), XML_DOCV.DOC_DATA.value('cliente/infoCliente/regiao[1]', 'int'), 
					NULLIF(XML_DOCV.DOC_DATA.value('cliente/infoCliente/pais[1]', 'varchar(2)'), ''), NULLIF(XML_DOCV.DOC_DATA.value('cliente/infoCliente/nif[1]', 'varchar(18)'), ''), 
					XML_DOCV.DOC_DATA.query('linhas')								
				FROM @FicheiroXML.nodes('DocsVendaToGIDWIN/Documento') as XML_DOCV(DOC_DATA)
			OPEN DocsVenda 
			FETCH NEXT FROM DocsVenda INTO @CodTipoDoc, @Data, @IDExterno, @Observacoes, @DocumentoOrigem, @CodCliente, @NomeCliente, @MoradaCliente, @LocalidadeCliente, 
				@CodigoPostalCliente, @LocalidadePostalCliente, @CodRegiaoCliente, @CodPaisCliente, @NIFCliente, @Linhas
			WHILE @@FETCH_STATUS = 0
			BEGIN		
-- efetua validações dos dados
				IF NOT EXISTS(SELECT TDO_DOCU FROM TAB_TDOC WITH(NOLOCK) WHERE TDO_TDOC = 1 AND TDO_DCON = 1 AND TDO_EXSF = 1 AND TDO_TDSF IN ('FT', 'ND', 'NC') AND TDO_DOCU = @CodTipoDoc)
					RAISERROR ('Tipo de documento "%s" invalido!', 16, 1, @CodTipoDoc)	
				IF (YEAR(@Data) >= 2023) AND (NOT EXISTS(SELECT 1 FROM TAB_NUMD WITH(NOLOCK) WHERE TDO_DOCU = @CodTipoDoc AND NUM_EANO = YEAR(@Data) AND ISNULL(NUM_CVAT, '') <> ''))
					RAISERROR ('Série do tipo de documento "%s" sem código de validação AT atrbuído!', 16, 2, @CodTipoDoc)
				IF EXISTS(SELECT TDO_DOCU FROM TAB_NUMD WHERE NUM_TDOC = 1 AND TDO_DOCU = @CodTipoDoc AND NUM_EANO = YEAR(@Data) AND NUM_DATA > @Data)
					RAISERROR ('Data não pode ser inferior a do ultimo documento!', 16, 3)		
				IF EXISTS(SELECT TDO_DOCU FROM TAB_TDOC WITH(NOLOCK) WHERE TDO_DOCU = @CodTipoDoc AND TDO_TDSF IN ('ND', 'NC')) AND (ISNULL(@DocumentoOrigem, '') = '')
					RAISERROR ('O documento de origem deverá estar preenchido!', 16, 4)		
-- verifica se cliente não existe e cria-o se restantes dados existirem				
				IF NOT EXISTS(SELECT CLI_CODI FROM TAB_CLIE WITH(NOLOCK) WHERE CLI_CODI = @CodCliente)
				BEGIN
					IF (ISNULL(@NomeCliente, '') <> '') AND (ISNULL(@MoradaCliente, '') <> '') AND (ISNULL(@CodPaisCliente, '') <> '') AND (ISNULL(@NIFCliente, '') <> '')
					BEGIN
						EXEC @NumErro = SP_Clientes_InsereOuEdita 0, @CodCliente, @NomeCliente, @MoradaCliente, @NIFCliente, 0, @CodRegiaoCliente, @LocalidadeCliente, @CodigoPostalCliente, @LocalidadePostalCliente, @CodPaisCliente, NULL, NULL, NULL, @Utilizador, @Erros OUTPUT
						IF @NumErro <> 0
							RAISERROR ('Erro na inserção do cliente "%s"! Erro: "%s".', 16, 5, @CodCliente, @Erros)							
					END
					ELSE	
						RAISERROR ('Código de cliente "%s" invalido!', 16, 6, @CodCliente)	
				END
-- obtem o InvoiceNumber do documento de origem referenciado
				IF ISNULL(@DocumentoOrigem, '') <> '' 
					SET @NumeroRefDocOrigem = ISNULL((SELECT TOP 1 DVE_INVN FROM FAC_DVEN WITH(NOLOCK) WHERE DVE_NEXT = @DocumentoOrigem), @DocumentoOrigem)					
				ELSE
					SET @NumeroRefDocOrigem = NULL
-- obtem o numero do doc. venda da tabela de numeradores
				SELECT @NumeroDoc = isnull(NUM_NUME, 0) + 1, @Serie = ISNULL(NULLIF(NUM_SERI, ''), '1')
				FROM TAB_NUMD 
				WHERE NUM_TDOC = 1 AND TDO_DOCU = @CodTipoDoc AND NUM_EANO = YEAR(@Data)
-- insere registo de cabeçalho do doc. venda
				INSERT INTO FAC_DVEN (DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_CTXT, DVE_DATA, CLI_CODI, DVE_CNOM, DVE_CMOR, DVE_CLOC, DVE_CCPO, DVE_CLPO, DVE_CNIF, PAI_CLIV, DVE_OBSV, 
					DVE_UTIC, DVE_DTCR, DVE_UTIA, DVE_DTAL, DVE_IN01, DVE_IN02, DVE_IN03, DVE_IN04, DVE_VI01, DVE_VI02, DVE_VI03, DVE_VI04, DVE_VLIQ, DVE_VIVA, DVE_VTOT, DVE_STAT, 
					DVE_DIPS, DVE_DFPS, TDO_TDSF, DVE_NEXT, DVE_NRDO, DVE_SERI)
				SELECT tdo.TDO_DOCU, @NumeroDoc, YEAR(@Data), tdo.TDO_TDOC, @Data, @CodCliente, ISNULL(@NomeCliente, cli.CLI_NOME), ISNULL(@MoradaCliente, cli.CLI_MORA), 
					ISNULL(@LocalidadeCliente, cli.CLI_LOCA), ISNULL(@CodigoPostalCliente, cli.CLI_CPOS), ISNULL(@LocalidadePostalCliente, cli.CLI_LPOS), 
					ISNULL(@NIFCliente, cli.CLI_NIF), ISNULL(@CodPaisCliente, cli.PAI_CODI), @Observacoes, @Utilizador, GETDATE(), @Utilizador, GETDATE(), 0 , 0, 0, 0, 0, 0, 0, 
					0, 0, 0, 0, 1, @Data, @Data, tdo.TDO_TDSF, @IDExterno, @NumeroRefDocOrigem, @Serie
				FROM TAB_TDOC AS tdo WITH(NOLOCK) INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON cli.CLI_CODI = @CodCliente
				WHERE tdo.TDO_DOCU = @CodTipoDoc
-- actualiza dados da tabela de numeradores
				UPDATE TAB_NUMD SET NUM_NUME = @NumeroDoc, NUM_DATA = @Data
				WHERE NUM_TDOC = 1 AND TDO_DOCU = @CodTipoDoc AND NUM_EANO = YEAR(@Data)
-- inicia variaveis
				SET @NumeroLinha = 0
				SET @TotalLiquido = 0
				SET @TotalIVA = 0
				SET @IncidenciaTxIVA01 = 0
				SET @IncidenciaTxIVA02 = 0
				SET @IncidenciaTxIVA03 = 0
				SET @IncidenciaTxIVA04 = 0
				SET @ValorTxIVA01 = 0
				SET @ValorTxIVA02 = 0
				SET @ValorTxIVA03 = 0
				SET @ValorTxIVA04 = 0
-- obtem as linhas do documento de venda
				DECLARE LinhasDoc CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
					SELECT XML_LINS.LIN_DATA.value('codigoArtigo[1]', 'int'), XML_LINS.LIN_DATA.value('descricaoArtigo[1]', 'varchar(500)'), 
						XML_LINS.LIN_DATA.value('quantidade[1]', 'decimal(18, 2)'), XML_LINS.LIN_DATA.value('valorUnitario[1]', 'decimal(18, 2)'), 
						XML_LINS.LIN_DATA.value('taxaIVA[1]', 'decimal(18, 2)'), NULLIF(XML_LINS.LIN_DATA.value('codigoIsencaoIVA[1]', 'varchar(3)'), '')
					FROM @Linhas.nodes('linhas/linha') as XML_LINS(LIN_DATA)
					ORDER BY XML_LINS.LIN_DATA.value('numero[1]', 'int')
				OPEN LinhasDoc
				FETCH NEXT FROM LinhasDoc INTO @CodRubrica, @DescricaoLinha, @Qtd, @ValorUnitario, @TaxaIVA, @CodIsencaoIVA
				WHILE @@FETCH_STATUS = 0
				BEGIN		
					SET @NumeroLinha = @NumeroLinha + 1	
-- efetua validações dos dados
					IF (@TaxaIVA = 0) AND (ISNULL(@CodIsencaoIVA, '') = '')
						RAISERROR ('Codigo de isencao IVA deverá estar preenchido!', 16, 7)		
					IF (ISNULL(@CodIsencaoIVA, '') <> '') AND (NOT EXISTS(SELECT IIV_CODI FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = @CodIsencaoIVA))
						RAISERROR ('Codigo de isencao IVA "%s" invalido!', 16, 8, @CodIsencaoIVA)	
					IF NOT EXISTS(SELECT RFC_CODI FROM TAB_RFCT WITH(NOLOCK) WHERE RFC_CODI = @CodRubrica)
					BEGIN
						INSERT INTO TAB_RFCT (RFC_CODI, RFC_NOME, RFC_IVA)
						VALUES (@CodRubrica, SUBSTRING(@DescricaoLinha, 1, 70), @TaxaIVA)
					END
-- insere linha de rubrica no documento de venda
					INSERT INTO FAC_DVDT(DVE_TDOC, DVE_NDOC, DVE_EANO, DVE_NLIN, RFC_CODI, DVD_NOME, DVD_QUAN, DVD_VALO, DVD_IVA, DVD_LCRB, DVD_CTXT, DVD_LHON, IIV_CODI, IIV_MENC, 
						CCO_CODI)
					SELECT @CodTipoDoc, @NumeroDoc, YEAR(@Data), @NumeroLinha, @CodRubrica, @DescricaoLinha, @Qtd, @ValorUnitario, @TaxaIVA, 1, 1, 
						(CASE RFC_TIPO WHEN 2 THEN 1 ELSE 0 END), @CodIsencaoIVA, 
						(SELECT IIV_MENC FROM GIDWIN.dbo.FAP_MIIV WITH(NOLOCK) WHERE IIV_CODI = @CodIsencaoIVA), CCO_CODI
					FROM TAB_RFCT WITH(NOLOCK)
					WHERE RFC_CODI = @CodRubrica
-- incrementa variaveis			
					SET @IVALinha = @ValorUnitario * (@TaxaIVA / 100)
					SET @TotalLiquido = @TotalLiquido + @ValorUnitario
					SET @TotalIVA = @TotalIVA + @IVALinha			
					IF @TxIVAIsenta = @TaxaIVA
					BEGIN
						SELECT @IncidenciaTxIVA01 = @IncidenciaTxIVA01 + @ValorUnitario
						SELECT @ValorTxIVA01 = @ValorTxIVA01 + @IVALinha
					END
					ELSE 
						IF @TxIVAReduzida = @TaxaIVA
						BEGIN
							SELECT @IncidenciaTxIVA02 = @IncidenciaTxIVA02 + @ValorUnitario
							SELECT @ValorTxIVA02 = @ValorTxIVA02 + @IVALinha
						END
						ELSE 
							IF @TxIVAIntermedia = @TaxaIVA
							BEGIN
								SELECT @IncidenciaTxIVA03 = @IncidenciaTxIVA03 + @ValorUnitario
								SELECT @ValorTxIVA03 = @ValorTxIVA03 + @IVALinha
							END
							ELSE 
								IF @TxIVANormal = @TaxaIVA
								BEGIN
									SELECT @IncidenciaTxIVA04 = @IncidenciaTxIVA04 + @ValorUnitario
									SELECT @ValorTxIVA04 = @ValorTxIVA04 + @IVALinha
								END		
					FETCH NEXT FROM LinhasDoc INTO @CodRubrica, @DescricaoLinha, @Qtd, @ValorUnitario, @TaxaIVA, @CodIsencaoIVA
				END
				CLOSE LinhasDoc
				DEALLOCATE LinhasDoc
-- valida o valor total do documento
				IF (@TotalLiquido + ROUND(@TotalIVA, 2)) = 0
					RAISERROR ('O valor total do documento nao pode ser zero!', 16, 9)
-- actualiza totais do documento de venda
				UPDATE FAC_DVEN SET DVE_VLIQ = @TotalLiquido, DVE_VIVA = ROUND(@TotalIVA, 2), DVE_VTOT = (@TotalLiquido + ROUND(@TotalIVA, 2)), DVE_IN01 = @IncidenciaTxIVA01, 
					DVE_IN02 = @IncidenciaTxIVA02, DVE_IN03 = @IncidenciaTxIVA03, DVE_IN04 = @IncidenciaTxIVA04, DVE_VI01 = ROUND(@ValorTxIVA01, 2), 
					DVE_VI02 = ROUND(@ValorTxIVA02, 0), DVE_VI03 = ROUND(@ValorTxIVA03, 2), DVE_VI04 = ROUND(@ValorTxIVA04, 2)
				WHERE DVE_TDOC = @CodTipoDoc and DVE_NDOC = @NumeroDoc and DVE_EANO = YEAR(@Data)
-- procede à geração do report em PDF para o documento de Conta
				IF (ISNULL(@PathReportAImprimir, '') <> '') AND (ISNULL(@DirFicheirosPDF, '') <> '')
				BEGIN
					SET @NomeFicheiroPDF = @CodTipoDoc + '.' + CAST(@NumeroDoc AS varchar(10)) + '.' + CAST(YEAR(@Data) AS varchar(4)) + '.pdf';		
					SET @PathFicheiroPDF = @DirFicheirosPDF + @NomeFicheiroPDF
					SET @ArgsGIDWinPDFExportTool = '-s' + @@SERVERNAME + ' -p' + @PwLoginGIDWin + ' -b' + DB_NAME() + ' -r' + @PathReportAImprimir + ' -c1 -a' + CAST(YEAR(@Data) AS varchar(4)) + ' -t' + @CodTipoDoc + ' -i' + CAST(@NumeroDoc AS varchar(20)) + ' -f' + QUOTENAME(@PathFicheiroPDF, '"')					
					EXEC GIDWIN.dbo.SP_Externo_ExecutaPrograma @PathGIDWinPDFExportTool, @ArgsGIDWinPDFExportTool, @Erros OUTPUT					
				END
				FETCH NEXT FROM DocsVenda INTO @CodTipoDoc, @Data, @IDExterno, @Observacoes, @DocumentoOrigem, @CodCliente, @NomeCliente, @MoradaCliente, @LocalidadeCliente, 
					@CodigoPostalCliente, @LocalidadePostalCliente, @CodRegiaoCliente, @CodPaisCliente, @NIFCliente, @Linhas
			END
			CLOSE DocsVenda
			DEALLOCATE DocsVenda
		END TRY
		BEGIN CATCH
-- constroi mensagem de erro detalhada
			SET @ListaErros = @ListaErros + 
								   '**********************************************************************************************************' + CHAR(12) +
								   '** ERRO NO TRATAMENTO DO FICHEIRO ************************************************************************' + CHAR(12) + 
								   '**********************************************************************************************************' + CHAR(12) + 
								   '.Nome Ficheiro:  ' + @NomeFicheiro + CHAR(12) +								   
								   '.Detalhe Erro:       ' + CHAR(12) +
								   '		*Data do Erro:       ' + CONVERT(varchar(23), GETDATE(), 126) + CHAR(12) + 
								   '		*Numero do Erro:     ' + CAST(ERROR_NUMBER() as varchar) + CHAR(12) + 
								   '		*Nivel do Erro:      ' + CAST(ERROR_SEVERITY() as varchar) + CHAR(12) + 
								   '		*Estado do Erro:     ' + CAST(ERROR_STATE() as varchar) + CHAR(12) + 
								   '		*Objeto do Erro:     ' + ERROR_PROCEDURE() + CHAR(12) + 
								   '		*Nº Linha do Erro:   ' + CAST(ERROR_LINE() as varchar) + CHAR(12) + 
								   '		*Mensagem do Erro:   ' + ERROR_MESSAGE() + CHAR(12)
-- liberta cursors caso ainda existam
			IF CURSOR_STATUS('local', 'DocsVenda') >= -1
				DEALLOCATE DocsVenda
			IF CURSOR_STATUS('local', 'LinhasDoc') >= -1
				DEALLOCATE LinhasDoc
		END CATCH
-- se ocorreram erros no tratamento do ficheiro ou processamento das declarações, gera ficheiro de erros
		IF ISNULL(@ListaErros, '') <> ''
		BEGIN	
			SET @PathFicheiroErro = @DirDestinoFicheiroErros + '/' + @NomeFicheiro + '.err'															
			SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			WHILE @i > 0
			BEGIN
				SET @Linha = SUBSTRING(@ListaErros, 1, @i - 1)
				EXEC GIDWIN.dbo.SP_Externo_EscreveLinhaFicheiro @PathFicheiroErro, @Linha, @Erros OUTPUT
				IF ISNULL(@Erros, '') <> ''
					RAISERROR ('Não foi possível escrever no ficheiro "%s"! ERRO: "%s".', 16, 99, @PathFicheiroErro, @Erros)				
				SET @ListaErros = STUFF(@ListaErros, 1, @i, '')
				SET @i = CHARINDEX(CHAR(12), @ListaErros, 0)
			END			
		END					
		FETCH NEXT FROM Ficheiros INTO @PathFicheiro, @NomeFicheiro
	END
	CLOSE Ficheiros
	DEALLOCATE Ficheiros
-- remove a tabela temporária
	DROP TABLE #ConteudoFicheiro
END

ALTER AUTHORIZATION ON [SP_Vendas_ImportaFicheirosXML] TO  SCHEMA OWNER 
GRANT EXECUTE ON [SP_Vendas_ImportaFicheirosXML] TO [public] AS [dbo]
/****** Object:  Trigger [TAD_AEX_ENLN]    Script Date: 04-11-2025 10:22:21 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_AEX_ENLN] ON [AEX_ENLN] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
-- atualiza o numero das linhas superiores à linha removida
    UPDATE AEX_ENLN SET ELN_NLIN = AEX_ENLN.ELN_NLIN - 1
    FROM (SELECT eln.EDG_EANO, eln.LME_CODI, eln.EDG_NUME, eln.ELN_NLIN
		FROM deleted as del INNER JOIN AEX_ENLN as eln ON del.EDG_EANO = eln.EDG_EANO and del.LME_CODI = eln.LME_CODI and del.EDG_NUME = eln.EDG_NUME
		WHERE eln.ELN_NLIN > del.ELN_NLIN
		GROUP BY eln.EDG_EANO, eln.LME_CODI, eln.EDG_NUME, eln.ELN_NLIN) as tln
	WHERE AEX_ENLN.EDG_EANO = tln.EDG_EANO and AEX_ENLN.LME_CODI = tln.LME_CODI and AEX_ENLN.EDG_NUME = tln.EDG_NUME and AEX_ENLN.ELN_NLIN = tln.ELN_NLIN
-- atualiza valores totais dos dados gerais da Entrada AEX
	UPDATE AEX_ENDG SET EDG_TVOL = ISNULL(tln.TOT_VOLS, 0), EDG_TPBR = ISNULL(tln.TOT_PBRT, 0), EDG_TVAL = ISNULL(tln.TOT_VALO, 0), EDG_TMCU = ISNULL(tln.TOT_MCUB, 0), 
		EDG_SVOL = ISNULL(tln.TOT_VOLS, 0), EDG_SPBR = ISNULL(tln.TOT_PBRT, 0)
	FROM (SELECT del.EDG_EANO, del.LME_CODI, del.EDG_NUME, SUM((CASE WHEN (eln.ELN_PART = 1) and (eln.ELN_NLIN > 1) THEN 0 ELSE eln.ELN_VOLS END)) as TOT_VOLS, 
			SUM(eln.ELN_PBRT) as TOT_PBRT, SUM(eln.ELN_VALO) as TOT_VALO, SUM(ROUND((eln.ELN_ALTU * eln.ELN_COMP * eln.ELN_LARG), 3)) as TOT_MCUB
		FROM deleted as del LEFT OUTER JOIN AEX_ENLN as eln ON del.EDG_EANO = eln.EDG_EANO and del.LME_CODI = eln.LME_CODI and del.EDG_NUME = eln.EDG_NUME
		GROUP BY del.EDG_EANO, del.LME_CODI, del.EDG_NUME) as tln
	WHERE AEX_ENDG.EDG_EANO = tln.EDG_EANO and AEX_ENDG.LME_CODI = tln.LME_CODI and AEX_ENDG.EDG_NUME = tln.EDG_NUME
END

ALTER TABLE [dbo].[AEX_ENLN] ENABLE TRIGGER [TAD_AEX_ENLN]
/****** Object:  Trigger [TAIU_AEX_ENLN]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_AEX_ENLN] ON [AEX_ENLN] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- atualiza o parte das linhas superiores à 1ª linha em que houve alteração do parte
	UPDATE AEX_ENLN SET ELN_PART = tln.ELN_PART
    FROM (SELECT ins.EDG_EANO, ins.LME_CODI, ins.EDG_NUME, ins.ELN_PART
		FROM inserted as ins INNER JOIN deleted as del ON ins.EDG_EANO = del.EDG_EANO and ins.LME_CODI = del.LME_CODI and ins.EDG_NUME = del.EDG_NUME			
		WHERE del.ELN_NLIN = 1 and ins.ELN_PART <> del.ELN_PART) as tln
	WHERE AEX_ENLN.EDG_EANO = tln.EDG_EANO and AEX_ENLN.LME_CODI = tln.LME_CODI and AEX_ENLN.EDG_NUME = tln.EDG_NUME and AEX_ENLN.ELN_NLIN > 1
-- atualiza valores totais dos dados gerais da Entrada AEX
	UPDATE AEX_ENDG SET EDG_TVOL = tln.TOT_VOLS, EDG_TPBR = tln.TOT_PBRT, EDG_TVAL = tln.TOT_VALO, EDG_TMCU = tln.TOT_MCUB, EDG_SVOL = tln.TOT_VOLS, EDG_SPBR = tln.TOT_PBRT
	FROM (SELECT ins.EDG_EANO, ins.LME_CODI, ins.EDG_NUME, SUM((CASE WHEN (eln.ELN_PART = 1) and (eln.ELN_NLIN > 1) THEN 0 ELSE eln.ELN_VOLS END)) as TOT_VOLS, 
			SUM(eln.ELN_PBRT) as TOT_PBRT, SUM(eln.ELN_VALO) as TOT_VALO, SUM(ROUND((eln.ELN_ALTU * eln.ELN_COMP * eln.ELN_LARG), 3)) as TOT_MCUB
		FROM inserted as ins INNER JOIN AEX_ENLN as eln ON ins.EDG_EANO = eln.EDG_EANO and ins.LME_CODI = eln.LME_CODI and ins.EDG_NUME = eln.EDG_NUME
		GROUP BY ins.EDG_EANO, ins.LME_CODI, ins.EDG_NUME) as tln
	WHERE AEX_ENDG.EDG_EANO = tln.EDG_EANO and AEX_ENDG.LME_CODI = tln.LME_CODI and AEX_ENDG.EDG_NUME = tln.EDG_NUME
END

ALTER TABLE [dbo].[AEX_ENLN] ENABLE TRIGGER [TAIU_AEX_ENLN]
/****** Object:  Trigger [TAIUD_AEX_SADG]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_AEX_SADG] ON [AEX_SADG] AFTER INSERT, UPDATE, DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- atualiza valores dos saldos dos dados gerais da Entrada AEX
	UPDATE AEX_ENDG SET EDG_SVOL = AEX_ENDG.EDG_SVOL + tdg.TOT_VOLS, EDG_SPBR = AEX_ENDG.EDG_SPBR + tdg.TOT_PBRT
	FROM (SELECT EDG_EANO, LME_CODI, EDG_NUME, SUM(SDG_VOLS) as TOT_VOLS, SUM(SDG_PBRT) as TOT_PBRT
		FROM deleted 
		WHERE SDG_ASAI = 1
		GROUP BY EDG_EANO, LME_CODI, EDG_NUME) as tdg
	WHERE AEX_ENDG.EDG_EANO = tdg.EDG_EANO and AEX_ENDG.LME_CODI = tdg.LME_CODI and AEX_ENDG.EDG_NUME = tdg.EDG_NUME	
-- atualiza valores dos saldos dos dados gerais da Entrada AEX
	UPDATE AEX_ENDG SET EDG_SVOL = AEX_ENDG.EDG_SVOL - tdg.TOT_VOLS, EDG_SPBR = AEX_ENDG.EDG_SPBR - tdg.TOT_PBRT
	FROM (SELECT EDG_EANO, LME_CODI, EDG_NUME, SUM(SDG_VOLS) as TOT_VOLS, SUM(SDG_PBRT) as TOT_PBRT
		FROM inserted 
		WHERE SDG_ASAI = 1 and SDG_ANUL = 0
		GROUP BY EDG_EANO, LME_CODI, EDG_NUME) as tdg
	WHERE AEX_ENDG.EDG_EANO = tdg.EDG_EANO and AEX_ENDG.LME_CODI = tdg.LME_CODI and AEX_ENDG.EDG_NUME = tdg.EDG_NUME
END

ALTER TABLE [dbo].[AEX_SADG] ENABLE TRIGGER [TAIUD_AEX_SADG]
/****** Object:  Trigger [TAU_FAC_CDOC]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_FAC_CDOC] ON [FAC_CDOC] FOR UPDATE AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis
	DECLARE @EntidadeMB varchar(5), @SubentidadeMB varchar(3), @AfectaCC bit, @tenti int, @tmovi int, @anul bit, @tipo varchar(4), @num int, @ano int, @data datetime, @entidade varchar(18), 
		@ncon varchar(18), @ndes varchar(3), @npro int, @vtot numeric(38,6), @vdeb numeric(38,6), @viva numeric(38,6), @iv01 numeric(38,6), @iv02 numeric(38,6), @iv03 numeric(38,6), 
		@iv04 numeric(38,6), @vinc01 numeric(38,6), @vinc02 numeric(38,6), @vinc03 numeric(38,6), @vinc04 numeric(38,6), @reca bit, @utic varchar(30), @utia varchar(30), @desc varchar(100), 
		@impresso bit, @contador int, @stat int, @descDoc varchar(100), @mvc_vtot numeric(38,6), @mvc_vdeb numeric(38,6), @DocContabilistico bit, @IdenConta int, @DadosAEncriptar nvarchar(4000), 
		@Hash nvarchar(200), @Versao int, @TipoCliente varchar(3), @CodValidacaoAT varchar(30), @ValorRetFonte numeric(38, 6), @InvoiceNumber varchar(60), @Serie varchar(20)
-- obtem dados de multibanco da empresa
	SELECT @EntidadeMB = ISNULL(EMP_MBEN, ''), @SubentidadeMB = ISNULL(EMP_MBSE, '')
	FROM GIDWIN.dbo.FAP_EMPR WITH(NOLOCK)
	WHERE EMP_CODI = DB_NAME()
-- obtem os dados das contas alteradas
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT i.CDO_TDOC, i.CDO_CNUM, i.CDO_EANO, i.CDO_DTEM, i.CLI_CCOR, i.NDE_CODI, i.CDO_NPRO, i.CDO_TTPR, i.CDO_IVA, i.CDO_TTRF, i.CDO_VI01, i.CDO_VI02, i.CDO_VI03, i.CDO_VI04, i.CDO_IN01, i.CDO_IN02, 
			i.CDO_IN03, i.CDO_IN04, i.CDO_UCRI,	i.CDO_UALT, i.CDO_IMPR, i.CDO_ANUL, i.CDO_STAT, i.CDO_CTIP, t.TDO_CONC, t.TDO_TENT, t.TDO_TMOV, t.TDO_MREC, c.CLI_NIF, t.TDO_DCON, t.TDO_DESC, 
			i.CDO_IDEN, i.CDO_SERI, n.NUM_CVAT, 
			SUBSTRING((i.CDO_TDOC + ' ' + ISNULL(i.CDO_SERI, '1') + '/' + CAST(i.CDO_CNUM AS varchar(10))), 1, 60), 
			(CONVERT(varchar(10), i.CDO_DTEM, 120) + ';' + CONVERT(varchar(19), i.CDO_DTCR, 126) + ';' + SUBSTRING((i.CDO_TDOC + ' ' + ISNULL(i.CDO_SERI, '1') + '/' + CAST(i.CDO_CNUM AS varchar(10))), 1, 60) + ';' + LTRIM(STR(ISNULL(i.CDO_TTPR, 0), 20, 2)) + ';' + ISNULL((SELECT TOP 1 CDO_HASH FROM FAC_CDOC WHERE CDO_TDOC = i.CDO_TDOC and CDO_EANO = i.CDO_EANO and CDO_CNUM = (i.CDO_CNUM - 1)), ''))
		FROM inserted AS i INNER JOIN TAB_TDOC AS t WITH(NOLOCK) ON i.CDO_TDOC = t.TDO_DOCU
			INNER JOIN TAB_CLIE AS c WITH(NOLOCK) ON i.CLI_CCOR = c.CLI_CODI	
			INNER JOIN TAB_NUMD AS n WITH(NOLOCK) ON i.CDO_TDOC = n.TDO_DOCU AND i.CDO_EANO = n.NUM_EANO
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ndes, @npro, @vtot, @viva, @ValorRetFonte, @iv01, @iv02, @iv03, @iv04, @vinc01, @vinc02, @vinc03, @vinc04, @utic, @utia, 
		@impresso, @anul, @stat, @TipoCliente, @AfectaCC, @tenti, @tmovi, @reca, @ncon, @DocContabilistico, @descDoc, @IdenConta, @Serie, @CodValidacaoAT, @InvoiceNumber, @DadosAEncriptar
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- para os documentos contabilisticos, caso tenham sido numerados calcula a respectiva assinatura digital
		IF (@DocContabilistico = 1) AND (@impresso = 1) AND (@stat = 1) AND (@num is not null) AND (UPDATE(CDO_CNUM))
		BEGIN
			EXEC SP_Facturacao_GeraChaveDocumento @DadosAEncriptar, @Hash OUTPUT, @Versao OUTPUT
			UPDATE FAC_CDOC SET CDO_HASH = @Hash, CDO_HCTR = @Versao, CDO_INVN = @InvoiceNumber
			WHERE CDO_EANO = @ano AND CDO_TDOC = @tipo AND CDO_IDEN = @IdenConta
		END
-- se código validação existir para o tipo documento/ano e documento tenha sido numerado, calcula o ATCUD
		IF (ISNULL(@CodValidacaoAT, '') <> '') AND (@impresso = 1) AND (@stat = 1) AND (@num is not null) AND (UPDATE(CDO_CNUM))
		BEGIN
			UPDATE FAC_CDOC SET CDO_ATCU = ISNULL((@CodValidacaoAT + '-' + CAST(@num AS varchar(10))), '0')
			WHERE CDO_EANO = @ano AND CDO_TDOC = @tipo AND CDO_IDEN = @IdenConta
		END
-- se dados multibanco configurados e tipo de cliente for "COD" e documento tenha sido numerado, calcula a referência MB
		IF (@EntidadeMB <> '') AND (@SubentidadeMB <> '') AND (@TipoCliente = 'COD') AND (@impresso = 1) AND (@stat = 1) AND (@num is not null) AND (UPDATE(CDO_CNUM))
		BEGIN
			UPDATE FAC_CDOC SET CDO_MBEN = @EntidadeMB, CDO_MBRF = dbo.FNT_Facturacao_CalculaReferenciaMB(@EntidadeMB, @SubentidadeMB, @num, (@vtot - @ValorRetFonte))
			WHERE CDO_EANO = @ano AND CDO_TDOC = @tipo AND CDO_IDEN = @IdenConta
		END
-- verifica se apenas foi alterado o campo status para remessa, sim não executa alteração na conta corrente
		IF (UPDATE(CDO_STAT)) AND (@stat = 2)
			SELECT @stat = 2
		ELSE
-- se afeta conta corrente e não está anulado, efetua a movimentação C.C.
			IF (@impresso = 1) AND (@AfectaCC = 1) AND (@anul = 0)
			BEGIN	
				SELECT @contador = COUNT(*)
				FROM FAC_MVCC 
				WHERE MVC_TDOC = @tipo AND MVC_NDOC = @num AND MVC_EANO = @ano
-- inserir informação referênte ao tipo de documento				
				IF @contador = 0
				BEGIN					
					INSERT INTO FAC_MVCC(MVC_TDOC, MVC_NDOC, MVC_EANO, MVC_DATA, MVC_TMOV, MVC_TENT, MVC_ENTI, MVC_NCON, MVC_NDES, MVC_NPRO, MVC_VTOT, MVC_VDEB, MVC_VIVA, MVC_VI01, MVC_VI02, 
						MVC_VI03, MVC_VI04, MVC_IN01, MVC_IN02, MVC_IN03, MVC_IN04, MVC_RECA, MVC_UTIC, MVC_DTCR, MVC_CTXT, MVC_IMPR, MVC_STAT, MVC_DORI, MVC_DINT, MVC_COMP, MVC_VRTF, MVC_SERI)
					VALUES(@tipo, @num, @ano, @data, @tmovi, @tenti, @entidade, @ncon, @ndes, @npro, (@vtot - @ValorRetFonte), (@vtot - @ValorRetFonte), @viva, @iv01, @iv02, 
						@iv03, @iv04, @vinc01, @vinc02, @vinc03, @vinc04, @reca, @utic, GETDATE(), 0, @impresso, @stat, (@descDoc + ' Nº ' + CAST(@num as varchar)), CAST(@num as varchar), 
						(@ndes + '.' + CAST(@npro as varchar) + '/' + CAST(@ano as varchar)), @ValorRetFonte, @Serie)	
				END
				ELSE  -- alterar ------------------------------------------------------------------
				BEGIN
					-- verifica se os novos motantes são iguais aos anteriores ---------------- 
					SELECT @mvc_vtot = MVC_VTOT, @mvc_vdeb = MVC_VDEB
					FROM FAC_MVCC WITH(NOLOCK)
					WHERE MVC_TDOC = @tipo AND MVC_NDOC = @num AND MVC_EANO = @ano
					IF @mvc_vtot <> (@vtot - @ValorRetFonte)
						SELECT @mvc_vdeb = (@vtot - @ValorRetFonte)
					-- actualizar informação referênte ao tipo de documento -------------------
					UPDATE FAC_MVCC SET MVC_TDOC = @tipo, MVC_NDOC = @num, MVC_EANO = @ano, MVC_DATA = @data, MVC_TMOV = @tmovi, MVC_TENT = @tenti, MVC_ENTI = @entidade, MVC_NCON = @ncon, 
						MVC_NDES = @ndes, MVC_NPRO = @npro, MVC_VTOT = (@vtot - @ValorRetFonte), MVC_VDEB = @mvc_vdeb, MVC_VIVA = @viva, MVC_VI01 = @iv01, MVC_VI02 = @iv02, MVC_VI03 = @iv03, 
						MVC_VI04 = @iv04, MVC_IN01 = @vinc01, MVC_IN02 = @vinc02, MVC_IN03 = @vinc03, MVC_IN04 = @vinc04, MVC_RECA = @reca, MVC_UTIA = @utia, MVC_DTAL = GETDATE(), MVC_CTXT = 0, 
						MVC_IMPR = @impresso, MVC_STAT = @stat,	MVC_DORI = (@descDoc + ' Nº ' + CAST(@num as varchar)), MVC_DINT = CAST(@num as varchar), 
						MVC_COMP = (@ndes + '.' + CAST(@npro as varchar) + '/' + CAST(@ano as varchar)), MVC_VRTF = @ValorRetFonte, MVC_SERI = @Serie
					WHERE MVC_TDOC = @tipo AND MVC_NDOC = @num AND MVC_EANO = @ano
				END
			END
			ELSE 
				IF (@impresso = 1) AND (@AfectaCC = 1) AND (@anul = 1)
				BEGIN 		
					DELETE FROM FAC_MVCC 
					WHERE MVC_TDOC = @tipo AND MVC_NDOC = @num AND MVC_EANO = @ano
				END
		FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ndes, @npro, @vtot, @viva, @ValorRetFonte, @iv01, @iv02, @iv03, @iv04, @vinc01, @vinc02, @vinc03, @vinc04, @utic, @utia, 
			@impresso, @anul, @stat, @TipoCliente, @AfectaCC, @tenti, @tmovi, @reca, @ncon, @DocContabilistico, @descDoc, @IdenConta, @Serie, @CodValidacaoAT, @InvoiceNumber, @DadosAEncriptar
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[FAC_CDOC] ENABLE TRIGGER [TAU_FAC_CDOC]
/****** Object:  Trigger [tr_FAC_CDOC_Atualizacoes_U]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_FAC_CDOC_Atualizacoes_U] ON [FAC_CDOC] AFTER UPDATE AS 
BEGIN	
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @Ano int, @CodTipoDoc varchar(4), @Id int
-- se documento "Anulado" e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO", coloca documento como pendente de envio para Portal MyRangel
	IF (UPDATE(CDO_ANUL)) AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT CDO_EANO, CDO_TDOC, CDO_IDEN
			FROM inserted 
			WHERE CDO_ANUL = 1 AND CDO_PMRP = 0
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @Ano, @CodTipoDoc, @Id
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE FAC_CDOC SET 
				CDO_PMRP = 1				
			WHERE CDO_EANO = @Ano AND CDO_TDOC = @CodTipoDoc AND CDO_IDEN = @Id
			FETCH NEXT FROM Documentos INTO @Ano, @CodTipoDoc, @Id
		END
		CLOSE Documentos
		DEALLOCATE Documentos				
	END
END

ALTER TABLE [dbo].[FAC_CDOC] ENABLE TRIGGER [tr_FAC_CDOC_Atualizacoes_U]
/****** Object:  Trigger [TAI_FAC_DVEN]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_FAC_DVEN] ON [FAC_DVEN] FOR INSERT AS
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis
	DECLARE @tipo varchar(4), @num int, @ano int, @data datetime, @entidade varchar(18), @ncon varchar(18), @ndes varchar(3), @npro int, @vtot numeric(38,6), @vdeb numeric(38,6), 
		@viva numeric(38,6), @iv01 numeric(38,6), @iv02 numeric(38,6), @iv03 numeric(38,6), @iv04 numeric(38,6), @vinc01 numeric(38,6), @vinc02 numeric(38,6), @vinc03 numeric(38,6), 
		@vinc04 numeric(38,6), @reca bit, @utic varchar(30), @dtcria datetime, @utia varchar(30), @dtalter datetime, @desc varchar(100), @tmovi int, @tenti int, @AfectaCC bit, @contexto int, 
		@impresso bit, @stat int, @nomeDoc varchar(20), @DocContabilistico bit, @DadosAEncriptar nvarchar(4000), @Hash nvarchar(200), @Versao int, @CodValidacaoAT varchar(30), 
		@InvoiceNumber varchar(60), @Serie varchar(20)
	-- busca dados a inserir
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT i.DVE_TDOC, i.DVE_NDOC, i.DVE_EANO, i.DVE_DATA, i.CLI_CODI, i.DVE_CNIF, i.NDE_CODI, i.DVE_NPRO, i.DVE_VTOT, i.DVE_VIVA, i.DVE_VI01, i.DVE_VI02, i.DVE_VI03, i.DVE_VI04, i.DVE_IN01, 
			i.DVE_IN02, i.DVE_IN03, i.DVE_IN04, i.DVE_UTIC, i.DVE_DTCR, i.DVE_UTIA, i.DVE_DTAL, i.DVE_CTXT, i.DVE_IMPR, i.DVE_STAT, i.DVE_SERI, t.TDO_DESC, t.TDO_CONC, t.TDO_TENT, t.TDO_TMOV, 
			t.TDO_MREC, t.TDO_DCON, n.NUM_CVAT, 
			SUBSTRING((i.DVE_TDOC + ' ' + i.DVE_SERI + '/' + CAST(i.DVE_NDOC AS varchar(10))), 1, 60), 
			CONVERT(varchar(10), i.DVE_DATA, 120) + ';' + CONVERT(varchar(19), i.DVE_DTCR, 126) + ';' + SUBSTRING((i.DVE_TDOC + ' ' + i.DVE_SERI + '/' + CAST(i.DVE_NDOC AS varchar(10))), 1, 60) + ';' + ltrim(str(i.DVE_VTOT, 20, 2)) + ';' + isnull((select DVE_HASH from FAC_DVEN where DVE_TDOC = i.DVE_TDOC and DVE_EANO = i.DVE_EANO and DVE_NDOC = (i.DVE_NDOC - 1)), '')
		FROM inserted AS i INNER JOIN TAB_TDOC AS t WITH(NOLOCK) ON i.DVE_TDOC = t.TDO_DOCU
			INNER JOIN TAB_NUMD AS n WITH(NOLOCK) ON i.DVE_TDOC = n.TDO_DOCU AND i.DVE_EANO = n.NUM_EANO
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @ndes, @npro, @vtot, @viva, @iv01, @iv02, @iv03, @iv04, @vinc01, @vinc02, @vinc03, @vinc04, @utic, @dtcria, @utia, 
		@dtalter, @contexto, @impresso, @stat, @Serie, @nomeDoc, @AfectaCC, @tenti, @tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber, @DadosAEncriptar
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- Para os documentos contabilisticos calcula a respectiva assinatura digital
		IF @DocContabilistico = 1
		BEGIN
			EXEC SP_Facturacao_GeraChaveDocumento @DadosAEncriptar, @Hash OUTPUT, @Versao OUTPUT
			ALTER TABLE FAC_DVEN DISABLE TRIGGER TAU_FAC_DVEN
			UPDATE FAC_DVEN SET DVE_HASH = @Hash, DVE_HCTR = @Versao, DVE_INVN = @InvoiceNumber
			WHERE DVE_TDOC = @tipo and DVE_NDOC = @num and DVE_EANO = @ano 
			ALTER TABLE FAC_DVEN ENABLE TRIGGER TAU_FAC_DVEN
		END
-- se código validação existir para o tipo documento/ano, calcula o ATCUD
		IF ISNULL(@CodValidacaoAT, '') <> ''
		BEGIN
			ALTER TABLE FAC_DVEN DISABLE TRIGGER TAU_FAC_DVEN
			UPDATE FAC_DVEN SET DVE_ATCU = ISNULL((@CodValidacaoAT + '-' + CAST(@num AS varchar(10))), '0')
			WHERE DVE_TDOC = @tipo and DVE_NDOC = @num and DVE_EANO = @ano 
			ALTER TABLE FAC_DVEN ENABLE TRIGGER TAU_FAC_DVEN			
		END
--se conta corrente = 1 movimenta C.C. 
		IF @AfectaCC = 1 
		BEGIN
			--inserir informação referênte ao tipo de documento 
			INSERT INTO FAC_MVCC(MVC_TDOC, MVC_NDOC, MVC_EANO, MVC_DATA, MVC_TMOV, MVC_TENT, MVC_ENTI, MVC_NCON, MVC_NDES, MVC_NPRO, MVC_VTOT, MVC_VDEB, MVC_VIVA, MVC_VI01, MVC_VI02, MVC_VI03, 
				MVC_VI04, MVC_IN01, MVC_IN02, MVC_IN03, MVC_IN04, MVC_RECA, MVC_UTIC, MVC_DTCR, MVC_UTIA, MVC_DTAL, MVC_CTXT, MVC_IMPR, MVC_STAT, MVC_DORI, MVC_COMP, MVC_DINT, MVC_SERI)
			VALUES(@tipo, @num, @ano, @data, @tmovi, @tenti, @entidade, @ncon, @ndes, @npro, @vtot, @vtot, @viva, @iv01, @iv02, @iv03, @iv04, @vinc01, @vinc02, @vinc03, @vinc04, @reca, @utic, 
				@dtcria, @utia, @dtalter, @contexto, @impresso, @stat, (@nomeDoc + ' N.º ' + cast(@num as varchar)), 
				(cast(@ndes as varchar) + '.' + cast(@npro as varchar) + '/' + cast(@ano as varchar)), '', @Serie)	
		END
		FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @ndes, @npro, @vtot, @viva, @iv01, @iv02, @iv03, @iv04, @vinc01, @vinc02, @vinc03, @vinc04, @utic, @dtcria, @utia, 
			@dtalter, @contexto, @impresso, @stat, @Serie, @nomeDoc, @AfectaCC, @tenti, @tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber, @DadosAEncriptar
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[FAC_DVEN] ENABLE TRIGGER [TAI_FAC_DVEN]
/****** Object:  Trigger [TAU_FAC_DVEN]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_FAC_DVEN] ON [FAC_DVEN] FOR UPDATE AS 
BEGIN
	SET NOCOUNT ON	
-- declaracao de variaveis -------------------------------------------------------------------------
	DECLARE @tipo varchar(4), @num int, @ano int, @data datetime, @entidade varchar(18), @ncon varchar(18), @ndes varchar(3), @npro int, @vtot numeric(38,6), @vdeb numeric(38,6), 
		@viva numeric(38,6), @iv01 numeric(38,6), @iv02 numeric(38,6), @iv03 numeric(38,6), @iv04 numeric(38,6), @vinc01 numeric(38,6), @vinc02 numeric(38,6), @vinc03 numeric(38,6), 
		@vinc04 numeric(38,6), @reca bit, @utic varchar(30), @dtcria datetime, @utia varchar(30), @dtalter datetime, @desc varchar(100), @tmovi int, @tenti int, @AfectaCC bit, @anulado bit, 
		@contexto int, @impresso bit, @stat int, @nomeDoc varchar(20), @DocContabilistico bit, @DadosAEncriptar nvarchar(4000), @Hash nvarchar(200), @Versao int, @CodValidacaoAT varchar(30), 
		@InvoiceNumber varchar(60), @Serie varchar(20)
-- busca dados a inserir ---------------------------------------------------------------------------
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT i.DVE_TDOC, i.DVE_NDOC, i.DVE_EANO, i.DVE_DATA, i.CLI_CODI, i.DVE_CNIF, i.NDE_CODI, i.DVE_NPRO, i.DVE_VTOT, i.DVE_VIVA, i.DVE_VI01, i.DVE_VI02, i.DVE_VI03, i.DVE_VI04, i.DVE_IMPR, 
			i.DVE_IN01, i.DVE_IN02, i.DVE_IN03, i.DVE_IN04, i.DVE_UTIC, i.DVE_DTCR, i.DVE_UTIA, i.DVE_DTAL, i.DVE_ANUL, i.DVE_CTXT, i.DVE_STAT, i.DVE_SERI, t.TDO_DESC, t.TDO_CONC, t.TDO_TENT, 
			t.TDO_TMOV, t.TDO_MREC, t.TDO_DCON, n.NUM_CVAT, 
			SUBSTRING((i.DVE_TDOC + ' ' + i.DVE_SERI + '/' + CAST(i.DVE_NDOC AS varchar(10))), 1, 60), 
			CONVERT(varchar(10), i.DVE_DATA, 120) + ';' + CONVERT(varchar(19), i.DVE_DTCR, 126) + ';' + SUBSTRING((i.DVE_TDOC + ' ' + i.DVE_SERI + '/' + CAST(i.DVE_NDOC AS varchar(10))), 1, 60) + ';' + ltrim(str(i.DVE_VTOT, 20, 2)) + ';' + isnull((select DVE_HASH from FAC_DVEN where DVE_TDOC = i.DVE_TDOC and DVE_EANO = i.DVE_EANO and DVE_NDOC = (i.DVE_NDOC - 1)), '')
		FROM inserted AS i INNER JOIN TAB_TDOC AS t WITH(NOLOCK) ON i.DVE_TDOC = t.TDO_DOCU
			INNER JOIN TAB_NUMD AS n WITH(NOLOCK) ON i.DVE_TDOC = n.TDO_DOCU AND i.DVE_EANO = n.NUM_EANO
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @ndes, @npro, @vtot, @viva, @iv01, @iv02, @iv03, @iv04, @impresso, @vinc01, @vinc02, @vinc03, @vinc04, @utic, @dtcria, 
		@utia, @dtalter, @anulado, @contexto, @stat, @Serie, @nomeDoc, @AfectaCC, @tenti, @tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber, @DadosAEncriptar
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- verifica se apenas foi alterado o campo status para remessa, sim não executa alteração na conta corrente
		IF UPDATE (DVE_STAT) AND (@stat = 2)
			SELECT @stat=2
		ELSE
		BEGIN
-- Para os documentos contabilisticos calcula a respectiva assinatura digital
			IF (@DocContabilistico = 1) and (NOT EXISTS(select DVE_NDOC from FAC_DVEN where DVE_TDOC = @tipo and DVE_EANO = @ano and DVE_NDOC = (@num + 1))) and ((UPDATE(DVE_DATA)) or (UPDATE(DVE_DTCR)) or (UPDATE(DVE_TDOC)) or (UPDATE(DVE_NDOC)) or (UPDATE(DVE_VTOT)) or (UPDATE(DVE_SERI)))
			BEGIN
				EXEC SP_Facturacao_GeraChaveDocumento @DadosAEncriptar, @Hash OUTPUT, @Versao OUTPUT				
				UPDATE FAC_DVEN set DVE_HASH = @Hash, DVE_HCTR = @Versao, DVE_INVN = @InvoiceNumber
				WHERE DVE_TDOC = @tipo and DVE_NDOC = @num and DVE_EANO = @ano
			END		
-- se código validação existir para o tipo documento/ano, calcula o ATCUD
			IF (ISNULL(@CodValidacaoAT, '') <> '') AND (UPDATE(DVE_NDOC))
			BEGIN				
				UPDATE FAC_DVEN SET DVE_ATCU = ISNULL((@CodValidacaoAT + '-' + CAST(@num AS varchar(10))), '0')
				WHERE DVE_TDOC = @tipo and DVE_NDOC = @num and DVE_EANO = @ano 				
			END				
			-- se conta corrente = 1 movimenta C.C. --------------------------------------------
			IF @AfectaCC = 1
			BEGIN
				-- se documento foi anulado apaga da conta corrente ------------------------
				IF @anulado = 1							
					DELETE FROM FAC_MVCC WHERE MVC_TDOC = @tipo and MVC_NDOC = @num and MVC_EANO = @ano		
				ELSE
				BEGIN			
					UPDATE FAC_MVCC SET MVC_DATA = @data, MVC_TMOV = @tmovi, MVC_TENT = @tenti, MVC_ENTI = @entidade, MVC_NCON = @ncon, MVC_NDES = @ndes, MVC_NPRO = @npro, MVC_VTOT = @vtot, 
						MVC_VDEB = @vtot, MVC_VIVA = @viva, MVC_VI01 = @iv01, MVC_VI02 = @iv02, MVC_VI03 = @iv03, MVC_VI04 = @iv04, MVC_IN01 = @vinc01, MVC_IN02 = @vinc02, MVC_IN03 = @vinc03, 
						MVC_IN04 = @vinc04, MVC_RECA = @reca, MVC_UTIC = @utic, MVC_DTCR = @dtcria, MVC_UTIA = @utia, MVC_DTAL = @dtalter, MVC_IMPR = @impresso, MVC_STAT = @stat, 
						MVC_DORI = (@nomeDoc+' N.º '+cast(@num as varchar)), MVC_COMP = (cast(@ndes as varchar) + '.' + cast(@npro as varchar) + '/' + cast(@ano as varchar)), MVC_SERI = @Serie
					WHERE MVC_TDOC = @tipo and MVC_NDOC = @num and MVC_EANO = @ano
				END
			END
		END
		FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @ndes, @npro, @vtot, @viva, @iv01, @iv02, @iv03, @iv04, @impresso, @vinc01, @vinc02, @vinc03, @vinc04, @utic, @dtcria, @utia, @dtalter, 
			@anulado, @contexto, @stat, @Serie, @nomeDoc, @AfectaCC, @tenti, @tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber, @DadosAEncriptar
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[FAC_DVEN] ENABLE TRIGGER [TAU_FAC_DVEN]
/****** Object:  Trigger [tr_FAC_DVEN_Atualizacoes_U]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_FAC_DVEN_Atualizacoes_U] ON [FAC_DVEN] AFTER UPDATE AS 
BEGIN	
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @Ano int, @CodTipoDoc varchar(4), @Numero int
-- se documento "Anulado" e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO", coloca documento como pendente de envio para Portal MyRangel
	IF (UPDATE(DVE_ANUL)) AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DVE_TDOC, DVE_NDOC, DVE_EANO
			FROM inserted 
			WHERE DVE_ANUL = 1 AND DVE_PMRP = 0
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @CodTipoDoc, @Numero, @Ano
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE FAC_DVEN SET 
				DVE_PMRP = 1				
			WHERE DVE_TDOC = @CodTipoDoc AND DVE_NDOC = @Numero AND DVE_EANO = @Ano 
			FETCH NEXT FROM Documentos INTO @CodTipoDoc, @Numero, @Ano
		END
		CLOSE Documentos
		DEALLOCATE Documentos				
	END
END

ALTER TABLE [dbo].[FAC_DVEN] ENABLE TRIGGER [tr_FAC_DVEN_Atualizacoes_U]
/****** Object:  Trigger [TAI_FAC_LCCT]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_FAC_LCCT] ON [FAC_LCCT] FOR INSERT AS 
BEGIN
	set nocount on	
--declaracao de variaveis
	DECLARE @tipo varchar(4), @num int, @ano int, @data datetime, @entidade varchar(18), 	@ncon varchar(18), @ndes varchar(3), @npro int, @vtot numeric(38,6), @vdeb numeric(38,6), 
		@viva numeric(38,6), @iv01 numeric(38,6), @iv02 numeric(38,6), @iv03 numeric(38,6), @iv04 numeric(38,6), @vinc01 numeric(38,6), @vinc02 numeric(38,6), @vinc03 numeric(38,6),
		@vinc04 numeric(38,6), @reca bit, @utic varchar(30), @dtcria datetime, @utia varchar(30), @dtalter datetime, @desc varchar(100), @tmovi int, @tenti int, @cc bit, @contexto int, 
		@impresso bit, @stat int, @dori varchar(20), @dint varchar(20), @comp varchar(50), @Serie varchar(20)
-- busca dados a inserir
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT LCC_TDOC, LCC_NDOC, LCC_EANO, LCC_DATA, CLI_CODI, LCC_CNIF, LCC_VTOT, LCC_UTIC, LCC_DTCR, LCC_UTIA, LCC_DTAL, LCC_CTXT, LCC_IMPR, LCC_SINA, LCC_STAT, LCC_DORI, LCC_DINT, LCC_COMP, 
			LCC_SERI
		FROM inserted
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @vtot, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, @tmovi, @stat, @dori, @dint, @comp, @Serie		  	
	WHILE @@FETCH_STATUS = 0
	BEGIN
--verifica o tipo de entidade, tipo de movimento, se contacorrente e mrec a true
		select @cc = TDO_CONC, @tenti = TDO_TENT, @reca = TDO_MREC
		from TAB_TDOC WITH(NOLOCK)
		where TDO_DOCU = @tipo
--se conta corrente = 1 movimenta C.C. 
		if @cc = 1 
		begin
			--inserir informação referênte ao tipo de documento 
			INSERT INTO FAC_MVCC(MVC_TDOC, MVC_NDOC, MVC_EANO, MVC_DATA, MVC_TMOV, MVC_TENT, MVC_ENTI, MVC_NCON, MVC_VTOT, MVC_VDEB, MVC_RECA, MVC_UTIC, MVC_DTCR, MVC_UTIA, MVC_DTAL, MVC_CTXT,
				MVC_IMPR, MVC_STAT, MVC_DORI, MVC_DINT, MVC_COMP, MVC_SERI)
			VALUES(@tipo, @num, @ano, @data, @tmovi, @tenti, @entidade, @ncon, @vtot, @vtot, @reca, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, @stat, @dori, @dint, @comp, @Serie)	
		end			
		FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @vtot, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, @tmovi, @stat, @dori, @dint, @comp, @Serie
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	set nocount off
END

ALTER TABLE [dbo].[FAC_LCCT] ENABLE TRIGGER [TAI_FAC_LCCT]
/****** Object:  Trigger [TAU_FAC_LCCT]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_FAC_LCCT] ON [FAC_LCCT] FOR UPDATE AS 
BEGIN
	set nocount on
	-- declaracao de variaveis -------------------------------------------------------------------------
	DECLARE @tipo varchar(4), @num int, @ano int, @data datetime, @entidade varchar(18), @ncon varchar(18), @vtot numeric(38,6), @reca bit, @utic varchar(30), @dtcria datetime, @utia varchar(30), 
		@dtalter datetime, @desc varchar(100), @tmovi int, @tenti int, @cc bit, @anulado bit, @contexto int, @impresso bit, @stat int, @dori varchar(20), @dint varchar(20), @comp varchar(50), 
		@Serie varchar(20)
	-- busca dados a inserir ---------------------------------------------------------------------------
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT LCC_TDOC, LCC_NDOC, LCC_EANO, LCC_DATA, CLI_CODI, LCC_CNIF, LCC_VTOT, LCC_UTIC, LCC_DTCR, LCC_UTIA, LCC_DTAL, LCC_ANUL, LCC_CTXT, LCC_IMPR, LCC_SINA, LCC_STAT, LCC_DORI, LCC_DINT, 
			LCC_COMP, LCC_SERI
		FROM inserted
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @vtot,	@utic, @dtcria, @utia, @dtalter, @anulado, @contexto, @impresso, @tmovi, @stat, @dori, @dint, @comp, @Serie
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- verifica se apenas foi alterado o campo status para remessa, sim não executa alteração na conta corrente
		IF UPDATE (LCC_STAT) AND @stat=2
		BEGIN
			SELECT @stat=2
		END
		ELSE
		BEGIN
			-- verifica o tipo de entidade, tipo de movimento, se contacorrente e mrec a true ----------		
			SELECT @cc = TDO_CONC, @tenti = TDO_TENT, @reca = TDO_MREC
			FROM TAB_TDOC WITH(NOLOCK)
			WHERE TDO_DOCU = @tipo
			-- se conta corrente = 1 movimenta C.C. ----------------------------------------------------
			IF @cc = 1
			BEGIN
				-- se documento foi anulado apaga da conta corrente --------------------------------
				IF @anulado = 1			
				BEGIN
					DELETE FROM FAC_MVCC WHERE MVC_TDOC = @tipo AND MVC_NDOC = @num AND MVC_EANO = @ano			
				END
				ELSE
				BEGIN
					UPDATE FAC_MVCC SET MVC_DATA = @data , MVC_TMOV = @tmovi, MVC_TENT = @tenti, MVC_IMPR = @impresso, MVC_ENTI = @entidade, MVC_NCON = @ncon, MVC_VTOT = @vtot, MVC_VDEB = @vtot, 
					   	MVC_RECA = @reca, MVC_UTIC = @utic, MVC_DTCR = @dtcria, MVC_UTIA = @utia, MVC_DTAL = @dtalter, MVC_STAT = @stat, MVC_DORI = @dori, MVC_DINT = @dint, MVC_COMP = @comp, 
						MVC_SERI = @Serie
					WHERE MVC_TDOC = @tipo and MVC_NDOC = @num and MVC_EANO = @ano
				END
			END
		END
		FETCH NEXT FROM Detalhe INTO @tipo, @num, @ano, @data, @entidade, @ncon, @vtot, @utic, @dtcria, @utia, @dtalter, @anulado, @contexto, @impresso, @tmovi, @stat, @dori, @dint, @comp, @Serie
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	set nocount off
END

ALTER TABLE [dbo].[FAC_LCCT] ENABLE TRIGGER [TAU_FAC_LCCT]
/****** Object:  Trigger [TAI_FAC_RECC]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_FAC_RECC] ON [FAC_RECC] FOR INSERT AS 
BEGIN
	SET NOCOUNT ON
--declaracao de variaveis
	DECLARE @rtipo varchar(4), @rnum int, @rano int, @data datetime, @vtot numeric(38,6), @vliq numeric(38,6), @vdes numeric(38,6), @pagt bit, @cc int, @tenti int, @tmovi int, @reca bit, 
		@entidade varchar(18), @ncon varchar(18), @utic varchar(30), @dtcria datetime, @utia varchar(30), @dtalter datetime, @contexto int, @impresso bit, @stat int, @nomeDoc varchar(50), 
		@docl varchar(50), @CodValidacaoAT varchar(30), @DocContabilistico bit, @InvoiceNumber varchar(60), @Serie varchar(20)
-- busca dados a inserir
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT i.REC_TDOC, i.REC_NDOC, i.REC_EANO, i.REC_DATA, i.REC_ENTI, i.REC_VLIQ, i.REC_VDES, i.REC_VTOT, i.REC_UTIC, i.REC_DTCR, i.REC_UTIA, i.REC_DTAL, i.REC_CTXT, i.REC_IMPR, i.REC_CNIF, 
			i.REC_DOCL, i.REC_SERI, t.TDO_DESC, t.TDO_CONC, t.TDO_TENT, t.TDO_TMOV, t.TDO_MREC, t.TDO_DCON, n.NUM_CVAT, 
			SUBSTRING((i.REC_TDOC + ' ' + i.REC_SERI + '/' + CAST(i.REC_NDOC AS varchar(10))), 1, 60)
		FROM inserted AS i INNER JOIN TAB_TDOC AS t WITH(NOLOCK) ON i.REC_TDOC = t.TDO_DOCU
			INNER JOIN TAB_NUMD AS n WITH(NOLOCK) ON i.REC_TDOC = n.TDO_DOCU AND i.REC_EANO = n.NUM_EANO
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @rtipo, @rnum, @rano, @data, @entidade, @vliq, @vdes, @vtot, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, @ncon, @docl, @Serie, @nomeDoc, @cc, @tenti, 
		@tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- Para os documentos contabilisticos preenche o invoice number
		IF @DocContabilistico = 1
		BEGIN
			ALTER TABLE FAC_RECC DISABLE TRIGGER TAU_FAC_RECC
			UPDATE FAC_RECC SET REC_INVN = @InvoiceNumber
			WHERE REC_TDOC = @rtipo and REC_NDOC = @rnum and REC_EANO = @rano 
			ALTER TABLE FAC_RECC ENABLE TRIGGER TAU_FAC_RECC	
		END
-- se código validação existir para o tipo documento/ano, calcula o ATCUD
		IF ISNULL(@CodValidacaoAT, '') <> ''
		BEGIN
			ALTER TABLE FAC_RECC DISABLE TRIGGER TAU_FAC_RECC
			UPDATE FAC_RECC SET REC_ATCU = ISNULL((@CodValidacaoAT + '-' + CAST(@rnum AS varchar(10))), '0')
			WHERE REC_TDOC = @rtipo and REC_NDOC = @rnum and REC_EANO = @rano 
			ALTER TABLE FAC_RECC ENABLE TRIGGER TAU_FAC_RECC			
		END
--se conta corrente = 1 movimenta C.C. 
		IF @cc = 1
		BEGIN
--inserir informação referênte ao tipo de documento 
			INSERT INTO FAC_MVCC(MVC_TDOC, MVC_NDOC, MVC_EANO, MVC_DATA, MVC_TMOV,  MVC_TENT, MVC_ENTI, MVC_NCON, MVC_NDES, MVC_NPRO, MVC_VTOT, MVC_VDEB, MVC_VIVA, MVC_VI01, MVC_VI02, MVC_VI03, 
				MVC_VI04, MVC_IN01, MVC_IN02, MVC_IN03, MVC_IN04, MVC_RECA, MVC_UTIC, MVC_DTCR, MVC_UTIA, MVC_DTAL, MVC_CTXT, MVC_IMPR, MVC_STAT, MVC_DORI, MVC_DINT, MVC_COMP, MVC_SERI)
			VALUES(@rtipo, @rnum, @rano, @data, @tmovi, @tenti, @entidade, @ncon, '', '', @vliq, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @reca, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, 1, 
				(@nomeDoc + ' N.º' + cast(@rnum as varchar)), @docl, '', @Serie)	
		END
		FETCH NEXT FROM Detalhe INTO @rtipo, @rnum, @rano, @data, @entidade, @vliq, @vdes, @vtot, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, @ncon, @docl, @Serie, @nomeDoc, @cc, @tenti, 
			@tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[FAC_RECC] ENABLE TRIGGER [TAI_FAC_RECC]
/****** Object:  Trigger [TAU_FAC_RECC]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_FAC_RECC] ON [FAC_RECC] FOR UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis -------------------------------------------------------------------------
	DECLARE @rtipo varchar(4), @rnum int, @rano int, @data datetime, @vtot numeric(38,6), @vliq numeric(38,6), @vdes numeric(38,6), @pagt bit, @cc int, @tenti int, @tmovi int, @reca bit, 
		@entidade varchar(18), @ncon varchar(18), @utic varchar(30), @dtcria datetime, @utia varchar(30), @dtalter datetime, @contexto int, @impresso bit, @stat int, @nomeDoc varchar(50), 
		@docl varchar(50), @CodValidacaoAT varchar(30), @DocContabilistico bit, @InvoiceNumber varchar(60), @Serie varchar(20)
-- busca dados a inserir -------------------------------------------------------------------
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT i.REC_TDOC, i.REC_NDOC, i.REC_EANO, i.REC_DATA, i.REC_ENTI, i.REC_VLIQ, i.REC_VDES, i.REC_VTOT, i.REC_UTIC, i.REC_DTCR, i.REC_UTIA, i.REC_DTAL, i.REC_CTXT, i.REC_IMPR, i.REC_CNIF, 
			i.REC_DOCL, i.REC_STAT, i.REC_SERI, t.TDO_DESC, t.TDO_CONC, t.TDO_TENT, t.TDO_TMOV, t.TDO_MREC, t.TDO_DCON, n.NUM_CVAT, 
			SUBSTRING((i.REC_TDOC + ' ' + i.REC_SERI + '/' + CAST(i.REC_NDOC AS varchar(10))), 1, 60)
		FROM inserted AS i INNER JOIN TAB_TDOC AS t WITH(NOLOCK) ON i.REC_TDOC = t.TDO_DOCU
			INNER JOIN TAB_NUMD AS n WITH(NOLOCK) ON i.REC_TDOC = n.TDO_DOCU AND i.REC_EANO = n.NUM_EANO
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @rtipo, @rnum, @rano, @data, @entidade, @vliq, @vdes, @vtot, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, @ncon, @docl, @stat, @Serie, @nomeDoc, @cc, 
		@tenti, @tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- verifica se apenas foi alterado o campo status para remessa, sim não executa alteração na conta corrente
		IF UPDATE (REC_STAT) AND (@stat = 2)
			SELECT @stat = 2		
		ELSE
		BEGIN	
-- Para os documentos contabilisticos calcula o invoice number
			IF (@DocContabilistico = 1) AND ((UPDATE(REC_TDOC)) OR (UPDATE(REC_NDOC)) OR (UPDATE(REC_SERI)))
			BEGIN				
				UPDATE FAC_RECC SET REC_INVN = @InvoiceNumber
				WHERE REC_TDOC = @rtipo and REC_NDOC = @rnum and REC_EANO = @rano 			
			END
-- se código validação existir para o tipo documento/ano, calcula o ATCUD
			IF (ISNULL(@CodValidacaoAT, '') <> '') AND (UPDATE(REC_NDOC))
			BEGIN				
				UPDATE FAC_RECC SET REC_ATCU = ISNULL((@CodValidacaoAT + '-' + CAST(@rnum AS varchar(10))), '0')
				WHERE REC_TDOC = @rtipo and REC_NDOC = @rnum and REC_EANO = @rano 
			END					
-- se conta corrente = 1 movimenta C.C. e se o novo estado não é remessa ------------
			IF @cc = 1 
			BEGIN
				-- actualiza a conta corrente ----------------------------------------------- 
				UPDATE FAC_MVCC SET MVC_DATA = @data, MVC_TMOV = @tmovi, MVC_TENT = @tenti, MVC_ENTI = @entidade, MVC_NCON = @ncon, MVC_VTOT = @vliq, MVC_RECA = @reca, MVC_UTIC = @utic, 
					MVC_DTCR = @dtcria, MVC_UTIA = @utia, MVC_DTAL = @dtalter, MVC_CTXT = @contexto, MVC_IMPR = @impresso, MVC_DORI = (@nomeDoc + ' N.º' + cast(@rnum as varchar)), 
					MVC_DINT = @docl, MVC_STAT = @stat, MVC_SERI = @Serie
				WHERE MVC_TDOC = @rtipo AND MVC_NDOC = @rnum AND MVC_EANO = @rano
			END
		END
		FETCH NEXT FROM Detalhe INTO @rtipo, @rnum, @rano, @data, @entidade, @vliq, @vdes, @vtot, @utic, @dtcria, @utia, @dtalter, @contexto, @impresso, @ncon, @docl, @stat, @Serie, @nomeDoc, @cc, 
			@tenti, @tmovi, @reca, @DocContabilistico, @CodValidacaoAT, @InvoiceNumber
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[FAC_RECC] ENABLE TRIGGER [TAU_FAC_RECC]
/****** Object:  Trigger [TAD_FAC_RECD]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_FAC_RECD] ON [FAC_RECD] FOR DELETE AS 
BEGIN
set nocount on
-- declaracao de variaveis
declare @mtipo varchar(4), @mnum int, @mano int, @vpag numeric(38,6), @vdes numeric(38,6), @tota numeric(38,6)
-- busca dados removidos
DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT MVC_TDOC, MVC_NDOC, MVC_EANO, REC_VPAG, REC_VDES
	FROM deleted
OPEN Detalhe
FETCH NEXT FROM Detalhe INTO @mtipo, @mnum, @mano, @vpag, @vdes
WHILE @@FETCH_STATUS = 0
BEGIN
	select @Tota = @VPag + @VDes
-- trata valores negativos
	IF @Tota < 0
		SELECT @Tota = @Tota * (-1)
--inserir informação referênte ao tipo de documento 
	UPDATE FAC_MVCC set MVC_VDEB = MVC_VDEB + @Tota
	WHERE MVC_TDOC = @mtipo and MVC_NDOC = @mnum and MVC_EANO = @mano 

	FETCH NEXT FROM Detalhe INTO @mtipo, @mnum, @mano, @vpag, @vdes
END
CLOSE Detalhe
DEALLOCATE Detalhe
set nocount off
END

ALTER TABLE [dbo].[FAC_RECD] ENABLE TRIGGER [TAD_FAC_RECD]
/****** Object:  Trigger [TAIU_FAC_RECD]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_FAC_RECD] ON [FAC_RECD] FOR INSERT, UPDATE AS 
BEGIN
set nocount on
-- declaracao de variaveis
declare @mtipo varchar(4), @mnum int, @mano int, @vdeb numeric(38,6)
-- busca dados removidos
DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT MVC_TDOC, MVC_NDOC, MVC_EANO, REC_VDEB
	FROM inserted
OPEN Detalhe
FETCH NEXT FROM Detalhe INTO @mtipo, @mnum, @mano, @vdeb
WHILE @@FETCH_STATUS = 0
BEGIN
-- trata valores negativos
	IF @vdeb < 0
		SELECT @vdeb = @vdeb * (-1)
--inserir informação referênte ao tipo de documento 
	UPDATE FAC_MVCC set MVC_VDEB = @vdeb
	WHERE MVC_TDOC = @mtipo and MVC_NDOC = @mnum and MVC_EANO = @mano 

	FETCH NEXT FROM Detalhe INTO @mtipo, @mnum, @mano, @vdeb
END
CLOSE Detalhe
DEALLOCATE Detalhe
set nocount off
END

ALTER TABLE [dbo].[FAC_RECD] ENABLE TRIGGER [TAIU_FAC_RECD]
/****** Object:  Trigger [TAIUD_PRO_DCON]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DCON] ON [PRO_DCON] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	if UPDATE(DCO_CNUM) or UPDATE(DCO_TIPO)
	begin
		insert into LOG_DCON (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO)
		select NEWID(), (case (select count(*) from deleted where DCO_IDEN = inserted.DCO_IDEN) when 0 then 0 else 1 end), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), DUC_EANO, 
			DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO
		from inserted
		where ((select count(*) from deleted where DCO_IDEN = inserted.DCO_IDEN) = 0)
			or ((select count(*) from deleted where DCO_IDEN = inserted.DCO_IDEN and ((isnull(DCO_CNUM, '') <> isnull(inserted.DCO_CNUM, '')) or 
			(isnull(DCO_TIPO, '') <> isnull(inserted.DCO_TIPO, '')))) > 0)
	end
	else
	begin
		insert into LOG_DCON (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_EANO, DUC_PNUM, DUA_CODI, DCO_CODI, DCO_CNUM, DCO_TIPO
		from deleted
		where (select count(*) from inserted where DCO_IDEN = deleted.DCO_IDEN) = 0
	end
END

ALTER TABLE [dbo].[PRO_DCON] ENABLE TRIGGER [TAIUD_PRO_DCON]
/****** Object:  Trigger [TAU_PRO_DCON]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DCON] ON [PRO_DCON] FOR UPDATE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @NumDeclaracao int, @AnoDeclaracao int, @NumAdicao int, @NumContentor int
-- verifica se campo "Contentor" foi alterado e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO" para colocar declarações como pendentes de envio para Portal MyRangel
	IF UPDATE(DCO_CNUM) AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO, DUA_CODI, DCO_CODI
			FROM inserted 
			WHERE DCO_PMRP = 0 
		OPEN Contentores
		FETCH NEXT FROM Contentores INTO @NumDeclaracao, @AnoDeclaracao, @NumAdicao, @NumContentor
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE PRO_DCON SET 
				DCO_PMRP = 1				
			WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao AND DUA_CODI = @NumAdicao AND DCO_CODI = @NumContentor
			FETCH NEXT FROM Contentores INTO @NumDeclaracao, @AnoDeclaracao, @NumAdicao, @NumContentor
		END
		CLOSE Contentores
		DEALLOCATE Contentores				
	END
END

ALTER TABLE [dbo].[PRO_DCON] ENABLE TRIGGER [TAU_PRO_DCON]
/****** Object:  Trigger [TAIU_PRO_DDOC_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DDOC_IMPCAU] ON [PRO_DDOC] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @NumProxRegisto int
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @CodDocumento varchar(5), @NomeDocumento varchar(150), @NumeroDocumento varchar(70), 
		@DataValidadeDocumento datetime, @CodPais varchar(2), @Montante numeric(38, 6), @InvoicNumber varchar(25), @TipoDocumento int, @EntidadeEmissora varchar(70), 
		@CodUnidMedida varchar(3), @Quantidade numeric(38, 6), @NumLinha int
-- se coluna do documento alterada, processa a inserção dos documentos configurados para cópia nas restantes adições
	IF UPDATE(DOC_CODI)
	BEGIN
-- insere os documentos configurados para cópia nas restantes adições e ainda não existentes no anexo de documentos da adição > 1
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUC_EANO, adi.DUC_PNUM, adi.DUA_CODI, ins.DOC_CODI, ins.DOC_NOME, ins.DDO_NUME, ins.DDO_DINI, ins.PAI_CODI, ins.DDO_MONT, ins.DDO_NINV, ins.DDO_TIPO, 
				ins.DDO_EEMI, ins.UME_CODI, ins.DDO_QTDE, ins.DDO_NLIN
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ins.DOC_CODI = doc.DOC_CODI
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI > 1	
			WHERE duc.DUC_DUNO = 2 AND ins.DUA_CODI = 1 AND doc.DOC_RSDA = 1 
				AND NOT EXISTS(SELECT DDO_IDEN 
								FROM PRO_DDOC WITH(NOLOCK)
								WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = adi.DUA_CODI AND DOC_CODI = doc.DOC_CODI AND DDO_AUTO = 0)
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataValidadeDocumento, @CodPais, 
			@Montante, @InvoicNumber, @TipoDocumento, @EntidadeEmissora, @CodUnidMedida, @Quantidade, @NumLinha
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(DDO_CODI), 0) + 1
			FROM PRO_DDOC
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento no detalhe de documentos da adição IMP-CAU
			INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, PAI_CODI, DDO_MONT, DDO_NINV, DDO_AUTO, DDO_TIPO, DDO_EEMI, 
				UME_CODI, DDO_QTDE, DDO_NLIN)			
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataValidadeDocumento, @CodPais, @Montante, @InvoicNumber, 0, @TipoDocumento, @EntidadeEmissora, 
				@CodUnidMedida, @Quantidade, (CASE WHEN @NumLinha IS NOT NULL THEN @NumAdicao ELSE NULL END))				
			FETCH NEXT FROM Documentos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataValidadeDocumento, @CodPais, 
				@Montante, @InvoicNumber, @TipoDocumento, @EntidadeEmissora, @CodUnidMedida, @Quantidade, @NumLinha
		END
		CLOSE Documentos
		DEALLOCATE Documentos				
	END
END

ALTER TABLE [dbo].[PRO_DDOC] ENABLE TRIGGER [TAIU_PRO_DDOC_IMPCAU]
/****** Object:  Trigger [TAIUD_PRO_DDOC]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DDOC] ON [PRO_DDOC] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	if UPDATE(DOC_CODI) or UPDATE(DDO_NUME) or UPDATE(DDO_DINI) or UPDATE(DDO_DFIM) or UPDATE(CEN_CODI) or UPDATE(PAI_CODI) or UPDATE(DDO_MONT) 
	or UPDATE(DDO_DPRZ) or UPDATE(DDO_NINV) or UPDATE(DDO_AUTO)
	begin
		insert into LOG_DDOC (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DDO_NUME, DDO_DINI, 
			DDO_DFIM, CEN_CODI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_NINV, DDO_AUTO)
		select NEWID(), (case (select count(*) from deleted where DDO_IDEN = inserted.DDO_IDEN) when 0 then 0 else 1 end), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), DUC_EANO, 
			DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DDO_NUME, DDO_DINI, DDO_DFIM, CEN_CODI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_NINV, DDO_AUTO
		from inserted
		where ((select count(*) from deleted where DDO_IDEN = inserted.DDO_IDEN) = 0)
			or ((select count(*) from deleted where DDO_IDEN = inserted.DDO_IDEN and ((DOC_CODI <> inserted.DOC_CODI) or 
			(isnull(DDO_NUME, '') <> isnull(inserted.DDO_NUME, '')) or (isnull(DDO_DINI, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.DDO_DINI, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or 
			(isnull(DDO_DFIM, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.DDO_DFIM, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (isnull(CEN_CODI, '') <> isnull(inserted.CEN_CODI, '')) or 
			(isnull(PAI_CODI, '') <> isnull(inserted.PAI_CODI, '')) or (isnull(DDO_MONT, -1) <> isnull(inserted.DDO_MONT, -1)) or 
			(isnull(DDO_DPRZ, -1) <> isnull(inserted.DDO_DPRZ, -1)) or (isnull(DDO_NINV, '') <> isnull(inserted.DDO_NINV, '')) or 
			(isnull(DDO_AUTO, -1) <> isnull(inserted.DDO_AUTO, -1)))) > 0)
	end
	else
	begin
		insert into LOG_DDOC (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DDO_NUME, DDO_DINI, 
			DDO_DFIM, CEN_CODI, PAI_CODI, DDO_MONT, DDO_DPRZ, DDO_NINV, DDO_AUTO)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DDO_NUME, DDO_DINI, DDO_DFIM, CEN_CODI, PAI_CODI, DDO_MONT, DDO_DPRZ, 
			DDO_NINV, DDO_AUTO
		from deleted
		where (select count(*) from inserted where DDO_IDEN = deleted.DDO_IDEN) = 0
	end
END

ALTER TABLE [dbo].[PRO_DDOC] ENABLE TRIGGER [TAIUD_PRO_DDOC]
/****** Object:  Trigger [TAU_PRO_DESS]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DESS] ON [PRO_DESS] AFTER UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @CodEstanciaA varchar(8), @NomeEstanciaA varchar(35), @NumeroDGA varchar(22), @DataDGA datetime, @IDLinhaAWBSDS int, @IDDocLinhaAWBSDS int
-- se colunas de estado de operação alterada para "Declaração Aceite" e número e data DGA alteradas para atribuição de valor
	IF UPDATE(DSS_ESTA) AND UPDATE(DSS_NDGA) AND UPDATE(DSS_DDGA)
	BEGIN
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR	
			SELECT ins.EAD_CODI, ins.EAD_NOME, ins.DSS_NDGA, ins.DSS_DDGA, dsa.DSD_IDNN
			FROM inserted AS ins INNER JOIN deleted AS del ON ins.DSS_IDEN = del.DSS_IDEN
				INNER JOIN PRO_DSSA AS dsa WITH(NOLOCK) ON ins.DSS_EANO = dsa.DSS_EANO AND ins.DCS_CODI = dsa.DCS_CODI AND ins.DSS_NPRO = dsa.DSS_NPRO
			WHERE ins.DSS_ESTA = 2 AND ISNULL(del.DSS_ESTA, 0) <> 2 AND ISNULL(ins.DSS_NDGA, '') <> '' AND ISNULL(del.DSS_NDGA, '') = '' AND ins.DSS_DDGA IS NOT NULL AND del.DSS_DDGA IS NULL
				AND dsa.DSD_IDNN IS NOT NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @CodEstanciaA, @NomeEstanciaA, @NumeroDGA, @DataDGA, @IDLinhaAWBSDS
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- obtem o próximo número a atribuir ao documento "4D01"
			SET @IDDocLinhaAWBSDS = ISNULL((SELECT MAX(SDD_NUME)
											FROM PRO_SDSD AS dsd WITH(NOLOCK) INNER JOIN PRO_SSDD AS sdd ON dsd.DSC_EANO = sdd.DSC_EANO AND dsd.DSC_NPRO = sdd.DSC_NPRO AND dsd.DSD_NUME = sdd.DSD_NUME
											WHERE dsd.DSD_IDNN = @IDLinhaAWBSDS), 0) + 1
-- insere o documento "4D01" na linha AWB do SDS - Via Aérea de Exportação 
			INSERT INTO PRO_SSDD(DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC)		
			SELECT dsd.DSC_EANO, dsd.DSC_NPRO, dsd.DSD_NUME, @IDDocLinhaAWBSDS, doc.DOC_CODI, doc.DOC_NOME, @NumeroDGA, @DataDGA, @CodEstanciaA, @NomeEstanciaA, 'T'
			FROM PRO_SDSD AS dsd WITH(NOLOCK) INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = '4D01'
			WHERE dsd.DSD_IDNN = @IDLinhaAWBSDS
			FETCH NEXT FROM Adicoes INTO @CodEstanciaA, @NomeEstanciaA, @NumeroDGA, @DataDGA, @IDLinhaAWBSDS
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END
END

ALTER TABLE [dbo].[PRO_DESS] ENABLE TRIGGER [TAU_PRO_DESS]
/****** Object:  Trigger [TAD_PRO_DU31_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DU31_IMPCAU] ON [PRO_DU31] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @IdRegisto int, @SomaVolumes numeric(38, 6)
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- obtem as marcas e volumes configuradas como parte nas restantes adições e existentes no anexo de marcas e volumes da adição > 1
	DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, dam.D31_IDEN
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI > 1
			INNER JOIN PRO_DU31 AS dam WITH(NOLOCK) ON adi.DUC_EANO = dam.DUC_EANO AND adi.DUC_PNUM = dam.DUC_PNUM AND adi.DUA_CODI = dam.DUA_CODI AND dam.D31_AUTO = 1
		WHERE duc.DUC_DUNO = 2 AND del.DUA_CODI = 1 AND del.D31_CASP = 1		
	OPEN MarcasEVolumes
	FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove marca e volume					
		DELETE FROM PRO_DU31
		WHERE D31_IDEN = @IdRegisto
-- atualiza numero de marcas e volumes posteriores
		UPDATE PRO_DU31 SET D31_CODI = D31_CODI - 1    
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND D31_IDEN > @IdRegisto 
		FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	END
	CLOSE MarcasEVolumes
	DEALLOCATE MarcasEVolumes		
-- obtem as declarações associadas às marcas e volumes não originadas em P/R removidas
	DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM
		FROM deleted AS del
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2 AND del.D31_AUTO <> 1
		GROUP BY del.DUC_EANO, del.DUC_PNUM
	OPEN MarcasEVolumes
	FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula a soma dos volumes das marcas e volumes não originadas em P/R de todas as adições da declaração IMP-CAU
		SET @SomaVolumes = ISNULL(
			(SELECT SUM(D31_QNTD)
			FROM PRO_DU31 WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND D31_AUTO <> 1), 0)
-- atualiza total de volumes na declaração IMP-CAU
		UPDATE PRO_DUCG SET 
			DUC_TVL6 = @SomaVolumes				
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
		FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao
	END
	CLOSE MarcasEVolumes
	DEALLOCATE MarcasEVolumes			
END

ALTER TABLE [dbo].[PRO_DU31] ENABLE TRIGGER [TAD_PRO_DU31_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DU31_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DU31_IMPCAU] ON [PRO_DU31] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @Marca varchar(512), @NumeroObjeto varchar(20), @CodUnidadeMedida varchar(3), @NomeUnidadeMedida varchar(35), @Parte bit, 
		@VolumesZero bit, @CodigoBarras varchar(30), @IdRegisto int, @NumProxRegisto int, @SomaVolumes numeric(38, 6)
-- se colunas da marca, tipo volume ou parte alteradas, processa a inserção/edição das marcas e volumes configuradas como parte nas restantes adições
	IF UPDATE(D31_MARC) OR UPDATE(UME_CODI) OR UPDATE(D31_CASP)
	BEGIN
-- insere/edita as marcas e volumes configuradas como parte nas restantes adições e ainda não existentes no anexo de marcas e volumes da adição > 1
		DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUC_EANO, adi.DUC_PNUM, adi.DUA_CODI, ins.D31_MARC, ins.D31_NUME, ins.UME_CODI, ins.UME_NOME, ins.D31_CASP, ins.D31_TTVL, ins.D31_LOPT, dam.D31_IDEN
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.D31_IDEN = del.D31_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI > 1
				LEFT OUTER JOIN PRO_DU31 AS dam WITH(NOLOCK) ON adi.DUC_EANO = dam.DUC_EANO AND adi.DUC_PNUM = dam.DUC_PNUM AND adi.DUA_CODI = dam.DUA_CODI AND dam.D31_AUTO = 1
			WHERE duc.DUC_DUNO = 2 AND ins.DUA_CODI = 1 AND ((ins.D31_CASP = 1) OR (del.D31_CASP = 1))							
		OPEN MarcasEVolumes
		FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @Marca, @NumeroObjeto, @CodUnidadeMedida, @NomeUnidadeMedida, @Parte, @VolumesZero, @CodigoBarras, 
			@IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere a marca e volume parte da adição
			IF (@IdRegisto IS NULL) AND (@Parte = 1)
			BEGIN 
-- obtem o próximo numero de registo de marcas e volumes da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(D31_CODI), 0) + 1
				FROM PRO_DU31
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere a marca e volume no detalhe de marcas e volumes da adição IMP-CAU
				INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_TTVL, D31_AUTO, D31_LOPT)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @Marca, @NumeroObjeto, 0, @CodUnidadeMedida, @NomeUnidadeMedida, 0, @VolumesZero, 1, @CodigoBarras)			
			END
			ELSE
-- edita a marca e volume parte da adição
				IF @Parte = 1
				BEGIN
					UPDATE PRO_DU31 SET											 
						D31_MARC = @Marca, 
						D31_NUME = @NumeroObjeto, 
						UME_CODI = @CodUnidadeMedida, 
						UME_NOME = @NomeUnidadeMedida, 
						D31_TTVL = @VolumesZero, 
						D31_LOPT = @CodigoBarras
					WHERE D31_IDEN = @IdRegisto
				END
				ELSE
				BEGIN
-- remove marca e volume					
					DELETE FROM PRO_DU31
					WHERE D31_IDEN = @IdRegisto
-- atualiza numero de marcas e volumes posteriores
					UPDATE PRO_DU31 SET D31_CODI = D31_CODI - 1    
					WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND D31_IDEN > @IdRegisto 
				END
			FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @Marca, @NumeroObjeto, @CodUnidadeMedida, @NomeUnidadeMedida, @Parte, @VolumesZero, @CodigoBarras, 
				@IdRegisto
		END
		CLOSE MarcasEVolumes
		DEALLOCATE MarcasEVolumes		
	END
-- se coluna de n.º volumes alterada, processa a edição do total de volumes na declaração IMP-CAU
	IF (ISNULL(CONTEXT_INFO(), 0x0) <> 0x44495341424C4544) AND (UPDATE(D31_QNTD)) --"DISABLED" em binário
	BEGIN
-- obtem as declarações associadas às marcas e volumes não originadas em P/R inseridas/editadas
		DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM
			FROM inserted AS ins 				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
			WHERE duc.DUC_DUNO = 2 AND ins.D31_AUTO <> 1
			GROUP BY ins.DUC_EANO, ins.DUC_PNUM
		OPEN MarcasEVolumes
		FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a soma dos volumes das marcas e volumes não originadas em P/R de todas as adições da declaração IMP-CAU
			SET @SomaVolumes = ISNULL(
				(SELECT SUM(D31_QNTD)
				FROM PRO_DU31 WITH(NOLOCK)
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND D31_AUTO <> 1), 0)
-- atualiza total de volumes na declaração IMP-CAU
			UPDATE PRO_DUCG SET 
				DUC_TVL6 = @SomaVolumes				
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
			FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao
		END
		CLOSE MarcasEVolumes
		DEALLOCATE MarcasEVolumes		
	END
END

ALTER TABLE [dbo].[PRO_DU31] ENABLE TRIGGER [TAIU_PRO_DU31_IMPCAU]
/****** Object:  Trigger [TAIUD_PRO_DU31]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DU31] ON [PRO_DU31] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	if UPDATE(D31_MARC) or UPDATE(D31_NUME) or UPDATE(D31_QNTD) or UPDATE(UME_CODI) or UPDATE(D31_CASP) or UPDATE(D31_CASR) or UPDATE(D31_CASC) or UPDATE(D31_TTVL)
	begin
		insert into LOG_DU31 (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, 
			UME_CODI, D31_CASP, D31_CASR, D31_CASC, D31_TTVL)
		select NEWID(), (case (select count(*) from deleted where D31_IDEN = inserted.D31_IDEN) when 0 then 0 else 1 end), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), DUC_EANO, 
			DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, D31_CASP, D31_CASR, D31_CASC, D31_TTVL
		from inserted
		where ((select count(*) from deleted where D31_IDEN = inserted.D31_IDEN) = 0)
			or ((select count(*) from deleted where D31_IDEN = inserted.D31_IDEN and ((isnull(D31_MARC, '') <> isnull(inserted.D31_MARC, '')) or 
			(isnull(D31_NUME, '') <> isnull(inserted.D31_NUME, '')) or (D31_QNTD <> inserted.D31_QNTD) or (isnull(UME_CODI, '') <> isnull(inserted.UME_CODI, '')) or 
			(D31_CASP <> inserted.D31_CASP) or (D31_CASR <> inserted.D31_CASR) or (D31_CASC <> inserted.D31_CASC) or (D31_TTVL <> inserted.D31_TTVL))) > 0)
	end
	else
	begin
		insert into LOG_DU31 (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, 
			UME_CODI, D31_CASP, D31_CASR, D31_CASC, D31_TTVL)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, D31_CASP, D31_CASR, D31_CASC, D31_TTVL
		from deleted
		where (select count(*) from inserted where D31_IDEN = deleted.D31_IDEN) = 0
	end
END

ALTER TABLE [dbo].[PRO_DU31] ENABLE TRIGGER [TAIUD_PRO_DU31]
/****** Object:  Trigger [TAD_PRO_DUAD_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUAD_IMPCAU] ON [PRO_DUAD] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumeroDeclaracao int, @NumeroAdicao int, @SomaAdicoes int, @SomaValorAduaneiro numeric(38, 6)
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- atualiza o numero das adições superiores à adição removida
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI
		FROM deleted AS del
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
		WHERE duc.DUC_DUNO = 2	
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumeroDeclaracao, @NumeroAdicao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE PRO_DUAD SET DUA_CODI = DUA_CODI - 1    
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumeroDeclaracao AND DUA_CODI > @NumeroAdicao
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumeroDeclaracao, @NumeroAdicao
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes   
-- obtem as declarações associadas às adições removidas
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM
		FROM deleted AS del
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2
		GROUP BY del.DUC_EANO, del.DUC_PNUM
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumeroDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula a soma do número de adições e do valor aduaneiro de todas as adições da declaração IMP-CAU
		SELECT @SomaAdicoes = COUNT(*), @SomaValorAduaneiro = SUM(ISNULL(DUA_VATO, 0))
		FROM PRO_DUAD WITH(NOLOCK)
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumeroDeclaracao
-- atualiza total de adições e valor aduaneiro total na declaração IMP-CAU
		UPDATE PRO_DUCG SET 
			DUC_ADI5 = @SomaAdicoes, 
			DUC_VATT = @SomaValorAduaneiro
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumeroDeclaracao
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumeroDeclaracao
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes	 
END

ALTER TABLE [dbo].[PRO_DUAD] ENABLE TRIGGER [TAD_PRO_DUAD_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUAD_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUAD_IMPCAU] ON [PRO_DUAD] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdRegisto bigint, @NumProxRegisto int, @Montante numeric(38, 6), @IdStrElementoTrib varchar(20), @SomaAdicoes int, @SomaValorAduaneiro numeric(38, 6)
	DECLARE @IdUtilizador int, @CambioFrete numeric(38, 6), @TaxaFDA numeric(38, 6), @PedeTaxaFDA bit
	DECLARE @IdAdicao int, @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @MassaLiquida numeric(38, 6), @Frete numeric(38, 6), @SomaFreteESeguro decimal(18, 2), 
		@Optativas numeric(38, 6), @VerbaTransitario numeric(38, 6), @ValorDireitosDDP numeric(38, 6), @Ajustamento numeric(38, 6), @BaseManual bit, 
		@BaseTributacao numeric(38, 6), @ETaxa bit, @TaxaValor numeric(38, 6), @NumeroCaucao varchar(24), @AnoCaucao varchar(4), @TipoCaucao varchar(1), @EntidadeCaucao int, 
		@CodAlfandegaCaucao varchar(8), @CodAcessoCaucao varchar(4), @OutrasReferenciasCaucao varchar(35), @NIFResponsavelCaucao varchar(17)
	DECLARE @CodRubricaReceita int, @NomeRubricaReceita varchar(35), @IVARubricaReceita bit, @ImposicaoRubricaReceita varchar(3)
	DECLARE @CodDocumento varchar(5), @NomeDocumento varchar(150), @NumeroDocumento varchar(70), @DataValidadeDocumento datetime, @TipoDocumento int, @CodPais varchar(2), 
		@InvoicNumber varchar(25), @EntidadeEmissora varchar(70), @CodUnidadeMedida varchar(3), @Quantidade numeric(38, 6), @NumLinha int
	DECLARE @Marca varchar(512), @NumeroObjeto varchar(20), @NomeUnidadeMedida varchar(35), @Parte bit, @VolumesZero bit, @CodigoBarras varchar(30)
	DECLARE @IdPedido int, @NumeroPedido varchar(512)	
	DECLARE @TipoAcrescimoDeducao tinyint, @CodAcrescimoDeducao varchar(2)
	DECLARE @CodUnidadeMedida2 varchar(6), @TipoOrigem int, @IdStrRegisto varchar(20)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- se colunas do artigo, massa líquida, base de tributação ou garantia/caução alteradas, processa a gestão de imposições dos artigos no detalhe de outras imposições das adições IMP-CAU inseridas/alteradas
	IF UPDATE(APA_CO33) OR UPDATE(DUA_ML38) OR UPDATE(DUA_BTRI) OR UPDATE(DUA_CAUD) OR UPDATE(DUA_CAND) OR UPDATE(DUA_CTID) OR UPDATE(DUA_CEND) OR UPDATE(ALF_CODI) OR UPDATE(DUA_CCAD) 
	OR UPDATE(DUA_CORD) OR UPDATE(DUA_CNRD)
	BEGIN
-- insere/edita as imposições configuradas no artigo no detalhe de outras imposições das adições IMP-CAU
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.DUA_ML38, ISNULL(doi.DUO_BMAN, 0), 
				ISNULL((CASE ISNULL(doi.DUO_BMAN, 0) WHEN 1 THEN ISNULL(doi.DUO_BTRI, 0) ELSE NULL END), ISNULL(ins.DUA_BTRI, 0)), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CAUC ELSE NULL END), ins.DUA_CAUD), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CANO ELSE NULL END), ins.DUA_CAND), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CTIP ELSE NULL END), ins.DUA_CTID), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CENT ELSE NULL END), ins.DUA_CEND), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.ALF_CODI ELSE NULL END), ins.ALF_CODI), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CCAC ELSE NULL END), ins.DUA_CCAD), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CORF ELSE NULL END), ins.DUA_CORD), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CNRD ELSE NULL END), ins.DUA_CNRD), 				
				rre.RRE_CODI, rre.RRE_NOME, rre.RRE_IVA, rre.RRE_IMPO, doi.DUO_IDEN, 				
				ISNULL((CASE ISNULL(doi.DUO_BMAN, 0) WHEN 1 THEN doi.DUO_TIPO ELSE NULL END), (CASE ISNULL(aoi.APO_OIMP, 0) WHEN 0 THEN CAST(0 AS bit) ELSE CAST(1 AS bit) END)), 
				ISNULL(doi.DUO_TXVL, (CASE ISNULL(aoi.APO_OIMP, 0) WHEN 0 THEN ISNULL(aoi.APO_VALO, 0) ELSE ISNULL(aoi.APO_OIMP, 0) END))
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.APA_CO33 = art.APA_CODI
				INNER JOIN TAB_APOI AS aoi WITH(NOLOCK) ON art.APA_CHVE = aoi.APA_CHVE
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON aoi.RRE_CODI = rre.RRE_CODI
				LEFT OUTER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND rre.RRE_CODI = doi.RRE_CODI AND doi.DUO_AUTO = 6
			WHERE duc.DUC_DUNO = 2 
				AND NOT EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE RRE_CDPT = rre.RRE_CODI)
				AND NOT EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE RRE_CDAL = rre.RRE_CODI)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @MassaLiquida, @BaseManual, @BaseTributacao, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, 
			@CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, @CodRubricaReceita, @NomeRubricaReceita, @IVARubricaReceita, @ImposicaoRubricaReceita, 
			@IdRegisto, @ETaxa, @TaxaValor
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a base de tributação apenas quando é valor e base não é manual
			IF (@ETaxa = 0) AND (@BaseManual = 0)
				SET @BaseTributacao = ROUND(@MassaLiquida, 2)	
-- calcula o montante em função se é taxa ou valor
			IF @ETaxa = 1
				SET @Montante = ROUND(@BaseTributacao * @TaxaValor / 100, 2)			
			ELSE
				SET @Montante = ROUND(@BaseTributacao * @TaxaValor, 2)	
-- insere ou edita a imposição do artigo
			IF @IdRegisto IS NULL
			BEGIN				
-- obtem o próximo numero de registo de outras imposições da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(DUO_CODI), 0) + 1
				FROM PRO_DUOI
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere a imposição no detalhe de outras imposições da adição IMP-CAU
				INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_LIVA, DUO_IMPO, DUO_AUTO, DUO_BMAN, DUO_CAUC, DUO_CANO, 
					DUO_CTIP, DUO_CENT, ALF_CODI, DUO_CCAC, DUO_CORF, DUO_CNRD)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodRubricaReceita, @NomeRubricaReceita, @ETaxa, @BaseTributacao, @TaxaValor, @Montante, @IVARubricaReceita, 
					@ImposicaoRubricaReceita, 6, @BaseManual, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, 
					@NIFResponsavelCaucao)			
			END
			ELSE
			BEGIN
				UPDATE PRO_DUOI SET											 
					DUO_TIPO = @ETaxa, 
					DUO_BTRI = @BaseTributacao, 
					DUO_MONT = @Montante, 													
					DUO_CAUC = @NumeroCaucao, 
					DUO_CANO = @AnoCaucao, 
					DUO_CTIP = @TipoCaucao, 
					DUO_CENT = @EntidadeCaucao, 
					ALF_CODI = @CodAlfandegaCaucao, 
					DUO_CCAC = @CodAcessoCaucao, 
					DUO_CORF = @OutrasReferenciasCaucao, 
					DUO_CNRD = @NIFResponsavelCaucao
				WHERE DUO_IDEN = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @MassaLiquida, @BaseManual, @BaseTributacao, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, 
				@CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, @CodRubricaReceita, @NomeRubricaReceita, @IVARubricaReceita, @ImposicaoRubricaReceita, 
				@IdRegisto, @ETaxa, @TaxaValor
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes			
-- remove as imposições existentes no detalhe de outras imposições das adições IMP-CAU mas já não existentes na configuração do artigo
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT doi.DUC_EANO, doi.DUC_PNUM, doi.DUA_CODI, doi.DUO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 6
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.APA_CO33 = art.APA_CODI				
				LEFT OUTER JOIN TAB_APOI AS aoi WITH(NOLOCK) ON art.APA_CHVE = aoi.APA_CHVE AND doi.RRE_CODI = aoi.RRE_CODI
			WHERE duc.DUC_DUNO = 2 AND aoi.APO_CODI IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove imposição					
			DELETE FROM PRO_DUOI
			WHERE DUO_IDEN = @IdRegisto
-- atualiza numero de imposições posteriores
			UPDATE PRO_DUOI SET DUO_CODI = DUO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DUO_IDEN > @IdRegisto
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes					
	END
-- se colunas de direitos da unidade medida, quantidade, rúbrica, imposição, base manual, base de tributação, taxa/valor, montante ou garantia/caução alteradas, processa a gestão da imposição dos direitos no detalhe de outras imposições das adições IMP-CAU inseridas/alteradas
	IF UPDATE(UME_CODI) OR UPDATE(DUA_QTDD) OR UPDATE(RRE_PREF) OR UPDATE(DUA_IMPO) OR UPDATE(DUA_BMAN) OR UPDATE(DUA_BTRI) OR UPDATE(DUA_TXCO) OR UPDATE(DUA_TXVL) OR UPDATE(DUA_MTRI) OR UPDATE(DUA_CAUD) OR UPDATE(DUA_CAND) 
	OR UPDATE(DUA_CTID) OR UPDATE(DUA_CEND) OR UPDATE(ALF_CODI) OR UPDATE(DUA_CCAD) OR UPDATE(DUA_CORD) OR UPDATE(DUA_CNRD)
	BEGIN
-- insere/edita a imposição de direitos no detalhe de outras imposições das adições IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.UME_CODI, ins.DUA_IMPO, ins.DUA_BMAN, ISNULL(ins.DUA_BTRI, 0), ISNULL(ins.DUA_TXVL, 0), ISNULL(ins.DUA_MTRI, 0), ins.DUA_CAUD, 
				ins.DUA_CAND, ins.DUA_CTID, ins.DUA_CEND, ins.ALF_CODI, ins.DUA_CCAD, ins.DUA_CORD, ins.DUA_CNRD, ins.DUA_QTDD, rre.RRE_CODI, rre.RRE_NOME, rre.RRE_IVA, doi.DUO_IDEN, 
				(CASE ins.DUA_TXCO WHEN 1 THEN CAST(0 AS bit) ELSE CAST(1 AS bit) END) 
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM		
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON ins.RRE_PREF = rre.RRE_CODI	
				LEFT OUTER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 1								
			WHERE duc.DUC_DUNO = 2 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @ImposicaoRubricaReceita, @BaseManual, @BaseTributacao, @TaxaValor, @Montante, @NumeroCaucao, 
			@AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, @Quantidade, @CodRubricaReceita, @NomeRubricaReceita, 
			@IVARubricaReceita, @IdRegisto, @ETaxa
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
-- obtem o próximo numero de registo de outras imposições da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(DUO_CODI), 0) + 1
				FROM PRO_DUOI
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere a imposição no detalhe de outras imposições da adição IMP-CAU
				INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_LIVA, DUO_IMPO, DUO_AUTO, DUO_BMAN, 
					DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT, ALF_CODI, DUO_CCAC, DUO_CORF, DUO_CNRD, DUO_QTDE)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodRubricaReceita, @NomeRubricaReceita, @ETaxa, @CodUnidadeMedida, @BaseTributacao, @TaxaValor, @Montante, @IVARubricaReceita, 
					@ImposicaoRubricaReceita, 1, @BaseManual, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, 
					@NIFResponsavelCaucao, @Quantidade)
			END
			ELSE
			BEGIN
				UPDATE PRO_DUOI SET
					RRE_CODI = @CodRubricaReceita, 
					RRE_NOME = @NomeRubricaReceita, 
					DUO_TIPO = @ETaxa, 
					UME_CODI = @CodUnidadeMedida, 
					DUO_BTRI = @BaseTributacao, 
					DUO_TXVL = @TaxaValor, 
					DUO_MONT = @Montante, 
					RRE_LIVA = @IVARubricaReceita, 
					DUO_IMPO = @ImposicaoRubricaReceita, 					
					DUO_BMAN = @BaseManual, 
					DUO_CAUC = @NumeroCaucao, 
					DUO_CANO = @AnoCaucao, 
					DUO_CTIP = @TipoCaucao, 
					DUO_CENT = @EntidadeCaucao, 
					ALF_CODI = @CodAlfandegaCaucao, 
					DUO_CCAC = @CodAcessoCaucao, 
					DUO_CORF = @OutrasReferenciasCaucao, 
					DUO_CNRD = @NIFResponsavelCaucao, 
					DUO_QTDE = @Quantidade
				WHERE DUO_IDEN = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @ImposicaoRubricaReceita, @BaseManual, @BaseTributacao, @TaxaValor, @Montante, @NumeroCaucao, 
				@AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, @Quantidade, @CodRubricaReceita, @NomeRubricaReceita, 
				@IVARubricaReceita, @IdRegisto, @ETaxa
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove a imposição de direitos existente no detalhe de outras imposições das adições IMP-CAU mas já não existente nas rúbricas de receita
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT doi.DUC_EANO, doi.DUC_PNUM, doi.DUA_CODI, doi.DUO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 1
				LEFT OUTER JOIN TAB_RREC AS rre WITH(NOLOCK) ON doi.RRE_CODI = rre.RRE_CODI
			WHERE duc.DUC_DUNO = 2 AND rre.RRE_CODI IS NULL				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove imposição					
			DELETE FROM PRO_DUOI
			WHERE DUO_IDEN = @IdRegisto
-- atualiza numero de imposições posteriores
			UPDATE PRO_DUOI SET DUO_CODI = DUO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DUO_IDEN > @IdRegisto 
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END
-- se colunas de IVA da rúbrica, imposição, base de tributação, taxa, montante ou garantia/caução alteradas, processa a gestão da imposição do IVA no detalhe de outras imposições das adições IMP-CAU inseridas/alteradas
	IF UPDATE(RRE_CODI) OR UPDATE(DUA_IMPI) OR UPDATE(DUA_BTIV) OR UPDATE(DUA_TIVA) OR UPDATE(DUA_VIVA) OR UPDATE(DUA_CAUI) OR UPDATE(DUA_CANI) OR UPDATE(DUA_CTII) OR UPDATE(DUA_CENI) 
	OR UPDATE(ALF_CODI1) OR UPDATE(DUA_CCAI) OR UPDATE(DUA_CORI) OR UPDATE(DUA_CNRI)
	BEGIN
-- insere/edita a imposição de IVA no detalhe de outras imposições das adições IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.DUA_IMPI, ISNULL(ins.DUA_BTIV, 0), ISNULL(ins.DUA_TIVA, 0), ISNULL(ins.DUA_VIVA, 0), ins.DUA_CAUI, ins.DUA_CANI, 
				ins.DUA_CTII, ins.DUA_CENI, ins.ALF_CODI1, ins.DUA_CCAI, ins.DUA_CORI, ins.DUA_CNRI, rre.RRE_CODI, rre.RRE_NOME, rre.RRE_IVA, doi.DUO_IDEN				
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM		
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON ins.RRE_CODI = rre.RRE_CODI	
				LEFT OUTER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 2
			WHERE duc.DUC_DUNO = 2 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @ImposicaoRubricaReceita, @BaseTributacao, @TaxaValor, @Montante, @NumeroCaucao, @AnoCaucao, @TipoCaucao, 
			@EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, @CodRubricaReceita, @NomeRubricaReceita, @IVARubricaReceita, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
-- obtem o próximo numero de registo de outras imposições da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(DUO_CODI), 0) + 1
				FROM PRO_DUOI
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere a imposição no detalhe de outras imposições da adição IMP-CAU
				INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_LIVA, DUO_IMPO, DUO_AUTO, DUO_BMAN, DUO_CAUC, DUO_CANO, 
					DUO_CTIP, DUO_CENT, ALF_CODI, DUO_CCAC, DUO_CORF, DUO_CNRD)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodRubricaReceita, @NomeRubricaReceita, 1, @BaseTributacao, @TaxaValor, @Montante, @IVARubricaReceita, 
					@ImposicaoRubricaReceita, 2, 0, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao)
			END
			ELSE
			BEGIN
				UPDATE PRO_DUOI SET
					RRE_CODI = @CodRubricaReceita, 
					RRE_NOME = @NomeRubricaReceita, 					
					DUO_BTRI = @BaseTributacao, 
					DUO_TXVL = @TaxaValor, 
					DUO_MONT = @Montante, 
					RRE_LIVA = @IVARubricaReceita, 
					DUO_IMPO = @ImposicaoRubricaReceita, 										
					DUO_CAUC = @NumeroCaucao, 
					DUO_CANO = @AnoCaucao, 
					DUO_CTIP = @TipoCaucao, 
					DUO_CENT = @EntidadeCaucao, 
					ALF_CODI = @CodAlfandegaCaucao, 
					DUO_CCAC = @CodAcessoCaucao, 
					DUO_CORF = @OutrasReferenciasCaucao, 
					DUO_CNRD = @NIFResponsavelCaucao
				WHERE DUO_IDEN = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @ImposicaoRubricaReceita, @BaseTributacao, @TaxaValor, @Montante, @NumeroCaucao, @AnoCaucao, @TipoCaucao, 
				@EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, @CodRubricaReceita, @NomeRubricaReceita, @IVARubricaReceita, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove a imposição de IVA existente no detalhe de outras imposições das adições IMP-CAU mas já não existente nas rúbricas de receita
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT doi.DUC_EANO, doi.DUC_PNUM, doi.DUA_CODI, doi.DUO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 2
				LEFT OUTER JOIN TAB_RREC AS rre WITH(NOLOCK) ON doi.RRE_CODI = rre.RRE_CODI
			WHERE duc.DUC_DUNO = 2 AND rre.RRE_CODI IS NULL				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove imposição					
			DELETE FROM PRO_DUOI
			WHERE DUO_IDEN = @IdRegisto
-- atualiza numero de imposições posteriores
			UPDATE PRO_DUOI SET DUO_CODI = DUO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DUO_IDEN > @IdRegisto 
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END
-- se colunas da massa líquida, base de tributação ou garantia/caução alteradas, processa a gestão de imposições manuais no detalhe de outras imposições das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_ML38) OR UPDATE(DUA_BTRI) OR UPDATE(DUA_CAUD) OR UPDATE(DUA_CAND) OR UPDATE(DUA_CTID) OR UPDATE(DUA_CEND) OR UPDATE(ALF_CODI) OR UPDATE(DUA_CCAD) OR UPDATE(DUA_CORD) 
	OR UPDATE(DUA_CNRD)
	BEGIN
-- edita as imposições configuradas no artigo no detalhe de outras imposições das adições IMP-CAU
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_ML38, doi.DUO_BMAN, 
				ISNULL((CASE doi.DUO_BMAN WHEN 1 THEN ISNULL(doi.DUO_BTRI, 0) ELSE NULL END), ISNULL(ins.DUA_BTRI, 0)), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CAUC ELSE NULL END), ins.DUA_CAUD), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CANO ELSE NULL END), ins.DUA_CAND), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CTIP ELSE NULL END), ins.DUA_CTID), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CENT ELSE NULL END), ins.DUA_CEND), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.ALF_CODI ELSE NULL END), ins.ALF_CODI), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CCAC ELSE NULL END), ins.DUA_CCAD), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CORF ELSE NULL END), ins.DUA_CORD), 
				ISNULL((CASE duc.DUC_CGLB WHEN 0 THEN doi.DUO_CNRD ELSE NULL END), ins.DUA_CNRD), 				
				doi.DUO_IDEN, doi.DUO_TIPO, ISNULL(doi.DUO_TXVL, 0)
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.RRE_CODI <> 999 AND doi.DUO_AUTO = 0
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON doi.RRE_CODI = rre.RRE_CODI
			WHERE duc.DUC_DUNO = 2 
				AND NOT EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE RRE_CDPT = rre.RRE_CODI)
				AND NOT EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE RRE_CDAL = rre.RRE_CODI)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @MassaLiquida, @BaseManual, @BaseTributacao, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, 
			@OutrasReferenciasCaucao, @NIFResponsavelCaucao, @IdRegisto, @ETaxa, @TaxaValor
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a base de tributação apenas quando é valor
			IF (@ETaxa = 0) AND (@BaseManual = 0)
				SET @BaseTributacao = ROUND(@MassaLiquida, 2)	
-- calcula o montante em função se é taxa ou valor
			IF @ETaxa = 1
				SET @Montante = ROUND(@BaseTributacao * @TaxaValor / 100, 2)			
			ELSE
				SET @Montante = ROUND(@BaseTributacao * @TaxaValor, 2)	
-- edita a imposição do artigo			
			UPDATE PRO_DUOI SET											 
				DUO_TIPO = @ETaxa, 
				DUO_BTRI = @BaseTributacao, 
				DUO_MONT = @Montante, 													
				DUO_CAUC = @NumeroCaucao, 
				DUO_CANO = @AnoCaucao, 
				DUO_CTIP = @TipoCaucao, 
				DUO_CENT = @EntidadeCaucao, 
				ALF_CODI = @CodAlfandegaCaucao, 
				DUO_CCAC = @CodAcessoCaucao, 
				DUO_CORF = @OutrasReferenciasCaucao, 
				DUO_CNRD = @NIFResponsavelCaucao
			WHERE DUO_IDEN = @IdRegisto			
			FETCH NEXT FROM Adicoes INTO @MassaLiquida, @BaseManual, @BaseTributacao, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, 
				@OutrasReferenciasCaucao, @NIFResponsavelCaucao, @IdRegisto, @ETaxa, @TaxaValor
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes						
	END
-- se coluna do artigo alterada, processa a gestão de documentos do artigo no detalhe de documentos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(APA_CO33)
	BEGIN
-- insere os documentos configurados no artigo mas ainda não existentes no anexo de documentos da adição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, doc.DOC_CODI, doc.DOC_NOME, 
				(CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END), 
				(CASE LEFT(doc.DOC_CODI, 1) WHEN 'N' THEN 0 ELSE 2 END)
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.APA_CO33 = art.APA_CODI
				INNER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON art.APA_CHVE = ado.APA_CHVE
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND doc.DOC_CODI = dad.DOC_CODI AND dad.DDO_AUTO = 8				
			WHERE duc.DUC_DUNO = 2 AND ado.ADC_UIMP = 1 AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND dad.DDO_IDEN IS NULL	
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @TipoDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(DDO_CODI), 0) + 1
			FROM PRO_DDOC
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento como "Suporte"/"Referência Adicional" no detalhe de documentos da adição IMP-CAU
			INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_AUTO, DDO_TIPO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodDocumento, @NomeDocumento, @NumeroDocumento, 8, @TipoDocumento)
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @TipoDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
-- remove os documentos existentes no detalhe de documentos da adição mas já não existentes na configuração do artigo
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.DUC_EANO, dad.DUC_PNUM, dad.DUA_CODI, dad.DDO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND dad.DDO_AUTO = 8
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.APA_CO33 = art.APA_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON art.APA_CHVE = ado.APA_CHVE AND doc.DOC_CODI = ado.DOC_CODI
			WHERE duc.DUC_DUNO = 2 AND (ado.ADC_UIMP = 0 OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR ado.ADC_CODI IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove documento					
			DELETE FROM PRO_DDOC
			WHERE DDO_IDEN = @IdRegisto
-- atualiza numero de documentos posteriores
			UPDATE PRO_DDOC SET DDO_CODI = DDO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DDO_IDEN > @IdRegisto 			
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes					
	END
-- se coluna do número da adição alterada, processa a inserção dos documentos configurados para cópia existentes na 1ª adição
	IF UPDATE(DUA_CODI)
	BEGIN
-- insere os documentos configurados como cópia na 1ª adição mas ainda não existentes no anexo de documentos da adição > 1
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, doc.DOC_CODI, doc.DOC_NOME, dad.DDO_NUME, dad.DDO_DINI, dad.PAI_CODI, dad.DDO_MONT, dad.DDO_NINV, dad.DDO_TIPO, 
				dad.DDO_EEMI, dad.UME_CODI, dad.DDO_QTDE, dad.DDO_NLIN
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI = 1
				INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON adi.DUC_EANO = dad.DUC_EANO AND adi.DUC_PNUM = dad.DUC_PNUM AND adi.DUA_CODI = dad.DUA_CODI 	
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI			
			WHERE duc.DUC_DUNO = 2 AND ins.DUA_CODI > 1 AND doc.DOC_RSDA = 1 
				AND NOT EXISTS(SELECT DDO_IDEN 
								FROM PRO_DDOC WITH(NOLOCK)
								WHERE DUC_EANO = ins.DUC_EANO AND DUC_PNUM = ins.DUC_PNUM AND DUA_CODI = ins.DUA_CODI AND DOC_CODI = doc.DOC_CODI AND DDO_AUTO = 0)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataValidadeDocumento, @CodPais, @Montante, 
			@InvoicNumber, @TipoDocumento, @EntidadeEmissora, @CodUnidadeMedida, @Quantidade, @NumLinha
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(DDO_CODI), 0) + 1
			FROM PRO_DDOC
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento no detalhe de documentos da adição IMP-CAU
			INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, PAI_CODI, DDO_MONT, DDO_NINV, DDO_AUTO, DDO_TIPO, DDO_EEMI, 
				UME_CODI, DDO_QTDE, DDO_NLIN)			
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataValidadeDocumento, @CodPais, @Montante, @InvoicNumber, 0, @TipoDocumento, @EntidadeEmissora, 
				@CodUnidadeMedida, @Quantidade, (CASE WHEN @NumLinha IS NOT NULL THEN @NumAdicao ELSE NULL END))					
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @DataValidadeDocumento, @CodPais, @Montante, 
				@InvoicNumber, @TipoDocumento, @EntidadeEmissora, @CodUnidadeMedida, @Quantidade, @NumLinha
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
	END
-- se coluna exportador alterada, processa a gestão do documento fixo "3E18" no detalhe de documentos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(FOR_CODI)
	BEGIN
-- insere o documento fixo "3E18" como "Suporte" no detalhe de documentos da adição IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, doc.DOC_CODI, doc.DOC_NOME, doc.DOC_DTRA, 
				(CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END)				
			FROM inserted AS ins 	
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_FORN AS frn WITH(NOLOCK) ON ins.FOR_CODI = frn.FOR_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI	= '3E18'
				LEFT OUTER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND dad.DDO_AUTO = 9					
			WHERE duc.DUC_DUNO = 2 AND duc.DUC_ANXB <> 'H2' AND frn.FOR_TNIF = 5 AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND dad.DDO_IDEN IS NULL	
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(DDO_CODI), 0) + 1
			FROM PRO_DDOC
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento como "Suporte" no detalhe de documentos da adição IMP-CAU
			INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_AUTO, DDO_TIPO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodDocumento, @NomeDocumento, @NumeroDocumento, 9, @TipoDocumento)			
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento, @NumeroDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o documento fixo "3E18" existente no detalhe de documentos da adição mas já não existente na configuração do exportador
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.DUC_EANO, dad.DUC_PNUM, dad.DUA_CODI, dad.DDO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND dad.DDO_AUTO = 9
				LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON ins.FOR_CODI = frn.FOR_CODI
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI				
			WHERE duc.DUC_DUNO = 2 AND (duc.DUC_ANXB = 'H2' OR ISNULL(frn.FOR_TNIF, -1) <> 5 OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_CODI IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove documento					
			DELETE FROM PRO_DDOC
			WHERE DDO_IDEN = @IdRegisto
-- atualiza numero de documentos posteriores
			UPDATE PRO_DDOC SET DDO_CODI = DDO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DDO_IDEN > @IdRegisto 	
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END
-- se coluna do número da adição alterada, processa a inserção/edição das marcas e volumes configuradas como parte nas restantes adições
	IF UPDATE(DUA_CODI)
	BEGIN
-- insere os documentos configurados como cópia na 1ª adição mas ainda não existentes no anexo de documentos da adição > 1
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, dam.D31_MARC, dam.D31_NUME, dam.UME_CODI, dam.UME_NOME, dam.D31_TTVL, dam.D31_LOPT
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND adi.DUA_CODI = 1
				INNER JOIN PRO_DU31 AS dam WITH(NOLOCK) ON adi.DUC_EANO = dam.DUC_EANO AND adi.DUC_PNUM = dam.DUC_PNUM AND adi.DUA_CODI = dam.DUA_CODI AND dam.D31_CASP = 1				
			WHERE duc.DUC_DUNO = 2 AND ins.DUA_CODI > 1
				AND NOT EXISTS(SELECT D31_IDEN 
								FROM PRO_DU31 WITH(NOLOCK)
								WHERE DUC_EANO = ins.DUC_EANO AND DUC_PNUM = ins.DUC_PNUM AND DUA_CODI = ins.DUA_CODI AND D31_AUTO = 1)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @Marca, @NumeroObjeto, @CodUnidadeMedida, @NomeUnidadeMedida, @VolumesZero, @CodigoBarras
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- obtem o próximo numero de registo de marcas e volumes da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(D31_CODI), 0) + 1
			FROM PRO_DU31
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere a marca e volume no detalhe de marcas e volumes da adição IMP-CAU
			INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_NUME, D31_QNTD, UME_CODI, UME_NOME, D31_CASP, D31_TTVL, D31_AUTO, D31_LOPT)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @Marca, @NumeroObjeto, 0, @CodUnidadeMedida, @NomeUnidadeMedida, 0, @VolumesZero, 1, @CodigoBarras)				
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @Marca, @NumeroObjeto, @CodUnidadeMedida, @NomeUnidadeMedida, @VolumesZero, @CodigoBarras
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
	END
-- se colunas do regime, desdobramento 1 ou desdobramento 2 alteradas, processa a gestão de pedidos "G1CFA" e "I1CII" no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_RG37) OR UPDATE(DUA_R37B) OR UPDATE(DUA_R37C)
	BEGIN
-- insere o pedido "G1CFA" no detalhe de pedidos da adição IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, NULLIF(SUBSTRING(tdp.TXM_TEXT, 1, 512), '')
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1CFA'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 1		
			WHERE duc.DUC_DUNO = 2 AND ((ISNULL(ins.DUA_RG37, '') IN ('4000', '4071', '4078') AND ISNULL(ins.DUA_R37B, '') = '4FD' AND ISNULL(ins.DUA_R37C, '') IN ('', '431')) 
				OR (ISNULL(ins.DUA_RG37, '') IN ('4000', '4053', '4071', '4078') AND ISNULL(ins.DUA_R37B, '') = 'C01')
				OR (ISNULL(ins.DUA_RG37, '') IN ('4000', '4053', '4054', '4071', '4078') AND ISNULL(ins.DUA_R37B, '') IN ('C26', 'C27', 'C28', 'C29', 'C30', 'C31', 'C32'))
				OR (ISNULL(ins.DUA_RG37, '') IN ('4200', '4251', '4253', '4254', '4271', '4278') AND ISNULL(ins.DUA_R37B, '') IN ('C34', 'C35', 'C36', 'C37', 'C38'))
				OR (ISNULL(ins.DUA_RG37, '') IN ('4053', '4054', '4071', '4078') AND ISNULL(ins.DUA_R37B, '') = 'C58')
				OR (ISNULL(ins.DUA_RG37, '') = '4000' AND ISNULL(ins.DUA_R37B, '') IN ('C02', 'C03', 'C04', 'C06', 'C09', 'C10', 'C11', 'C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C19', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C33', 'C40', 'C41', 'C42', 'C43', 'C44', 'C45', 'C46', 'C47', 'C48', 'C49', 'C50', 'C51', 'C52', 'C53', 'C54', 'C55', 'C56', 'C57', 'C59', 'C60', 'C61', 'F01', 'F02', 'F03', 'F05', 'F21', 'F22'))					
				OR (ISNULL(ins.DUA_RG37, '') = '0100' AND ISNULL(ins.DUA_R37B, '') IN ('F21', 'F22'))
				OR (ISNULL(ins.DUA_RG37, '') = '0110' AND ISNULL(ins.DUA_R37B, '') IN ('F01', 'F02', 'F03'))) AND dap.id IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN							
			INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 1, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o pedido "G1CFA" existente no detalhe de pedidos da adição mas já não satisfaz a condição do regime e/ou desdobramento 1 e/ou desdobramento 2
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 1				
			WHERE duc.DUC_DUNO = 2 AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4000', '4071', '4078') OR ISNULL(ins.DUA_R37B, '') <> '4FD' OR ISNULL(ins.DUA_R37C, '') NOT IN ('', '431')) 
				AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4000', '4053', '4071', '4078') OR ISNULL(ins.DUA_R37B, '') <> 'C01') 
				AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4000', '4053', '4054', '4071', '4078') OR ISNULL(ins.DUA_R37B, '') NOT IN ('C26', 'C27', 'C28', 'C29', 'C30', 'C31', 'C32'))
				AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4200', '4251', '4253', '4254', '4271', '4278') OR ISNULL(ins.DUA_R37B, '') NOT IN ('C34', 'C35', 'C36', 'C37', 'C38'))
				AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4053', '4054', '4071', '4078') OR ISNULL(ins.DUA_R37B, '') <> 'C58')
				AND (ISNULL(ins.DUA_RG37, '') <> '4000' OR ISNULL(ins.DUA_R37B, '') NOT IN ('C02', 'C03', 'C04', 'C06', 'C09', 'C10', 'C11', 'C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C19', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C33', 'C40', 'C41', 'C42', 'C43', 'C44', 'C45', 'C46', 'C47', 'C48', 'C49', 'C50', 'C51', 'C52', 'C53', 'C54', 'C55', 'C56', 'C57', 'C59', 'C60', 'C61', 'F01', 'F02', 'F03', 'F05', 'F21', 'F22'))
				AND (ISNULL(ins.DUA_RG37, '') <> '0100' OR ISNULL(ins.DUA_R37B, '') NOT IN ('F21', 'F22'))
				AND (ISNULL(ins.DUA_RG37, '') <> '0110' OR ISNULL(ins.DUA_R37B, '') NOT IN ('F01', 'F02', 'F03'))
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
-- insere o pedido "I1CII" no detalhe de pedidos da adição IMP-CAU 		
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, NULLIF(SUBSTRING(tdp.TXM_TEXT, 1, 512), '')
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'I1CII'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 20	
			WHERE duc.DUC_DUNO = 2 AND ((ISNULL(ins.DUA_RG37, '') IN ('4000', '4071', '4078') AND ISNULL(ins.DUA_R37B, '') = '4FD' AND ISNULL(ins.DUA_R37C, '') IN ('413', '414', '415'))
				OR (ISNULL(ins.DUA_RG37, '') IN ('4000', '4071', '4078') AND ISNULL(ins.DUA_R37B, '') IN ('454', '455', '456', '457', '458', '459'))
				OR (ISNULL(ins.DUA_RG37, '') IN ('4000', '4053', '4071', '4078') AND ISNULL(ins.DUA_R37B, '') = 'C01')				
				OR (ISNULL(ins.DUA_RG37, '') = '4000' AND ISNULL(ins.DUA_R37B, '') IN ('402', '403', '404', '405', '406', '407', '408', '409', '411', '412', '413', '414', '415', '416', '417', '418', '419', '420', '421', '422', '423', '424', '425', '426', '427', '428', '429', '430', '431', '432', '433', '434', '435', '436', '437', '438', '439', '440', '441', '442', '443', '444', '445', '446', '447', '448', '449')))
				AND dap.id IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN							
			INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 20, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o pedido "I1CII" existente no detalhe de pedidos da adição mas já não satisfaz a condição do regime e/ou desdobramento 1
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 20			
			WHERE duc.DUC_DUNO = 2 AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4000', '4071', '4078') OR ISNULL(ins.DUA_R37B, '') <> '4FD' OR ISNULL(ins.DUA_R37C, '') NOT IN ('413', '414', '415'))
				AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4000', '4071', '4078') OR ISNULL(ins.DUA_R37B, '') NOT IN ('454', '455', '456', '457', '458', '459'))
				AND (ISNULL(ins.DUA_RG37, '') NOT IN ('4000', '4053', '4071', '4078') OR ISNULL(ins.DUA_R37B, '') <> 'C01') 
				AND (ISNULL(ins.DUA_RG37, '') <> '4000' OR ISNULL(ins.DUA_R37B, '') NOT IN ('402', '403', '404', '405', '406', '407', '408', '409', '411', '412', '413', '414', '415', '416', '417', '418', '419', '420', '421', '422', '423', '424', '425', '426', '427', '428', '429', '430', '431', '432', '433', '434', '435', '436', '437', '438', '439', '440', '441', '442', '443', '444', '445', '446', '447', '448', '449'))
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
	END	
-- se colunas do regime ou valor aduaneiro alteradas, processa a gestão do pedido "I13CP" no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_RG37) OR UPDATE(DUA_VATO)
	BEGIN
-- insere ou altera o pedido "I13CP" no detalhe de pedidos da adição IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, LTRIM(STR(ISNULL(ins.DUA_VATO, 0), 18, 2)), uti.UTI_IDTY, tdp.TXM_IDTY, dap.id 
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'I13CP'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 21		
			WHERE duc.DUC_DUNO = 2 AND ISNULL(LEFT(ins.DUA_RG37, 2), '') IN ('51', '53') 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumeroPedido, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN					
			IF @IdRegisto IS NULL
			BEGIN		
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 21, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET					
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumeroPedido, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o pedido "I13CP" existente no detalhe de pedidos da adição mas já não satisfaz a condição do regime
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 21				
			WHERE duc.DUC_DUNO = 2 AND ISNULL(LEFT(ins.DUA_RG37, 2), '') NOT IN ('51', '53') 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END
-- se colunas do frete ou seguro alterada, processa a gestão do código "AK"/"BA" no detalhe de acréscimos/deduções das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_VFRE) OR UPDATE(DUA_VSEG) OR UPDATE(DUA_AJUS) /*DUA_AJUS para recalcular acrescimo/dedução uma vez que é atualizado quando nos dados gerais os campos DUC_FR20, DUC_TXFR ou DUC_TXSE são alterados*/
	BEGIN
-- insere/edita o código "AK"/"BA" no detalhe de acréscimos/deduções da adição IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, uti.UTI_IDTY, daa.id, 
				(ROUND(ISNULL(ins.DUA_VFRE, 0) / ISNULL(duc.DUC_TXFR, 0), 2) + ROUND(ISNULL(ins.DUA_VSEG, 0) / ISNULL(duc.DUC_TXSE, 0), 2)), 
				(CASE WHEN ISNULL(NULLIF(CHARINDEX('+', ISNULL(duc.DUC_FR20, '')), 0), 999999) > ISNULL(NULLIF(CHARINDEX('-', ISNULL(duc.DUC_FR20, '')), 0), 999999) THEN 1 ELSE 0 END)
			FROM inserted AS ins 					
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes AS daa WITH(NOLOCK) ON ins.DUA_IDEN = daa.id_adicao AND origem = 1												
			WHERE duc.DUC_DUNO = 2 AND duc.DUC_SERV = 0 AND duc.DUC_ANXB NOT IN ('H2', 'H3', 'H4', 'H6') AND ISNULL(duc.DUC_FR20, '') <> '' 
				AND (ROUND(ISNULL(ins.DUA_VFRE, 0) / ISNULL(duc.DUC_TXFR, 0), 2) + ROUND(ISNULL(ins.DUA_VSEG, 0) / ISNULL(duc.DUC_TXSE, 0), 2)) > 0
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdRegisto, @SomaFreteESeguro, @TipoAcrescimoDeducao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @TipoAcrescimoDeducao = 0 --Acrescimo
				SET @CodAcrescimoDeducao = 'AK'
			ELSE
				SET @CodAcrescimoDeducao = 'BA'
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes(id_adicao, tipo, codigo, montante, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdAdicao, @TipoAcrescimoDeducao, @CodAcrescimoDeducao, @SomaFreteESeguro, 1, @IdUtilizador, @DataAtual)				
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes SET
					tipo = @TipoAcrescimoDeducao, 
					codigo = @CodAcrescimoDeducao, 
					montante = @SomaFreteESeguro, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdRegisto, @SomaFreteESeguro, @TipoAcrescimoDeducao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o código "AK"/"BA" existente no detalhe de acréscimos/deduções da adição mas já não satisfazem a condição do valor do frete + seguro
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT daa.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes AS daa WITH(NOLOCK) ON ins.DUA_IDEN = daa.id_adicao AND origem = 1			
			WHERE duc.DUC_DUNO = 2 AND duc.DUC_SERV = 0 AND (duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H6') OR ISNULL(duc.DUC_FR20, '') = '' 
				OR (ROUND(ISNULL(ins.DUA_VFRE, 0) / ISNULL(duc.DUC_TXFR, 0), 2) + ROUND(ISNULL(ins.DUA_VSEG, 0) / ISNULL(duc.DUC_TXSE, 0), 2)) = 0)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes				
	END
-- se colunas de direitos DDP ou método de avaliação alterada, processa a gestão do código "BC" no detalhe de acréscimos/deduções das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_VDIR) OR UPDATE(DUA_MAVA)
	BEGIN
-- insere/edita o código "BC" no detalhe de acréscimos/deduções da adição IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, uti.UTI_IDTY, daa.id, ISNULL(ins.DUA_VDIR, 0)
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes AS daa WITH(NOLOCK) ON ins.DUA_IDEN = daa.id_adicao AND origem = 2									
			WHERE duc.DUC_DUNO = 2 AND duc.DUC_ANXB NOT IN ('H2', 'H3', 'H4', 'H6') AND ISNULL(ins.DUA_VDIR, 0) > 0 AND ISNULL(ins.DUA_MAVA, 0) <= 1
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdRegisto, @ValorDireitosDDP
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes(id_adicao, tipo, codigo, montante, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdAdicao, 1, 'BC', @ValorDireitosDDP, 2, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes SET					
					montante = @ValorDireitosDDP, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdRegisto, @ValorDireitosDDP
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o código "BC" existente no detalhe de acréscimos/deduções da adição mas já não satisfaz a condição do valor dos direitos DDP
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT daa.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes AS daa WITH(NOLOCK) ON ins.DUA_IDEN = daa.id_adicao AND origem = 2				
			WHERE duc.DUC_DUNO = 2 AND (duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H6') OR ISNULL(ins.DUA_VDIR, 0) = 0 OR ISNULL(ins.DUA_MAVA, 0) > 1)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END
-- se colunas de frete, optativas, verba transitário ou ajustamento alteradas, processa a gestão do pedido “G1VDA” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_VFRE) OR UPDATE(DUA_VOPT) OR UPDATE(DUA_VTRA) OR UPDATE(DUA_AJUS)
	BEGIN
-- insere/edita o pedido “G1VDA” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ISNULL(ins.DUA_VFRE, 0), ISNULL(ins.DUA_VOPT, 0), ISNULL(ins.DUA_VTRA, 0), ins.DUA_AJUS, ins.DUA_IDEN, ISNULL(duc.DUC_TXFR, 0), ISNULL(duc.DUC_TFDA, 0), uti.UTI_IDTY, 
				mtr.MTR_PTAX, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 							
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL	
				INNER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON duc.MTR_PT18 = mtr.MTR_CODI
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1VDA'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 6								
			WHERE duc.DUC_DUNO = 2 AND duc.DUC_ANXB <> 'H2' AND (ISNULL(ins.DUA_VOPT, 0) > 0 OR ISNULL(ins.DUA_VTRA, 0) > 0)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @Frete, @Optativas, @VerbaTransitario, @Ajustamento, @IdAdicao, @CambioFrete, @TaxaFDA, @IdUtilizador, @PedeTaxaFDA, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula o montante a apurar em função se meio de transporte da declaracao pede taxa FDA
			IF @PedeTaxaFDA = 1
			BEGIN
				IF @Ajustamento >= 0
					SET @Montante = ROUND((@Optativas + (@Frete / @CambioFrete / 100 * (100 - @TaxaFDA))), 2)
				ELSE
					SET @Montante = ROUND((@Optativas + (@Frete / @CambioFrete / 100 * @TaxaFDA)), 2)
			END
			ELSE
				SET @Montante = ROUND((@Optativas + @VerbaTransitario), 2)
-- calcula o número do pedido
			SET @NumeroPedido = LTRIM(STR(@Montante, 18, 2))
-- insere ou edita o pedido “G1VDA” no detalhe de pedidos da adição IMP-CAU
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 6, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @Frete, @Optativas, @VerbaTransitario, @Ajustamento, @IdAdicao, @CambioFrete, @TaxaFDA, @IdUtilizador, @PedeTaxaFDA, @IdPedido, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o pedido “G1VDA” existente no detalhe de pedidos da adição mas já não satisfaz a condição das optativas ou verba transitário
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 6			
			WHERE duc.DUC_DUNO = 2 AND ((duc.DUC_ANXB = 'H2') OR (ISNULL(ins.DUA_VOPT, 0) = 0 AND ISNULL(ins.DUA_VTRA, 0) = 0))
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END
-- se colunas do artigo, massa líquida, massa bruta ou unidades alteradas, processa a gestão dos elementos p/ tributação dos artigos no detalhe de elementos p/ tributação das adições IMP-CAU inseridas/alteradas
	IF UPDATE(APA_CO33) OR UPDATE(DUA_ML38) OR UPDATE(DUA_MB35) OR UPDATE(DUA_US41)
	BEGIN
-- insere/edita os elementos p/ tributação configurados no artigo no detalhe de elementos p/ tributação das adições IMP-CAU
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, aet.UME_CODI, ume.UME_COD2, aet.RRE_CODI, aet.RRE_NOME, rre.RRE_IMPO, aet.AET_TAXA, aet.AET_TXVL, aet.AET_IDST, det.DET_IDEN,
				(CASE WHEN ISNULL(aet.AET_ORIG, 0) IN (1, 2, 3) THEN 2 ELSE 3 END), 
				(CASE ISNULL(aet.AET_ORIG, 0) 
					WHEN 1 THEN ROUND(ISNULL(ins.DUA_US41, 0) / ISNULL(NULLIF(ume.UME_FACT, 0), 1), 3)
					WHEN 2 THEN ROUND(ins.DUA_ML38 / ISNULL(NULLIF(ume.UME_FACT, 0), 1), 3)
					WHEN 3 THEN ROUND(ins.DUA_MB35 / ISNULL(NULLIF(ume.UME_FACT, 0), 1), 3)
					ELSE 0 
				END)
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.APA_CO33 = art.APA_CODI
				INNER JOIN TAB_AETR AS aet WITH(NOLOCK) ON art.APA_CHVE = aet.APA_CHVE
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON aet.UME_CODI = ume.UME_CODI
				LEFT OUTER JOIN TAB_RREC AS rre WITH(NOLOCK) ON aet.RRE_CODI = rre.RRE_CODI
				LEFT OUTER JOIN PRO_DUET AS det WITH(NOLOCK) ON ins.DUC_EANO = det.DUC_EANO AND ins.DUC_PNUM = det.DUC_PNUM AND ins.DUA_CODI = det.DUA_CODI AND det.DET_AUTO = (CASE WHEN ISNULL(aet.AET_ORIG, 0) IN (1, 2, 3) THEN 2 ELSE 3 END) AND aet.AET_IDST = det.DIT_IDST
			WHERE duc.DUC_DUNO = 2 				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @CodUnidadeMedida2, @CodRubricaReceita, @NomeRubricaReceita, @ImposicaoRubricaReceita, 
			@ETaxa, @TaxaValor, @IdStrRegisto, @IdRegisto, @TipoOrigem, @Quantidade									
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere ou edita o elemento p/ tributação do artigo
			IF @IdRegisto IS NULL
			BEGIN				
				SET @IdStrElementoTrib = REPLACE(CONVERT(numeric(38, 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), '.', ',')
-- obtem o próximo numero de registo de elementos p/ tributação da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(DET_CODI), 0) + 1
				FROM PRO_DUET
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o elemento p/ tributação no detalhe de elementos p/ tributação da adição IMP-CAU
				INSERT INTO PRO_DUET(DUC_EANO, DUC_PNUM, DUA_CODI, DET_CODI, DET_TIPO, UME_CODI, UME_COD2, DET_QTDE, DET_AUTO, DIT_IDST, RRE_CODI, RRE_NOME, DET_IMPO, DET_TAXA, DET_TXVL, DET_IDST)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, 1, @CodUnidadeMedida, @CodUnidadeMedida2, @Quantidade, @TipoOrigem, @IdStrRegisto, @CodRubricaReceita, 
					@NomeRubricaReceita, @ImposicaoRubricaReceita, @ETaxa, @TaxaValor, @IdStrElementoTrib)
			END
			ELSE
			BEGIN
				UPDATE PRO_DUET SET					
					UME_CODI = @CodUnidadeMedida, 
					UME_COD2 = @CodUnidadeMedida2, 
					DET_QTDE = @Quantidade, 
					RRE_CODI = @CodRubricaReceita, 
					RRE_NOME = @NomeRubricaReceita, 
					DET_IMPO = @ImposicaoRubricaReceita, 
					DET_TAXA = @ETaxa, 
					DET_TXVL = @TaxaValor
				WHERE DET_IDEN = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @CodUnidadeMedida2, @CodRubricaReceita, @NomeRubricaReceita, @ImposicaoRubricaReceita, 
				@ETaxa, @TaxaValor, @IdStrRegisto, @IdRegisto, @TipoOrigem, @Quantidade	
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes			
-- remove os elementos p/ tributação existentes no detalhe de elementos p/ tributação das adições IMP-CAU mas já não existentes na configuração do artigo
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT det.DUC_EANO, det.DUC_PNUM, det.DUA_CODI, det.DET_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUET AS det WITH(NOLOCK) ON ins.DUC_EANO = det.DUC_EANO AND ins.DUC_PNUM = det.DUC_PNUM AND ins.DUA_CODI = det.DUA_CODI AND det.DET_AUTO IN (2, 3)
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.APA_CO33 = art.APA_CODI				
				LEFT OUTER JOIN TAB_AETR AS aet WITH(NOLOCK) ON art.APA_CHVE = aet.APA_CHVE AND det.DIT_IDST = aet.AET_IDST
			WHERE duc.DUC_DUNO = 2 AND aet.AET_CODI IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove elemento p/ tributação					
			DELETE FROM PRO_DUET
			WHERE DET_IDEN = @IdRegisto
-- atualiza numero de elementos p/ tributação posteriores
			UPDATE PRO_DUET SET DET_CODI = DET_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DET_IDEN > @IdRegisto 
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END
-- se coluna do valor aduaneiro alterada, processa a atualização dos campos de total adições e total valor aduaneiro na declaração das adições IMP-CAU inseridas/alteradas
	IF (ISNULL(CONTEXT_INFO(), 0x0) <> 0x44495341424C4544) AND (UPDATE(DUA_VATO)) --"DISABLED" em binário
	BEGIN
-- obtem as declarações associadas às adições inseridas/editadas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM
			FROM inserted AS ins
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
			WHERE duc.DUC_DUNO = 2
			GROUP BY ins.DUC_EANO, ins.DUC_PNUM
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a soma do número de adições e do valor aduaneiro de todas as adições da declaração IMP-CAU
			SELECT @SomaAdicoes = COUNT(*), @SomaValorAduaneiro = SUM(ISNULL(DUA_VATO, 0))
			FROM PRO_DUAD WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
-- atualiza total de adições e valor aduaneiro total na declaração IMP-CAU
			UPDATE PRO_DUCG SET 
				DUC_ADI5 = @SomaAdicoes, 
				DUC_VATT = @SomaValorAduaneiro
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	 		
	END
-- se coluna do valor aduaneiro alterada, processa a gestão do pedido “I07CP” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_VATO)
	BEGIN
-- insere/edita o pedido “I07CP” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, LTRIM(STR(ISNULL(ins.DUA_VATO, 0), 18, 2)), uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 							
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'I07CP'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 15
			WHERE duc.DUC_DUNO = 2 AND duc.DUC_ANXB = 'H3' AND ISNULL(ins.DUA_VATO, 0) > 0
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumeroPedido, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 15, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumeroPedido, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- remove o pedido “I07CP” existente no detalhe de pedidos da adição mas já não satisfaz a condição do valor aduaneiro
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 15
			WHERE duc.DUC_DUNO = 2 AND (duc.DUC_ANXB <> 'H3' OR ISNULL(ins.DUA_VATO, 0) = 0)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END
-- se coluna do regime alterada, processa a gestão do pedido “G1RED” no detalhe de pedidos ou o documento "C601" no detalhe de documentos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_RG37)
	BEGIN
-- obtem as adições IMP-CAU dos regimes "0151" ou "0153" e cujo cliente importador tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, doc.DOC_CODI, doc.DOC_NOME, cau.CAU_NDOC
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C601'
				INNER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON duc.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND doc.DOC_CODI = dad.DOC_CODI AND dad.DDO_AUTO = 12
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DUA_RG37, '') IN ('0151', '0153') AND doc.DOC_DESP = 1 AND doc.DOC_TRAN = 0 AND LEN(doc.DOC_CODI) <= 4 AND dad.DDO_IDEN IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(DDO_CODI), 0) + 1
			FROM PRO_DDOC
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento "C601" como "Documento Suporte" no detalhe de documentos da adição IMP-CAU
			INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_AUTO, DDO_TIPO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodDocumento, @NomeDocumento, @NumeroDocumento, 12, 0)			
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
-- obtem os documentos "C601" das adições IMP-CAU com regime "0151" ou "0153" e cliente importador tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.DUC_EANO, dad.DUC_PNUM, dad.DUA_CODI, dad.DDO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND dad.DDO_AUTO = 12
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI	
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON duc.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
			WHERE duc.DUC_DUNO = 2 AND (ISNULL(ins.DUA_RG37, '') NOT IN ('0151', '0153') OR doc.DOC_DESP = 0 OR doc.DOC_TRAN = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL OR cau.CAU_IDEN IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove documento					
			DELETE FROM PRO_DDOC
			WHERE DDO_IDEN = @IdRegisto
-- atualiza numero de documentos posteriores
			UPDATE PRO_DDOC SET DDO_CODI = DDO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DDO_IDEN > @IdRegisto 
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem as adições IMP-CAU dos regimes "0151" ou "0153" e cujo cliente importador não tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, NULLIF(SUBSTRING(tdp.TXM_TEXT, 1, 512), '')
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL						
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1RED'
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C601'
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON duc.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 22
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DUA_RG37, '') IN ('0151', '0153') AND cau.CAU_IDEN IS NULL AND dap.id IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere o pedido "G1RED" no detalhe de pedidos da adição IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 22, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
-- obtem os pedidos "G1RED" das adições IMP-CAU com regime "0151" ou "0153" e cliente importador não tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON ins.DUA_IDEN = dap.id_adicao AND dap.origem = 22
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C601'
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON duc.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
			WHERE duc.DUC_DUNO = 2 AND (ISNULL(ins.DUA_RG37, '') NOT IN ('0151', '0153') OR cau.CAU_IDEN IS NOT NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END
-- se coluna do desdobramento 1 alterada, processa a gestão de documentos do desdobramento no detalhe de documentos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUA_R37B)
	BEGIN
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, doc.DOC_CODI, doc.DOC_NOME
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM								
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', '417', '418') THEN '3E06' ELSE NULL END) 
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', 'C02', 'C03', 'C09', '417', '418', '421') THEN '3E14' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', 'C02', 'C04', '417', '418') THEN '3G14' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', 'C02', '417', '418') THEN '3G21' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C02', 'C03', '418', '421') THEN '9Z08' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C09', 'C10', '421') THEN '3Z61' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C33', 'C40', 'C44', 'C45', 'C46', 'C47', '422', '423', '424', '426', '427', '428', '441') THEN '3X06' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('417', '418') THEN 'N041' ELSE NULL END)
				LEFT OUTER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND doc.DOC_CODI = dad.DOC_CODI AND dad.DDO_AUTO = 13
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DUA_R37B, '') IN ('C01', 'C02', 'C03', 'C04', 'C09', 'C10', 'C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C33', 'C40', 'C44', 'C45', 'C46', 'C47', '417', '418', '421', '422', '423', '424', '426', '427', '428', '441') 
				AND doc.DOC_DESP = 1 AND doc.DOC_TRAN = 0 AND LEN(doc.DOC_CODI) <= 4 AND dad.DDO_IDEN IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(DDO_CODI), 0) + 1
			FROM PRO_DDOC
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento do desdobramento como "Documento Suporte" no detalhe de documentos da adição IMP-CAU
			INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_AUTO, DDO_TIPO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodDocumento, @NomeDocumento, 13, 0)			
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
-- obtem os documentos do desdobramento das adições IMP-CAU
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.DUC_EANO, dad.DUC_PNUM, dad.DUA_CODI, dad.DDO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUA_IDEN = del.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON ins.DUC_EANO = dad.DUC_EANO AND ins.DUC_PNUM = dad.DUC_PNUM AND ins.DUA_CODI = dad.DUA_CODI AND dad.DDO_AUTO = 13
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON (doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', '417', '418') THEN '3E06' ELSE NULL END) 
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', 'C02', 'C03', 'C09', '417', '418', '421') THEN '3E14' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', 'C02', 'C04', '417', '418') THEN '3G14' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C01', 'C02', '417', '418') THEN '3G21' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C02', 'C03', '418', '421') THEN '9Z08' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C09', 'C10', '421') THEN '3Z61' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C33', 'C40', 'C44', 'C45', 'C46', 'C47', '422', '423', '424', '426', '427', '428', '441') THEN '3X06' ELSE NULL END)
														OR doc.DOC_CODI = (CASE WHEN ISNULL(ins.DUA_R37B, '') IN ('417', '418') THEN 'N041' ELSE NULL END))
														AND dad.DOC_CODI = doc.DOC_CODI
			WHERE duc.DUC_DUNO = 2 AND (ISNULL(ins.DUA_R37B, '') NOT IN ('C01', 'C02', 'C03', 'C04', 'C09', 'C10', 'C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C33', 'C40', 'C44', 'C45', 'C46', 'C47', '417', '418', '421', '422', '423', '424', '426', '427', '428', '441') 
				OR doc.DOC_DESP = 0 OR doc.DOC_TRAN = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove documento					
			DELETE FROM PRO_DDOC
			WHERE DDO_IDEN = @IdRegisto
-- atualiza numero de documentos posteriores
			UPDATE PRO_DDOC SET DDO_CODI = DDO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DDO_IDEN > @IdRegisto 
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END
END

ALTER TABLE [dbo].[PRO_DUAD] ENABLE TRIGGER [TAIU_PRO_DUAD_IMPCAU]
/****** Object:  Trigger [TAIUD_PRO_DUAD]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DUAD] ON [PRO_DUAD] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
    if UPDATE(APA_CO33) or UPDATE(UME_CODI) or UPDATE(DUA_TIVA) or UPDATE(DUA_TRIB) or UPDATE(DUA_PLIQ) or UPDATE(DUA_GRAD) or UPDATE(PAI_CO34) 
	or UPDATE(DUA_MB35) or UPDATE(PRE_CO36) or UPDATE(RRE_PREF) or UPDATE(DUA_RG37) or UPDATE(DUA_R37B) or UPDATE(DUA_ML38) or UPDATE(DUA_CO39) 
	or UPDATE(DUA_US41) or UPDATE(USU_CO41) or UPDATE(DUA_VA42) or UPDATE(DUA_VFRE) or UPDATE(DUA_VSEG) or UPDATE(DUA_VTRA) or UPDATE(DUA_ROYA) 
	or UPDATE(DUA_VROY) or UPDATE(DUA_VDIR) or UPDATE(DUA_VOPT) or UPDATE(DUA_DESG) or UPDATE(DUA_LCMB) or UPDATE(DUA_CAUC) or UPDATE(DUA_CANO) 
	or UPDATE(DUA_CTIP) or UPDATE(DUA_CENT) or UPDATE(ARM_CO49) or UPDATE(AGE_CO50) or UPDATE(ALF_CO53) or UPDATE(DUA_VEST) or UPDATE(DUA_AJUS) 
	or UPDATE(DUA_CORE) or UPDATE(DUA_CONR) or UPDATE(DUA_DANO) or UPDATE(DUA_DNUM) or UPDATE(DUA_DNRS) or UPDATE(DUA_DDAT) or UPDATE(DUA_LINH) 
	or UPDATE(DUA_VATO) or UPDATE(DUA_NEPO) or UPDATE(DUA_BTRI) or UPDATE(DUA_TXCO) or UPDATE(DUA_TXVL) or UPDATE(DUA_MTRI) or UPDATE(DUA_IVAV) 
	or UPDATE(DUA_BTIV) or UPDATE(RRE_CODI) or UPDATE(DUA_MPAG) or UPDATE(FLE_CODI) or UPDATE(DUA_VSEL) or UPDATE(DUA_VIVA) or UPDATE(DUA_VAEU) 
	or UPDATE(APA_CP33) or UPDATE(DUA_TC31) or UPDATE(DUA_TC44) or UPDATE(DUA_MTPR) or UPDATE(DUA_QUAL) or UPDATE(DOC_CODI) or UPDATE(EAD_CODI) 
	or UPDATE(MTR_CODI) or UPDATE(DUA_IMPO) or UPDATE(DUA_ATAR) or UPDATE(DUA_AIVA) or UPDATE(DUA_CS50) or UPDATE(DUA_R37C) or UPDATE(DUA_ADRE)
	begin
		insert into LOG_DUAD (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, 
			DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, DUA_ML38, DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, 
			DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_LCMB, DUA_CAUC, DUA_CANO, DUA_CTIP, DUA_CENT, ARM_CO49, AGE_CO50, ALF_CO53, DUA_VEST, 
			DUA_AJUS, DUA_CORE, DUA_CONR, DUA_DANO, DUA_DNUM, DUA_DNRS, DUA_DDAT, DUA_LINH, DUA_VATO, DUA_NEPO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, 
			DUA_BTIV, RRE_CODI, DUA_MPAG, FLE_CODI, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, DUA_TC31, DUA_TC44, DUA_MTPR, DUA_QUAL, DOC_CODI, EAD_CODI, MTR_CODI, 
			DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, DUA_ADRE)
		select NEWID(), (case (select count(*) from deleted where DUA_IDEN = inserted.DUA_IDEN) when 0 then 0 else 1 end), 
			GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), 
			DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, 
			DUA_ML38, DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_LCMB, DUA_CAUC, 
			DUA_CANO, DUA_CTIP, DUA_CENT, ARM_CO49, AGE_CO50, ALF_CO53, DUA_VEST, DUA_AJUS, DUA_CORE, DUA_CONR, DUA_DANO, DUA_DNUM, DUA_DNRS, DUA_DDAT, DUA_LINH, 
			DUA_VATO, DUA_NEPO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, FLE_CODI, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, 
			DUA_TC31, DUA_TC44, DUA_MTPR, DUA_QUAL, DOC_CODI, EAD_CODI, MTR_CODI, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, DUA_ADRE
		from inserted
		where ((select count(*) from deleted where DUA_IDEN = inserted.DUA_IDEN) = 0)
			or ((select count(*) from deleted where DUA_IDEN = inserted.DUA_IDEN and ((isnull(APA_CO33, '') <> isnull(inserted.APA_CO33, '')) or 
			(isnull(UME_CODI, '') <> isnull(inserted.UME_CODI, '')) or (isnull(DUA_TIVA, -1) <> isnull(inserted.DUA_TIVA, -1)) or 
			(isnull(DUA_TRIB, -1) <> isnull(inserted.DUA_TRIB, -1)) or (isnull(DUA_PLIQ, -1) <> isnull(inserted.DUA_PLIQ, -1)) or 
			(isnull(DUA_GRAD, -1) <> isnull(inserted.DUA_GRAD, -1)) or (isnull(PAI_CO34, '') <> isnull(inserted.PAI_CO34, '')) or (DUA_MB35 <> inserted.DUA_MB35) or 
			(isnull(PRE_CO36, '') <> isnull(inserted.PRE_CO36, '')) or (isnull(RRE_PREF, -1) <> isnull(inserted.RRE_PREF, -1)) or 
			(isnull(DUA_RG37, '') <> isnull(inserted.DUA_RG37, '')) or (isnull(DUA_R37B, '') <> isnull(inserted.DUA_R37B, '')) or (DUA_ML38 <> inserted.DUA_ML38) or 
			(isnull(DUA_CO39, '') <> isnull(inserted.DUA_CO39, '')) or (isnull(DUA_US41, -1) <> isnull(inserted.DUA_US41, -1)) or 
			(isnull(USU_CO41, '') <> isnull(inserted.USU_CO41, '')) or (isnull(DUA_VA42, -1) <> isnull(inserted.DUA_VA42, -1)) or 
			(isnull(DUA_VFRE, -1) <> isnull(inserted.DUA_VFRE, -1)) or (isnull(DUA_VSEG, -1) <> isnull(inserted.DUA_VSEG, -1)) or 
			(isnull(DUA_VTRA, -1) <> isnull(inserted.DUA_VTRA, -1)) or (isnull(DUA_ROYA, -1) <> isnull(inserted.DUA_ROYA, -1)) or 
			(isnull(DUA_VROY, -1) <> isnull(inserted.DUA_VROY, -1)) or (isnull(DUA_VDIR, -1) <> isnull(inserted.DUA_VDIR, -1)) or 
			(isnull(DUA_VOPT, -1) <> isnull(inserted.DUA_VOPT, -1)) or (isnull(DUA_DESG, '') <> isnull(inserted.DUA_DESG, '')) or (DUA_LCMB <> inserted.DUA_LCMB) or 
			(isnull(DUA_CAUC, '') <> isnull(inserted.DUA_CAUC, '')) or (isnull(DUA_CANO, '') <> isnull(inserted.DUA_CANO, '')) or 
			(isnull(DUA_CTIP, '') <> isnull(inserted.DUA_CTIP, '')) or (isnull(DUA_CENT, -1) <> isnull(inserted.DUA_CENT, -1)) or 
			(isnull(ARM_CO49, '') <> isnull(inserted.ARM_CO49, '')) or (isnull(AGE_CO50, '') <> isnull(inserted.AGE_CO50, '')) or 
			(isnull(ALF_CO53, '') <> isnull(inserted.ALF_CO53, '')) or (DUA_VEST <> inserted.DUA_VEST) or (DUA_AJUS <> inserted.DUA_AJUS) or 
			(isnull(DUA_CORE, -1) <> isnull(inserted.DUA_CORE, -1)) or (isnull(DUA_CONR, '') <> isnull(inserted.DUA_CONR, '')) or 
			(isnull(DUA_DANO, -1) <> isnull(inserted.DUA_DANO, -1)) or (isnull(DUA_DNUM, '') <> isnull(inserted.DUA_DNUM, '')) or 
			(isnull(DUA_DNRS, '') <> isnull(inserted.DUA_DNRS, '')) or (isnull(DUA_DDAT, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.DUA_DDAT, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or 
			(isnull(DUA_LINH, '') <> isnull(inserted.DUA_LINH, '')) or (isnull(DUA_VATO, -1) <> isnull(inserted.DUA_VATO, -1)) or 
			(isnull(DUA_NEPO, '') <> isnull(inserted.DUA_NEPO, '')) or (isnull(DUA_BTRI, -1) <> isnull(inserted.DUA_BTRI, -1)) or (DUA_TXCO <> inserted.DUA_TXCO) or 
			(isnull(DUA_TXVL, -1) <> isnull(inserted.DUA_TXVL, -1)) or (isnull(DUA_MTRI, -1) <> isnull(inserted.DUA_MTRI, -1)) or 
			(isnull(DUA_IVAV, -1) <> isnull(inserted.DUA_IVAV, -1)) or (isnull(DUA_BTIV, -1) <> isnull(inserted.DUA_BTIV, -1)) or 
			(isnull(RRE_CODI, -1) <> isnull(inserted.RRE_CODI, -1)) or (isnull(DUA_MPAG, '') <> isnull(inserted.DUA_MPAG, '')) or 
			(isnull(FLE_CODI, -1) <> isnull(inserted.FLE_CODI, -1)) or (isnull(DUA_VSEL, -1) <> isnull(inserted.DUA_VSEL, -1)) or 
			(isnull(DUA_VIVA, -1) <> isnull(inserted.DUA_VIVA, -1)) or (isnull(DUA_VAEU, -1) <> isnull(inserted.DUA_VAEU, -1)) or 
			(isnull(APA_CP33, '') <> isnull(inserted.APA_CP33, '')) or (isnull(DUA_TC31, '') <> isnull(inserted.DUA_TC31, '')) or 
			(isnull(DUA_TC44, '') <> isnull(inserted.DUA_TC44, '')) or (isnull(DUA_MTPR, -1) <> isnull(inserted.DUA_MTPR, -1)) or 
			(isnull(DUA_QUAL, '') <> isnull(inserted.DUA_QUAL, '')) or (isnull(DOC_CODI, '') <> isnull(inserted.DOC_CODI, '')) or 
			(isnull(EAD_CODI, '') <> isnull(inserted.EAD_CODI, '')) or (isnull(MTR_CODI, '') <> isnull(inserted.MTR_CODI, '')) or 
			(isnull(DUA_IMPO, '') <> isnull(inserted.DUA_IMPO, '')) or (isnull(DUA_ATAR, '') <> isnull(inserted.DUA_ATAR, '')) or 
			(isnull(DUA_AIVA, -1) <> isnull(inserted.DUA_AIVA, -1)) or (DUA_CS50 <> inserted.DUA_CS50) or (isnull(DUA_R37C, '') <> isnull(inserted.DUA_R37C, '')) or 
			(isnull(DUA_ADRE, '') <> isnull(inserted.DUA_ADRE, '')))) > 0)
	end
	else
	begin
		insert into LOG_DUAD (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, 
			DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, RRE_PREF, DUA_RG37, DUA_R37B, DUA_ML38, DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, 
			DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, DUA_DESG, DUA_LCMB, DUA_CAUC, DUA_CANO, DUA_CTIP, DUA_CENT, ARM_CO49, AGE_CO50, ALF_CO53, DUA_VEST, 
			DUA_AJUS, DUA_CORE, DUA_CONR, DUA_DANO, DUA_DNUM, DUA_DNRS, DUA_DDAT, DUA_LINH, DUA_VATO, DUA_NEPO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, 
			DUA_BTIV, RRE_CODI, DUA_MPAG, FLE_CODI, DUA_VSEL, DUA_VIVA, DUA_VAEU, APA_CP33, DUA_TC31, DUA_TC44, DUA_MTPR, DUA_QUAL, DOC_CODI, EAD_CODI, MTR_CODI, 
			DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, DUA_ADRE)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_EANO, DUC_PNUM, DUA_CODI, APA_CO33, UME_CODI, DUA_TIVA, DUA_TRIB, DUA_PLIQ, DUA_GRAD, PAI_CO34, DUA_MB35, PRE_CO36, 
			RRE_PREF, DUA_RG37, DUA_R37B, DUA_ML38, DUA_CO39, DUA_US41, USU_CO41, DUA_VA42, DUA_VFRE, DUA_VSEG, DUA_VTRA, DUA_ROYA, DUA_VROY, DUA_VDIR, DUA_VOPT, 
			DUA_DESG, DUA_LCMB, DUA_CAUC, DUA_CANO, DUA_CTIP, DUA_CENT, ARM_CO49, AGE_CO50, ALF_CO53, DUA_VEST, DUA_AJUS, DUA_CORE, DUA_CONR, DUA_DANO, DUA_DNUM, 
			DUA_DNRS, DUA_DDAT, DUA_LINH, DUA_VATO, DUA_NEPO, DUA_BTRI, DUA_TXCO, DUA_TXVL, DUA_MTRI, DUA_IVAV, DUA_BTIV, RRE_CODI, DUA_MPAG, FLE_CODI, DUA_VSEL, 
			DUA_VIVA, DUA_VAEU, APA_CP33, DUA_TC31, DUA_TC44, DUA_MTPR, DUA_QUAL, DOC_CODI, EAD_CODI, MTR_CODI, DUA_IMPO, DUA_ATAR, DUA_AIVA, DUA_CS50, DUA_R37C, 
			DUA_ADRE
		from deleted
		where (select count(*) from inserted where DUA_IDEN = deleted.DUA_IDEN) = 0
	end
END

ALTER TABLE [dbo].[PRO_DUAD] ENABLE TRIGGER [TAIUD_PRO_DUAD]
/****** Object:  Trigger [TAU_PRO_DUAD]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DUAD] ON [PRO_DUAD] FOR UPDATE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @NumDeclaracao int, @AnoDeclaracao int, @NumAdicao int
-- verifica se campos "Cod. Pautal Artigo", "Tx. IVA", "Massa Líquida", "Qtd. Unidades", "Valor", "Frete", "Seguro", "Verba Transitário", "Royalties", "Optativas", "Valor Estatístico", "Valor Aduaneiro", "Taxa/Valor Direitos", "Montante Direitos", "Montante IVA" ou "Valor EUR" foram alterados e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO" para colocar declarações como pendentes de envio para Portal MyRangel
	IF (UPDATE(APA_CP33) OR UPDATE(DUA_TIVA) OR UPDATE(DUA_ML38) OR UPDATE(DUA_US41) OR UPDATE(DUA_VA42) OR UPDATE(DUA_VFRE) OR UPDATE(DUA_VSEG) OR UPDATE(DUA_VTRA) OR UPDATE(DUA_VROY) OR UPDATE(DUA_VOPT) OR UPDATE(DUA_VEST) OR UPDATE(DUA_VATO) OR UPDATE(DUA_TXVL) OR UPDATE(DUA_MTRI) OR UPDATE(DUA_VIVA) OR UPDATE(DUA_VAEU)) 
		AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO, DUA_CODI
			FROM inserted 
			WHERE DUA_PMRP = 0 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @NumDeclaracao, @AnoDeclaracao, @NumAdicao 
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE PRO_DUAD SET 
				DUA_PMRP = 1				
			WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao AND DUA_CODI = @NumAdicao
			FETCH NEXT FROM Adicoes INTO @NumDeclaracao, @AnoDeclaracao, @NumAdicao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes				
	END
END

ALTER TABLE [dbo].[PRO_DUAD] ENABLE TRIGGER [TAU_PRO_DUAD]
/****** Object:  Trigger [TAU_PRO_DUAD_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DUAD_IMPCAU] ON [PRO_DUAD] FOR UPDATE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdAdicao int, @IdUtilizador int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- se coluna do método de avaliação alterada, processa remoções dos detalhes de acréscimos/deduções das adições IMP-CAU alteradas
	IF UPDATE(DUA_MAVA)
	BEGIN
-- obtem as adições IMP-CAU que não satisfaçam as condições p/ ter acréscimos/deduções
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUA_IDEN, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL				
			WHERE duc.DUC_DUNO = 2 AND (duc.DUC_ANXB IN ('H2', 'H3', 'H4', 'H6') OR ISNULL(ins.DUA_MAVA, 0) > 1)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nos acréscimos/deduções o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_adicao = @IdAdicao
-- remove os acréscimos/deduções da adição
			DELETE FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes
			WHERE id_adicao = @IdAdicao
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END	
END

ALTER TABLE [dbo].[PRO_DUAD] ENABLE TRIGGER [TAU_PRO_DUAD_IMPCAU]
/****** Object:  Trigger [TAD_PRO_DUBT_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUBT_IMPCAU] ON [PRO_DUBT] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdRegisto bigint, @IdUtilizador int
	DECLARE @SomaMontanteISV numeric(38, 6), @BaseTributacaoIVA numeric(38, 6), @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @NumVeiculo int, @FormulaCondEntrega varchar(70), 
		@TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os veículos das declarações IMP-CAU removidos
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, del.DBT_CODI
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2
		GROUP BY del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, del.DBT_CODI
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove as matrículas/chassis associadas ao veículo
		DELETE FROM PRO_DUVE 
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DBT_CODI = @NumVeiculo
		FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos
-- obtem as adições pertencentes aos veículos removidos 
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0)
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2 
		GROUP BY del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, duc.DUC_FR20, duc.DUC_TFDA, duc.DUC_TXFR
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula a soma dos valores ISV dos veículos da adição 
		SET @SomaMontanteISV = ISNULL(
			(SELECT SUM(ISNULL(DBT_NVEI, 0) * DBT_VLIA)
			FROM PRO_DUBT WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao), 0)
-- atualiza valor ISV, base tributação do IVA e montante IVA na adição
		UPDATE PRO_DUAD SET 
			DUA_IVAV = @SomaMontanteISV, 
			@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega,@TaxaFDA, @CambioFrete, DUA_VFRE, DUA_AJUS, DUA_VEST, DUA_VTRA, DUA_VOPT, DUA_MTRI, @SomaMontanteISV, DUA_ABTI, DUA_MIVI),
			DUA_VIVA = ROUND(@BaseTributacaoIVA * DUA_TIVA / 100, 2)
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao 
		FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos
-- remove o pedido “G1HTV” ou “G1CHV” existente no detalhe de pedidos da adição quando o documento IMT está definido
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 2 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_DIMT, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos
-- remove o pedido “G1COV” existente no detalhe de pedidos da adição quando a tabela tem o valor "A" e tem emissão CO2
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 3 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_TABE, '') = 'A' AND ISNULL(del.DBT_VCO2, 0) > 0
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos
-- remove o pedido “G1TTV” existente no detalhe de pedidos da adição quando a tabela tem o valor "A" e tem tipo CO2
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 4 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_TABE, '') = 'A' AND ISNULL(del.DBT_TCO2, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos
-- remove o pedido “G1BTV” existente no detalhe de pedidos da adição quando a autonomia está definida
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 5 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_AUTN, 0) > 0
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos
-- remove o pedido “G1QFV” existente no detalhe de pedidos da adição quando o qualificador está definido
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 9 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_QUAL, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos	
-- remove o pedido “G1CTV” existente no detalhe de pedidos da adição quando a categoria está definida
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 10 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.CAT_CODI, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos			
-- remove o pedido “G1TFV” existente no detalhe de pedidos da adição quando o tipo de veículo está definido
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 11 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.TVE_CODI, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos	
-- remove o pedido “G1CBV” existente no detalhe de pedidos da adição quando o tipo de combustível está definido
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 12 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.TCO_CODI, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos		
-- remove o pedido “G1C3V” existente no detalhe de pedidos da adição quando a cilindrada está definida
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 13 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND del.DBT_QTDE > 0
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos		
-- remove o pedido “G1EPV” existente no detalhe de pedidos da adição quando a emissão de partículas está definida
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 14 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_OUTR, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos
-- remove o pedido “G1MAV” existente no detalhe de pedidos da adição quando a marca está definida
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 16 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_MARC, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos			
-- remove o pedido “G1MDV” existente no detalhe de pedidos da adição quando o modelo está definido
	DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 17 AND del.DBT_IDEN = dap.id_veiculo			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DBT_MODE, '') <> ''
	OPEN Veiculos
	FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Veiculos
	DEALLOCATE Veiculos		
END

ALTER TABLE [dbo].[PRO_DUBT] ENABLE TRIGGER [TAD_PRO_DUBT_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUBT_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUBT_IMPCAU] ON [PRO_DUBT] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdRegisto bigint
	DECLARE @SomaMontanteISV numeric(38, 6), @BaseTributacaoIVA numeric(38, 6), @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @FormulaCondEntrega varchar(70), 
		@TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6), @IdVeiculo int, @IdAdicao int, @IdUtilizador int, @IdPedido int, @NumeroPedido varchar(512)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- se colunas do n.º unidades ou valor ISV alteradas, processa a atualização das adições IMP-CAU associadas aos veículos inseridos/alterados
	IF UPDATE(DBT_NVEI) OR UPDATE(DBT_VLIA) 
	BEGIN
-- obtem as adições pertencentes aos veículos inseridos/alterados
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0)
			FROM inserted AS ins 				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
			WHERE duc.DUC_DUNO = 2
			GROUP BY ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, duc.DUC_FR20, duc.DUC_TFDA, duc.DUC_TXFR
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a soma dos valores ISV dos veículos da adição 
			SET @SomaMontanteISV = ISNULL(
				(SELECT SUM(ISNULL(DBT_NVEI, 0) * DBT_VLIA)
				FROM PRO_DUBT WITH(NOLOCK)
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao), 0)
-- atualiza valor ISV, base tributação do IVA e montante IVA na adição
			UPDATE PRO_DUAD SET 
				DUA_IVAV = @SomaMontanteISV, 
				@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega,@TaxaFDA, @CambioFrete, DUA_VFRE, DUA_AJUS, DUA_VEST, DUA_VTRA, DUA_VOPT, DUA_MTRI, @SomaMontanteISV, DUA_ABTI, DUA_MIVI),
				DUA_VIVA = ROUND(@BaseTributacaoIVA * DUA_TIVA / 100, 2)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao 
			FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se colunas da homologação técnica ou documento IMT alteradas, processa a gestão do pedido “G1HTV” ou “G1CHV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_HOMO) OR UPDATE(DBT_DIMT)
	BEGIN
-- insere/edita o pedido “G1HTV” ou “G1CHV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.DBT_HOMO, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON ins.DBT_DIMT = tdp.TXM_CODI 
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 2	AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_DIMT, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 2, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET	
					id_pedido = @IdPedido, 				
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1HTV” ou “G1CHV” existente no detalhe de pedidos da adição mas já não satisfaz a condição do documento IMT
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 2 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_DIMT, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se colunas da tabela ou emissão CO2 alteradas, processa a gestão do pedido “G1COV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_TABE) OR UPDATE(DBT_VCO2)
	BEGIN
-- insere/edita o pedido “G1COV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, CAST(ins.DBT_VCO2 AS varchar(10)), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1COV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 3	AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_TABE, '') = 'A' AND ISNULL(ins.DBT_VCO2, 0) > 0
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 3, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1COV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da tabela ou emissão CO2
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 3 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND (ISNULL(ins.DBT_TABE, '') <> 'A' OR ISNULL(ins.DBT_VCO2, 0) = 0)
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se colunas da tabela ou tipo CO2 alteradas, processa a gestão do pedido “G1TTV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_TABE) OR UPDATE(DBT_TCO2)
	BEGIN
-- insere/edita o pedido “G1TTV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, ins.DBT_TCO2, adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1TTV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 4	AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_TABE, '') = 'A' AND ISNULL(ins.DBT_TCO2, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 4, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1TTV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da tabela ou tipo CO2
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 4 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND (ISNULL(ins.DBT_TABE, '') <> 'A' OR ISNULL(ins.DBT_TCO2, '') = '')
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna da autonomia alterada, processa a gestão do pedido “G1BTV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_AUTN)
	BEGIN
-- insere/edita o pedido “G1BTV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, CAST(ins.DBT_AUTN AS varchar(10)), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1BTV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 5	AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_AUTN, 0) > 0
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 5, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1BTV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da autonomia
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 5 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_AUTN, 0) = 0
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna do qualificador alterada, processa a gestão do pedido “G1QFV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_QUAL)
	BEGIN
-- insere/edita o pedido “G1QFV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.DBT_QUAL, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1QFV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 9	AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_QUAL, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 9, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1QFV” existente no detalhe de pedidos da adição mas já não satisfaz a condição do qualificador
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 9 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_QUAL, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna do categoria alterada, processa a gestão do pedido “G1CTV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(CAT_CODI)
	BEGIN
-- insere/edita o pedido “G1CTV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.CAT_CODI, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1CTV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 10 AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.CAT_CODI, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 10, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1CTV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da categoria
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 10 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.CAT_CODI, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna do tipo de veículo alterada, processa a gestão do pedido “G1TFV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(TVE_CODI)
	BEGIN
-- insere/edita o pedido “G1TFV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.TVE_CODI, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1TFV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 11 AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.TVE_CODI, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 11, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1TFV” existente no detalhe de pedidos da adição mas já não satisfaz a condição do tipo de veículo
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 11 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.TVE_CODI, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna do tipo de combustível alterada, processa a gestão do pedido “G1CBV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(TCO_CODI)
	BEGIN
-- insere/edita o pedido “G1CBV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.TCO_CODI, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1CBV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 12 AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.TCO_CODI, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 12, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1CBV” existente no detalhe de pedidos da adição mas já não satisfaz a condição do tipo de combustível
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 12 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.TCO_CODI, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna da cilindrada alterada, processa a gestão do pedido “G1C3V” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_QTDE)
	BEGIN
-- insere/edita o pedido “G1C3V” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, LTRIM(STR(CAST(ins.DBT_QTDE AS int), 18, 0)), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1C3V'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 13 AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ins.DBT_QTDE > 0
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 13, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1C3V” existente no detalhe de pedidos da adição mas já não satisfaz a condição da cilindrada
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 13 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ins.DBT_QTDE = 0
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna da emissão de partículas alterada, processa a gestão do pedido “G1EPV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_OUTR)
	BEGIN
-- insere/edita o pedido “G1EPV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.DBT_OUTR, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1EPV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 14 AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_OUTR, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 14, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1EPV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da emissão de partículas
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 14 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_OUTR, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna da marca alterada, processa a gestão do pedido “G1MAV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_MARC)
	BEGIN
-- insere/edita o pedido “G1MAV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.DBT_MARC, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1MAV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 16 AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_MARC, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 16, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1MAV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da marca
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 16 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_MARC, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
-- se coluna do modelo alterada, processa a gestão do pedido “G1MDV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DBT_MODE)
	BEGIN
-- insere/edita o pedido “G1MDV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DBT_IDEN, NULLIF(ins.DBT_MODE, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1MDV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 17 AND ins.DBT_IDEN = dap.id_veiculo								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_MODE, '') <> ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_veiculo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 17, @IdUtilizador, @DataAtual, @IdVeiculo)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Veiculos INTO @IdVeiculo, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
-- remove o pedido “G1MDV” existente no detalhe de pedidos da adição mas já não satisfaz a condição do modelo
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 17 AND ins.DBT_IDEN = dap.id_veiculo			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DBT_MODE, '') = ''
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Veiculos INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos		
	END
END

ALTER TABLE [dbo].[PRO_DUBT] ENABLE TRIGGER [TAIU_PRO_DUBT_IMPCAU]
/****** Object:  Trigger [TAIUD_PRO_DUBT]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DUBT] ON [PRO_DUBT] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	if UPDATE(UME_CODI) or UPDATE(DBT_QTDE) or UPDATE(DBT_NVEI) or UPDATE(TVE_CODI) or UPDATE(DBT_QUAL) or UPDATE(DBT_VIEC) or UPDATE(DBT_VCO2) 
	or UPDATE(CAT_CODI) or UPDATE(TCO_CODI) or UPDATE(DBT_OUTR) or UPDATE(DBT_AUTO) or UPDATE(DBT_VLIA)
	begin
		insert into LOG_DUBT (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, UME_CODI, DBT_QTDE, DBT_NVEI, 
			TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, DBT_AUTO, DBT_VLIA)
		select NEWID(), (case (select count(*) from deleted where DBT_IDEN = inserted.DBT_IDEN) when 0 then 0 else 1 end), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), DUC_EANO, 
			DUC_PNUM, DUA_CODI, DBT_CODI, UME_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, DBT_AUTO, DBT_VLIA
		from inserted
		where ((select count(*) from deleted where DBT_IDEN = inserted.DBT_IDEN) = 0)
			or ((select count(*) from deleted where DBT_IDEN = inserted.DBT_IDEN and ((isnull(UME_CODI, '') <> isnull(inserted.UME_CODI, '')) or 
			(DBT_QTDE <> inserted.DBT_QTDE) or (isnull(DBT_NVEI, -1) <> isnull(inserted.DBT_NVEI, -1)) or (isnull(TVE_CODI, '') <> isnull(inserted.TVE_CODI, '')) or 
			(isnull(DBT_QUAL, '') <> isnull(inserted.DBT_QUAL, '')) or (isnull(DBT_VIEC, '') <> isnull(inserted.DBT_VIEC, '')) or 
			(isnull(DBT_VCO2, -1) <> isnull(inserted.DBT_VCO2, -1)) or (isnull(CAT_CODI, '') <> isnull(inserted.CAT_CODI, '')) or 
			(isnull(TCO_CODI, '') <> isnull(inserted.TCO_CODI, '')) or (isnull(DBT_OUTR, '') <> isnull(inserted.DBT_OUTR, '')) or 
			(DBT_AUTO <> inserted.DBT_AUTO) or (DBT_VLIA <> inserted.DBT_VLIA))) > 0)
	end
	else
	begin
		insert into LOG_DUBT (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, UME_CODI, DBT_QTDE, DBT_NVEI, 
			TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, TCO_CODI, DBT_OUTR, DBT_AUTO, DBT_VLIA)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_EANO, DUC_PNUM, DUA_CODI, DBT_CODI, UME_CODI, DBT_QTDE, DBT_NVEI, TVE_CODI, DBT_QUAL, DBT_VIEC, DBT_VCO2, CAT_CODI, 
			TCO_CODI, DBT_OUTR, DBT_AUTO, DBT_VLIA
		from deleted
		where (select count(*) from inserted where DBT_IDEN = deleted.DBT_IDEN) = 0
	end
END

ALTER TABLE [dbo].[PRO_DUBT] ENABLE TRIGGER [TAIUD_PRO_DUBT]
/****** Object:  Trigger [TAU_PRO_DUBT_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DUBT_IMPCAU] ON [PRO_DUBT] AFTER UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @NumVeiculo int, @NumAdicaoDEL int, @NumVeiculoDEL int
-- se colunas do n.º adição ou n.º veículo alteradas, processa atualização do detalhe de matrículas/chassis das declarações IMP-CAU alteradas
	IF UPDATE(DUA_CODI) OR UPDATE(DBT_CODI)
	BEGIN
-- obtem os veículos das declarações IMP-CAU alterados
		DECLARE Veiculos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.DBT_CODI, del.DUA_CODI, del.DBT_CODI
			FROM inserted AS ins
				INNER JOIN deleted AS del ON ins.DBT_IDEN = del.DBT_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
			WHERE duc.DUC_DUNO = 2		
		OPEN Veiculos
		FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo, @NumAdicaoDEL, @NumVeiculoDEL
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza as matrículas/chassis associadas ao veículo
			UPDATE PRO_DUVE SET
				DUA_CODI = @NumAdicao,
				DBT_CODI = @NumVeiculo
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicaoDEL AND DBT_CODI = @NumVeiculoDEL
			FETCH NEXT FROM Veiculos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo, @NumAdicaoDEL, @NumVeiculoDEL
		END
		CLOSE Veiculos
		DEALLOCATE Veiculos
	END
END

ALTER TABLE [dbo].[PRO_DUBT] ENABLE TRIGGER [TAU_PRO_DUBT_IMPCAU]
/****** Object:  Trigger [TAD_PRO_DUCG]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUCG] ON [PRO_DUCG] FOR DELETE AS 
BEGIN
set nocount on
-- declaracao de variaveis
DECLARE @ano int, @cod int
-- busca dados removidos
DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	select DUC_EANO, DUC_PNUM
	from deleted
OPEN Detalhe
FETCH NEXT FROM Detalhe INTO @ano, @cod
WHILE @@FETCH_STATUS = 0
BEGIN
	-- apagar informação das Adições ------------------------------------------------
	DELETE FROM PRO_DUAD WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DDOC WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DCON WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DULR WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DUOI WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DU31 WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DUOD WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DURA WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
	DELETE FROM PRO_DUBT WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
	DELETE FROM PRO_DUVE WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
	DELETE FROM PRO_DUET WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
	DELETE FROM PRO_DUMI WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
	DELETE FROM PRO_DUIT WHERE DUC_PNUM = @cod AND DUC_EANO = @ano
	-- apagar informação referênte ao modelo ATR ------------------------------------
	DELETE FROM PRO_AATR WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_ATRC WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_AEUR WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DEC_CODI = '0'
	DELETE FROM PRO_EUR1 WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DEC_CODI = '0'
	-- apagar informação referênte à guia G156 --------------------------------------
	DELETE FROM PRO_CG15 WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_G156 WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	-- apagar informação referênte à DV1 --------------------------------------------
	DELETE FROM PRO_ADV1 WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	DELETE FROM PRO_DV1C WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	
	-- apagar informação referênte às Cauções ---------------------------------------
	DELETE FROM PRO_MCAU WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DUC_TIPO = 0
	DELETE FROM PRO_CCCA WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DUC_TIPO = 0
	-- apagar informação referênte às Incidências do Histórico ----------------------
	DELETE FROM PRO_DUIN WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	

	FETCH NEXT FROM Detalhe INTO @ano, @cod
END
CLOSE Detalhe
DEALLOCATE Detalhe
set nocount off
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAD_PRO_DUCG]
/****** Object:  Trigger [TAD_PRO_DUCG_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUCG_IMPCAU] ON [PRO_DUCG] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoConta int, @CodTipoDocConta varchar(4), @IdConta int
-- obtem os documentos de contas das declarações removidas quando ainda não foram emitidos (s/ número atribuído)
	DECLARE Contas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT cdo.CDO_EANO, cdo.CDO_TDOC, cdo.CDO_IDEN
		FROM deleted AS del 
			INNER JOIN FAC_CDOC AS cdo ON del.DUC_PNUM = cdo.CDO_NPRO AND del.DUC_EANO = cdo.CDO_PANO AND cdo.CDO_CNUM IS NULL AND cdo.CDO_IMEX = 0 AND cdo.id_declaracaoDAR IS NULL
		WHERE (del.DUC_DUNO = 2 OR del.DUC_SERV = 1) AND del.DUC_CNTN IS NULL AND cdo.CDO_STAT = 0
	OPEN Contas
	FETCH NEXT FROM Contas INTO @AnoConta, @CodTipoDocConta, @IdConta
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- remove dados gerais do documento de conta
		DELETE FROM FAC_CDOC 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdConta
-- remove despesas documentadas do documento de conta
		DELETE FROM FAC_DCDO 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdConta
		DELETE FROM FAC_DDCD 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdConta
-- remove despesas inerentes do documento de conta
		DELETE FROM FAC_ICDO 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdConta        
        DELETE FROM FAC_DICD 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdConta  
-- remove gestão documental do documento de conta		      
        DELETE FROM FAC_CDDO 
		WHERE CDO_EANO = @AnoConta AND CDO_TDOC = @CodTipoDocConta AND CDO_IDEN = @IdConta
		FETCH NEXT FROM Contas INTO @AnoConta, @CodTipoDocConta, @IdConta
	END
	CLOSE Contas
	DEALLOCATE Contas
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAD_PRO_DUCG_IMPCAU]
/****** Object:  Trigger [TAI_PRO_DUCG_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_DUCG_IMPCAU] ON [PRO_DUCG] AFTER INSERT AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @Id bigint, @Numero int, @ProximoNumero int
-- obtem as declarações inseridas quando a numeração é automática
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT ins.DUC_IDTY, ins.DUC_PNUM, pde.PDE_NPRO
		FROM inserted AS ins INNER JOIN TAB_PDES AS pde ON pde.PDE_NPRO > 0		
		WHERE ins.DUC_DUNO = 2 OR ins.DUC_SERV = 1
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @Id, @Numero, @ProximoNumero
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- se número da declaração diferente do próximo numero a atribuir, atualiza numero da declaração
		IF @Numero <> @ProximoNumero
		BEGIN
			UPDATE PRO_DUCG SET DUC_PNUM = @ProximoNumero
			WHERE DUC_IDTY = @Id
		END
-- atualiza próximo numero nas configurações
		UPDATE TAB_PDES SET PDE_NPRO = PDE_NPRO + 1			
		FETCH NEXT FROM Declaracoes INTO @Id, @Numero, @ProximoNumero
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAI_PRO_DUCG_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUCG]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUCG] ON [PRO_DUCG] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @InterfaceDUContas bit, @CodTipoDocFT varchar(4), @CodTipoDocOR varchar(4)
-- verifica alteração dos campos de cliente "Destinatário" ou "Natureza" e nos Parâmetros de Despacho o campo "Interface DU/Contas (Aut. Saída) ou DU/Docs. Venda" selecionado e o valor do campo "Campos Adicionais" é "FEDEX/TNT" ou "TNT"
	IF (UPDATE(DUC_DST8) OR UPDATE(DUC_TPDS) OR UPDATE(NDE_CODI) OR UPDATE(DUC_VLRC)) AND (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE ISNULL(PDE_TDOC, '') <> '' AND PDE_IDCV = 1 AND PDE_CADI IN (1, 4)))
	BEGIN
-- obtem tipo de documento configurado como "FT"
		SELECT TOP 1 @CodTipoDocFT = PDE_TDOC
		FROM TAB_PDES WITH(NOLOCK)
-- obtem tipo de documento configurado como "OR"
		SELECT TOP 1 @CodTipoDocOR = TDO_DOCU 
		FROM TAB_TDOC WITH(NOLOCK) 
		WHERE TDO_TDOC = 0 AND TDO_TCNT = 0 AND TDO_DCON = 1 AND TDO_EXSF = 1 AND TDO_TDSF = 'OR'
-- atualiza o tipo de documento na declaração em função da natureza e restantes condições
		UPDATE PRO_DUCG SET TDO_DOCU = (CASE ISNULL(nat.NDE_TLCV, -1)
			WHEN 0 THEN (CASE 
							WHEN ins.NDE_CODI IN ('11', '12', '29', '30', 'ZDU') THEN @CodTipoDocOR
							WHEN ins.NDE_CODI IN ('45', '55', '60', '62', '65') AND (cli.CLI_CPAG > 0) THEN @CodTipoDocOR
							WHEN ins.NDE_CODI NOT IN ('11', '12', '29', '30', '32', '45', '55', '60', '62', 'ZDU') AND (nat.NDE_FEDI = 1) AND (cli.CLI_CPAG > 0) THEN @CodTipoDocOR
							WHEN ins.NDE_CODI NOT IN ('11', '12', '29', '30', '32', '45', '55', '60', '62', 'ZDU') AND (nat.NDE_FEDI = 1) AND (cli.CLI_CPAG = 0) AND ((ins.DUC_TPDS > 0 AND ISNULL(ins.DUC_VLRC, 0) <= 50) OR (ins.DUC_TPDS = 0 AND (ISNULL(ins.DUC_VLRC, 0) - (CASE ins.DUC_BIVA WHEN 1 THEN (SELECT SUM(ISNULL(DUA_VIVA, 0)) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_PNUM = ins.DUC_PNUM and DUC_EANO = ins.DUC_EANO) ELSE 0 END)) <= 1500)) THEN @CodTipoDocOR
							ELSE @CodTipoDocFT
						END)		
			ELSE NULL
			END)
		FROM PRO_DUCG AS duc WITH(NOLOCK) INNER JOIN inserted AS ins ON duc.DUC_IDTY = ins.DUC_IDTY
			INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.NDE_CODI = nat.NDE_CODI
			INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.DUC_DST8 = cli.CLI_CODI						
	END
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAIU_PRO_DUCG]
/****** Object:  Trigger [TAIU_PRO_DUCG_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUCG_IMPCAU] ON [PRO_DUCG] FOR INSERT, UPDATE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdRegisto bigint, @IdPais int
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @IdDeclaracao bigint, @CodNatureza varchar(3), @CodCliente varchar(18), @NumDocTransporte varchar(18), 
		@Utilizador varchar(30), @IdUtilizador int, @VerbaTransitario decimal(18, 2), @ValorLiqRecapitulativa numeric(18, 2), @CodTipoDocConta varchar(4), @NumMascaras int, 
		@TipoMascara int, @CodMascara int, @Observacoes varchar(5000), @ValorHonorarios decimal(18, 2), @ValorDireitosDDP decimal(18, 2), @NIFImportador varchar(18), 
		@CodPaisImportador varchar(2)
	DECLARE @CodStatusIncidencia varchar(8), @NumIncidencia int, @NomeStatusIncidencia varchar(60), @ReleaseHold int
	DECLARE @CodPedidoEletronico varchar(5), @TextoPedidoEletronico varchar(3000), @NumPedido int
	DECLARE @IdDocumento int, @NumeroDocumento varchar(70), @DataValidadeDocumento datetime, @TipoDocumento tinyint		
	DECLARE @Funcao	varchar(3)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- se coluna da natureza alterada, processa a gestão da incidência no detalhe de incidências das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(NDE_CODI)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, nde.SIN_CODI
			FROM inserted AS ins 				
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON ins.NDE_CODI = nde.NDE_CODI				
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ISNULL(nde.SIN_CODI, '') <> ''
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @NomeStatusIncidencia = NULL
-- obtem o nome do status de incidência ou cosmo code
			SELECT @NomeStatusIncidencia = SIN_DESP, @ReleaseHold = NULL
			FROM TAB_SINC WITH(NOLOCK)
			WHERE SIN_CODI = @CodStatusIncidencia
			IF ISNULL(@NomeStatusIncidencia, '') = ''
			BEGIN
				SELECT @NomeStatusIncidencia = COS_POST, @ReleaseHold = (CASE WHEN (COS_RELI = 1) THEN 0 WHEN (COS_HOLD = 1) THEN 1 ELSE NULL END)
				FROM TAB_COSM WITH(NOLOCK)
				WHERE COS_CODE = @CodStatusIncidencia
			END
-- obtem o próximo numero de registo de incidência
			SELECT @NumIncidencia = ISNULL(MAX(DUI_CODI), 0) + 1
			FROM PRO_DUIN
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
-- insere a incidência no detalhe de incidências da declaração IMP-CAU 
			INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM, DUI_REHO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumIncidencia, @CodStatusIncidencia, @NomeStatusIncidencia, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), 
				CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime), CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime), 
				@ReleaseHold)
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END		
-- se coluna do importador alterada, processa a gestão do cosmo code no detalhe de incidências das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_DST8)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, (CASE RIGHT(ins.ALF_CODI, 3) WHEN '015' THEN cli.COS_CDLS WHEN '020' THEN cli.COS_CDPO ELSE NULL END)
			FROM inserted AS ins 				
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.DUC_DST8 = cli.CLI_CODI					
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ISNULL((CASE RIGHT(ins.ALF_CODI, 3) WHEN '015' THEN cli.COS_CDLS WHEN '020' THEN cli.COS_CDPO ELSE NULL END), '') <> ''
				AND NOT EXISTS(SELECT DUI_CODI FROM PRO_DUIN WITH(NOLOCK) WHERE DUC_EANO = ins.DUC_EANO AND DUC_PNUM = ins.DUC_PNUM AND SIN_CODI = (CASE RIGHT(ins.ALF_CODI, 3) WHEN '015' THEN cli.COS_CDLS WHEN '020' THEN cli.COS_CDPO ELSE NULL END))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @NomeStatusIncidencia = NULL
-- obtem o nome do cosmo code
			SELECT @NomeStatusIncidencia = COS_POST, @ReleaseHold = (CASE WHEN (COS_RELI = 1) THEN 0 WHEN (COS_HOLD = 1) THEN 1 ELSE NULL END)
			FROM TAB_COSM WITH(NOLOCK)
			WHERE COS_CODE = @CodStatusIncidencia			
-- obtem o próximo numero de registo de incidência
			SELECT @NumIncidencia = ISNULL(MAX(DUI_CODI), 0) + 1
			FROM PRO_DUIN
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
-- insere a incidência no detalhe de incidências da declaração IMP-CAU 
			INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM, DUI_REHO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumIncidencia, @CodStatusIncidencia, @NomeStatusIncidencia, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), 
				CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime), CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime), 
				@ReleaseHold)
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END		
-- se coluna do importador alterada, processa a gestão do documento OEA no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_DST8)
	BEGIN
-- insere/edita o documento OEA como "Referência Adicional" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, NULLIF(cli.CLI_NAOE, ''), ddo.id
			FROM inserted AS ins 	
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.DUC_DST8 = cli.CLI_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cli.DOC_CDOE = doc.DOC_CODI	
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 2					
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND cli.CLI_FXOE IN (0, 1) AND ISNULL(cli.CLI_NAOE, '') <> '' AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 2, @IdDocumento, @NumeroDocumento, 2, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesDocumentos SET
					id_documento = @IdDocumento, 
					numero = @NumeroDocumento, 					
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento OEA existente no detalhe de documentos da declaração mas já não existente na configuração do cliente
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 2					
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.DUC_DST8 = cli.CLI_CODI	
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cli.DOC_CDOE = doc.DOC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (cli.CLI_FXOE NOT IN (0, 1) OR ISNULL(cli.CLI_NAOE, '') = '' OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se coluna do importador alterada, processa a gestão de documentos no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_DST8)
	BEGIN		
-- insere os documentos como "Suporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, ddo.id, 
				ISNULL(NULLIF(cdo.CLD_NDOC, ''), (CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END)), cdo.CLD_DDOC
			FROM inserted AS ins 
				INNER JOIN TAB_CLDO AS cdo WITH(NOLOCK) ON ins.DUC_DST8 = cdo.CLI_CODI				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cdo.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 3
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND cdo.CLD_UIMP = 1 AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @IdRegisto, @NumeroDocumento, @DataValidadeDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
		    IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, dataValidade, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 0, @IdDocumento, @NumeroDocumento, @DataValidadeDocumento, 3, @IdUtilizador, @DataAtual)				
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesDocumentos SET					
					numero = @NumeroDocumento, 
					dataValidade = @DataValidadeDocumento, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @IdRegisto, @NumeroDocumento, @DataValidadeDocumento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- remove os documentos existentes no detalhe de documentos da declaração mas já não existentes na configuração do cliente
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 3				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_CLDO AS cdo WITH(NOLOCK) ON ins.DUC_DST8 = cdo.CLI_CODI AND doc.DOC_CODI = cdo.DOC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (cdo.CLD_UIMP = 0 OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR cdo.DOC_CODI IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se colunas do declarante ou tipo declarante alteradas, processa a gestão do documento OEA no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DEC_CO14) OR UPDATE(DUC_TPDC)
	BEGIN
-- insere/edita o documento OEA como "Suporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, NULLIF(dcl.DEC_NAOE, ''), ddo.id
			FROM inserted AS ins 	
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.DEC_CO14 = dcl.DEC_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON (CASE ins.DUC_TPDC WHEN 2 THEN dcl.DOC_CDOE ELSE dcl.DOC_CODI2 END) = doc.DOC_CODI	
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 4					
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND dcl.DEC_FXOE IN (0, 1) AND ISNULL(dcl.DEC_NAOE, '') <> '' AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 2, @IdDocumento, @NumeroDocumento, 4, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesDocumentos SET
					id_documento = @IdDocumento, 
					numero = @NumeroDocumento, 					
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento OEA existente no detalhe de documentos da declaração mas já não existente na configuração do declarante
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 4					
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.DEC_CO14 = dcl.DEC_CODI
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON (CASE ins.DUC_TPDC WHEN 2 THEN dcl.DOC_CDOE ELSE dcl.DOC_CODI2 END) = doc.DOC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (dcl.DEC_FXOE NOT IN (0, 1) OR ISNULL(dcl.DEC_NAOE, '') = '' OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se colunas do declarante ou tipo declaração adicional alteradas, processa a gestão do documento RSI no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DEC_CO14) OR UPDATE(TDE_2CAS)
	BEGIN
-- insere/edita o documento RSI como "Suporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, NULLIF(dcl.DEC_ARSI, ''), dcl.DEC_DRSI, ddo.id
			FROM inserted AS ins 	
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.DEC_CO14 = dcl.DEC_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dcl.DOC_CODI1 = doc.DOC_CODI	
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 5
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.TDE_2CAS IN ('C', 'Y', 'Z') AND ISNULL(dcl.DEC_ARSI, '') <> '' AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @DataValidadeDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, dataValidade, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 0, @IdDocumento, @NumeroDocumento, @DataValidadeDocumento, 5, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesDocumentos SET
					id_documento = @IdDocumento, 
					numero = @NumeroDocumento, 
					dataValidade = @DataValidadeDocumento, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @DataValidadeDocumento, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento RSI existente no detalhe de documentos da declaração mas já não existente na configuração do declarante
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 5					
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.DEC_CO14 = dcl.DEC_CODI
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dcl.DOC_CODI1 = doc.DOC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ins.TDE_2CAS NOT IN ('C', 'Y', 'Z') OR ISNULL(dcl.DEC_ARSI, '') = '' OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se colunas do estatuto, cédula ou importador alteradas, processa a gestão do pedido fixo "G1PRO" no detalhe de pedidos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_TPDC) OR UPDATE(DEC_CENI) OR UPDATE(DUC_DST8)
	BEGIN		
-- obtem o pedido "G1PRO" associado ao estatuto das declarações IMP-CAU inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ped.TXM_CODI, NULLIF(cli.CLI_NDHA, ''), dpd.DPD_IDEN
			FROM inserted AS ins 				
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.DUC_DST8 = cli.CLI_CODI
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'G1PRO'		
				LEFT OUTER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND ped.TXM_CODI = dpd.TXM_CODI AND dpd.DPD_ORIG = 2		
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (CASE WHEN ins.DUC_TPDC IS NULL THEN LEFT(RIGHT(ins.DEC_CENI, 2), 1) ELSE 'I' END) = 'I'			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere/atualiza o pedido "G1PRO" no detalhe de pedidos da declaração IMP-CAU
			IF @IdRegisto IS NULL
			BEGIN
				SELECT @NumPedido = ISNULL(MAX(DPD_CODI), 0) + 1 FROM PRO_DUPD WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
				INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC, DPD_ORIG)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumPedido, @CodPedidoEletronico, @TextoPedidoEletronico, 2)
			END
			ELSE
			BEGIN
				UPDATE PRO_DUPD SET
					TXM_CODI = @CodPedidoEletronico, 
					DPD_DESC = @TextoPedidoEletronico
				WHERE DPD_IDEN = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- obtem o pedido "G1PRO" existente no detalhe de pedidos da declaração IMP-CAU cuja origem é do estatuto mas que já não satisfaz a condição
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, dpd.DPD_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND dpd.DPD_ORIG = 2
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpd.TXM_CODI = ped.TXM_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ((CASE WHEN ins.DUC_TPDC IS NULL THEN LEFT(RIGHT(ins.DEC_CENI, 2), 1) ELSE 'I' END) <> 'I' OR ped.TXM_CODI IS NULL)			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove pedido					
			DELETE FROM PRO_DUPD
			WHERE DPD_IDEN = @IdRegisto
-- atualiza numero de pedidos posteriores
			UPDATE PRO_DUPD SET DPD_CODI = DPD_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DPD_IDEN > @IdRegisto 			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes												
	END
-- se coluna de estância de sujeição alterada, processa a gestão de documentos no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(ALF_CODI)
	BEGIN		
-- insere os documentos como "Suporte"/"Transporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, doc.DOC_DTRA, uti.UTI_IDTY, 				 
				(CASE 
					WHEN (doc.DOC_CODI ='N740' AND LEFT(ins.MTR_PT18, 1) = '4') OR (doc.DOC_CODI ='N750' AND LEFT(ins.MTR_PT18, 1) = '5') 
						OR (doc.DOC_CODI ='N705' AND LEFT(ins.MTR_PT18, 1) IN ('1', '2')) OR (doc.DOC_CODI ='N704' AND LEFT(ins.MTR_PT18, 1) IN ('1', '2'))
						OR (doc.DOC_CODI ='N704' AND LEFT(ins.MTR_PT18, 1) = '3' AND LEFT(ins.MTR_FT21, 1) = '1') 
						OR (doc.DOC_CODI ='N821' AND LEFT(ins.MTR_PT18, 1) = '3' AND LEFT(ins.MTR_FT21, 1) = '3') THEN NULLIF(ins.DUC_CPRT, '')
					WHEN doc.DOC_CODI = '3E01' AND ISNULL(ins.DUC_VTRN, 0) > 0 THEN 'S/N'
					WHEN doc.DOC_TDNU = 1 THEN 'S/N' 
					WHEN doc.DOC_TDNU = 2 THEN 'N/A' 
					WHEN doc.DOC_TDNU = 3 THEN 'DEC' 
					ELSE NULL 
				END), 
				(CASE 
					WHEN (doc.DOC_CODI ='N740' AND LEFT(ins.MTR_PT18, 1) = '4') OR (doc.DOC_CODI ='N704' AND LEFT(ins.MTR_PT18, 1) IN ('1', '2'))
						OR (doc.DOC_CODI ='N704' AND LEFT(ins.MTR_PT18, 1) = '3' AND LEFT(ins.MTR_FT21, 1) = '1') 
						OR (doc.DOC_CODI ='N821' AND LEFT(ins.MTR_PT18, 1) = '3' AND LEFT(ins.MTR_FT21, 1) = '3') THEN ins.DUC_DDDT
					WHEN (doc.DOC_CODI ='N750' AND LEFT(ins.MTR_PT18, 1) = '5') OR (doc.DOC_CODI ='N705' AND LEFT(ins.MTR_PT18, 1) IN ('1', '2')) THEN ins.DUC_DATA 
					WHEN (doc.DOC_CODI = '3E01' AND ISNULL(ins.DUC_VTRN, 0) > 0) THEN CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime)					
					ELSE NULL 
				END),
				(CASE WHEN (doc.DOC_CODI = '3E01' AND ISNULL(ins.DUC_VTRN, 0) > 0) THEN ISNULL(ins.DUC_VTRN, 0) ELSE 0 END), 
				(CASE WHEN (doc.DOC_CODI = '3E01' AND ISNULL(ins.DUC_VTRN, 0) > 0) THEN pai.PAI_IDTY ELSE NULL END)
			FROM inserted AS ins 				
				INNER JOIN TAB_ALFD AS ado WITH(NOLOCK) ON ins.ALF_CODI = ado.ALF_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 6	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_PAPL AS pap WITH(NOLOCK) ON 1 = 1
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON pap.PAI_CODI = pai.PAI_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND doc.DOC_DESP = 1 AND LEN(doc.DOC_CODI) <= 4 AND ddo.id IS NULL 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador, @NumeroDocumento, @DataValidadeDocumento, @VerbaTransitario, @IdPais
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, dataValidade, id_paisMoeda, montante, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @TipoDocumento, @IdDocumento, @NumeroDocumento, @DataValidadeDocumento, @IdPais, @VerbaTransitario, 6, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador, @NumeroDocumento, @DataValidadeDocumento, @VerbaTransitario, @IdPais
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- remove os documentos existentes no detalhe de documentos da declaração mas já não existentes na configuração da alfândega
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 6			
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_ALFD AS ado WITH(NOLOCK) ON ins.ALF_CODI = ado.ALF_CODI AND doc.DOC_CODI = ado.DOC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (doc.DOC_DESP = 0 OR LEN(doc.DOC_CODI) > 4 OR ado.DOC_CODI IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
	END
-- se coluna tipo declaração adicional alterada, processa a gestão do pedido fixo "G1DSA" no detalhe de pedidos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(TDE_2CAS)
	BEGIN
-- obtem o pedido "G1DSA" associado ao estatuto das declarações IMP-CAU inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ped.TXM_CODI, SUBSTRING(ped.TXM_TEXT, 1, 512)
			FROM inserted AS ins 								
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'G1DSA'		
				LEFT OUTER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND ped.TXM_CODI = dpd.TXM_CODI AND dpd.DPD_ORIG = 3	
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ISNULL(ins.TDE_2CAS, '') = 'B' AND dpd.DPD_CODI IS NULL		
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere o pedido "G1DSA" no detalhe de pedidos da declaração IMP-CAU			
			SELECT @NumPedido = ISNULL(MAX(DPD_CODI), 0) + 1 FROM PRO_DUPD WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
			INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC, DPD_ORIG)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumPedido, @CodPedidoEletronico, @TextoPedidoEletronico, 3)	
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- obtem o pedido "G1DSA" existente no detalhe de pedidos da declaração IMP-CAU cuja origem é do tipo declaração adicional mas que já não satisfaz a condição
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, dpd.DPD_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND dpd.DPD_ORIG = 3
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpd.TXM_CODI = ped.TXM_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ISNULL(ins.TDE_2CAS, '') <> 'B' OR ped.TXM_CODI IS NULL)			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove pedido					
			DELETE FROM PRO_DUPD
			WHERE DPD_IDEN = @IdRegisto
-- atualiza numero de pedidos posteriores
			UPDATE PRO_DUPD SET DPD_CODI = DPD_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DPD_IDEN > @IdRegisto 			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- se coluna do tipo de declaração alterada, processa a gestão de pedidos no detalhe de pedidos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(TDE_CODI)
	BEGIN
-- insere os pedidos no detalhe de pedidos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, tdp.TXM_CODI, SUBSTRING(tdp.TDP_TEXT, 1, 512)
			FROM inserted AS ins 				
				INNER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON ins.TDE_CODI = tdp.TDE_CODI		
				LEFT OUTER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND tdp.TXM_CODI = dpd.TXM_CODI AND dpd.DPD_ORIG = 1		
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ASAI = 0 AND dpd.DPD_CODI IS NULL
			ORDER BY tdp.TDP_CODI
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem o próximo numero de registo de pedido
			SELECT @NumPedido = ISNULL(MAX(DPD_CODI), 0) + 1
			FROM PRO_DUPD
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
-- insere o pedido no detalhe de pedidos da declaração IMP-CAU 
			INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC, DPD_ORIG)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumPedido, @CodPedidoEletronico, @TextoPedidoEletronico, 1)
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove os pedidos existentes no detalhe de pedidos da declaração mas já não existentes na configuração do tipo de declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, dpd.DPD_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND dpd.DPD_ORIG = 1	
				LEFT OUTER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON ins.TDE_CODI = tdp.TDE_CODI AND dpd.TXM_CODI = tdp.TXM_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ASAI = 0 AND tdp.TXM_CODI IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove pedido					
			DELETE FROM PRO_DUPD
			WHERE DPD_IDEN = @IdRegisto
-- atualiza numero de pedidos posteriores
			UPDATE PRO_DUPD SET DPD_CODI = DPD_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DPD_IDEN > @IdRegisto 			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes					
	END		
-- se coluna do tipo de declaração alterada, processa a gestão de documentos no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(TDE_CODI)
	BEGIN
-- insere os documentos como "Suporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, 
				(CASE DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END)				
			FROM inserted AS ins 				
				INNER JOIN TAB_TDED AS tdd WITH(NOLOCK) ON ins.TDE_CODI = tdd.TDE_CODI				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON tdd.DOC_CODI = doc.DOC_CODI		
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 1
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ASAI = 0 AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND ddo.id IS NULL 
			ORDER BY tdd.TDD_CODI
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, 0, @IdDocumento, @NumeroDocumento, 1, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove os documentos existentes no detalhe de documentos da declaração mas já não existentes na configuração do tipo de declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 1				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_TDED AS tdd WITH(NOLOCK) ON ins.TDE_CODI = tdd.TDE_CODI AND doc.DOC_CODI = tdd.DOC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ASAI = 0 AND (doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR tdd.DOC_CODI IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END		
-- se colunas do anexo B ou exportador alteradas, processa a gestão do documento fixo "3E18" no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_ANXB) OR UPDATE(DUC_EXP2)
	BEGIN
-- insere o documento fixo "3E18" como "Suporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 	
				INNER JOIN TAB_FORN AS frn WITH(NOLOCK) ON ins.DUC_EXP2 = frn.FOR_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI	= '3E18'
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 8					
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB <> 'H2' AND frn.FOR_TNIF = 5 AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND ddo.id IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, 0, @IdDocumento, 8, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento fixo "3E18" existente no detalhe de documentos da declaração mas já não existente na configuração do anexo B
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 8					
				LEFT OUTER JOIN TAB_FORN AS frn WITH(NOLOCK) ON ins.DUC_EXP2 = frn.FOR_CODI
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ins.DUC_ANXB = 'H2' OR ISNULL(frn.FOR_TNIF, -1) <> 5 OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se colunas do anexo B ou tipo NIF importador alteradas, processa a gestão do documento fixo "3E19" no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_ANXB) OR UPDATE(DUC_TPDS)
	BEGIN
-- insere o documento fixo "3E19" como "Suporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 					
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI	= '3E19'
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 9
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB <> 'H2' AND ins.DUC_TPDS = 5 AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND ddo.id IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, 0, @IdDocumento, 9, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento fixo "3E19" existente no detalhe de documentos da declaração mas já não existente na configuração do anexo B
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 9									
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ins.DUC_ANXB = 'H2' OR ISNULL(ins.DUC_TPDS, -1) <> 5 OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se coluna do regime alterada, processa a gestão do documento fixo "Y044" no detalhe de documentos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_REGI)
	BEGIN
-- insere o documento fixo "Y044" como "Referência Adicional" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 					
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI	= 'Y044'
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 12
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND LEFT(ins.DUC_REGI, 2) IN ('42', '63') AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND ddo.id IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, 2, @IdDocumento, 12, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento fixo "Y044" existente no detalhe de documentos da declaração mas já não existente na configuração do regime
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 12 								
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (LEFT(ins.DUC_REGI, 2) NOT IN ('42', '63') OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se coluna do regime alterada, processa a gestão do documento fixo "N960"/"N337" no detalhe de precedentes das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_REGI)
	BEGIN
-- insere o documento fixo "N960"/"N337" no detalhe de precedentes da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 									
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE WHEN (ins.DUC_REGI = '4071') THEN 'N960' WHEN ((LEFT(ins.DUC_REGI, 2) = '40' AND ins.DUC_REGI <> '4071') OR (LEFT(ins.DUC_REGI, 2) = '61')) THEN 'N337' ELSE NULL END) OR doc.DOC_CODI = (CASE WHEN LEFT(ins.DUC_REGI, 2) = '61' THEN 'N960' ELSE NULL END)
				LEFT OUTER JOIN tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) ON ins.DUC_IDTY = dpr.id_declaracaoIMP AND doc.DOC_IDTY = dpr.id_documento AND origem = 1				
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND LEFT(ins.DUC_REGI, 2) IN ('40', '61') AND doc.DOC_CA40 = 1 AND dpr.id IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO tb_IMP_DeclaracoesPrecedentes(id_declaracaoIMP, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdDocumento, '*****N/A*****', 1, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento fixo "N960"/"N337" existente no detalhe de precedentes da declaração mas já não existente na configuração do regime
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpr.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) ON ins.DUC_IDTY = dpr.id_declaracaoIMP AND origem = 1								
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY AND doc.DOC_CODI = (CASE WHEN (ins.DUC_REGI = '4071') THEN 'N960' WHEN ((LEFT(ins.DUC_REGI, 2) = '40' AND ins.DUC_REGI <> '4071') OR (LEFT(ins.DUC_REGI, 2) = '61')) THEN 'N337' ELSE NULL END) OR doc.DOC_CODI = (CASE WHEN LEFT(ins.DUC_REGI, 2) = '61' THEN 'N960' ELSE NULL END)
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (LEFT(ins.DUC_REGI, 2) NOT IN ('40', '61') OR doc.DOC_CA40 = 0 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesPrecedentes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesPrecedentes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se coluna do regime alterada, processa a gestão do pedido fixo "I1PGI" no detalhe de pedidos das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_REGI)
	BEGIN
-- obtem o pedido "I1PGI" associado ao regime "42" das declarações IMP-CAU inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ped.TXM_CODI, SUBSTRING(ped.TXM_TEXT, 1, 512)
			FROM inserted AS ins 								
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'I1PGI'		
				LEFT OUTER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND ped.TXM_CODI = dpd.TXM_CODI AND dpd.DPD_ORIG = 4
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND LEFT(ins.DUC_REGI, 2) = '42' AND dpd.DPD_CODI IS NULL		
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere o pedido "I1PGI" no detalhe de pedidos da declaração IMP-CAU			
			SELECT @NumPedido = ISNULL(MAX(DPD_CODI), 0) + 1 FROM PRO_DUPD WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
			INSERT INTO PRO_DUPD(DUC_EANO, DUC_PNUM, DPD_CODI, TXM_CODI, DPD_DESC, DPD_ORIG)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumPedido, @CodPedidoEletronico, @TextoPedidoEletronico, 4)	
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodPedidoEletronico, @TextoPedidoEletronico
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- obtem o pedido "I1PGI" existente no detalhe de pedidos da declaração IMP-CAU cuja origem é do regime "42" mas que já não satisfaz a condição
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, dpd.DPD_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN PRO_DUPD AS dpd WITH(NOLOCK) ON ins.DUC_EANO = dpd.DUC_EANO AND ins.DUC_PNUM = dpd.DUC_PNUM AND dpd.DPD_ORIG = 4
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpd.TXM_CODI = ped.TXM_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (LEFT(ins.DUC_REGI, 2) <> '42' OR ped.TXM_CODI IS NULL)			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove pedido					
			DELETE FROM PRO_DUPD
			WHERE DPD_IDEN = @IdRegisto
-- atualiza numero de pedidos posteriores
			UPDATE PRO_DUPD SET DPD_CODI = DPD_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DPD_IDEN > @IdRegisto 			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- se coluna do regime alterada, processa a gestão das referências fiscais associadas no detalhe de referências fiscais das declarações IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_REGI) OR UPDATE(DUC_DNIF) OR UPDATE(PAI_DLIV) OR UPDATE(DUC_TPDS)
	BEGIN
-- insere a referência fiscal "FR1"/"FR2" no detalhe de referências fiscais da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, ins.DUC_DNIF, ins.PAI_DLIV, uti.UTI_IDTY, t.funcao, drf.id
			FROM inserted AS ins 			
				INNER JOIN (SELECT 'FR1' AS funcao UNION SELECT 'FR2' AS funcao) AS t ON 1 = 1										
				LEFT OUTER JOIN tb_IMP_DeclaracoesReferenciasFiscais AS drf WITH(NOLOCK) ON ins.DUC_IDTY = drf.id_declaracaoIMP AND drf.funcao = t.funcao AND origem = 2				
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ((ISNULL(ins.DUC_REGI, '') = '4200' AND t.funcao IN ('FR1', 'FR2')) 
				OR (ISNULL(ins.DUC_TPDS, -1) IN (3, 4, 6) AND t.funcao = 'FR1')) --NP, BI, NE
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NIFImportador, @CodPaisImportador, @IdUtilizador, @Funcao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesReferenciasFiscais(id_declaracaoIMP, funcao, nif, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, @Funcao, LEFT((@CodPaisImportador + @NIFImportador), 17), 2, @IdUtilizador, @DataAtual)			
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesReferenciasFiscais SET
					nif = LEFT((@CodPaisImportador + @NIFImportador), 17), 					
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NIFImportador, @CodPaisImportador, @IdUtilizador, @Funcao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove a referência fiscal "FR1"/"FR2" existente no detalhe de referências fiscais da declaração mas já não existente na configuração do regime
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT drf.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesReferenciasFiscais AS drf WITH(NOLOCK) ON ins.DUC_IDTY = drf.id_declaracaoIMP AND origem = 2												
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL			
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ISNULL(ins.DUC_REGI, '') <> '4200' OR drf.funcao NOT IN ('FR1', 'FR2')) 
				AND (ISNULL(ins.DUC_TPDS, -1) NOT IN (3, 4, 6) OR drf.funcao <> 'FR1') --NP, BI, NE
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesReferenciasFiscais SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesReferenciasFiscais		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
	END
-- se colunas várias alteradas, processa a gestão do documento de contas das declarações IMP-CAU inseridas/alteradas
	IF (UPDATE(DUC_EANO) OR UPDATE(DUC_PNUM) OR UPDATE(DUC_DATA) OR UPDATE(DUC_CPRT) OR UPDATE(DUC_NORD) OR UPDATE(DUC_NDAT) OR UPDATE(NDE_CODI) OR UPDATE(DUC_EXP2) OR UPDATE(DUC_ENOM) 
		OR UPDATE(DUC_DST8) OR UPDATE(DUC_TPDS) OR UPDATE(MTR_PT18) OR UPDATE(DUC_MT18) OR UPDATE(DUC_COBR) OR UPDATE(DUC_VATT) OR UPDATE(DEC_CO14) OR UPDATE(ALF_CODI) OR UPDATE(DUC_TVL6) 
		OR UPDATE(DUC_ADI5) OR UPDATE(DUC_MBRT) OR UPDATE(DUC_MLQT) OR UPDATE(TDO_DOCU) OR UPDATE(DUC_TX23) OR UPDATE(DUC_VEUR) OR UPDATE(DUC_VDES) OR UPDATE(DUC_VDIR) OR UPDATE(DUC_VLRC) 
		OR UPDATE(DUC_REGL) OR UPDATE(DUC_DTRL) OR UPDATE(DUC_TSHI) OR UPDATE(TDO_DOCU1) OR UPDATE(NDE_CODI1) OR UPDATE(DUC_BIVA) OR UPDATE(DUC_PDVU) OR UPDATE(DUC_MASC) OR UPDATE(DUC_TMSF)
		OR UPDATE(DUC_DGEN)) 
		AND (NOT EXISTS(SELECT FTA_IDEN FROM TAB_PFTA WITH(NOLOCK) WHERE FTA_ACTI = 1))
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_PNUM, ins.DUC_EANO, ins.NDE_CODI, ISNULL(cli.CLI_CCOR, ins.DUC_DST8), ins.DUC_CPRT, ISNULL(ins.DUC_UALT, ins.DUC_UCRI), ISNULL(ins.DUC_VLRC, 0), ins.DUC_MASC, 
				ins.DUC_TMSF, 
				(CASE WHEN (pde.PDE_IDCV = 1) AND (ISNULL(nat.NDE_TLCV, -1) = 0) THEN ins.TDO_DOCU ELSE pde.PDE_TDOC END), 
				(CASE WHEN ISNULL(CAST(nat.NDE_FORM AS varchar(MAX)), '') <> '' THEN dbo.fn_Geral_ObtemHonorariosImportacao(ISNULL(ins.DUC_VATT, 0)) ELSE 0 END)
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.NDE_CODI = nat.NDE_CODI
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.DUC_DST8 = cli.CLI_CODI				
				INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''
			WHERE (ins.DUC_DUNO = 2 OR ins.DUC_SERV = 1) AND ins.DUC_TSHI < 2 AND nat.NDE_CRCO = 1 AND ISNULL(nat.NDE_TLCV, -1) <> 1 AND cli.CLI_DUCT = 1 AND pde.PDE_LFCT = 0 
				AND del.DUC_IDTY IS NULL 				 										
			UNION
			SELECT ins.DUC_PNUM, ins.DUC_EANO, ins.NDE_CODI, ISNULL(cli.CLI_CCOR, ins.DUC_DST8), ins.DUC_CPRT, ISNULL(ins.DUC_UALT, ins.DUC_UCRI), ISNULL(ins.DUC_VLRC, 0), ins.DUC_MASC, 
				ins.DUC_TMSF, 
				(CASE WHEN (pde.PDE_IDCV = 1) AND (ISNULL(nat.NDE_TLCV, -1) = 0) THEN ins.TDO_DOCU ELSE pde.PDE_TDOC END), 
				(CASE WHEN ISNULL(CAST(nat.NDE_FORM AS varchar(MAX)), '') <> '' THEN dbo.fn_Geral_ObtemHonorariosImportacao(ISNULL(ins.DUC_VATT, 0)) ELSE 0 END)
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.NDE_CODI = nat.NDE_CODI
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.DUC_DST8 = cli.CLI_CODI
				INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''				
				INNER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON ins.DUC_EANO = cnt.CDO_PANO AND ins.DUC_PNUM = cnt.CDO_NPRO AND cnt.CDO_IMEX = 0
			WHERE (ins.DUC_DUNO = 2 OR ins.DUC_SERV = 1) AND ins.DUC_TSHI < 2 AND cnt.CDO_STAT = 0 
				AND ((pde.PDE_BCNR = 0) OR (pde.PDE_BCNR = 2 AND ins.DUC_ASAI = 0)) 
				AND ((pde.PDE_LFCT = 0 AND nat.NDE_CRCO = 1 AND ISNULL(nat.NDE_TLCV, -1) <> 1 AND cli.CLI_DUCT = 1) OR (pde.PDE_LFCT = 1 AND pde.PDE_IDCV = 0))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @NumDeclaracao, @AnoDeclaracao, @CodNatureza, @CodCliente, @NumDocTransporte, @Utilizador, @ValorLiqRecapitulativa, @CodMascara, @TipoMascara, 
			@CodTipoDocConta, @ValorHonorarios
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- obtem as observações para a Conta
			EXEC SP_ObtemObservacoesParaConta @CodMascara, @AnoDeclaracao, @NumDeclaracao, @CodCliente, @CodNatureza, '', @Observacoes OUTPUT			
-- processa a geração do documento de Conta
			EXEC SP_geraContas @NumDeclaracao, @AnoDeclaracao, @CodTipoDocConta, @CodNatureza, @Utilizador, @TipoMascara, @CodMascara, @ValorHonorarios, @Observacoes, @ValorLiqRecapitulativa, @NumDocTransporte, 0, NULL, 0			
			FETCH NEXT FROM Declaracoes INTO @NumDeclaracao, @AnoDeclaracao, @CodNatureza, @CodCliente, @NumDocTransporte, @Utilizador, @ValorLiqRecapitulativa, @CodMascara, @TipoMascara, 
				@CodTipoDocConta, @ValorHonorarios
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAIU_PRO_DUCG_IMPCAU]
/****** Object:  Trigger [TAIUD_PRO_DUCG]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DUCG] ON [PRO_DUCG] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- verifica alteração de vários campos p/ registar no Histórico de Alterações da Declaração
	if UPDATE(DUC_DATA) or UPDATE(NDE_CODI) or UPDATE(DUC_CPRT) or UPDATE(DUC_NORD) or UPDATE(DUC_NDAT) or UPDATE(DUC_CNTN) or UPDATE(DUC_PENV) or UPDATE(DUC_NPRO) 
	or UPDATE(TDE_CODI) or UPDATE(ALF_CODI) or UPDATE(DUC_ADI5) or UPDATE(DUC_TVL6) or UPDATE(DUC_REF7) or UPDATE(PAI_P15A) or UPDATE(PAI_PA16) or UPDATE(PAI_PA17) 
	or UPDATE(PAI_P17B) or UPDATE(MTR_PT18) or UPDATE(DUC_MT18) or UPDATE(PAI_PA18) or UPDATE(MTR_FT21) or UPDATE(DUC_MT21) or UPDATE(PAI_PA21) or UPDATE(DUC_CT19) 
	or UPDATE(CEN_CO20) or UPDATE(DUC_DE20) or UPDATE(NTR_CO24) or UPDATE(LME_CO30) or UPDATE(DUC_LC30) or UPDATE(DUC_MT22) or UPDATE(DUC_TX23) or UPDATE(DUC_FRET) 
	or UPDATE(DUC_SEGU) or UPDATE(DUC_MLQT) or UPDATE(DUC_MBRT) or UPDATE(DUC_VTRN) or UPDATE(DUC_VEUR) or UPDATE(DUC_DIRT) or UPDATE(DUC_ENOM) or UPDATE(DUC_DNIF) 
	or UPDATE(DUC_VLRC) or UPDATE(DUC_VATT) or UPDATE(PAI_MO22) or UPDATE(DEC_CENI) or UPDATE(DUC_NFOR) or UPDATE(DUC_TREM) or UPDATE(DUC_ARTI) or UPDATE(DUC_TPDS) 
	or UPDATE(DUC_TPDC) or UPDATE(DUC_DTYP) or UPDATE(DUC_VFRC) or UPDATE(DUC_ANXB)
	begin
		insert into LOG_DUCG (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, DUC_NORD, DUC_NDAT, DUC_CNTN, 
			DUC_PENV, DUC_NPRO, TDE_CODI, ALF_CODI, DUC_ADI5, DUC_TVL6, DUC_REF7, PAI_P15A, PAI_PA16, PAI_PA17, PAI_P17B, MTR_PT18, DUC_MT18, PAI_PA18, MTR_FT21, DUC_MT21, 
			PAI_PA21, DUC_CT19, CEN_CO20, DUC_DE20, NTR_CO24, LME_CO30, DUC_LC30, DUC_MT22, DUC_TX23, DUC_FRET, DUC_SEGU, DUC_MLQT, DUC_MBRT, DUC_VTRN, DUC_VEUR, DUC_DIRT, 
			DUC_ENOM, DUC_DNIF, DUC_VLRC, DUC_VATT, PAI_MO22, DEC_CENI, DUC_NFOR, DUC_TREM, DUC_ARTI, DUC_TPDS, DUC_TPDC, DUC_DTYP, DUC_VFRC, DUC_ANXB)
		select NEWID(), (case (select count(*) from deleted where DUC_EANO = inserted.DUC_EANO and DUC_PNUM = inserted.DUC_PNUM) when 0 then 0 else 1 end), 
			GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), 
			DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, DUC_NORD, DUC_NDAT, DUC_CNTN, DUC_PENV, DUC_NPRO, TDE_CODI, ALF_CODI, DUC_ADI5, DUC_TVL6, DUC_REF7, PAI_P15A, 
			PAI_PA16, PAI_PA17, PAI_P17B, MTR_PT18, DUC_MT18, PAI_PA18, MTR_FT21, DUC_MT21, PAI_PA21, DUC_CT19, CEN_CO20, DUC_DE20, NTR_CO24, LME_CO30, DUC_LC30, DUC_MT22, 
			DUC_TX23, DUC_FRET, DUC_SEGU, DUC_MLQT, DUC_MBRT, DUC_VTRN, DUC_VEUR, DUC_DIRT, DUC_ENOM, DUC_DNIF, DUC_VLRC, DUC_VATT, PAI_MO22, DEC_CENI, DUC_NFOR, DUC_TREM, 
			DUC_ARTI, DUC_TPDS, DUC_TPDC, DUC_DTYP, DUC_VFRC, DUC_ANXB
		from inserted
		where ((select count(*) from deleted where DUC_EANO = inserted.DUC_EANO and DUC_PNUM = inserted.DUC_PNUM) = 0) 
			or ((select count(*) from deleted where DUC_EANO = inserted.DUC_EANO and DUC_PNUM = inserted.DUC_PNUM and ((DUC_DATA <> inserted.DUC_DATA) or 
			(NDE_CODI <> inserted.NDE_CODI) or (isnull(DUC_CPRT, '') <> isnull(inserted.DUC_CPRT, '')) or (isnull(DUC_NORD, '') <> isnull(inserted.DUC_NORD, '')) or 
			(isnull(DUC_NDAT, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.DUC_NDAT, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (isnull(DUC_CNTN, '') <> isnull(inserted.DUC_CNTN, '')) or 
			(isnull(DUC_PENV, '') <> isnull(inserted.DUC_PENV, '')) or (isnull(DUC_NPRO, '') <> isnull(inserted.DUC_NPRO, '')) or (TDE_CODI <> inserted.TDE_CODI) or 
			(ALF_CODI <> inserted.ALF_CODI) or (DUC_ADI5 <> inserted.DUC_ADI5) or (isnull(DUC_TVL6, -1) <> isnull(inserted.DUC_TVL6, -1)) or 
			(isnull(DUC_REF7, '') <> isnull(inserted.DUC_REF7, '')) or (isnull(PAI_P15A, '') <> isnull(inserted.PAI_P15A, '')) or (isnull(PAI_PA16, '') <> isnull(inserted.PAI_PA16, '')) or 
			(isnull(PAI_PA17, '') <> isnull(inserted.PAI_PA17, '')) or (isnull(PAI_P17B, -1) <> isnull(inserted.PAI_P17B, -1)) or 
			(isnull(MTR_PT18, '') <> isnull(inserted.MTR_PT18, '')) or (isnull(DUC_MT18, '') <> isnull(inserted.DUC_MT18, '')) or 
			(isnull(PAI_PA18, '') <> isnull(inserted.PAI_PA18, '')) or (isnull(MTR_FT21, '') <> isnull(inserted.MTR_FT21, '')) or 
			(isnull(DUC_MT21, '') <> isnull(inserted.DUC_MT21, '')) or (isnull(PAI_PA21, '') <> isnull(inserted.PAI_PA21, '')) or 
			(DUC_CT19 <> inserted.DUC_CT19) or (isnull(CEN_CO20, '') <> isnull(inserted.CEN_CO20, '')) or (isnull(DUC_DE20, '') <> isnull(inserted.DUC_DE20, '')) or 
			(isnull(NTR_CO24, '') <> isnull(inserted.NTR_CO24, '')) or (isnull(LME_CO30, '') <> isnull(inserted.LME_CO30, '')) or 
			(isnull(DUC_LC30, '') <> isnull(inserted.DUC_LC30, '')) or (isnull(DUC_MT22, -1) <> isnull(inserted.DUC_MT22, -1)) or 
			(isnull(DUC_TX23, -1) <> isnull(inserted.DUC_TX23, -1)) or (isnull(DUC_FRET, -1) <> isnull(inserted.DUC_FRET, -1)) or 
			(isnull(DUC_SEGU, -1) <> isnull(inserted.DUC_SEGU, -1)) or (isnull(DUC_MLQT, -1) <> isnull(inserted.DUC_MLQT, -1)) or 
			(isnull(DUC_MBRT, -1) <> isnull(inserted.DUC_MBRT, -1)) or (isnull(DUC_VTRN, -1) <> isnull(inserted.DUC_VTRN, -1)) or 
			(isnull(DUC_VEUR, -1) <> isnull(inserted.DUC_VEUR, -1)) or (isnull(DUC_DIRT, -1) <> isnull(inserted.DUC_DIRT, -1)) or 
			(isnull(DUC_ENOM, '') <> isnull(inserted.DUC_ENOM, '')) or (isnull(DUC_DNIF, '') <> isnull(inserted.DUC_DNIF, '')) or 
			(isnull(DUC_VLRC, -1) <> isnull(inserted.DUC_VLRC, -1)) or (isnull(DUC_VATT, -1) <> isnull(inserted.DUC_VATT, -1)) or 
			(isnull(PAI_MO22, '') <> isnull(inserted.PAI_MO22, '')) or (isnull(DEC_CENI, '') <> isnull(inserted.DEC_CENI, '')) or 
			(isnull(DUC_NFOR, -1) <> isnull(inserted.DUC_NFOR, -1)) or (isnull(DUC_TREM, -1) <> isnull(inserted.DUC_TREM, -1)) or 
			(isnull(DUC_ARTI, -1) <> isnull(inserted.DUC_ARTI, -1)) or (isnull(DUC_TPDS, -1) <> isnull(inserted.DUC_TPDS, -1)) or 
			(isnull(DUC_TPDC, -1) <> isnull(inserted.DUC_TPDC, -1)) or (isnull(DUC_DTYP, '') <> isnull(inserted.DUC_DTYP, '')) or 
			(DUC_VFRC <> inserted.DUC_VFRC) or (DUC_ANXB <> inserted.DUC_ANXB))) > 0)
	end
	else
	begin
		insert into LOG_DUCG (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, DUC_NORD, DUC_NDAT, DUC_CNTN, 
			DUC_PENV, DUC_NPRO, TDE_CODI, ALF_CODI, DUC_ADI5, DUC_TVL6, DUC_REF7, PAI_P15A, PAI_PA16, PAI_PA17, PAI_P17B, MTR_PT18, DUC_MT18, PAI_PA18, MTR_FT21, DUC_MT21, 
			PAI_PA21, DUC_CT19, CEN_CO20, DUC_DE20, NTR_CO24, LME_CO30, DUC_LC30, DUC_MT22, DUC_TX23, DUC_FRET, DUC_SEGU, DUC_MLQT, DUC_MBRT, DUC_VTRN, DUC_VEUR, DUC_DIRT, 
			DUC_ENOM, DUC_DNIF, DUC_VLRC, DUC_VATT, PAI_MO22, DEC_CENI, DUC_NFOR, DUC_TREM, DUC_ARTI, DUC_TPDS, DUC_TPDC, DUC_DTYP, DUC_VFRC, DUC_ANXB)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_PNUM, DUC_EANO, DUC_DATA, NDE_CODI, DUC_CPRT, DUC_NORD, DUC_NDAT, DUC_CNTN, DUC_PENV, DUC_NPRO, TDE_CODI, ALF_CODI, 
			DUC_ADI5, DUC_TVL6, DUC_REF7, PAI_P15A, PAI_PA16, PAI_PA17, PAI_P17B, MTR_PT18, DUC_MT18, PAI_PA18, MTR_FT21, DUC_MT21, PAI_PA21, DUC_CT19, CEN_CO20, 
			DUC_DE20, NTR_CO24, LME_CO30, DUC_LC30, DUC_MT22, DUC_TX23, DUC_FRET, DUC_SEGU, DUC_MLQT, DUC_MBRT, DUC_VTRN, DUC_VEUR, DUC_DIRT, DUC_ENOM, DUC_DNIF, 
			DUC_VLRC, DUC_VATT, PAI_MO22, DEC_CENI, DUC_NFOR, DUC_TREM, DUC_ARTI, DUC_TPDS, DUC_TPDC, DUC_DTYP, DUC_VFRC, DUC_ANXB
		from deleted
		where (select count(*) from inserted where DUC_EANO = deleted.DUC_EANO and DUC_PNUM = deleted.DUC_PNUM) = 0
	end
-- verifica alteração do campo "Estado Follow-UP" p/ registar no Histórico de Alterações de Follow-Up da Declaração
	if UPDATE(FUP_CODI)
	begin
		insert into PRO_DUFW(DUC_EANO, DUC_PNUM, DFW_CODI, DFW_DATA, FUP_CODI, UTI_UTIL)
		select DUC_EANO, DUC_PNUM, ((select COUNT(*) from PRO_DUFW where DUC_EANO = inserted.DUC_EANO and DUC_PNUM = inserted.DUC_PNUM) + 1), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), FUP_CODI, 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME())
		from inserted
		where FUP_CODI IS NOT NULL and (((select count(*) from deleted where DUC_EANO = inserted.DUC_EANO and DUC_PNUM = inserted.DUC_PNUM) = 0) 
			or ((select count(*) from deleted where DUC_EANO = inserted.DUC_EANO and DUC_PNUM = inserted.DUC_PNUM and 
			isnull(FUP_CODI, -1) <> isnull(inserted.FUP_CODI, -1)) > 0))
	end
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAIUD_PRO_DUCG]
/****** Object:  Trigger [TAU_PRO_DUCG]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DUCG] ON [PRO_DUCG] FOR UPDATE AS 
BEGIN
	SET DATEFORMAT DMY
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @DUC_PNUM int, @DUC_EANO int, @DUC_NORD varchar(20), @DUC_NDAT datetime, @NumTD int, @ValorEUR numeric(38, 6), @DataLiquidacao datetime, @CodNatureza varchar(3), 
		@CodTipoDocConta varchar(4), @Utilizador varchar(30), @CodCliente varchar(18), @NumMascaras int, @TipoMascara int, @CodMascara int, @Observacoes varchar(5000), 
		@ValorLiqRecapitulativa numeric(38, 6), @NumDocTransporte varchar(18), @TipoCliente varchar(3), @NumContribuinte varchar(18), @CodPais varchar(2), @Artigo int, @DataVoo datetime, 
		@CodAlfandega varchar(8), @NomeAlfandega varchar(70), @AnoSDS int, @NumSDS int, @NLinhaSDS int, @CodDocSDS varchar(5), @NomeDocSDS varchar(70), @NDocSDS int, @TipoDestinatario int, 
		@Data datetime, @CaucaoGlobal bit, @CaucaoNumero varchar(24), @CaucaoTipoEntidade int, @CaucaoAno varchar(4), @CaucaoTipo varchar(1), @TotalAdicoes int, @NumRegLiquidacao varchar(20), 
		@CaucaoCodEntidade varchar(18), @DescricaoDeclaracao varchar(15), @AdicionalIVA int, @TotalMovsCaucao int, @TotalMovsCaucaoCC int, @ContextoIMP int
-- obtem das declarações para efetuar o respetivo lançamento na caução
	IF UPDATE(DUC_DATA) OR UPDATE(NDE_CODI) OR UPDATE(DUC_DST8) OR UPDATE(DEC_CO14) OR UPDATE(DUC_NORD) OR UPDATE(DUC_NDAT) OR UPDATE(DUC_CGLB) OR UPDATE(DUC_CAUC) OR UPDATE(DUC_CENT) 
	OR UPDATE(DUC_CANO) OR UPDATE(DUC_CTIP) OR UPDATE(DUC_ADI5) OR UPDATE(ALF_CODI) OR UPDATE(DUC_VLRC) OR UPDATE(DUC_REGL)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO, DUC_DATA, DUC_DST8, DUC_NORD, DUC_NDAT, DUC_CGLB, DUC_CAUC, DUC_CENT, DUC_CANO, DUC_CTIP, DUC_ADI5, ALF_CODI, ISNULL(DUC_VLRC, 0), DUC_REGL, DUC_DUNO, 
				(CASE DUC_CENT WHEN 0 THEN DEC_CO14 ELSE DUC_DST8 END), 
				(NDE_CODI + '.' + REPLICATE('0', 6 - LEN(CAST(DUC_PNUM AS varchar(10)))) + CAST(DUC_PNUM AS varchar(10)) + '/' + CAST(DUC_EANO AS varchar(4))), 
				(SELECT TOP 1 DUA_AIVA FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = inserted.DUC_EANO AND DUC_PNUM = inserted.DUC_PNUM AND DUA_CODI = 1),
				(SELECT COUNT(*) FROM PRO_MCAU WITH(NOLOCK) WHERE DUC_PNUM = inserted.DUC_PNUM and DUC_EANO = inserted.DUC_EANO), 
				(SELECT COUNT(*) FROM PRO_CCCA WITH(NOLOCK) WHERE DUC_PNUM = inserted.DUC_PNUM and DUC_EANO = inserted.DUC_EANO)
			FROM inserted
			WHERE DUC_DUNO IN (1, 2) AND DATEDIFF(MONTH, ISNULL(DUC_DTRL, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) < 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @Data, @CodCliente, @DUC_NORD, @DUC_NDAT, @CaucaoGlobal, @CaucaoNumero, @CaucaoTipoEntidade, @CaucaoAno, @CaucaoTipo, @TotalAdicoes, 
			@CodAlfandega, @ValorLiqRecapitulativa, @NumRegLiquidacao, @ContextoIMP, @CaucaoCodEntidade, @DescricaoDeclaracao, @AdicionalIVA, @TotalMovsCaucao, @TotalMovsCaucaoCC
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF (ISNULL(@CodCliente, '') <> '') AND (@CaucaoGlobal = 1) AND (ISNULL(@CaucaoNumero, '') <> '') AND (@TotalAdicoes > 0) AND (ISNULL(@NumRegLiquidacao, '') <> '')
			BEGIN
				IF (@TotalMovsCaucao = @TotalMovsCaucaoCC) OR ((@TotalMovsCaucao * 2) = @TotalMovsCaucaoCC)
				BEGIN
					IF @ContextoIMP = 2 --em IMP-CAU extrai apenas o número 
					BEGIN
						IF CHARINDEX('/', @CaucaoNumero) = 0
							SET @CaucaoNumero = RIGHT(@CaucaoNumero, 7)						
						ELSE
						BEGIN
							SET @CaucaoNumero = STUFF(@CaucaoNumero, 1, CHARINDEX('/', @CaucaoNumero), '')
							SET @CaucaoNumero = SUBSTRING(@CaucaoNumero, 1, CHARINDEX('/', @CaucaoNumero) - 1)
						END
					END
					EXEC SP_lancaDocUnicoCaucao @CaucaoTipoEntidade, @CaucaoCodEntidade, @CaucaoNumero, @CaucaoAno, @CaucaoTipo, @CodAlfandega, @DUC_PNUM, @DUC_EANO, @Data, @DescricaoDeclaracao, @DUC_NORD, @DUC_NDAT, @CodCliente, @ValorLiqRecapitulativa, 0, 0, @AdicionalIVA
				END
			END
			ELSE
			BEGIN
				DELETE FROM PRO_MCAU
				WHERE DUC_PNUM = @DUC_PNUM and DUC_EANO = @DUC_EANO
			END
			FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @Data, @CodCliente, @DUC_NORD, @DUC_NDAT, @CaucaoGlobal, @CaucaoNumero, @CaucaoTipoEntidade, @CaucaoAno, @CaucaoTipo, @TotalAdicoes, 
				@CodAlfandega, @ValorLiqRecapitulativa, @NumRegLiquidacao, @ContextoIMP, @CaucaoCodEntidade, @DescricaoDeclaracao, @AdicionalIVA, @TotalMovsCaucao, @TotalMovsCaucaoCC
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- verifica se campos de Num Ordem DGA e Data foram alterados
	IF UPDATE(DUC_NORD) or UPDATE(DUC_NDAT)
	BEGIN	
-- busca dados alterados
		DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO, DUC_NORD, DUC_NDAT
			FROM inserted
		OPEN Detalhe
		FETCH NEXT FROM Detalhe INTO @DUC_PNUM, @DUC_EANO, @DUC_NORD, @DUC_NDAT
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- actualiza Num Ordem DGA e Data na Caução 
			UPDATE PRO_MCAU SET MCA_NORD = @DUC_NORD, MCA_DORD = @DUC_NDAT	
			WHERE DUC_PNUM = @DUC_PNUM and DUC_EANO = @DUC_EANO and DUC_TIPO = 0
-- actualiza Num Ordem DGA e Data na Conta 
			ALTER TABLE FAC_CDOC DISABLE TRIGGER TAU_FAC_CDOC
			UPDATE FAC_CDOC SET CDO_NORD = @DUC_NORD, CDO_DTAC = @DUC_NDAT
			WHERE CDO_PANO = @DUC_EANO and CDO_NPRO = @DUC_PNUM and CDO_IMEX = 0
			ALTER TABLE FAC_CDOC ENABLE TRIGGER TAU_FAC_CDOC

			FETCH NEXT FROM Detalhe INTO @DUC_PNUM, @DUC_EANO, @DUC_NORD, @DUC_NDAT
		END
		CLOSE Detalhe
		DEALLOCATE Detalhe
	END
-- verifica se campo Data de Liquidaçao foi alterado
	IF UPDATE(DUC_DTRL)
	BEGIN	
-- busca dados alterados
		DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO, DUC_DTRL
			FROM inserted
		OPEN Detalhe
		FETCH NEXT FROM Detalhe INTO @DUC_PNUM, @DUC_EANO, @DataLiquidacao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- actualiza Data de Liquidaçao na Caução 
			UPDATE PRO_MCAU SET MCA_DTRL = @DataLiquidacao
			WHERE DUC_PNUM = @DUC_PNUM and DUC_EANO = @DUC_EANO and DUC_TIPO = 0
			FETCH NEXT FROM Detalhe INTO @DUC_PNUM, @DUC_EANO, @DataLiquidacao
		END
		CLOSE Detalhe
		DEALLOCATE Detalhe
	END	
-- verifica se campo de "Nº Titulo Depósito" foi alterado
	IF UPDATE(DUC_NTDP)
	BEGIN		
-- obtem declarações alteradas que tenham adições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO, DUC_NTDP
			FROM inserted
			WHERE DUC_DUNO IN (0, 1) AND EXISTS(SELECT DUA_CODI FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = inserted.DUC_EANO and DUC_PNUM = inserted.DUC_PNUM and DUA_CODI = 1)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @NumTD
		WHILE @@FETCH_STATUS = 0
		BEGIN			
-- verifica se documento "9Z07" já existe na 1ª adição. Se sim edita dados, senão insere documento
			IF EXISTS(SELECT DDO_CODI FROM PRO_DDOC WITH(NOLOCK) WHERE DUC_EANO = @DUC_EANO and DUC_PNUM = @DUC_PNUM and DUA_CODI = 1 and DOC_CODI = '9Z07')
			BEGIN
				UPDATE PRO_DDOC SET DDO_NUME = CAST(@NumTD as varchar(20)), DDO_DINI = CAST(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 105) as datetime)
				WHERE DUC_EANO = @DUC_EANO and DUC_PNUM = @DUC_PNUM and DUA_CODI = 1 and DOC_CODI = '9Z07'				
			END
			ELSE
			BEGIN				
				INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_DINI, DDO_MONT, DDO_DPRZ)
				SELECT @DUC_EANO, @DUC_PNUM, 1, (ISNULL((SELECT MAX(DDO_CODI) FROM PRO_DDOC WHERE DUC_EANO = @DUC_EANO and DUC_PNUM = @DUC_PNUM and DUA_CODI = 1), 0) + 1), 
					DOC_CODI, DOC_NOME, CAST(@NumTD as varchar(20)), CAST(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 105) as datetime), 0, 0
				FROM TAB_DOCU WITH(NOLOCK)
				WHERE DOC_CODI = '9Z07'
			END
-- processa remoção da menção "PCEDP"		
			DELETE PRO_DDOC 
			WHERE DUC_EANO = @DUC_EANO and DUC_PNUM = @DUC_PNUM and DUA_CODI = 1 and DOC_CODI = 'PCEDP'
-- processa a atualização dos códigos internos dos documentos
			UPDATE PRO_DDOC SET DDO_CODI = NEW_CODI
			FROM PRO_DDOC AS ddo INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY DDO_CODI) AS NEW_CODI, DDO_CODI
				FROM PRO_DDOC
				WHERE DUC_EANO = @DUC_EANO and DUC_PNUM = @DUC_PNUM and DUA_CODI = 1) AS ddn ON ddo.DDO_CODI = ddn.DDO_CODI
			WHERE ddo.DUC_EANO = @DUC_EANO and ddo.DUC_PNUM = @DUC_PNUM and ddo.DUA_CODI = 1 and ddo.DDO_CODI <> ddn.NEW_CODI		
			FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @NumTD
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- verifica se campo de "Artigo Franquia" ou campo "NIF Destinatário" foram alterados e campos adicionais dos Par. Despachos for "FEDEX", "UPS", "DHL" ou "TNT"
	IF (UPDATE(DUC_ARTI) OR UPDATE(DUC_DNIF)) and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI IN (1, 2, 3, 4)))
	BEGIN	
-- obtem declarações alteradas que tenham o "Artigo Franquia" preenchido e o "País Destinatário" como "PT" e "NIF Destinatário" a começar por "1", "2", "3" , "5", "6", "7", "8" ou "9" ou "País Destinatário" diferente de "PT" e que ainda não tenham "Aut. Saída"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ALF_CODI, ALF_NOME, DUC_CPRT, DUC_VEUR, DUC_DNIF, PAI_DLIV, DUC_ARTI, DUC_DTVO, DUC_TPDS
			FROM inserted
			WHERE DUC_ARTI IS NOT NULL AND DUC_ASAI = 0 AND DUC_DUNO IN (1, 2) 
				AND ((PAI_DLIV = 'PT' AND SUBSTRING(DUC_DNIF, 1, 1) IN ('1', '2', '3', '5', '6', '7', '8', '9')) OR (PAI_DLIV <> 'PT')) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @CodAlfandega, @NomeAlfandega, @NumDocTransporte, @ValorEUR, @NumContribuinte, @CodPais, @Artigo, @DataVoo, @TipoDestinatario
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT TOP 1 @AnoSDS = dsd.DSC_EANO, @NumSDS = dsd.DSC_NPRO, @NLinhaSDS = dsd.DSD_NUME
			FROM PRO_SDSD AS dsd WITH(NOLOCK) 
				INNER JOIN PRO_SDSC AS dsc WITH(NOLOCK) ON dsd.DSC_EANO = dsc.DSC_EANO AND dsd.DSC_NPRO = dsc.DSC_NPRO
			WHERE dsc.DSC_TIPO = 0 AND dsd.DSD_NRMH = @NumDocTransporte AND CAST(CONVERT(varchar(10), dsc.DSC_DTVO, 105) AS datetime) = CAST(CONVERT(varchar(10), @DataVoo, 105) AS datetime)
-- se AWB existir num Manifesto de Importação SDS p/ a Data de Voo c/ status de "Por Enviar", processa atualizações
			IF @AnoSDS IS NOT NULL
			BEGIN
-- actualiza campos de "Id. Destinatário", "Valor" e "Artigo Franquia" da AWB do Manifesto de Importação SDS relacionado			
				UPDATE PRO_SDSD SET 
					DSD_IDED = (CASE 
									WHEN (@CodPais = 'PT') AND (@TipoDestinatario <> 3) THEN (@CodPais + '/NIF/' + @NumContribuinte) 
									WHEN (@CodPais <> 'PT') AND (@TipoDestinatario = 3) THEN (@CodPais + '/P/' + @NumContribuinte) ELSE (@CodPais + '/EORI/' + @NumContribuinte) 
								END), 
					DSD_VALO = @ValorEUR, 
					DSD_AFRQ = @Artigo, 
					DSD_EFRQ = 0, 
					DSD_DNOW = GETDATE()
				WHERE DSC_EANO = @AnoSDS AND DSC_NPRO = @NumSDS AND DSD_NUME = @NLinhaSDS
-- processa a inserção/edição do detalhe de documentos da linha AWB do Manifesto de Importação SDS relacionado
				IF (UPDATE(DUC_ARTI)) AND (@Artigo IN (23, 25, 42, 87))
				BEGIN
					DECLARE Docs CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
						SELECT DOC_CODI, DOC_NOME
						FROM TAB_DOCU WITH(NOLOCK)
						WHERE DOC_CODI IN (SELECT tbl.DOC_CODI
							FROM (SELECT (CASE @Artigo WHEN 23 THEN 'IFC07' WHEN 25 THEN 'IFC08' ELSE NULL END) AS DOC_CODI
								UNION
								SELECT (CASE @Artigo WHEN 23 THEN 'PFC07' WHEN 25 THEN 'PFC08' WHEN 42 THEN 'PFC11' WHEN 87 THEN 'PFC31' ELSE NULL END)) as tbl
							WHERE ISNULL(tbl.DOC_CODI, '') <> '')
					OPEN Docs
					FETCH NEXT FROM Docs INTO @CodDocSDS, @NomeDocSDS
					WHILE @@FETCH_STATUS = 0
					BEGIN
						IF NOT EXISTS(SELECT SDD_NUME FROM PRO_SSDD WITH(NOLOCK) WHERE DSC_EANO = @AnoSDS AND DSC_NPRO = @NumSDS AND DSD_NUME = @NLinhaSDS AND DOC_CODI = @CodDocSDS)
						BEGIN
							SET @NDocSDS = ISNULL((SELECT MAX(SDD_NUME) FROM PRO_SSDD WHERE DSC_EANO = @AnoSDS AND DSC_NPRO = @NumSDS AND DSD_NUME = @NLinhaSDS), 0) + 1
							INSERT INTO PRO_SSDD(DSC_EANO, DSC_NPRO, DSD_NUME, SDD_NUME, DOC_CODI, DOC_NOME, SDD_NDOC, SDD_DDOC, EAD_CODI, EAD_NOME, SDD_SDOC)
							VALUES(@AnoSDS, @NumSDS, @NLinhaSDS, @NDocSDS, @CodDocSDS, @NomeDocSDS, @NumDocTransporte, CAST(CONVERT(varchar(10), GETDATE(), 105) AS datetime), 
								@CodAlfandega, @NomeAlfandega, 'T')
						END
						ELSE
						BEGIN
							UPDATE PRO_SSDD SET SDD_NDOC = @NumDocTransporte, SDD_DDOC = CAST(CONVERT(varchar(10), GETDATE(), 105) AS datetime), EAD_CODI = @CodAlfandega, 
								EAD_NOME = @NomeAlfandega, SDD_SDOC = 'T'
							WHERE DSC_EANO = @AnoSDS AND DSC_NPRO = @NumSDS AND DSD_NUME = @NLinhaSDS AND DOC_CODI = @CodDocSDS 
						END
						FETCH NEXT FROM Docs INTO @CodDocSDS, @NomeDocSDS
					END
					CLOSE Docs
					DEALLOCATE Docs
				END
			END
			FETCH NEXT FROM Declaracoes INTO @CodAlfandega, @NomeAlfandega, @NumDocTransporte, @ValorEUR, @NumContribuinte, @CodPais, @Artigo, @DataVoo, @TipoDestinatario
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- verifica se campo de "Montante Casa 22" foi alterado e campos adicionais dos Par. Despachos for "CTT"	
	IF (UPDATE(DUC_MT22)) and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 5))
    BEGIN   
-- obtem declarações alteradas da Natureza "PRE"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO, DUC_VEUR
			FROM inserted
			WHERE NDE_CODI = 'PRE'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @ValorEUR
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- actualiza Método de Avaliação e Regime B das adições da declaração
			UPDATE PRO_DUAD SET DUA_MAVA = NULL, DUA_R37B = (CASE WHEN @ValorEUR < 150 THEN 'C07' ELSE DUA_R37B END)
			WHERE DUC_PNUM = @DUC_PNUM and DUC_EANO = @DUC_EANO
			FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @ValorEUR
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes                           
    END       
-- verifica se campo "Natureza" foi alterado e campos adicionais dos Par. Despachos for "CTT"       
	IF (UPDATE(NDE_CODI)) and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 5))
    BEGIN   
-- obtem declarações alteradas para a Natureza "BAL"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO
			FROM inserted
			WHERE NDE_CODI = 'BAL'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- actualiza Nº.Referência(7) da declaração            
			UPDATE PRO_DUCG SET DUC_REF7 = ('BAL/' + CAST(@DUC_PNUM as varchar(20)) + '/' + CAST(@DUC_EANO as varchar(4)))
			WHERE DUC_PNUM = @DUC_PNUM and DUC_EANO = @DUC_EANO
			FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes 
    END     
-- verifica se campo de "Status" foi alterado e campos adicionais dos Par. Despachos for "CTT"	
	IF (UPDATE(DUC_STAT)) and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 5))
    BEGIN   
-- obtem declarações alteradas da Natureza "PRE"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO
			FROM inserted
			WHERE NDE_CODI = 'PRE'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- actualiza Natureza da declaração		
			UPDATE PRO_DUCG SET NDE_CODI = 'DAR', NDE_NOME = (SELECT NDE_NOME FROM TAB_NDES WITH(NOLOCK) WHERE NDE_CODI = 'DAR')
			WHERE DUC_PNUM = @DUC_PNUM and DUC_EANO = @DUC_EANO
			FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes                           
    END  
-- verifica se campo de "Aut. Saída" foi alterado e campo de "Faturação Automática Ativa" selecionado nos Par. Faturação Automática
	IF (UPDATE(DUC_ASAI)) and (EXISTS(SELECT FTA_IDEN FROM TAB_PFTA WITH(NOLOCK) WHERE FTA_ACTI = 1))
    BEGIN   
-- obtem declarações alteradas c/ campo "Aut. Saída" 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT duc.DUC_PNUM, duc.DUC_EANO, duc.NDE_CODI, duc.DUC_DST8, duc.DUC_CPRT, duc.DUC_UALT, ISNULL(duc.DUC_VLRC, 0), 
				(CASE ISNULL(nat.NDE_TLCV, -1) WHEN 0 THEN duc.TDO_DOCU ELSE (SELECT PDE_TDOC FROM TAB_PDES WITH(NOLOCK)) END), 
				(CASE WHEN (SELECT PDE_IDCV FROM TAB_PDES WITH(NOLOCK)) = 0 THEN NULL WHEN duc.DUC_DTYP IN ('A5' , 'A6') THEN 'ACC' WHEN duc.DUC_DTYP = 'CA' THEN 'COD' WHEN duc.DUC_DTYP IN ('D5', 'D6') THEN 'EXB' ELSE NULL END)
			FROM inserted AS duc INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI
			WHERE duc.DUC_ASAI = 1 AND duc.DUC_TSHI < 2 AND cli.CLI_DUCT = 1 AND nat.NDE_CRCO = 1 and ISNULL(nat.NDE_TLCV, 0) <> 1 
				AND (CASE (SELECT FTA_DUVR FROM TAB_PFTA WITH(NOLOCK)) WHEN 1 THEN (CASE WHEN ISNULL(duc.DUC_NVRF, '') <> '' THEN 1 ELSE 0 END) WHEN 2 THEN (CASE WHEN ISNULL(duc.DUC_NVRF, '') = '' THEN 1 ELSE 0 END) ELSE 1 END) = 1
				AND (SELECT COUNT(*) from FAC_CDOC WITH(NOLOCK) where CDO_IMEX = 0 and CDO_PANO = duc.DUC_EANO and CDO_NPRO = duc.DUC_PNUM) = 0
				AND (SELECT COUNT(*) from FAC_DVEN WITH(NOLOCK) where DVE_IMEX = 0 and DVE_PANO = duc.DUC_EANO and DVE_NPRO = duc.DUC_PNUM) = 0
				AND (CASE WHEN ISNULL(nat.NDE_TLCV, -1) = 0 AND ISNULL(duc.TDO_DOCU, '') = '' THEN 0 ELSE 1 END) = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @CodNatureza, @CodCliente, @NumDocTransporte, @Utilizador, @ValorLiqRecapitulativa, @CodTipoDocConta, @TipoCliente
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem a máscara para a Conta
			SET @TipoMascara = 0
			SET @CodMascara = 0
			EXEC SP_ObtemMascaraFacturacao @CodCliente, @CodNatureza, @NumMascaras OUTPUT, @TipoMascara OUTPUT, @CodMascara OUTPUT
-- atualiza na declaração a máscara obtida p/ o documento de Conta
			UPDATE PRO_DUCG SET DUC_TMSF = @TipoMascara, DUC_MASC = @CodMascara
			WHERE DUC_PNUM = @DUC_PNUM AND DUC_EANO = @DUC_EANO
-- obtem as observações para a Conta
			EXEC SP_ObtemObservacoesParaConta @CodMascara, @DUC_EANO, @DUC_PNUM, @CodCliente, @CodNatureza, '', @Observacoes OUTPUT			
-- processa a geração do documento de Conta
			EXEC SP_geraContas @DUC_PNUM, @DUC_EANO, @CodTipoDocConta, @CodNatureza, @Utilizador, @TipoMascara, @CodMascara, 0, @Observacoes, @ValorLiqRecapitulativa, @NumDocTransporte, 0, @TipoCliente, 1
			FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO, @CodNatureza, @CodCliente, @NumDocTransporte, @Utilizador, @ValorLiqRecapitulativa, @CodTipoDocConta, @TipoCliente
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes    
    END
-- verifica se campo "Tipo de Shipment" foi alterado, processar a cópia dos valores totais originais nas declarações cujo tipo de shipment mudou p/ "Part-Shipment"
	IF UPDATE(DUC_TSHI)
    BEGIN   
-- grava os valores totais originais para as declarações cujo tipo de shipment mudou p/ "Part-Shipment" e valores originais ainda não guardados
		UPDATE PRO_DUCG SET DUC_TMOO = ISNULL(del.DUC_MT22, 0), DUC_TFRO = ISNULL(del.DUC_FRET, 0), DUC_TSEO = ISNULL(del.DUC_SEGU, 0), DUC_TMLO = ISNULL(del.DUC_MLQT, 0), DUC_TMBO = ISNULL(del.DUC_MBRT, 0), 
			DUC_TVEO = ISNULL(del.DUC_VEUR, 0), DUC_TVAO = ISNULL(del.DUC_VATT, 0), DUC_TLRO = ISNULL(del.DUC_VLRC, 0), 
			DUC_TOPO = ISNULL((SELECT SUM(ISNULL(ad.DUA_VOPT, 0)) FROM PRO_DUAD AS ad WITH(NOLOCK) WHERE ad.DUC_EANO = del.DUC_EANO AND ad.DUC_PNUM = del.DUC_PNUM), 0)			
		FROM PRO_DUCG AS duc WITH(NOLOCK) INNER JOIN inserted AS ins ON duc.DUC_IDTY = ins.DUC_IDTY
			INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY			
		WHERE ins.DUC_TSHI = 1 AND del.DUC_TSHI = 0 AND ins.DUC_TMOO = 0 AND del.DUC_TMOO = 0 
-- grava o valor do iva original das adições para as declarações cujo tipo de shipment mudou p/ "Part-Shipment" e valores originais ainda não guardados
		UPDATE PRO_DUAD SET DUA_TIVO = ISNULL(dua.DUA_VIVA, 0)		
		FROM PRO_DUAD AS dua WITH(NOLOCK) INNER JOIN inserted AS ins ON dua.DUC_EANO = ins.DUC_EANO AND dua.DUC_PNUM = ins.DUC_PNUM
			INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY			
		WHERE ins.DUC_TSHI = 1 AND del.DUC_TSHI = 0 AND dua.DUA_TIVO = 0
-- copia o detalhe da liquidação recapitulativa para as declarações cujo tipo de shipment mudou p/ "Part-Shipment" e valores originais ainda não guardados
		INSERT INTO PRO_DULO(DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, DUL_MONT, DUL_RPRO, DUL_MTAG, DUL_UCRI, DUL_DTCR)
		SELECT dlr.DUC_PNUM, dlr.DUC_EANO, dlr.RRE_CODI, dlr.RRE_NOME, ISNULL(dlr.DUL_MONT, 0), ISNULL(dlr.DUL_RPRO, 0), dlr.DUL_MTAG, ins.DUC_UALT, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
		FROM PRO_DULR AS dlr WITH(NOLOCK) INNER JOIN inserted AS ins ON dlr.DUC_PNUM = ins.DUC_PNUM AND dlr.DUC_EANO = ins.DUC_EANO
			INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY			
		WHERE ins.DUC_TSHI = 1 AND del.DUC_TSHI = 0 AND NOT EXISTS(SELECT DUC_PNUM FROM PRO_DULO WHERE DUC_PNUM = ins.DUC_PNUM AND DUC_EANO = ins.DUC_EANO)
    END     
-- verifica se campos "Status", "Versão", "Revisão" ou "Estado Operação" foram alterados e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO" para colocar declarações como pendentes de envio para Portal MyRangel
	IF (UPDATE(DUC_STAT) OR UPDATE(DUC_VERS) OR UPDATE(DUC_REVI) OR UPDATE(DUC_ESTO)) AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DUC_PNUM, DUC_EANO
			FROM inserted 
			WHERE DUC_STAT = 3 OR DUC_VERS > 0 OR DUC_REVI > 0 OR ISNULL(DUC_ESTO, '') <> ''
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE PRO_DUCG SET 
				DUC_PMRP = 1				
			WHERE DUC_PNUM = @DUC_PNUM AND DUC_EANO = @DUC_EANO
			FETCH NEXT FROM Declaracoes INTO @DUC_PNUM, @DUC_EANO
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
	END
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAU_PRO_DUCG]
/****** Object:  Trigger [TAU_PRO_DUCG_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DUCG_IMPCAU] ON [PRO_DUCG] FOR UPDATE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdRegisto bigint, @IdPais int, @SQLAExecutar varchar(MAX), @ProcesssaCalculos varchar(20)
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @IdDeclaracao bigint, @IdUtilizador int, @VerbaTransitario decimal(18, 2)
	DECLARE @CodStatusIncidencia varchar(8), @NumIncidencia int, @NomeStatusIncidencia varchar(60)
	DECLARE @IdDocumento int, @NumeroDocumento varchar(70), @DataValidadeDocumento datetime, @NumDocumento int, @CodDocumento varchar(5), @NomeDocumento varchar(150)
	DECLARE @NumAdicao int, @IdAdicao int, @ValorEUR numeric(38, 6), @Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @ValorAduaneiro numeric(38, 6), 
		@BaseTributacaoDireitos numeric(38, 6), @TaxaValorDireitos numeric(38, 6), @MontanteDireitos numeric(38, 6), @Optativas numeric(38, 6), @BaseTributacaoIVA numeric(38, 6), 
		@TaxaIVA numeric(38, 6)		
	DECLARE @IdPedido int, @NumeroPedido varchar(512)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- se coluna de declarante alterada, processa remoções do detalhe de outros intervenientes das declarações IMP-CAU alteradas
	IF UPDATE(DEC_CO14)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.DEC_CO14 = dcl.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ((dcl.DEC_FXOE NOT IN (0, 1)) OR (ISNULL(dcl.DEC_NAOE, '') = ''))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nos outros intervenientes o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesIntervenientes SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove os outros intervenientes da declaração
			DELETE FROM tb_IMP_DeclaracoesIntervenientes
			WHERE id_declaracaoIMP = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END		
-- se coluna de estado de operação alterada, processa a gestão de incidências fixas "AS" e "ND" no detalhe de incidências das declarações IMP-CAU alteradas
	IF UPDATE(DUC_ESTO)
	BEGIN
-- insere status de incidência "A00" no detalhe de incidências da declaração IMP-CAU 				
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, inc.SIN_CODI, inc.SIN_DESP
			FROM inserted AS ins 
				INNER JOIN TAB_SINC AS inc WITH(NOLOCK) ON inc.SIN_CODI	= 'A00'
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ESTO = 'AS'			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia, @NomeStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN			
-- obtem o próximo numero de registo de incidência
			SELECT @NumIncidencia = ISNULL(MAX(DUI_CODI), 0) + 1
			FROM PRO_DUIN
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
-- insere a incidência no detalhe de incidências da declaração IMP-CAU 
			INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumIncidencia, @CodStatusIncidencia, @NomeStatusIncidencia, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), 
				CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime), CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime))			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia, @NomeStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- insere status de incidência "ND" no detalhe de incidências da declaração IMP-CAU
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, inc.SIN_CODI, inc.SIN_DESP
			FROM inserted AS ins 
				INNER JOIN TAB_SINC AS inc WITH(NOLOCK) ON ins.DUC_ESTO = inc.SIN_CODI					
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ESTO = 'ND'			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia, @NomeStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN						
-- obtem o próximo numero de registo de incidência
			SELECT @NumIncidencia = ISNULL(MAX(DUI_CODI), 0) + 1
			FROM PRO_DUIN
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao							
-- insere a incidência no detalhe de incidências da declaração IMP-CAU 
			INSERT INTO PRO_DUIN(DUC_EANO, DUC_PNUM, DUI_CODI, SIN_CODI, SIN_DESC, DUI_DINI, DUI_HINI, DUI_DFIM, DUI_HFIM)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumIncidencia, @CodStatusIncidencia, @NomeStatusIncidencia, CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), 
				CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime), CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), CAST(CONVERT(varchar(8), @DataAtual, 108) AS datetime))			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodStatusIncidencia, @NomeStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- se coluna de verba transitário alterada, processa a gestão do documento "3E01" de origem automatica da estancia de sujeição no detalhe de documentos das declarações IMP-CAU alteradas
	IF UPDATE(DUC_VTRN)
	BEGIN
-- edita o documento "3E01" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ISNULL(ins.DUC_VTRN, 0), uti.UTI_IDTY, ddo.id, 
				(CASE WHEN ISNULL(ins.DUC_VTRN, 0) > 0 THEN pai.PAI_IDTY ELSE NULL END)
			FROM inserted AS ins 				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = '3E01'
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 6	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL		
				INNER JOIN TAB_PAPL AS pap WITH(NOLOCK) ON 1 = 1
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON pap.PAI_CODI = pai.PAI_CODI				
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @VerbaTransitario, @IdUtilizador, @IdRegisto, @IdPais
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET 
				id_paisMoeda = @IdPais, 
				montante = @VerbaTransitario, 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdRegisto			
			FETCH NEXT FROM Declaracoes INTO @VerbaTransitario, @IdUtilizador, @IdRegisto, @IdPais
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- se coluna de título de depósito alterada, processa a gestão do documento fixo "9Z07" no detalhe de documentos das declarações IMP-CAU alteradas
	IF UPDATE(DUC_NTDP)
	BEGIN		
-- insere o documento fixo "9Z07" como "Suporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, CAST(ins.DUC_NTDP as varchar(20)), CAST(CONVERT(varchar(10), @DataAtual, 105) AS datetime), ddo.id
			FROM inserted AS ins 					
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI	= '9Z07'
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 11
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL				
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_NTDP IS NOT NULL AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @DataValidadeDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, dataValidade, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 0, @IdDocumento, @NumeroDocumento, @DataValidadeDocumento, 11, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesDocumentos SET
					id_documento = @IdDocumento, 
					numero = @NumeroDocumento, 
					dataValidade = @DataValidadeDocumento,					
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @DataValidadeDocumento, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- remove o documento fixo "9Z07" existente no detalhe de documentos da declaração mas já não satisfaz a condição do título depósito
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.DUC_IDTY = ddo.id_declaracaoIMP AND origem = 11			
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL						
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ins.DUC_NTDP IS NULL OR doc.DOC_DESP = 0 OR doc.DOC_DTRA = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes									
	END
-- se coluna de anexo B alterada, processa remoções dos detalhes de referências fiscais, acréscimos/deduções e detalhes do aperfeiçoamento das declarações IMP-CAU alteradas
	IF UPDATE(DUC_ANXB)
	BEGIN
-- obtem as declarações IMP-CAU que não satisfaçam as condições p/ ter referências fiscais
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB NOT IN ('H1', 'H6', 'I1')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nas referências fiscais o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesReferenciasFiscais SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove as referências fiscais da declaração
			DELETE FROM tb_IMP_DeclaracoesReferenciasFiscais
			WHERE id_declaracaoIMP = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem as declarações IMP-CAU que não satisfaçam as condições p/ ter acréscimos/deduções
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB IN ('H2', 'H3', 'H4', 'H6')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nos acréscimos/deduções o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesAcrescimosDeducoes SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove os acréscimos/deduções da declaração
			DELETE FROM tb_IMP_DeclaracoesAcrescimosDeducoes
			WHERE id_declaracaoIMP = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem as declarações IMP-CAU que não satisfaçam as condições p/ ter proprietários das mercadorias de aperfeiçoamento
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB IN ('H1', 'H2', 'H4', 'H5', 'H6', 'I1', 'I2')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nos proprietários das mercadorias o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesProprietarios SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove os proprietários das mercadorias da declaração
			DELETE FROM tb_IMP_DeclaracoesProprietarios
			WHERE id_declaracaoIMP = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem as declarações IMP-CAU que não satisfaçam as condições p/ ter estâncias de apuramento ou locais de transformação de aperfeiçoamento
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB IN ('H1', 'H2', 'H5', 'H6', 'I1', 'I2')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nas estâncias de apuramento o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesEstancias SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove as estâncias de apuramento da declaração
			DELETE FROM tb_IMP_DeclaracoesEstancias
			WHERE id_declaracaoIMP = @IdDeclaracao
-- atualiza nos locais de transformação o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesLocaisTransformacao SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove os locais de transformação da declaração
			DELETE FROM tb_IMP_DeclaracoesLocaisTransformacao
			WHERE id_declaracaoIMP = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem as declarações IMP-CAU que não satisfaçam as condições p/ ter produtos transformados ou condições económicas de aperfeiçoamento
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ins.DUC_UALT = uti.UTI_UTIL
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB IN ('H1', 'H2', 'H3', 'H5', 'H6', 'I1', 'I2')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nos produtos transformados o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesProdutosTransformados SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove os produtos transformados da declaração
			DELETE FROM tb_IMP_DeclaracoesProdutosTransformados
			WHERE id_declaracaoIMP = @IdDeclaracao
-- atualiza nas condições económicas o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesCondicoesEconomicas SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoIMP = @IdDeclaracao
-- remove as condições económicas da declaração
			DELETE FROM tb_IMP_DeclaracoesCondicoesEconomicas
			WHERE id_declaracaoIMP = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- se colunas de contentores e n.º contentor alteradas, processa remoções dos detalhes de contentores das adições das declarações IMP-CAU alteradas
	IF UPDATE(DUC_CT19) OR UPDATE(DUC_CONT)
	BEGIN
-- obtem as declarações IMP-CAU que não satisfaçam as condições p/ ter contentores nas adições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM
			FROM inserted AS ins 				
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ins.DUC_CT19 = 0 OR ISNULL(ins.DUC_CONT, '') <> '')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove os contentores de todas as adições da declaração
			DELETE FROM PRO_DCON
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- se colunas de anexo B, tipo declaração, exportador, vendedor, comprador, natureza de transação, numero NRUR, despacho centralizado, beneficiario de IVA, regime, direitos DDP, frete, seguro, verba transitário, verbas automáticas, garantia global, NRG, NIF Responsável, Fórmula, Taxa FDA, Câmbio Montante, Câmbio Frete, Câmbio Seguro, Meio Transporte Chegada, Total Adições, Total Volumes e Total Optativas alteradas, processa atualizações nos campos das adições das declarações IMP-CAU alteradas
	IF UPDATE(DUC_ANXB) OR UPDATE(TDE_CODI) OR UPDATE(DUC_ENOM) OR UPDATE(FOR_NOME) OR UPDATE(CLI_NOME1) OR UPDATE(NTR_CO24) OR UPDATE(DUC_REF7) OR UPDATE(DUC_DCEN) 
	OR UPDATE(DUC_BIVA) OR UPDATE(DUC_REGI) OR UPDATE(DUC_DIRT) OR UPDATE(DUC_FRET) OR UPDATE(DUC_SEGU) OR UPDATE(DUC_VTRN) OR UPDATE(DUC_VBAT) OR UPDATE(DUC_CGLB) 
	OR UPDATE(DUC_CAUC) OR UPDATE(DUC_CNIR) OR UPDATE(DUC_FR20) OR UPDATE(DUC_TFDA) OR UPDATE(DUC_TX23) OR UPDATE(DUC_TXFR) OR UPDATE(DUC_TXSE) OR UPDATE(MTR_PT18) 
	OR UPDATE(DUC_ADI5) OR UPDATE(DUC_TVL6) OR UPDATE(DUC_OP18) OR UPDATE(PAI_PA15)
	BEGIN
		DECLARE @LimpaVendedor tinyint, @LimpaComprador tinyint, @LimpaContingente tinyint, @LimpaMassaLiquida tinyint, @AtualizaPreferencia tinyint, @AtualizaMetodoAvaliacao tinyint, 
			@LimpaPaisPreferencial tinyint, @AtualizaAdicionaisNacionais tinyint, @AtualizaTipoMercadoria tinyint, @LimpaExportador tinyint, @LimpaPaisExpedicao tinyint, 
			@LimpaNaturezaTransacao tinyint, @LimpaPaisDestino tinyint, @LimpaRegiao tinyint, @AtualizaPaisOrigem tinyint, @LimpaNumeroNRUR tinyint, @AtualizaAdicionalIVA tinyint, 
			@AtualizaRegime tinyint,@LimpaIndicadorAvaliacao tinyint, @LimpaDireitos tinyint, @AtualizaFrete tinyint, @AtualizaSeguro tinyint, @AtualizaVerbaTransitario tinyint, 
			@AtualizaNRG tinyint, @AtualizaNIFResponsavel tinyint, @AtualizaAjustamento tinyint, @AtualizaValorEUR tinyint, @AtualizaValorOptativas tinyint
		DECLARE @SQLJoinTBL_Desdobramentos varchar(1000), @SQLJoinTAB_PREF varchar(1000), @SQLJoinTAB_CLIE varchar(1000), @SQLJoinTAB_APAU varchar(1000)
-- obtem as adições das declarações IMP-CAU que satisfaçam as condições associadas ao anexo B ou exportador
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUA_IDEN, 
				(CASE 
					WHEN ((ins.DUC_ANXB <> 'H1' AND del.DUC_ANXB IN ('H1', '##')) OR (ISNULL(ins.FOR_NOME, '') <> '' AND ISNULL(del.FOR_NOME, '') = '')) AND ISNULL(adi.FOR_NOME1, '') <> '' THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ((ins.DUC_ANXB <> 'H1' AND del.DUC_ANXB IN ('H1', '##')) OR (ISNULL(ins.CLI_NOME1, '') <> '' AND ISNULL(del.CLI_NOME1, '') = '')) AND ISNULL(adi.CLI_NOME, '') <> '' THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB NOT IN ('H1', 'I1') AND del.DUC_ANXB IN ('H1', 'I1', '##') AND ISNULL(adi.DUA_CO39, '') <> '' THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB IN ('H2', 'H3', 'I2') AND del.DUC_ANXB NOT IN ('H2', 'H3', 'I2') AND adi.DUA_ML38 <> 0 THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB IN ('H2', 'H5', 'H6') AND del.DUC_ANXB NOT IN ('H2', 'H5', 'H6') AND ISNULL(adi.PRE_CO36, '') <> '000' THEN 1 
					WHEN ins.DUC_ANXB NOT IN ('H2', 'H5', 'H6') AND ins.DUC_ASAI = 0 AND ins.TDE_CODI <> del.TDE_CODI AND ISNULL(tde.PRE_CODI, '') <> '' AND ISNULL(tde.PRE_CODI, '') <> ISNULL(adi.PRE_CO36, '') THEN 2
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') AND del.DUC_ANXB NOT IN ('H2', 'H6', 'I1', 'I2') AND adi.DUA_MAVA IS NOT NULL THEN 1 
					WHEN ins.DUC_ANXB NOT IN ('H2', 'H6', 'I1', 'I2') AND del.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2', '##') AND adi.DUA_R37B NOT IN ('E01', 'E02') AND adi.DUA_MAVA IS NULL THEN 2
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB IN ('H5', 'H6', 'I2') AND del.DUC_ANXB NOT IN ('H5', 'H6', 'I2') AND ISNULL(adi.PAI_CODI5, '') <> '' THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB IN ('H6', 'I2') AND del.DUC_ANXB NOT IN ('H6', 'I2') AND ((ISNULL(adi.DUA_1TAR, '') <> '') OR (ISNULL(adi.DUA_2TAR, '') <> '') OR (ISNULL(adi.DUA_3TAR, '') <> '') OR (ISNULL(adi.DUA_4TAR, '') <> '') OR (ISNULL(adi.DUA_5TAR, '') <> '') OR (ISNULL(adi.APA_CCUS, '') <> '') OR (ISNULL(adi.DUA_US41, 0) <> 0)) THEN 1 
					WHEN ins.DUC_ANXB NOT IN ('H6', 'I2') AND del.DUC_ANXB IN ('H6', 'I2') AND ISNULL(adi.DUA_1TAR, '') = '' AND ISNULL(adi.DUA_2TAR, '') = '' AND ISNULL(adi.DUA_3TAR, '') = '' AND ISNULL(adi.DUA_4TAR, '') = '' AND ISNULL(adi.DUA_5TAR, '') = '' AND ISNULL(adi.APA_CCUS, '') = '' THEN 2
					WHEN ins.DUC_ANXB NOT IN ('H6', 'I2') AND del.DUC_ANXB = '##' AND ISNULL(adi.DUA_4TAR, '') = '' AND ISNULL(adi.DUA_5TAR, '') = '' AND ISNULL(adi.APA_CCUS, '') = '' THEN 3
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB NOT IN ('H6', 'I2') AND del.DUC_ANXB IN ('H6', 'I2', '##') AND ISNULL(adi.DUA_TMER, '') <> '' THEN 1 
					WHEN ins.DUC_ANXB IN ('H6', 'I2') AND del.DUC_ANXB NOT IN ('H6', 'I2') AND ISNULL(adi.DUA_TMER, '') = '' THEN 2
					ELSE 0 
				END), 
				(CASE 
					WHEN ((ins.DUC_ANXB IN ('H6', 'I2') AND del.DUC_ANXB NOT IN ('H6', 'I2')) OR (ISNULL(ins.DUC_ENOM, '') <> '' AND ISNULL(del.DUC_ENOM, '') = '')) AND (ISNULL(adi.FOR_NOME, '') <> '') THEN 1 
					ELSE 0 
				END),
				(CASE 
					WHEN ((ins.DUC_ANXB IN ('H6', 'I2') AND del.DUC_ANXB NOT IN ('H6', 'I2')) OR (ISNULL(ins.PAI_PA15, '') <> '' AND ISNULL(del.PAI_PA15, '') = '')) AND (ISNULL(adi.PAI_CODI1, '') <> '') THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ((ins.DUC_ANXB IN ('H2', 'H6', 'I1', 'I2') AND del.DUC_ANXB NOT IN ('H2', 'H6', 'I1', 'I2')) OR (ISNULL(ins.NTR_CO24, '') <> '' AND ISNULL(del.NTR_CO24, '') = '')) AND ISNULL(adi.NTR_CODI, '') <> '' THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB IN ('H6', 'I1', 'I2') AND del.DUC_ANXB NOT IN ('H6', 'I1', 'I2') AND ISNULL(adi.PAI_CODI2, '') <> '' THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ((ins.DUC_ANXB IN ('H6', 'I1', 'I2') AND del.DUC_ANXB NOT IN ('H6', 'I1', 'I2')) OR (ins.DUC_DCEN = 0 AND del.DUC_DCEN = 1)) AND adi.RES_CODI IS NOT NULL THEN 1 
					ELSE 0 
				END), 
				(CASE 
					WHEN ins.DUC_ANXB = 'I2' AND del.DUC_ANXB <> 'I2' AND ISNULL(adi.PAI_CO34, '') <> '' THEN 1 
					WHEN ins.DUC_ANXB <> 'I2' AND del.DUC_ANXB = 'I2' AND ISNULL(adi.PAI_CO34, '') = '' THEN 2
					ELSE 0 
				END), 
				(CASE 
					WHEN ((ins.DUC_ANXB = 'I2' AND del.DUC_ANXB <> 'I2') OR (ISNULL(ins.DUC_REF7, '') <> '' AND ISNULL(del.DUC_REF7, '') = '')) AND ISNULL(adi.DUA_NRUR, '') <> '' THEN 1 
					ELSE 0 
				END),
				(CASE 
					WHEN ((LEFT(ISNULL(ins.DUC_REGI, ''), 2) = '42' AND LEFT(ISNULL(del.DUC_REGI, ''), 2) <> '42') OR (ins.DUC_BIVA = 1 AND del.DUC_BIVA = 0)) AND adi.DUA_AIVA IS NOT NULL THEN 1
					WHEN LEFT(ISNULL(ins.DUC_REGI, ''), 2) <> '42' AND ins.DUC_BIVA = 0 AND ((LEFT(ISNULL(ins.DUC_REGI, ''), 2) <> LEFT(ISNULL(del.DUC_REGI, ''), 2)) OR (ins.DUC_BIVA <> del.DUC_BIVA)) AND adi.DUA_AIVA IS NULL THEN 2
					ELSE 0
				END), 
				(CASE 
					WHEN ISNULL(ins.DUC_REGI, '') <> ISNULL(del.DUC_REGI, '') AND ISNULL(ins.DUC_REGI, '') <> ISNULL(adi.DUA_RG37, '') THEN 1
					ELSE 0
				END), 
				(CASE 
					WHEN ins.DUC_ANXB IN ('H2', 'H3', 'H6', 'I2') AND del.DUC_ANXB NOT IN ('H2', 'H3', 'H6', 'I2') AND ISNULL(adi.DUA_IAVA, '') <> '' THEN 1 					
					ELSE 0 
				END), 
				(CASE
					WHEN ISNULL(ins.DUC_DIRT, 0) = 0 AND ISNULL(del.DUC_DIRT, 0) <> 0 AND ISNULL(adi.DUA_VDIR, 0) <> 0 THEN 1
					ELSE 0
				END),
				(CASE
					WHEN ISNULL(ins.DUC_FRET, 0) = 0 AND ISNULL(del.DUC_FRET, 0) <> 0 AND ISNULL(adi.DUA_VFRE, 0) <> 0 THEN 1
					WHEN ISNULL(ins.DUC_FRET, 0) > 0 AND ins.DUC_VBAT = 1 AND ((del.DUC_VBAT = 0) OR (ISNULL(ins.DUC_FRET, 0) <> ISNULL(del.DUC_FRET, 0))) THEN 2
					ELSE 0
				END),
				(CASE
					WHEN ISNULL(ins.DUC_SEGU, 0) = 0 AND ISNULL(del.DUC_SEGU, 0) <> 0 AND ISNULL(adi.DUA_VSEG, 0) <> 0 THEN 1
					WHEN ISNULL(ins.DUC_SEGU, 0) > 0 AND ins.DUC_VBAT = 1 AND ((del.DUC_VBAT = 0) OR (ISNULL(ins.DUC_SEGU, 0) <> ISNULL(del.DUC_SEGU, 0))) THEN 2
					ELSE 0
				END), 
				(CASE
					WHEN ISNULL(ins.DUC_VTRN, 0) = 0 AND ISNULL(del.DUC_VTRN, 0) <> 0 AND ISNULL(adi.DUA_VTRA, 0) <> 0 THEN 1
					WHEN ISNULL(ins.DUC_VTRN, 0) > 0 AND ins.DUC_VBAT = 1 AND ((del.DUC_VBAT = 0) OR (ISNULL(ins.DUC_VTRN, 0) <> ISNULL(del.DUC_VTRN, 0))) THEN 2					
					ELSE 0
				END), 
				(CASE					
					WHEN (ins.DUC_ANXB IN ('H2', 'I1', 'I2') AND del.DUC_ANXB NOT IN ('H2', 'I1', 'I2')) OR (ins.DUC_CGLB = 1 AND (ins.DUC_CGLB <> del.DUC_CGLB OR ISNULL(ins.DUC_CAUC, '') <> ISNULL(del.DUC_CAUC, ''))) THEN 1
					WHEN ins.DUC_ANXB NOT IN ('H2', 'I1', 'I2') AND ins.DUC_BIVA <> del.DUC_BIVA THEN 2
					ELSE 0
				END),
				(CASE					
					WHEN (ins.DUC_ANXB IN ('H2', 'I1', 'I2') AND del.DUC_ANXB NOT IN ('H2', 'I1', 'I2')) OR (ins.DUC_CGLB = 1 AND (ins.DUC_CGLB <> del.DUC_CGLB OR ISNULL(ins.DUC_CNIR, '') <> ISNULL(del.DUC_CNIR, ''))) THEN 1
					WHEN ins.DUC_ANXB NOT IN ('H2', 'I1', 'I2') AND ins.DUC_BIVA <> del.DUC_BIVA THEN 2
					ELSE 0
				END), 
				(CASE 
					WHEN (ISNULL(ins.DUC_FR20, '') <> ISNULL(del.DUC_FR20, '')) OR (ISNULL(ins.DUC_TFDA, 0) <> ISNULL(del.DUC_TFDA, 0)) OR (ISNULL(ins.DUC_TXFR, 0) <> ISNULL(del.DUC_TXFR, 0)) OR (ISNULL(ins.DUC_TXSE, 0) <> ISNULL(del.DUC_TXSE, 0)) THEN 1
					ELSE 0
				END), 
				(CASE 
					WHEN ISNULL(ins.DUC_TX23, 0) <> ISNULL(del.DUC_TX23, 0) THEN 1
					ELSE 0
				END), 
				(CASE WHEN (ISNULL(ins.MTR_PT18, '') <> ISNULL(del.MTR_PT18, '')) OR (ISNULL(ins.DUC_OP18, 0) <> ISNULL(del.DUC_OP18, 0)) OR (((ins.DUC_ADI5 <> del.DUC_ADI5) OR (ISNULL(ins.DUC_TVL6, 0) <> ISNULL(del.DUC_TVL6, 0))) AND (mtr.MTR_VPVL = 2)) THEN 1
					ELSE 0
				END)
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DUC_IDTY = del.DUC_IDTY
				INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON ins.TDE_CODI = tde.TDE_CODI
				INNER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON ins.MTR_PT18 = mtr.MTR_CODI
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM										
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdAdicao, @LimpaVendedor, @LimpaComprador, @LimpaContingente, @LimpaMassaLiquida, @AtualizaPreferencia, @AtualizaMetodoAvaliacao, @LimpaPaisPreferencial, 
			@AtualizaAdicionaisNacionais, @AtualizaTipoMercadoria, @LimpaExportador, @LimpaPaisExpedicao, @LimpaNaturezaTransacao, @LimpaPaisDestino, @LimpaRegiao, @AtualizaPaisOrigem, @LimpaNumeroNRUR, 
			@AtualizaAdicionalIVA, @AtualizaRegime, @LimpaIndicadorAvaliacao, @LimpaDireitos, @AtualizaFrete, @AtualizaSeguro, @AtualizaVerbaTransitario, @AtualizaNRG, @AtualizaNIFResponsavel,
			@AtualizaAjustamento, @AtualizaValorEUR, @AtualizaValorOptativas
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			SET @ProcesssaCalculos = REPLICATE('0', 20)
			SET @SQLAExecutar = '' 
			SET @SQLJoinTBL_Desdobramentos = ''
			SET @SQLJoinTAB_PREF = ''
			SET @SQLJoinTAB_CLIE = ''
-- atualiza nas adições os campos de Vendedor quando o anexo B não é "H1" ou vendedor preenchido
			IF @LimpaVendedor = 1			
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'FOR_CODI1 = NULL, FOR_NOME1 = NULL, FOR_MORA1 = NULL, FOR_LOCA1 = NULL, FOR_CPOS1 = NULL, FOR_LPOS1 = NULL, PAI_CODI3 = NULL, FOR_NIF1 = NULL'
			END		
-- atualiza nas adições os campos de Comprador quando o anexo B não é "H1" ou comprador preenchido
			IF @LimpaComprador = 1		
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'CLI_CODI = NULL, CLI_NOME = NULL, CLI_MORA = NULL,	CLI_LOCA = NULL, CLI_CPOS = NULL, CLI_LPOS = NULL, PAI_CODI4 = NULL, CLI_NIF = NULL'
			END	
-- atualiza nas adições o campo de Contingente quando o anexo B não é "H1" ou "I1" 
			IF @LimpaContingente = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_CO39 = NULL'
			END
-- atualiza nas adições o campo de Massa Líquida quando o anexo B é "H2", "H3" ou "I2"
			IF @LimpaMassaLiquida = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_ML38 = 0'				
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI		
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 10, 1, '1') -- DUA_QTDD
			END
-- atualiza nas adições o campo de Preferência quando o anexo B é "H2", "H5" ou "H6"
			IF @AtualizaPreferencia = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'PRE_CO36 = ISNULL(pr0.PRE_CODI, prd.PRE_CODI), PRE_NOME = ISNULL(pr0.PRE_NOME, prd.PRE_NOME), RRE_PREF = rrp.RRE_CODI, RRE_NOME1 = rrp.RRE_NOME, DUA_IMPO = rrp.RRE_IMPO'	
				SET @SQLJoinTAB_PREF = 'LEFT OUTER JOIN TAB_PREF AS pr0 WITH(NOLOCK) ON pr0.PRE_CODI = ''000'' '
				SET @SQLJoinTAB_PREF = @SQLJoinTAB_PREF + 'LEFT OUTER JOIN TAB_PREF AS prd WITH(NOLOCK) ON tde.PRE_CODI = prd.PRE_CODI '
				SET @SQLJoinTAB_PREF = @SQLJoinTAB_PREF + 'LEFT OUTER JOIN TAB_RREC AS rrp WITH(NOLOCK) ON ISNULL(pr0.RRE_CODI, prd.RRE_CODI) = rrp.RRE_CODI'
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 6, 1, '1') -- DUA_TXVL
			END
			ELSE
-- atualiza nas adições o campo de Preferência quando o tipo de declaração alterou
				IF @AtualizaPreferencia = 2
				BEGIN				
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'PRE_CO36 = prd.PRE_CODI, PRE_NOME = prd.PRE_NOME, RRE_PREF = rrp.RRE_CODI, RRE_NOME1 = rrp.RRE_NOME, DUA_IMPO = rrp.RRE_IMPO'	
					SET @SQLJoinTAB_PREF = 'LEFT OUTER JOIN TAB_PREF AS prd WITH(NOLOCK) ON tde.PRE_CODI = prd.PRE_CODI '
					SET @SQLJoinTAB_PREF = @SQLJoinTAB_PREF + 'LEFT OUTER JOIN TAB_RREC AS rrp WITH(NOLOCK) ON prd.RRE_CODI = rrp.RRE_CODI'
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 6, 1, '1') -- DUA_TXVL
				END
-- atualiza nas adições o campo do Método de Avaliação quando o anexo B é "H2", "H6", "I1" ou "I2"
			IF @AtualizaMetodoAvaliacao = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_MAVA = NULL'								
			END
			ELSE
-- atualiza nas adições o campo de Método de Avaliação quando o anexo B não é "H2", "H6", "I1" ou "I2" 
				IF @AtualizaMetodoAvaliacao = 2
				BEGIN
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_MAVA = (CASE DUA_CODI WHEN 1 THEN 1 ELSE (SELECT DUA_MAVA FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI = 1) END)'					
				END
-- atualiza nas adições o campo de País de Origem Preferencial quando o anexo B é "H5", "H6" ou "I2" 
			IF @LimpaPaisPreferencial = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'PAI_CODI5 = NULL'
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 6, 1, '1') -- DUA_TXVL
			END
-- atualiza nas adições os campos de adicional nacional, codigo CUS e unidades quando o anexo B é "H6" ou "I2"
			IF @AtualizaAdicionaisNacionais = 1
			BEGIN		
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '		
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_1TAR = NULL, DUA_2TAR = NULL, DUA_3TAR = NULL, DUA_4TAR = NULL, DUA_5TAR = NULL, APA_CCUS = NULL, DUA_US41 = 0'
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI		
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 6, 1, '1') -- DUA_TXVL	
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 10, 1, '1') -- DUA_QTDD							
			END
			ELSE
-- atualiza nas adições os campos de adicional nacional e codigo CUS quando o anexo B não é "H6" ou "I2"
				IF @AtualizaAdicionaisNacionais = 2
				BEGIN
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_1TAR = apa.APA_AIC1, DUA_2TAR = apa.APA_AIC2, DUA_3TAR = apa.APA_AIC3, DUA_4TAR = apa.APA_AIC4, DUA_5TAR = apa.APA_AIC5, APA_CCUS = apa.APA_CCUS'
					SET @SQLJoinTAB_APAU = 'INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON adi.APA_CO33 = apa.APA_CODI'
				END
				ELSE
-- atualiza nas adições os campos de adicional nacional e codigo CUS quando o anexo B não é "H6" ou "I2" mas está em conversão de DUI2
					IF @AtualizaAdicionaisNacionais = 3
					BEGIN
						IF @SQLAExecutar <> ''
							SET @SQLAExecutar = @SQLAExecutar + ', '
						SET @SQLAExecutar = @SQLAExecutar + 'DUA_4TAR = apa.APA_AIC4, DUA_5TAR = apa.APA_AIC5, APA_CCUS = apa.APA_CCUS'
						SET @SQLJoinTAB_APAU = 'INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON adi.APA_CO33 = apa.APA_CODI'
					END
-- atualiza nas adições o campo de Tipo de Mercadoria quando o anexo B não é "H6" ou "I2" 
			IF @AtualizaTipoMercadoria = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_TMER = NULL'
			END
			ELSE
-- atualiza nas adições o campo de Tipo de Mercadoria quando o anexo B é "H6" ou "I2" 
				IF @AtualizaTipoMercadoria = 2
				BEGIN
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_TMER = apa.APA_TMER'
					SET @SQLJoinTAB_APAU = 'INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON adi.APA_CO33 = apa.APA_CODI'
				END
-- atualiza nas adições os campos de Exportador e País de Expedição quando o anexo B é "H6" ou "I2" ou exportador preenchido
			IF @LimpaExportador = 1		
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'FOR_CODI = NULL, FOR_NOME = NULL, FOR_MORA = NULL,	FOR_LOCA = NULL, FOR_CPOS = NULL, FOR_LPOS = NULL, PAI_CODI = NULL, FOR_NIF = NULL'
			END
-- atualiza nas adições o campo de País de Expedição quando o anexo B é "H6" ou "I2" ou paísd e expedição preenchido
			IF @LimpaPaisExpedicao = 1		
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'PAI_CODI1 = NULL'
			END
-- atualiza nas adições o campo de Natureza de Transação quando o anexo B é "H2", "H6", "I1" ou "I2" ou natureza de transação preenchida
			IF @LimpaNaturezaTransacao = 1			
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'NTR_CODI = NULL'
			END
-- atualiza nas adições o campo de País de Destino quando o anexo B é "H6", "I1" ou "I2" 
			IF @LimpaPaisDestino = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'PAI_CODI2 = NULL'
			END
-- atualiza nas adições o campo de Região quando o anexo B é "H6", "I1" ou "I2" ou despacho não é centralizado
			IF @LimpaRegiao = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'RES_CODI = NULL'
			END
-- atualiza nas adições o campo de País Origem quando o anexo B é "I2"
			IF @AtualizaPaisOrigem = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'PAI_CO34 = NULL, PAI_NOME = NULL'						
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 6, 1, '1') -- DUA_TXVL
			END
			ELSE
-- atualiza nas adições o campo de País Origem quando o anexo B não é "I2" 
				IF @AtualizaPaisOrigem = 2
				BEGIN
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'PAI_CO34 = duc.PAI_PA15, PAI_NOME = duc.PAI_NO15'
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 6, 1, '1') -- DUA_TXVL
				END
-- atualiza nas adições o campo de Número NRUR quando o anexo B é "I2" ou número NRUR preenchido
			IF @LimpaNumeroNRUR = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_NRUR = NULL'
			END
-- atualiza nas adições o campo de adicional IVA quando o regime é "42" ou é beneficiário IVA
			IF @AtualizaAdicionalIVA = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_AIVA = NULL'
			END
			ELSE
-- atualiza nas adições o campo de adicional IVA quando o regime não é "42" e não é beneficiário IVA
				IF @AtualizaAdicionalIVA = 2
				BEGIN
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_AIVA = cli.CLI_AIVA'
					SET @SQLJoinTAB_CLIE = 'INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI'
				END			
-- atualiza nas adições o campo de regime quando o regime é diferente do regime da adição
			IF @AtualizaRegime = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_RG37 = duc.DUC_REGI, id_desdobramento = ddb.id, DUA_R37B = ddb.desdobramento1, DUA_R37C = ddb.desdobramento2'	
				SET @SQLJoinTBL_Desdobramentos = 'LEFT OUTER JOIN tb_TBL_Desdobramentos AS ddb WITH(NOLOCK) ON duc.TDE_1CAS = ddb.tipoDeclaracao AND duc.DUC_REGI = ddb.regime AND tde.TDE_DESD = ddb.desdobramento1 AND ISNULL(ddb.desdobramento2, '''') = '''' AND ISNULL(ddb.desdobramento3, '''') = '''' AND ISNULL(ddb.desdobramento4, '''') = '''' AND ISNULL(ddb.desdobramento5, '''') = '''''
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 8, 1, '1') -- DUA_TIVA
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 6, 1, '1') -- DUA_TXVL
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 9, 1, '1') -- DUA_MAVA
			END
-- atualiza nas adições o campo de Indicador Avaliação quando o anexo B é "H2", "H3", "H6" ou "I2" 
			IF @LimpaIndicadorAvaliacao = 1
			BEGIN
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_IAVA = NULL'
			END
-- atualiza nas adições o campo de Direitos quando não há direitos DDP
			IF @LimpaDireitos = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_VDIR = 0'				
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 1, 1, '1') -- DUA_AJUS
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 3, 1, '1') -- DUA_VEST
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 4, 1, '1') -- DUA_VATO
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI
			END
-- atualiza nas adições o campo de Frete quando não há valor de frete
			IF @AtualizaFrete = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_VFRE = 0'				
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 1, 1, '1') -- DUA_AJUS
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 3, 1, '1') -- DUA_VEST
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 4, 1, '1') -- DUA_VATO
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI
			END
			ELSE
				IF @AtualizaFrete = 2
				BEGIN				
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_VFRE = ROUND((CASE WHEN (duc.DUC_ADI5 > 1) AND (adi.DUA_CODI = duc.DUC_ADI5) THEN (duc.DUC_FRET - (SELECT SUM(DUA_VFRE) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI <> adi.DUA_CODI)) ELSE (adi.DUA_MB35 * duc.DUC_FRET / duc.DUC_MBRT) END), 3)'				
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 1, 1, '1') -- DUA_AJUS
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 3, 1, '1') -- DUA_VEST
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 4, 1, '1') -- DUA_VATO
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI
				END
-- atualiza nas adições o campo de Seguro quando não há valor de seguro
			IF @AtualizaSeguro = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_VSEG = 0'				
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 1, 1, '1') -- DUA_AJUS
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 3, 1, '1') -- DUA_VEST
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 4, 1, '1') -- DUA_VATO
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI
			END
			ELSE
				IF @AtualizaSeguro = 2
				BEGIN				
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_VSEG = ROUND((CASE WHEN (duc.DUC_ADI5 > 1) AND (adi.DUA_CODI = duc.DUC_ADI5) THEN (duc.DUC_SEGU - (SELECT SUM(DUA_VSEG) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI <> adi.DUA_CODI)) ELSE (adi.DUA_VA42 * duc.DUC_SEGU / duc.DUC_MT22) END), 3)'				
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 1, 1, '1') -- DUA_AJUS
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 3, 1, '1') -- DUA_VEST
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 4, 1, '1') -- DUA_VATO
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI
				END
-- atualiza nas adições o campo de Verba Transitário quando não há valor de verba transitário
			IF @AtualizaVerbaTransitario = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_VTRA = 0'				
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 20, 1, '1')
			END
			ELSE
				IF @AtualizaVerbaTransitario = 2
				BEGIN				
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_VTRA = ROUND((CASE WHEN (duc.DUC_ADI5 > 1) AND (adi.DUA_CODI = duc.DUC_ADI5) THEN (duc.DUC_VTRN - (SELECT SUM(DUA_VTRA) FROM PRO_DUAD WITH(NOLOCK) WHERE DUC_EANO = adi.DUC_EANO AND DUC_PNUM = adi.DUC_PNUM AND DUA_CODI <> adi.DUA_CODI)) ELSE (adi.DUA_MB35 * duc.DUC_VTRN / duc.DUC_MBRT) END), 2)'				
					SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 20, 1, '1')
				END
-- atualiza nas adições o campo de NRG quando não há NRG definido
			IF @AtualizaNRG = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_CAUC = duc.DUC_CAUC, DUA_CANO = duc.DUC_CANO, DUA_CTIP = duc.DUC_CTIP, DUA_CENT = duc.DUC_CENT, '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_CAUD = duc.DUC_CAUC, DUA_CAND = duc.DUC_CANO, DUA_CTID = duc.DUC_CTIP, DUA_CEND = duc.DUC_CENT, ALF_CODI = duc.ALF_CODI2, DUA_CCAD = duc.DUC_CCAC, DUA_CORD = duc.DUC_CORF, '
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_CAUI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CAUC ELSE NULL END), DUA_CANI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CANO ELSE NULL END), DUA_CTII = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CTIP ELSE NULL END), DUA_CENI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CENT ELSE NULL END), ALF_CODI1 = (CASE duc.DUC_BIVA WHEN 0 THEN duc.ALF_CODI2 ELSE NULL END), DUA_CCAI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CCAC ELSE NULL END), DUA_CORI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CORF ELSE NULL END)'
			END
			ELSE
				IF @AtualizaNRG = 2
				BEGIN				
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '						
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_CAUI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CAUC ELSE NULL END), DUA_CANI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CANO ELSE NULL END), DUA_CTII = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CTIP ELSE NULL END), DUA_CENI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CENT ELSE NULL END), ALF_CODI1 = (CASE duc.DUC_BIVA WHEN 0 THEN duc.ALF_CODI2 ELSE NULL END), DUA_CCAI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CCAC ELSE NULL END), DUA_CORI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CORF ELSE NULL END)'
				END
-- atualiza nas adições o campo de NIF Responsável Garantia quando não há NIF reponsável garantia definido
			IF @AtualizaNIFResponsavel = 1
			BEGIN				
				IF @SQLAExecutar <> ''
					SET @SQLAExecutar = @SQLAExecutar + ', '					
				SET @SQLAExecutar = @SQLAExecutar + 'DUA_CNRD = duc.DUC_CNIR, DUA_CNRI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CNIR ELSE NULL END)'
			END
			ELSE
				IF @AtualizaNIFResponsavel = 2
				BEGIN				
					IF @SQLAExecutar <> ''
						SET @SQLAExecutar = @SQLAExecutar + ', '						
					SET @SQLAExecutar = @SQLAExecutar + 'DUA_CNRI = (CASE duc.DUC_BIVA WHEN 0 THEN duc.DUC_CNIR ELSE NULL END)'
				END
-- atualiza nas adições o campo de ajustamento quando a formula ou a taxa FDA foram alteradas
			IF @AtualizaAjustamento = 1
			BEGIN
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 1, 1, '1') -- DUA_AJUS
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 3, 1, '1') -- DUA_VEST
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 4, 1, '1') -- DUA_VATO
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI
			END
-- atualiza nas adições o campo de valor EUR quando a taxa de câmbio foi alterada
			IF @AtualizaValorEUR = 1
			BEGIN
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 2, 1, '1') -- DUA_VAEU
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 3, 1, '1') -- DUA_VEST
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 4, 1, '1') -- DUA_VATO
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 5, 1, '1') -- DUA_BTRI
			END
-- atualiza nas adições o campo de valor optativas quando o meio de transporte, total adições, total volumes, total massa bruta, valor aduaneiro total ou total optativas alterados
			IF @AtualizaValorOptativas = 1
				SET @ProcesssaCalculos = STUFF(@ProcesssaCalculos, 7, 1, '1') -- DUA_VOPT
-- processa a atualização dos campos na adição
			IF @SQLAExecutar <> ''
			BEGIN
				SET @SQLAExecutar = 'UPDATE PRO_DUAD SET ' + @SQLAExecutar + ' '
				SET @SQLAExecutar = @SQLAExecutar + 'FROM PRO_DUAD AS adi WITH(NOLOCK) '
				SET @SQLAExecutar = @SQLAExecutar + 'INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM '
				SET @SQLAExecutar = @SQLAExecutar + 'INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON duc.TDE_CODI = tde.TDE_CODI '
				IF @SQLJoinTBL_Desdobramentos <> ''
					SET @SQLAExecutar = @SQLAExecutar + @SQLJoinTBL_Desdobramentos + ' '				
				IF @SQLJoinTAB_PREF <> ''
					SET @SQLAExecutar = @SQLAExecutar + @SQLJoinTAB_PREF + ' '
				IF @SQLJoinTAB_CLIE <> ''
					SET @SQLAExecutar = @SQLAExecutar + @SQLJoinTAB_CLIE + ' '
				IF @SQLJoinTAB_APAU <> ''
					SET @SQLAExecutar = @SQLAExecutar + @SQLJoinTAB_APAU + ' '								
				SET @SQLAExecutar = @SQLAExecutar + 'WHERE adi.DUA_IDEN = ' + CAST(@IdAdicao AS varchar(10))
				EXEC (@SQLAExecutar)
			END
-- atualiza a atualização dos campos de valores da tributação de direitos e IVA na adição
			IF @ProcesssaCalculos <> REPLICATE('0', 20)
			BEGIN				
				UPDATE PRO_DUAD SET 										
					@Ajustamento = DUA_AJUS = (CASE 
												WHEN SUBSTRING(@ProcesssaCalculos, 1, 1) = '1' THEN dbo.fn_IMP_CalculaAjustamento(ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0), ISNULL(duc.DUC_TxSE, 0), adi.DUA_VFRE, adi.DUA_VSEG, adi.DUA_VDIR, adi.DUA_ACRE, adi.DUA_DEDU)
												ELSE adi.DUA_AJUS
											END),
					@ValorEUR = DUA_VAEU = (CASE 
												WHEN SUBSTRING(@ProcesssaCalculos, 2, 1) = '1' THEN ROUND(adi.DUA_VA42 / ISNULL(duc.DUC_TX23, 0), 2)
												ELSE adi.DUA_VAEU
											END), 
					@ValorEstatistico = DUA_VEST = (CASE 
														WHEN SUBSTRING(@ProcesssaCalculos, 3, 1) = '1' THEN dbo.fn_IMP_CalculaValorEstatistico(@ValorEUR, @Ajustamento)
														ELSE adi.DUA_VEST
													END),
					@ValorAduaneiro = DUA_VATO = (CASE 
													WHEN SUBSTRING(@ProcesssaCalculos, 4, 1) = '1' THEN @ValorEstatistico
													ELSE adi.DUA_VATO
												END),
					@BaseTributacaoDireitos = DUA_BTRI = (CASE 
															WHEN SUBSTRING(@ProcesssaCalculos, 5, 1) = '1' THEN dbo.fn_IMP_CalculaBaseTributacaoDireitos(adi.DUA_BMAN, adi.DUA_BTRI, adi.DUA_TRIB, adi.DUA_ML38, adi.DUA_US41, @ValorEstatistico, adi.UME_CODI) 
															ELSE adi.DUA_BTRI 
														END), 
					@TaxaValorDireitos = DUA_TXVL = (CASE 
														WHEN SUBSTRING(@ProcesssaCalculos, 6, 1) = '1' THEN dbo.fn_IMP_CalculaTaxaValorDireitos(@DataAtual, adi.APA_CO33, adi.PAI_CO34, adi.PAI_CODI5, pre.PRE_TAXA, adi.DUA_US41, adi.DUA_RG37, adi.DUA_R37B) 
														ELSE adi.DUA_TXVL 
													END), 					
					@MontanteDireitos = DUA_MTRI = dbo.fn_IMP_CalculaMontanteDireitos(adi.DUA_BMAN, adi.DUA_MTRI, (CASE adi.DUA_TXCO WHEN 1 THEN 0 ELSE 1 END), @TaxaValorDireitos, @BaseTributacaoDireitos),
					@Optativas = DUA_VOPT = (CASE 
												WHEN SUBSTRING(@ProcesssaCalculos, 7, 1) = '1' THEN dbo.fn_IMP_CalculaValorOptativas(adi.DUC_EANO, adi.DUC_PNUM, adi.DUA_CODI, duc.MTR_PT18, duc.DUC_ADI5, ISNULL(duc.DUC_TVL6, 0), ISNULL(duc.DUC_OP18, 0), ISNULL(duc.DUC_MBRT, 0), ISNULL(duc.DUC_VATT, 0), adi.DUA_MB35, @ValorAduaneiro)
												ELSE adi.DUA_VOPT
											END), 
					@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0), adi.DUA_VFRE, @Ajustamento, @ValorEstatistico, adi.DUA_VTRA, @Optativas, @MontanteDireitos, adi.DUA_IVAV, adi.DUA_ABTI, adi.DUA_MIVI), 
					@TaxaIVA = DUA_TIVA = (CASE 
											WHEN SUBSTRING(@ProcesssaCalculos, 8, 1) = '1' THEN (CASE 
																				WHEN (LEFT(ISNULL(adi.DUA_RG37, ''), 2) IN ('42', '51', '53', '71')) OR (ISNULL(adi.DUA_R37B, '') = '4II') OR (ISNULL(adi.DUA_R37B, '') = 'C01') OR (ISNULL(adi.DUA_R37B, '') = 'F48') OR (ISNUMERIC(adi.DUA_R37B) = 1 AND CAST(adi.DUA_R37B AS int) >= 401 AND CAST(adi.DUA_R37B AS int) <= 459) THEN 0 
																				WHEN (ISNULL(adi.DUA_RG37, '') = '6123') AND (ISNULL(adi.DUA_R37B, '') = 'F01') THEN 0 
																				ELSE ISNULL(apa.APA_TIVA, 0) 
																			END)
											ELSE adi.DUA_TIVA
										END), 
					DUA_VIVA = ROUND(@BaseTributacaoIVA * @TaxaIVA / 100, 2), 
					DUA_MAVA = (CASE 
									WHEN SUBSTRING(@ProcesssaCalculos, 9, 1) = '1' THEN (CASE 
																		WHEN adi.DUA_R37B IN ('E01', 'E02') THEN NULL 
																		ELSE adi.DUA_MAVA 
																	END) 				
									ELSE adi.DUA_MAVA 
								END), 
					DUA_QTDD = (CASE 
									WHEN SUBSTRING(@ProcesssaCalculos, 10, 1) = '1' THEN dbo.fn_IMP_CalculaBaseTributacaoDireitos(0, 0, adi.DUA_TRIB, adi.DUA_ML38, adi.DUA_US41, 0, adi.UME_CODI) 
									ELSE adi.DUA_QTDD 
								END)
				FROM PRO_DUAD AS adi WITH(NOLOCK) 
					INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
					INNER JOIN TAB_PREF AS pre WITH(NOLOCK) ON adi.PRE_CO36 = pre.PRE_CODI
					INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON adi.APA_CO33 = apa.APA_CODI
				WHERE adi.DUA_IDEN = @IdAdicao																	
-- processa atualização extra na adição para os campos da rúbrica de receita do IVA, apenas no caso de ter havido alteração da Taxa IVA																						
				IF SUBSTRING(@ProcesssaCalculos, 8, 1) = '1'
				BEGIN
					UPDATE PRO_DUAD SET 
						RRE_CODI = rre.RRE_CODI,
						RRE_NOME = rre.RRE_NOME,
						DUA_IMPI = rre.RRE_IMPO
					FROM PRO_DUAD AS adi WITH(NOLOCK) 
						INNER JOIN (SELECT PAP_TXIS, RRE_CDIS FROM TAB_PAPL WITH(NOLOCK) UNION SELECT PAP_TXRD, RRE_CDRD FROM TAB_PAPL WITH(NOLOCK) UNION SELECT PAP_TXIN, RRE_CDIN FROM TAB_PAPL WITH(NOLOCK) UNION SELECT PAP_TXNR, RRE_CDNR FROM TAB_PAPL WITH(NOLOCK)) AS t ON adi.DUA_TIVA = t.PAP_TXIS
						INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON t.RRE_CDIS = rre.RRE_CODI
					WHERE adi.DUA_IDEN = @IdAdicao
				END
			END
			FETCH NEXT FROM Declaracoes INTO @IdAdicao, @LimpaVendedor, @LimpaComprador, @LimpaContingente, @LimpaMassaLiquida, @AtualizaPreferencia, @AtualizaMetodoAvaliacao, @LimpaPaisPreferencial, 
				@AtualizaAdicionaisNacionais, @AtualizaTipoMercadoria, @LimpaExportador, @LimpaPaisExpedicao, @LimpaNaturezaTransacao, @LimpaPaisDestino, @LimpaRegiao, @AtualizaPaisOrigem, @LimpaNumeroNRUR, 
				@AtualizaAdicionalIVA, @AtualizaRegime, @LimpaIndicadorAvaliacao, @LimpaDireitos, @AtualizaFrete, @AtualizaSeguro, @AtualizaVerbaTransitario, @AtualizaNRG, @AtualizaNIFResponsavel, 
				@AtualizaAjustamento, @AtualizaValorEUR, @AtualizaValorOptativas
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- se coluna do anexo B alterada, processa remoções dos sub-detalhes de referências fiscais de todas as adições das declarações IMP-CAU alteradas
	IF UPDATE(DUC_ANXB)
	BEGIN
-- obtem as adições IMP-CAU que não satisfaçam as condições p/ ter referências fiscais
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUA_IDEN, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM										
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL				
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB NOT IN ('H1', 'H6', 'I1') 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdAdicao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nas referências fiscais o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesAdicoesReferenciasFiscais SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_adicao = @IdAdicao
-- remove as referências fiscais da adição
			DELETE FROM tb_IMP_DeclaracoesAdicoesReferenciasFiscais
			WHERE id_adicao = @IdAdicao
			FETCH NEXT FROM Declaracoes INTO @IdAdicao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- se coluna do anexo B alterada, processa remoções dos sub-detalhes de entrepostos de todas as adições das declarações IMP-CAU alteradas
	IF UPDATE(DUC_ANXB)
	BEGIN
-- obtem as adições IMP-CAU que não satisfaçam as condições p/ ter entrepostos
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUA_IDEN, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM										
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL				
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB NOT IN ('H1', 'H2', 'H3', 'H4') 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdAdicao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nos entrepostos o utilizador e data de controlo antes de remover
			UPDATE tb_IMP_DeclaracoesAdicoesEntrepostos SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_adicao = @IdAdicao
-- remove os entrepostos da adição
			DELETE FROM tb_IMP_DeclaracoesAdicoesEntrepostos
			WHERE id_adicao = @IdAdicao
			FETCH NEXT FROM Declaracoes INTO @IdAdicao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- se coluna do anexo B alterada, processa remoções dos sub-detalhes de veículos de todas as adições das declarações IMP-CAU alteradas
	IF UPDATE(DUC_ANXB)
	BEGIN
-- obtem as adições IMP-CAU que não satisfaçam as condições p/ ter veículos
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUC_EANO, adi.DUC_PNUM, adi.DUA_CODI
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM				
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB = 'H6' 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove os veículos da adição
			DELETE FROM PRO_DUBT
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- se coluna do anexo B alterada, processa alterações dos sub-detalhes de marcas e volumes de todas as adições das declarações IMP-CAU alteradas
	IF UPDATE(DUC_ANXB)
	BEGIN
-- obtem as marcas e volumes das adições IMP-CAU que não satisfaçam as condições p/ ter os campos de tipo de volumes e marcas preenchidos
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT mvl.D31_IDEN
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM				
				INNER JOIN PRO_DU31 AS mvl WITH(NOLOCK) ON adi.DUC_EANO = mvl.DUC_EANO AND adi.DUC_PNUM = mvl.DUC_PNUM AND adi.DUA_CODI = mvl.DUA_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ins.DUC_ANXB = 'H6' 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza nas marcas e volumes os campos de marcas e tipo de volumes
			UPDATE PRO_DU31 SET 
				D31_MARC = NULL,
				UME_CODI = NULL,
				UME_NOME = NULL,
				D31_TTVL = 0				
			WHERE D31_IDEN = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- se coluna do cliente importador alterada, processa remoções dos sub-detalhes de documentos "C601" ou pedidos "G1RED" de todas as adições das declarações IMP-CAU alteradas
	IF UPDATE(DUC_DST8)
	BEGIN
-- obtem as adições IMP-CAU dos regimes "0151" ou "0153" e cujo cliente importador tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, adi.DUA_CODI, doc.DOC_CODI, doc.DOC_NOME, cau.CAU_NDOC, dad.DDO_IDEN
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM		
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C601'
				INNER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON adi.DUC_EANO = dad.DUC_EANO AND adi.DUC_PNUM = dad.DUC_PNUM AND adi.DUA_CODI = dad.DUA_CODI AND doc.DOC_CODI = dad.DOC_CODI AND dad.DDO_AUTO = 12
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ISNULL(adi.DUA_RG37, '') IN ('0151', '0153') AND doc.DOC_DESP = 1 AND doc.DOC_TRAN = 0 AND LEN(doc.DOC_CODI) <= 4
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
				SELECT @NumDocumento = ISNULL(MAX(DDO_CODI), 0) + 1
				FROM PRO_DDOC
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento "C601" como "Documento Suporte" no detalhe de documentos da adição IMP-CAU
				INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_AUTO, DDO_TIPO)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumDocumento, @CodDocumento, @NomeDocumento, @NumeroDocumento, 12, 0)			
			END
			ELSE
			BEGIN
				UPDATE PRO_DDOC SET DDO_NUME = @NumeroDocumento
				WHERE DDO_IDEN = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos "C601" das adições IMP-CAU com regime "0151" ou "0153" e cliente importador tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.DUC_EANO, dad.DUC_PNUM, dad.DUA_CODI, dad.DDO_IDEN
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM		
				INNER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON adi.DUC_EANO = dad.DUC_EANO AND adi.DUC_PNUM = dad.DUC_PNUM AND adi.DUA_CODI = dad.DUA_CODI AND dad.DDO_AUTO = 12
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI	
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ISNULL(adi.DUA_RG37, '') NOT IN ('0151', '0153') OR doc.DOC_DESP = 0 OR doc.DOC_TRAN = 1 OR LEN(doc.DOC_CODI) > 4 OR doc.DOC_IDTY IS NULL OR cau.CAU_IDEN IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove documento					
			DELETE FROM PRO_DDOC
			WHERE DDO_IDEN = @IdRegisto
-- atualiza numero de documentos posteriores
			UPDATE PRO_DDOC SET DDO_CODI = DDO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DDO_IDEN > @IdRegisto 
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem as adições IMP-CAU dos regimes "0151" ou "0153" e cujo cliente importador não tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, NULLIF(SUBSTRING(tdp.TXM_TEXT, 1, 512), '')
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM		
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL						
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1RED'
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C601'
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 22
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND ISNULL(adi.DUA_RG37, '') IN ('0151', '0153') AND cau.CAU_IDEN IS NULL AND dap.id IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere o pedido "G1RED" no detalhe de pedidos da adição IMP-CAU
			INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 22, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
-- obtem os pedidos "G1RED" das adições IMP-CAU com regime "0151" ou "0153" e cliente importador não tenha uma autorização com o documento "C601" definida
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.DUC_UALT, ins.DUC_UCRI) = uti.UTI_UTIL	
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 22
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C601'
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.DUC_DST8 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
			WHERE ins.DUC_DUNO = 2 AND ins.DUC_SERV = 0 AND (ISNULL(adi.DUA_RG37, '') NOT IN ('0151', '0153') OR cau.CAU_IDEN IS NOT NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
	END	
END

ALTER TABLE [dbo].[PRO_DUCG] ENABLE TRIGGER [TAU_PRO_DUCG_IMPCAU]
/****** Object:  Trigger [TAD_PRO_DUET_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUET_IMPCAU] ON [PRO_DUET] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @IdRegisto int
-- obtem as outras imposições associadas aos elementos p/ tributação removidos pertencentes a declarações IMP-CAU
	DECLARE ElementosTrib CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT doi.DUC_EANO, doi.DUC_PNUM, doi.DUA_CODI, doi.DUO_IDEN
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
			INNER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON del.DUC_EANO = doi.DUC_EANO AND del.DUC_PNUM = doi.DUC_PNUM AND del.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 3 AND doi.DET_IDST = del.DET_IDST
		WHERE duc.DUC_DUNO = 2		
	OPEN ElementosTrib
	FETCH NEXT FROM ElementosTrib INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove imposição					
		DELETE FROM PRO_DUOI
		WHERE DUO_IDEN = @IdRegisto
-- atualiza numero de imposições posteriores
		UPDATE PRO_DUOI SET DUO_CODI = DUO_CODI - 1    
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DUO_IDEN > @IdRegisto 
		FETCH NEXT FROM ElementosTrib INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	END
	CLOSE ElementosTrib
	DEALLOCATE ElementosTrib
END

ALTER TABLE [dbo].[PRO_DUET] ENABLE TRIGGER [TAD_PRO_DUET_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUET_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE TRIGGER [TAIU_PRO_DUET_IMPCAU] ON [PRO_DUET] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdRegisto bigint, @NumProxRegisto int, @Montante numeric(38, 6)
	DECLARE @IdAdicao int, @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @CodUnidadeMedida varchar(3), @Quantidade numeric(38, 6), @ETaxa bit, @TaxaValor numeric(38, 6), 
		@IdStrRegisto varchar(20), @NumeroCaucao varchar(24), @AnoCaucao varchar(4), @TipoCaucao varchar(1), @EntidadeCaucao int, @CodAlfandegaCaucao varchar(8), @CodAcessoCaucao varchar(4), 
		@OutrasReferenciasCaucao varchar(35), @NIFResponsavelCaucao varchar(17)
	DECLARE @CodRubricaReceita int, @NomeRubricaReceita varchar(35), @IVARubricaReceita bit, @ImposicaoRubricaReceita varchar(3)
-- se colunas de unidade medida, quantidade, rúbrica de receita, imposição, taxa? ou taxa/valor alteradas, processa a gestão das imposições associadas aos elementos p/ tributação inseridos/alterados nas adições IMP-CAU 
	IF UPDATE(UME_CODI) OR UPDATE(DET_QTDE) OR UPDATE(RRE_CODI) OR UPDATE(RRE_NOME) OR UPDATE(DET_IMPO) OR UPDATE(DET_TAXA) OR UPDATE(DET_TXVL) 
	BEGIN
-- insere/edita a imposição de elementos p/ tributação no detalhe de outras imposições das adições IMP-CAU 
		DECLARE ElementosTrib CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.UME_CODI, ins.DET_QTDE, ins.RRE_CODI, ins.RRE_NOME, ins.DET_IMPO, ins.DET_TAXA, ins.DET_TXVL, ins.DET_IDST, adi.DUA_CAUD, 
				adi.DUA_CAND, adi.DUA_CTID, adi.DUA_CEND, adi.ALF_CODI, adi.DUA_CCAD, adi.DUA_CORD, adi.DUA_CNRD, rre.RRE_IVA, doi.DUO_IDEN, 
				dbo.fn_IMP_CalculaMontanteDireitos(0, 0, ins.DET_TAXA, ins.DET_TXVL, ins.DET_QTDE)
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM		
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI 
				INNER JOIN TAB_RREC AS rre WITH(NOLOCK) ON ins.RRE_CODI = rre.RRE_CODI	
				LEFT OUTER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 3 AND ins.DET_IDST = doi.DET_IDST								
			WHERE duc.DUC_DUNO = 2 AND ins.RRE_CODI IS NOT NULL
		OPEN ElementosTrib
		FETCH NEXT FROM ElementosTrib INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @Quantidade, @CodRubricaReceita, @NomeRubricaReceita, @ImposicaoRubricaReceita, @ETaxa, 
			@TaxaValor, @IdStrRegisto, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, 
			@IVARubricaReceita, @IdRegisto, @Montante
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
-- obtem o próximo numero de registo de outras imposições da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(DUO_CODI), 0) + 1
				FROM PRO_DUOI
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere a imposição no detalhe de outras imposições da adição IMP-CAU
				INSERT INTO PRO_DUOI(DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, RRE_NOME, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_LIVA, DUO_IMPO, DUO_AUTO, DUO_BMAN, 
					DUO_CAUC, DUO_CANO, DUO_CTIP, DUO_CENT, ALF_CODI, DUO_CCAC, DUO_CORF, DUO_CNRD, DET_IDST, DUO_QTDE)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodRubricaReceita, @NomeRubricaReceita, @ETaxa, @CodUnidadeMedida, @Quantidade, @TaxaValor, @Montante, 
					@IVARubricaReceita, @ImposicaoRubricaReceita, 3, 0, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, 
					@NIFResponsavelCaucao, @IdStrRegisto, @Quantidade)
			END
			ELSE
			BEGIN
				UPDATE PRO_DUOI SET
					RRE_CODI = @CodRubricaReceita, 
					RRE_NOME = @NomeRubricaReceita, 
					DUO_TIPO = @ETaxa, 
					UME_CODI = @CodUnidadeMedida, 
					DUO_BTRI = @Quantidade, 
					DUO_TXVL = @TaxaValor, 
					DUO_MONT = @Montante, 
					RRE_LIVA = @IVARubricaReceita, 
					DUO_IMPO = @ImposicaoRubricaReceita, 										
					DUO_CAUC = @NumeroCaucao, 
					DUO_CANO = @AnoCaucao, 
					DUO_CTIP = @TipoCaucao, 
					DUO_CENT = @EntidadeCaucao, 
					ALF_CODI = @CodAlfandegaCaucao, 
					DUO_CCAC = @CodAcessoCaucao, 
					DUO_CORF = @OutrasReferenciasCaucao, 
					DUO_CNRD = @NIFResponsavelCaucao,
					DUO_QTDE = @Quantidade
				WHERE DUO_IDEN = @IdRegisto
			END
			FETCH NEXT FROM ElementosTrib INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @Quantidade, @CodRubricaReceita, @NomeRubricaReceita, @ImposicaoRubricaReceita, 
				@ETaxa, @TaxaValor, @IdStrRegisto, @NumeroCaucao, @AnoCaucao, @TipoCaucao, @EntidadeCaucao, @CodAlfandegaCaucao, @CodAcessoCaucao, @OutrasReferenciasCaucao, @NIFResponsavelCaucao, 
				@IVARubricaReceita, @IdRegisto, @Montante
		END
		CLOSE ElementosTrib
		DEALLOCATE ElementosTrib
-- remove a imposição de elementos p/ tributação existente no detalhe de outras imposições das adições IMP-CAU mas já não existente nas rúbricas de receita
		DECLARE ElementosTrib CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT doi.DUC_EANO, doi.DUC_PNUM, doi.DUA_CODI, doi.DUO_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DET_IDEN = del.DET_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUOI AS doi WITH(NOLOCK) ON ins.DUC_EANO = doi.DUC_EANO AND ins.DUC_PNUM = doi.DUC_PNUM AND ins.DUA_CODI = doi.DUA_CODI AND doi.DUO_AUTO = 3 AND ins.DET_IDST = doi.DET_IDST				
			WHERE duc.DUC_DUNO = 2 AND ins.RRE_CODI IS NULL				
		OPEN ElementosTrib
		FETCH NEXT FROM ElementosTrib INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove imposição					
			DELETE FROM PRO_DUOI
			WHERE DUO_IDEN = @IdRegisto
-- atualiza numero de imposições posteriores
			UPDATE PRO_DUOI SET DUO_CODI = DUO_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DUO_IDEN > @IdRegisto 
			FETCH NEXT FROM ElementosTrib INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE ElementosTrib
		DEALLOCATE ElementosTrib			
	END
END

ALTER TABLE [dbo].[PRO_DUET] ENABLE TRIGGER [TAIU_PRO_DUET_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUIN]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUIN] ON [PRO_DUIN] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaracao de variaveis 
	DECLARE @NumDeclaracao int, @AnoDeclaracao int, @CodNatureza varchar(3), @CodTipoDocConta varchar(4), @Utilizador varchar(30), @CodCliente varchar(18), @NumMascaras int, 
		@TipoMascara int, @CodMascara int, @Observacoes varchar(5000), @ValorLiqRecapitulativa numeric(38, 6), @NumDocTransporte varchar(18), @TipoCliente varchar(3)
-- verifica se campo de "Código Incidência" foi alterado e campo de "Faturação Automática Ativa" selecionado nos Par. Faturação Automática
	IF (UPDATE(SIN_CODI)) and (EXISTS(SELECT FTA_IDEN FROM TAB_PFTA WITH(NOLOCK) WHERE FTA_ACTI = 1))
    BEGIN   
-- obtem declarações c/ campo "Aut. Saída" não seleccionado das incidências c/ código "A13" alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT duc.DUC_PNUM, duc.DUC_EANO, duc.NDE_CODI, duc.DUC_DST8, duc.DUC_CPRT, duc.DUC_UALT, ISNULL(duc.DUC_VLRC, 0), 
				(CASE ISNULL(nat.NDE_TLCV, -1) WHEN 0 THEN duc.TDO_DOCU ELSE (SELECT PDE_TDOC FROM TAB_PDES WITH(NOLOCK)) END), 
				(CASE WHEN (SELECT PDE_IDCV FROM TAB_PDES WITH(NOLOCK)) = 0 THEN NULL WHEN duc.DUC_DTYP IN ('A5' , 'A6') THEN 'ACC' WHEN duc.DUC_DTYP = 'CA' THEN 'COD' WHEN duc.DUC_DTYP IN ('D5', 'D6') THEN 'EXB' ELSE NULL END)
			FROM inserted AS dui INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON dui.DUC_EANO = duc.DUC_EANO AND dui.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON duc.DUC_DST8 = cli.CLI_CODI
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON duc.NDE_CODI = nat.NDE_CODI
			WHERE dui.SIN_CODI IN ('A13', 'ND') AND duc.DUC_ASAI = 0 and duc.DUC_TSHI < 2 AND cli.CLI_DUCT = 1 AND nat.NDE_CRCO = 1 and ISNULL(nat.NDE_TLCV, 0) <> 1 
				AND (CASE (SELECT FTA_DUVR FROM TAB_PFTA WITH(NOLOCK)) WHEN 1 THEN (CASE WHEN ISNULL(duc.DUC_NVRF, '') <> '' THEN 1 ELSE 0 END) WHEN 2 THEN (CASE WHEN ISNULL(duc.DUC_NVRF, '') = '' THEN 1 ELSE 0 END) ELSE 1 END) = 1
				AND (SELECT COUNT(*) FROM FAC_CDOC WITH(NOLOCK) WHERE CDO_IMEX = 0 and CDO_PANO = duc.DUC_EANO and CDO_NPRO = duc.DUC_PNUM) = 0
				AND (SELECT COUNT(*) FROM FAC_DVEN WITH(NOLOCK) WHERE DVE_IMEX = 0 and DVE_PANO = duc.DUC_EANO and DVE_NPRO = duc.DUC_PNUM) = 0
				AND (CASE WHEN ISNULL(nat.NDE_TLCV, -1) = 0 AND ISNULL(duc.TDO_DOCU, '') = '' THEN 0 ELSE 1 END) = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @NumDeclaracao, @AnoDeclaracao, @CodNatureza, @CodCliente, @NumDocTransporte, @Utilizador, @ValorLiqRecapitulativa, @CodTipoDocConta, @TipoCliente
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem a máscara para a Conta
			SET @TipoMascara = 0
			SET @CodMascara = 0
			EXEC SP_ObtemMascaraFacturacao @CodCliente, @CodNatureza, @NumMascaras OUTPUT, @TipoMascara OUTPUT, @CodMascara OUTPUT
-- atualiza na declaração a máscara obtida p/ o documento de Conta
			UPDATE PRO_DUCG SET DUC_TMSF = @TipoMascara, DUC_MASC = @CodMascara
			WHERE DUC_PNUM = @NumDeclaracao AND DUC_EANO = @AnoDeclaracao
-- obtem as observações para a Conta
			EXEC SP_ObtemObservacoesParaConta @CodMascara, @AnoDeclaracao, @NumDeclaracao, @CodCliente, @CodNatureza, '', @Observacoes OUTPUT
-- processa a geração do documento de Conta
			EXEC SP_geraContas @NumDeclaracao, @AnoDeclaracao, @CodTipoDocConta, @CodNatureza, @Utilizador, @TipoMascara, @CodMascara, 0, @Observacoes, @ValorLiqRecapitulativa, @NumDocTransporte, 0, @TipoCliente, 1
			FETCH NEXT FROM Declaracoes INTO @NumDeclaracao, @AnoDeclaracao, @CodNatureza, @CodCliente, @NumDocTransporte, @Utilizador, @ValorLiqRecapitulativa, @CodTipoDocConta, @TipoCliente
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes    
    END
END

ALTER TABLE [dbo].[PRO_DUIN] ENABLE TRIGGER [TAIU_PRO_DUIN]
/****** Object:  Trigger [TAIU_PRO_DUIN_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUIN_IMPCAU] ON [PRO_DUIN] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @CodNatureza varchar(3), @NomeNatureza varchar(35)
-- atualiza a natureza da declaração IMP-CAU se status de incidência/cosmo code assim estiver configurado
	IF UPDATE(SIN_CODI)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, 
				ISNULL(NULLIF(inc.NDE_CODI, ''), (CASE RIGHT(duc.ALF_CODI, 3) WHEN '015' THEN csc.NDE_CODI WHEN '020' THEN csc.NDE_CDPO ELSE NULL END))				
			FROM inserted AS ins 				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON ins.SIN_CODI = inc.SIN_CODI				
				LEFT OUTER JOIN TAB_COSM AS csc WITH(NOLOCK) ON ins.SIN_CODI = csc.COS_CODE				
			WHERE duc.DUC_DUNO = 2 AND ISNULL(inc.SIN_ANAT, csc.COS_ANAT) = 1 
				AND ISNULL(ISNULL(NULLIF(inc.NDE_CODI, ''), (CASE RIGHT(duc.ALF_CODI, 3) WHEN '015' THEN csc.NDE_CODI WHEN '020' THEN csc.NDE_CDPO ELSE NULL END)), '') <> ''
				AND duc.NDE_CODI <> ISNULL(NULLIF(inc.NDE_CODI, ''), (CASE RIGHT(duc.ALF_CODI, 3) WHEN '015' THEN csc.NDE_CODI WHEN '020' THEN csc.NDE_CDPO ELSE NULL END))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodNatureza
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem o nome da natureza
			SELECT @NomeNatureza = NDE_NOME
			FROM TAB_NDES WITH(NOLOCK) 
			WHERE NDE_CODI = @CodNatureza
-- atualiza a natureza na declaração IMP-CAU
			UPDATE PRO_DUCG SET 
				NDE_CODI = @CodNatureza, 
				NDE_NOME = @NomeNatureza
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @CodNatureza
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
	END
END

ALTER TABLE [dbo].[PRO_DUIN] ENABLE TRIGGER [TAIU_PRO_DUIN_IMPCAU]
/****** Object:  Trigger [TAD_PRO_DUIT_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUIT_IMPCAU] ON [PRO_DUIT] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @IdRegisto int
-- obtem os elementos p/ tributação associados à tributação IEC removidas pertencentes a declarações IMP-CAU
	DECLARE TributacaoIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT det.DUC_EANO, det.DUC_PNUM, det.DUA_CODI, det.DET_IDEN
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
			INNER JOIN PRO_DUET AS det WITH(NOLOCK) ON del.DUC_EANO = det.DUC_EANO AND del.DUC_PNUM = det.DUC_PNUM AND del.DUA_CODI = det.DUA_CODI AND det.DET_AUTO = 1 AND det.DIT_IDST = del.DIT_IDST
		WHERE duc.DUC_DUNO = 2		
	OPEN TributacaoIEC
	FETCH NEXT FROM TributacaoIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove elemento p/ tributação
		DELETE FROM PRO_DUET
		WHERE DET_IDEN = @IdRegisto
-- atualiza numero dos elementos p/ tributação posteriores
		UPDATE PRO_DUET SET DET_CODI = DET_CODI - 1    
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DET_IDEN > @IdRegisto 
		FETCH NEXT FROM TributacaoIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	END
	CLOSE TributacaoIEC
	DEALLOCATE TributacaoIEC
END

ALTER TABLE [dbo].[PRO_DUIT] ENABLE TRIGGER [TAD_PRO_DUIT_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUIT_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUIT_IMPCAU] ON [PRO_DUIT] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdRegisto bigint, @NumProxRegisto int, @IdStrElementoTrib varchar(20)
	DECLARE @IdAdicao int, @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @CodUnidadeMedida varchar(3), @CodUnidadeMedida2 varchar(6), @Quantidade numeric(38, 6), @CodRubricaReceita int, 
		@NomeRubricaReceita varchar(35), @Imposicao varchar(3), @ETaxa bit, @TaxaValor numeric(38, 6), @IdStrRegisto varchar(20), @AdicionalIEC varchar(4)
-- se colunas de unidade de medida, quantidade, rúbrica de receita, imposição, taxa? ou taxa/valor alteradas, processa a gestão dos elementos p/ tributação associados à tributação IEC inseridos/alterados nas adições IMP-CAU 
	IF UPDATE(UME_CODI) OR UPDATE(UME_COD2) OR UPDATE(DIT_QTDE) OR UPDATE(RRE_CODI) OR UPDATE(RRE_NOME) OR UPDATE(DIT_IMPO) OR UPDATE(DIT_TAXA) OR UPDATE(DIT_TXVL) 
	BEGIN
-- insere/edita o elemento p/ tributação no detalhe de elementos p/ tributação das adições IMP-CAU 
		DECLARE TributacaoIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.UME_CODI, ins.UME_COD2, ins.DIT_QTDE, ins.RRE_CODI, ins.RRE_NOME, ins.DIT_IMPO, ins.DIT_TAXA, ins.DIT_TXVL, ins.DIT_IDST, 
				dmi.DMI_AIEC, det.DET_IDEN
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM		
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI 
				INNER JOIN PRO_DUMI AS dmi WITH(NOLOCK) ON ins.DUC_EANO = dmi.DUC_EANO AND ins.DUC_PNUM = dmi.DUC_PNUM AND ins.DUA_CODI = dmi.DUA_CODI AND ins.DMI_CODI = dmi.DMI_CODI				
				LEFT OUTER JOIN PRO_DUET AS det WITH(NOLOCK) ON ins.DUC_EANO = det.DUC_EANO AND ins.DUC_PNUM = det.DUC_PNUM AND ins.DUA_CODI = det.DUA_CODI AND det.DET_AUTO = 1 AND ins.DIT_IDST = det.DIT_IDST								
			WHERE duc.DUC_DUNO = 2 AND ins.RRE_CODI IS NOT NULL
		OPEN TributacaoIEC
		FETCH NEXT FROM TributacaoIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @CodUnidadeMedida2, @Quantidade, @CodRubricaReceita, @NomeRubricaReceita, @Imposicao, 
			@ETaxa, @TaxaValor, @IdStrRegisto, @AdicionalIEC, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				SET @IdStrElementoTrib = REPLACE(CONVERT(numeric(38, 10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()), '.', ',')
-- obtem o próximo numero de registo de elementos p/ tributação da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(DET_CODI), 0) + 1
				FROM PRO_DUET
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o elemento p/ tributação no detalhe de elementos p/ tributação da adição IMP-CAU
				INSERT INTO PRO_DUET(DUC_EANO, DUC_PNUM, DUA_CODI, DET_CODI, DET_TIPO, DET_CIEC, UME_CODI, UME_COD2, DET_QTDE, DET_AUTO, DIT_IDST, RRE_CODI, RRE_NOME, DET_IMPO, DET_TAXA, 
					DET_TXVL, DET_IDST)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, 2, @AdicionalIEC, @CodUnidadeMedida, @CodUnidadeMedida2, @Quantidade, 1, @IdStrRegisto, @CodRubricaReceita, 
					@NomeRubricaReceita, @Imposicao, @ETaxa, @TaxaValor, @IdStrElementoTrib)
			END
			ELSE
			BEGIN
				UPDATE PRO_DUET SET
					DET_CIEC = @AdicionalIEC, 
					UME_CODI = @CodUnidadeMedida, 
					UME_COD2 = @CodUnidadeMedida2, 
					DET_QTDE = @Quantidade, 
					RRE_CODI = @CodRubricaReceita, 
					RRE_NOME = @NomeRubricaReceita, 
					DET_IMPO = @Imposicao, 
					DET_TAXA = @ETaxa, 
					DET_TXVL = @TaxaValor
				WHERE DET_IDEN = @IdRegisto
			END
			FETCH NEXT FROM TributacaoIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodUnidadeMedida, @CodUnidadeMedida2, @Quantidade, @CodRubricaReceita, @NomeRubricaReceita, @Imposicao, 
				@ETaxa, @TaxaValor, @IdStrRegisto, @AdicionalIEC, @IdRegisto
		END
		CLOSE TributacaoIEC
		DEALLOCATE TributacaoIEC
-- remove o elemento p/ tributação existente no detalhe de elementos p/ tributação das adições IMP-CAU mas já não existente nas rúbricas de receita
		DECLARE TributacaoIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT det.DUC_EANO, det.DUC_PNUM, det.DUA_CODI, det.DET_IDEN
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DIT_IDEN = del.DIT_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN PRO_DUET AS det WITH(NOLOCK) ON ins.DUC_EANO = det.DUC_EANO AND ins.DUC_PNUM = det.DUC_PNUM AND ins.DUA_CODI = det.DUA_CODI AND det.DET_AUTO = 1 AND ins.DIT_IDST = det.DIT_IDST				
			WHERE duc.DUC_DUNO = 2 AND ins.RRE_CODI IS NULL				
		OPEN TributacaoIEC
		FETCH NEXT FROM TributacaoIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove elemento p/ tributação					
			DELETE FROM PRO_DUET
			WHERE DET_IDEN = @IdRegisto
-- atualiza numero de elementos p/ tributação posteriores
			UPDATE PRO_DUET SET DET_CODI = DET_CODI - 1    
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DET_IDEN > @IdRegisto 
			FETCH NEXT FROM TributacaoIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
		END
		CLOSE TributacaoIEC
		DEALLOCATE TributacaoIEC			
	END
END

ALTER TABLE [dbo].[PRO_DUIT] ENABLE TRIGGER [TAIU_PRO_DUIT_IMPCAU]
/****** Object:  Trigger [TAD_PRO_DUMI_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUMI_IMPCAU] ON [PRO_DUMI] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @IdRegisto bigint, @IdUtilizador int
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @NumMercadoria int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem as mercadorias IEC das declarações IMP-CAU removidas
	DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, del.DMI_CODI
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2
		GROUP BY del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, del.DMI_CODI
	OPEN MercadoriasIEC
	FETCH NEXT FROM MercadoriasIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumMercadoria
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove a tributação IEC associadas à mercadoria IEC
		DELETE FROM PRO_DUIT
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DMI_CODI = @NumMercadoria
		FETCH NEXT FROM MercadoriasIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumMercadoria
	END
	CLOSE MercadoriasIEC
	DEALLOCATE MercadoriasIEC
-- remove o pedido “G0TAH” ou “G1TAH” existente no detalhe de pedidos da adição quando o código de pedido está definido
	DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 7 AND del.DMI_IDEN = dap.id_mercadoriaIEC
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DMI_CPED, '') <> ''
	OPEN MercadoriasIEC
	FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
	END
	CLOSE MercadoriasIEC
	DEALLOCATE MercadoriasIEC
-- remove o pedido “G0SEL” ou “G1SEL” existente no detalhe de pedidos da adição quando o tipo IEC é "Tabaco" ou "Alcool" e tem selagem definida
	DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 8 AND del.DMI_IDEN = dap.id_mercadoriaIEC
		WHERE duc.DUC_DUNO = 2 AND del.DMI_TIPO IN (1, 3) AND ISNULL(del.DMI_SELA, '') <> ''
	OPEN MercadoriasIEC
	FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
	END
	CLOSE MercadoriasIEC
	DEALLOCATE MercadoriasIEC
END

ALTER TABLE [dbo].[PRO_DUMI] ENABLE TRIGGER [TAD_PRO_DUMI_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUMI_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUMI_IMPCAU] ON [PRO_DUMI] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdRegisto bigint
	DECLARE @IdMercadoriaIEC int, @IdAdicao int, @IdUtilizador int, @IdPedido int, @NumeroPedido varchar(512)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- se colunas da marca ou código do pedido alteradas, processa a gestão do pedido “G0TAH” ou “G1TAH” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DMI_MARC) OR UPDATE(DMI_CPED)
	BEGIN
-- insere/edita o pedido “G0TAH” ou “G1TAH” no detalhe de pedidos da adição IMP-CAU 
		DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DMI_IDEN, NULLIF(ins.DMI_MARC, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON ins.DMI_CPED = tdp.TXM_CODI 
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 7	AND ins.DMI_IDEN = dap.id_mercadoriaIEC
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DMI_CPED, '') <> ''
		OPEN MercadoriasIEC
		FETCH NEXT FROM MercadoriasIEC INTO @IdMercadoriaIEC, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_mercadoriaIEC)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 7, @IdUtilizador, @DataAtual, @IdMercadoriaIEC)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET	
					id_pedido = @IdPedido, 				
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM MercadoriasIEC INTO @IdMercadoriaIEC, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE MercadoriasIEC
		DEALLOCATE MercadoriasIEC
-- remove o pedido “G0TAH” ou “G1TAH” existente no detalhe de pedidos da adição mas já não satisfaz a condição do código de pedido
		DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DMI_IDEN = del.DMI_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 7 AND ins.DMI_IDEN = dap.id_mercadoriaIEC
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DMI_CPED, '') = ''
		OPEN MercadoriasIEC
		FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
		END
		CLOSE MercadoriasIEC
		DEALLOCATE MercadoriasIEC		
	END
-- se colunas da tipo IEC, marca, n.º embalagens, selagem ou ano declaração alteradas, processa a gestão do pedido "G0SEL" ou “G1SEL” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DUC_EANO) OR UPDATE(DMI_TIPO) OR UPDATE(DMI_MARC) OR UPDATE(DMI_NEMB) OR UPDATE(DMI_SELA)
	BEGIN
-- insere/edita o pedido "G0SEL" ou “G1SEL” no detalhe de pedidos da adição IMP-CAU 
		DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DMI_IDEN, adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id, 
				(CASE 
					WHEN (ins.DMI_TIPO = 1) AND (ISNULL(ins.DMI_SELA, '') <> 'N') THEN (ISNULL(ins.DMI_MARC, '') + ', ' + ISNULL(ins.DMI_SELA, '') + ', ' + CAST(ins.DMI_NEMB AS varchar(10))) 
					WHEN (ins.DMI_TIPO = 3) AND (ISNULL(ins.DMI_SELA, '') <> 'N') THEN CAST(ins.DUC_EANO AS varchar(4)) 
					ELSE NULL
				END) 
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = (CASE ISNULL(ins.DMI_SELA, '') WHEN 'N' THEN 'G0SEL' ELSE 'G1SEL' END)
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 8	AND ins.DMI_IDEN = dap.id_mercadoriaIEC								
			WHERE duc.DUC_DUNO = 2 AND ins.DMI_TIPO IN (1, 3) AND ISNULL(ins.DMI_SELA, '') <> ''
		OPEN MercadoriasIEC
		FETCH NEXT FROM MercadoriasIEC INTO @IdMercadoriaIEC, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto, @NumeroPedido 
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_mercadoriaIEC)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 8, @IdUtilizador, @DataAtual, @IdMercadoriaIEC)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET		
					id_pedido = @IdPedido, 								
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM MercadoriasIEC INTO @IdMercadoriaIEC, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto, @NumeroPedido
		END
		CLOSE MercadoriasIEC
		DEALLOCATE MercadoriasIEC
-- remove o pedido "G0SEL" ou “G1SEL” existente no detalhe de pedidos da adição mas já não satisfaz a condição do tipo IEC ou da selagem
		DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DMI_IDEN = del.DMI_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 8 AND ins.DMI_IDEN = dap.id_mercadoriaIEC			
			WHERE duc.DUC_DUNO = 2 AND (ins.DMI_TIPO NOT IN (1, 3) OR ISNULL(ins.DMI_SELA, '') = '')
		OPEN MercadoriasIEC
		FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM MercadoriasIEC INTO @IdRegisto, @IdUtilizador
		END
		CLOSE MercadoriasIEC
		DEALLOCATE MercadoriasIEC		
	END
END

ALTER TABLE [dbo].[PRO_DUMI] ENABLE TRIGGER [TAIU_PRO_DUMI_IMPCAU]
/****** Object:  Trigger [TAU_PRO_DUMI_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DUMI_IMPCAU] ON [PRO_DUMI] AFTER UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @NumMercadoria int, @NumAdicaoDEL int, @NumMercadoriaDEL int
-- se colunas do n.º adição ou n.º mercadoria IEC alteradas, processa atualização do detalhe de tributação IEC das declarações IMP-CAU alteradas
	IF UPDATE(DUA_CODI) OR UPDATE(DMI_CODI)
	BEGIN
-- obtem os veículos das declarações IMP-CAU alterados
		DECLARE MercadoriasIEC CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.DMI_CODI, del.DUA_CODI, del.DMI_CODI
			FROM inserted AS ins
				INNER JOIN deleted AS del ON ins.DMI_IDEN = del.DMI_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
			WHERE duc.DUC_DUNO = 2		
		OPEN MercadoriasIEC
		FETCH NEXT FROM MercadoriasIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumMercadoria, @NumAdicaoDEL, @NumMercadoriaDEL
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza a tributação IEC associadas à mercadoria IEC
			UPDATE PRO_DUIT SET
				DUA_CODI = @NumAdicao,
				DMI_CODI = @NumMercadoria
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicaoDEL AND DMI_CODI = @NumMercadoriaDEL
			FETCH NEXT FROM MercadoriasIEC INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumMercadoria, @NumAdicaoDEL, @NumMercadoriaDEL
		END
		CLOSE MercadoriasIEC
		DEALLOCATE MercadoriasIEC
	END
END

ALTER TABLE [dbo].[PRO_DUMI] ENABLE TRIGGER [TAU_PRO_DUMI_IMPCAU]
/****** Object:  Trigger [TAD_PRO_DUOD_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUOD_IMPCAU] ON [PRO_DUOD] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @VolsDirty int, @VolsClean int, @VolsScan int
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- atualiza os volumes Dirty, Clean e Scan da declaração IMP-CAU se linhas manifesto tiverem definido o campo "Documento de Transporte"
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, 
			SUM((CASE del.DUO_TIPO WHEN 0 THEN 1 ELSE 0 END)), 
			SUM((CASE del.DUO_TIPO WHEN 1 THEN 1 ELSE 0 END)), 
			SUM((CASE del.DUO_TIPO WHEN 2 THEN 1 ELSE 0 END)) 
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DUO_CPA2, '') <> ''
		GROUP BY del.DUC_EANO, del.DUC_PNUM
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @VolsDirty, @VolsClean, @VolsScan
	WHILE @@FETCH_STATUS = 0
	BEGIN
		UPDATE PRO_DUCG SET 
			DUC_VDIR = ISNULL(DUC_VDIR, 0) - @VolsDirty, 
			DUC_VCLE = ISNULL(DUC_VCLE, 0) - @VolsClean, 
			DUC_VSCA = DUC_VSCA - @VolsScan
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @VolsDirty, @VolsClean, @VolsScan
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER TABLE [dbo].[PRO_DUOD] ENABLE TRIGGER [TAD_PRO_DUOD_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUOD_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUOD_IMPCAU] ON [PRO_DUOD] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @VolsDirty int, @VolsClean int, @VolsScan int
-- atualiza os volumes Dirty, Clean e Scan da declaração IMP-CAU se linhas manifesto tiverem definido o campo "Documento de Transporte"
	IF (ISNULL(CONTEXT_INFO(), 0x0) <> 0x44495341424C4544) AND (UPDATE(DUO_TIPO) OR UPDATE(DUO_CPA2)) --"DISABLED" em binário
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, 
				SUM((CASE WHEN (ins.DUO_TIPO = 0) AND (ISNULL(ins.DUO_CPA2, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.DUO_TIPO = 0) AND (ISNULL(del.DUO_CPA2, '') <> '') THEN 1 ELSE 0 END)), 
				SUM((CASE WHEN (ins.DUO_TIPO = 1) AND (ISNULL(ins.DUO_CPA2, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.DUO_TIPO = 1) AND (ISNULL(del.DUO_CPA2, '') <> '') THEN 1 ELSE 0 END)), 
				SUM((CASE WHEN (ins.DUO_TIPO = 2) AND (ISNULL(ins.DUO_CPA2, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.DUO_TIPO = 2) AND (ISNULL(del.DUO_CPA2, '') <> '') THEN 1 ELSE 0 END)) 
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.DUC_EANO = del.DUC_EANO AND ins.DUC_PNUM = del.DUC_PNUM AND ins.DUO_CODI = del.DUO_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
			WHERE duc.DUC_DUNO = 2 AND ((ISNULL(ins.DUO_CPA2, '') <> '') OR (ISNULL(del.DUO_CPA2, '') <> ''))
			GROUP BY ins.DUC_EANO, ins.DUC_PNUM
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @VolsDirty, @VolsClean, @VolsScan
		WHILE @@FETCH_STATUS = 0
		BEGIN
			UPDATE PRO_DUCG SET 
				DUC_VDIR = ISNULL(DUC_VDIR, 0) + @VolsDirty, 
				DUC_VCLE = ISNULL(DUC_VCLE, 0) + @VolsClean, 
				DUC_VSCA = DUC_VSCA + @VolsScan
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @NumDeclaracao, @VolsDirty, @VolsClean, @VolsScan
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
END

ALTER TABLE [dbo].[PRO_DUOD] ENABLE TRIGGER [TAIU_PRO_DUOD_IMPCAU]
/****** Object:  Trigger [TAD_PRO_DUOI_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE TRIGGER [TAD_PRO_DUOI_IMPCAU] ON [PRO_DUOI] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @SomaMontanteRubricasIVA numeric(38, 6), @BaseTributacaoIVA numeric(38, 6), @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @FormulaCondEntrega varchar(70), 
		@TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6), @ValorTotalLiquidacaoRecapitulativa numeric(38, 6)
-- obtem as adições pertencentes às imposições removidas e não originadas de direitos e IVA e que sejam de IVA
	DECLARE Imposicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0)
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2 AND del.DUO_AUTO NOT IN (1, 2) AND del.RRE_LIVA = 1
		GROUP BY del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, duc.DUC_FR20, duc.DUC_TFDA, duc.DUC_TXFR
	OPEN Imposicoes
	FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula a soma dos montantes das imposições de IVA da adição e não originadas de direitos e IVA
		SET @SomaMontanteRubricasIVA = ISNULL(
			(SELECT SUM(DUO_MONT)
			FROM PRO_DUOI WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND RRE_LIVA = 1 AND DUO_AUTO NOT IN (1, 2)), 0)
-- atualiza montante IVA das imposições, base tributação do IVA e montante IVA na adição
		UPDATE PRO_DUAD SET 
			DUA_MIVI = @SomaMontanteRubricasIVA, 
			@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega,@TaxaFDA, @CambioFrete, DUA_VFRE, DUA_AJUS, DUA_VEST, DUA_VTRA, DUA_VOPT, DUA_MTRI, DUA_IVAV, DUA_ABTI, @SomaMontanteRubricasIVA),
			DUA_VIVA = ROUND(@BaseTributacaoIVA * DUA_TIVA / 100, 2)
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao 
		FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
	END
	CLOSE Imposicoes
	DEALLOCATE Imposicoes	
-- obtem as declarações pertencentes às imposições inseridas/editadas
	DECLARE Imposicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM
		FROM deleted AS del
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2 
		GROUP BY del.DUC_EANO, del.DUC_PNUM
	OPEN Imposicoes
	FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove a liquidação recapitualtiva atualmente existente
		DELETE FROM PRO_DULR
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
-- insere a liquidação recapitulativa para a declaração IMP-CAU
		INSERT INTO PRO_DULR(DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, DUL_MONT, DUL_RPRO, DUL_MTAG)
		SELECT DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, SUM((CASE DUO_DEST WHEN 0 THEN ISNULL(DUO_MONT, 0) ELSE 0 END)), 0, SUM((CASE DUO_DEST WHEN 1 THEN DUO_MTAG ELSE 0 END))
		FROM PRO_DUOI WITH(NOLOCK)
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao 
		GROUP BY DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME
-- calcula a soma do montante da liquidação recapitulativa anteriormente inserido
		SET @ValorTotalLiquidacaoRecapitulativa = ISNULL(
			(SELECT SUM(DUL_MONT)
			FROM PRO_DULR WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao), 0)
-- atualiza valor da liquidação recapitulativa e respetivo valor extenso na declaração IMP-CAU
		UPDATE PRO_DUCG SET 
			DUC_VLRC = @ValorTotalLiquidacaoRecapitulativa, 
			DUC_VLRE = dbo.FNT_Extenso_ValorPorExtenso(@ValorTotalLiquidacaoRecapitulativa, 'euros', 'cêntimos')
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao 
		FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao
	END
	CLOSE Imposicoes
	DEALLOCATE Imposicoes				
END

ALTER TABLE [dbo].[PRO_DUOI] ENABLE TRIGGER [TAD_PRO_DUOI_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUOI_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE TRIGGER [TAIU_PRO_DUOI_IMPCAU] ON [PRO_DUOI] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @SomaMontanteRubricasIVA numeric(38, 6), @BaseTributacaoIVA numeric(38, 6), @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @FormulaCondEntrega varchar(70), 
		@TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6), @ValorTotalLiquidacaoRecapitulativa numeric(38, 6)
-- se colunas do check IVA ou montante alteradas, processa a atualização das adições IMP-CAU associadas às imposições inseridas/alteradas
	IF UPDATE(RRE_LIVA) OR UPDATE(DUO_MONT) 
	BEGIN
-- obtem as adições pertencentes às imposições inseridas/editadas e não originadas de direitos e IVA e que sejam de IVA
		DECLARE Imposicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0)
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.DUO_IDEN = del.DUO_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
			WHERE duc.DUC_DUNO = 2 AND ins.DUO_AUTO NOT IN (1, 2) AND ((ins.RRE_LIVA = 1) OR (del.RRE_LIVA = 1))
			GROUP BY ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, duc.DUC_FR20, duc.DUC_TFDA, duc.DUC_TXFR
		OPEN Imposicoes
		FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a soma dos montantes das imposições de IVA da adição e não originadas de direitos e IVA
			SET @SomaMontanteRubricasIVA = ISNULL(
				(SELECT SUM(DUO_MONT)
				FROM PRO_DUOI WITH(NOLOCK)
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND RRE_LIVA = 1 AND DUO_AUTO NOT IN (1, 2)), 0)
-- atualiza montante IVA das imposições, base tributação do IVA e montante IVA na adição
			UPDATE PRO_DUAD SET 
				DUA_MIVI = @SomaMontanteRubricasIVA, 
				@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega,@TaxaFDA, @CambioFrete, DUA_VFRE, DUA_AJUS, DUA_VEST, DUA_VTRA, DUA_VOPT, DUA_MTRI, DUA_IVAV, DUA_ABTI, @SomaMontanteRubricasIVA),
				DUA_VIVA = ROUND(@BaseTributacaoIVA * DUA_TIVA / 100, 2)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao 
			FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete
		END
		CLOSE Imposicoes
		DEALLOCATE Imposicoes		
	END
-- se colunas da rúbrica, montante, tipo destino ou montante a garantir alteradas, processa a gestão da liquidação recapitulativa das declarações IMP-CAU associadas às imposições inseridas/alteradas
	IF UPDATE(RRE_CODI) OR UPDATE(DUO_MONT) OR UPDATE(DUO_DEST) OR UPDATE(DUO_MTAG)
	BEGIN
-- obtem as declarações pertencentes às imposições inseridas/editadas
		DECLARE Imposicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DUC_EANO, ins.DUC_PNUM
			FROM inserted AS ins 				
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
			WHERE duc.DUC_DUNO = 2 
			GROUP BY ins.DUC_EANO, ins.DUC_PNUM
		OPEN Imposicoes
		FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove a liquidação recapitualtiva atualmente existente
			DELETE FROM PRO_DULR
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao
-- insere a liquidação recapitulativa para a declaração IMP-CAU
			INSERT INTO PRO_DULR(DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, DUL_MONT, DUL_RPRO, DUL_MTAG)
			SELECT DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME, SUM((CASE DUO_DEST WHEN 0 THEN ISNULL(DUO_MONT, 0) ELSE 0 END)), 0, SUM((CASE DUO_DEST WHEN 1 THEN DUO_MTAG ELSE 0 END))
			FROM PRO_DUOI WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao 
			GROUP BY DUC_PNUM, DUC_EANO, RRE_CODI, RRE_NOME
-- calcula a soma do montante da liquidação recapitulativa anteriormente inserido
			SET @ValorTotalLiquidacaoRecapitulativa = ISNULL(
				(SELECT SUM(DUL_MONT)
				FROM PRO_DULR WITH(NOLOCK)
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao), 0)
-- atualiza valor da liquidação recapitulativa e respetivo valor extenso na declaração IMP-CAU
			UPDATE PRO_DUCG SET 
				DUC_VLRC = @ValorTotalLiquidacaoRecapitulativa, 
				DUC_VLRE = dbo.FNT_Extenso_ValorPorExtenso(@ValorTotalLiquidacaoRecapitulativa, 'euros', 'cêntimos')
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao 
			FETCH NEXT FROM Imposicoes INTO @AnoDeclaracao, @NumDeclaracao
		END
		CLOSE Imposicoes
		DEALLOCATE Imposicoes		
	END
END

ALTER TABLE [dbo].[PRO_DUOI] ENABLE TRIGGER [TAIU_PRO_DUOI_IMPCAU]
/****** Object:  Trigger [TAIUD_PRO_DUOI]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DUOI] ON [PRO_DUOI] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	if UPDATE(RRE_CODI) or UPDATE(DUO_TIPO) or UPDATE(UME_CODI) or UPDATE(DUO_BTRI) or UPDATE(DUO_TXVL) or UPDATE(DUO_MONT) or UPDATE(RRE_AGRO) 
	or UPDATE(RRE_LIVA) or UPDATE(DUO_IMPO) or UPDATE(DUO_AUTO)
	begin
		insert into LOG_DUOI (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, DUO_TIPO, UME_CODI, 
			DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_AGRO, RRE_LIVA, DUO_IMPO, DUO_AUTO)
		select NEWID(), (case (select count(*) from deleted where DUO_IDEN = inserted.DUO_IDEN) when 0 then 0 else 1 end), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), DUC_EANO, 
			DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_AGRO, RRE_LIVA, DUO_IMPO, DUO_AUTO
		from inserted
		where ((select count(*) from deleted where DUO_IDEN = inserted.DUO_IDEN) = 0)
			or ((select count(*) from deleted where DUO_IDEN = inserted.DUO_IDEN and ((isnull(RRE_CODI, -1) <> isnull(inserted.RRE_CODI, -1)) or 
			(DUO_TIPO <> inserted.DUO_TIPO) or (isnull(UME_CODI, '') <> isnull(inserted.UME_CODI, '')) or (isnull(DUO_BTRI, -1) <> isnull(inserted.DUO_BTRI, -1)) or 
			(isnull(DUO_TXVL, -1) <> isnull(inserted.DUO_TXVL, -1)) or (isnull(DUO_MONT, -1) <> isnull(inserted.DUO_MONT, -1)) or 
			(RRE_AGRO <> inserted.RRE_AGRO) or (isnull(RRE_LIVA, 0) <> isnull(inserted.RRE_LIVA, 0)) or (isnull(DUO_IMPO, '') <> isnull(inserted.DUO_IMPO, '')) or 
			(DUO_AUTO <> inserted.DUO_AUTO))) > 0)
	end
	else
	begin
		insert into LOG_DUOI (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, DUO_TIPO, UME_CODI, 
			DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_AGRO, RRE_LIVA, DUO_IMPO, DUO_AUTO)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_EANO, DUC_PNUM, DUA_CODI, DUO_CODI, RRE_CODI, DUO_TIPO, UME_CODI, DUO_BTRI, DUO_TXVL, DUO_MONT, RRE_AGRO, RRE_LIVA, 
			DUO_IMPO, DUO_AUTO
		from deleted
		where (select count(*) from inserted where DUO_IDEN = deleted.DUO_IDEN) = 0
	end
END

ALTER TABLE [dbo].[PRO_DUOI] ENABLE TRIGGER [TAIUD_PRO_DUOI]
/****** Object:  Trigger [TAIU_PRO_DUPD_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUPD_IMPCAU] ON [PRO_DUPD] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime
	DECLARE @IdDeclaracao bigint, @IdUtilizador int	
	DECLARE @IdDocumento int, @NumeroDocumento varchar(70), @TipoDocumento tinyint	
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()   
-- se coluna do pedido alterada, processa a gestão do documento no detalhe de documentos das declarações IMP-CAU associadas aos pedidos inseridos/alterados
	IF UPDATE(TXM_CODI)
	BEGIN
-- insere o documento como "Suporte"/"Transporte" no detalhe de documentos da declaração IMP-CAU 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT duc.DUC_IDTY, doc.DOC_IDTY, doc.DOC_DTRA, uti.UTI_IDTY, 
				(CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END)				
			FROM inserted AS ins 	
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ins.TXM_CODI = ped.TXM_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ped.DOC_CODI = doc.DOC_CODI	
				LEFT OUTER JOIN tb_IMP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON duc.DUC_IDTY = ddo.id_declaracaoIMP AND doc.DOC_IDTY = ddo.id_documento AND origem = 10				
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			WHERE duc.DUC_DUNO = 2 AND doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND ddo.id IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO tb_IMP_DeclaracoesDocumentos(id_declaracaoIMP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @TipoDocumento, @IdDocumento, @NumeroDocumento, 10, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador, @NumeroDocumento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
	END
END

ALTER TABLE [dbo].[PRO_DUPD] ENABLE TRIGGER [TAIU_PRO_DUPD_IMPCAU]
/****** Object:  Trigger [TAIUD_PRO_DURA]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_DURA] ON [PRO_DURA] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	if UPDATE(EAD_CODI) or UPDATE(DOC_CODI) or UPDATE(DRA_APAN) or UPDATE(DRA_APC1) or UPDATE(DRA_APC2) or UPDATE(DOC_COD2) or UPDATE(DRA_APRG) or UPDATE(DRA_APDT)
	begin
		insert into LOG_DURA (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, EAD_CODI, DOC_CODI, DRA_APAN, 
			DRA_APC1, DRA_APC2, DOC_COD2, DRA_APRG, DRA_APDT)
		select NEWID(), (case (select count(*) from deleted where DRA_IDEN = inserted.DRA_IDEN) when 0 then 0 else 1 end), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), DUC_EANO, 
			DUC_PNUM, DUA_CODI, DRA_CODI, EAD_CODI, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DOC_COD2, DRA_APRG, DRA_APDT
		from inserted
		where ((select count(*) from deleted where DRA_IDEN = inserted.DRA_IDEN) = 0)
			or ((select count(*) from deleted where DRA_IDEN = inserted.DRA_IDEN and ((EAD_CODI <> inserted.EAD_CODI) or 
			(isnull(DOC_CODI, '') <> isnull(inserted.DOC_CODI, '')) or (DRA_APAN <> inserted.DRA_APAN) or (DRA_APC1 <> inserted.DRA_APC1) or 
			(DRA_APC2 <> inserted.DRA_APC2) or (isnull(DOC_COD2, '') <> isnull(inserted.DOC_COD2, '')) or (DRA_APRG <> inserted.DRA_APRG) or 
			(DRA_APDT <> inserted.DRA_APDT))) > 0)
	end
	else
	begin
		insert into LOG_DURA (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, EAD_CODI, DOC_CODI, DRA_APAN, 
			DRA_APC1, DRA_APC2, DOC_COD2, DRA_APRG, DRA_APDT)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), DUC_EANO, DUC_PNUM, DUA_CODI, DRA_CODI, EAD_CODI, DOC_CODI, DRA_APAN, DRA_APC1, DRA_APC2, DOC_COD2, DRA_APRG, DRA_APDT
		from deleted
		where (select count(*) from inserted where DRA_IDEN = deleted.DRA_IDEN) = 0
	end
END

ALTER TABLE [dbo].[PRO_DURA] ENABLE TRIGGER [TAIUD_PRO_DURA]
/****** Object:  Trigger [TAU_PRO_DURA]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_DURA] ON [PRO_DURA] AFTER UPDATE AS 
BEGIN	
	SET NOCOUNT ON;
-- processa atualizações quando há alteração no campo de "N.º Adição"
	IF UPDATE(DUA_CODI)
	BEGIN
-- coloca as linhas de declaração sumária da nova 1ª adição como de origem manuais
		UPDATE PRO_DURA SET DRA_CODR = NULL, DRA_AUTO = 0
		FROM PRO_DURA AS ads WITH(NOLOCK) INNER JOIN inserted AS ins ON ads.DRA_IDEN = ins.DRA_IDEN
			INNER JOIN deleted AS del ON ins.DRA_IDEN = del.DRA_IDEN
		WHERE del.DUA_CODI <> ins.DUA_CODI AND ins.DUA_CODI = 1
-- coloca as linhas de declaração sumária das restantes adições como de origem da nova 1ª adição
		UPDATE PRO_DURA SET DRA_CODR = (SELECT DRA_IDCR FROM PRO_DURA WITH(NOLOCK) WHERE DUC_EANO = ins.DUC_EANO AND DUC_PNUM = ins.DUC_PNUM AND DUA_CODI = 1 AND DRA_CODI = ins.DRA_CODI)
		FROM PRO_DURA AS ads WITH(NOLOCK) INNER JOIN inserted AS ins ON ads.DRA_IDEN = ins.DRA_IDEN
			INNER JOIN deleted AS del ON ins.DRA_IDEN = del.DRA_IDEN
		WHERE del.DUA_CODI <> ins.DUA_CODI AND ins.DUA_CODI > 1
	END
END

ALTER TABLE [dbo].[PRO_DURA] ENABLE TRIGGER [TAU_PRO_DURA]
/****** Object:  Trigger [TAD_PRO_DUVE_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_DUVE_IMPCAU] ON [PRO_DUVE] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @TotalVeiculos int, @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @NumVeiculo int, @IdRegisto bigint, @IdUtilizador int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os veículos pertencentes às matrículas/chassis removidos
	DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, del.DBT_CODI
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2
		GROUP BY del.DUC_EANO, del.DUC_PNUM, del.DUA_CODI, del.DBT_CODI
	OPEN Chassis
	FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula o n.º de matrículas/chassis do veículo
		SET @TotalVeiculos = ISNULL(
			(SELECT COUNT(*)
			FROM PRO_DUVE WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DBT_CODI = @NumVeiculo), 0)
-- atualiza o n.º unidades no veículo
		UPDATE PRO_DUBT SET 
			DBT_NVEI = @TotalVeiculos
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DBT_CODI = @NumVeiculo
		FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo
	END
	CLOSE Chassis
	DEALLOCATE Chassis
-- obtem as marcas e volumes associados às matrículas/chassis removidas pertencentes a declarações IMP-CAU
	DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dam.DUC_EANO, dam.DUC_PNUM, dam.DUA_CODI, dam.D31_IDEN
		FROM deleted AS del 
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM				
			INNER JOIN PRO_DU31 AS dam WITH(NOLOCK) ON del.DUC_EANO = dam.DUC_EANO AND del.DUC_PNUM = dam.DUC_PNUM AND del.DUA_CODI = dam.DUA_CODI AND dam.D31_AUTO = 2 AND del.DVC_IDEN = dam.DVC_IDEN
		WHERE duc.DUC_DUNO = 2		
	OPEN Chassis
	FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove marca e volume
		DELETE FROM PRO_DU31
		WHERE D31_IDEN = @IdRegisto
-- atualiza numero das marcas e volumes posteriores
		UPDATE PRO_DU31 SET D31_CODI = D31_CODI - 1    
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND D31_IDEN > @IdRegisto 
		FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @IdRegisto
	END
	CLOSE Chassis
	DEALLOCATE Chassis
-- remove o pedido “G1MTV” existente no detalhe de pedidos da adição quando a matrícula está definida
	DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 18 AND del.DVC_IDEN = dap.id_chassi			
		WHERE duc.DUC_DUNO = 2 AND ISNULL(del.DVC_MATR, '') <> ''
	OPEN Chassis
	FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Chassis
	DEALLOCATE Chassis	
-- remove o pedido “G1DMV” existente no detalhe de pedidos da adição quando a data matrícula está definida
	DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dap.id, uti.UTI_IDTY
		FROM deleted AS del 
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.DUC_EANO = adi.DUC_EANO AND del.DUC_PNUM = adi.DUC_PNUM AND del.DUA_CODI = adi.DUA_CODI
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON del.DUC_EANO = duc.DUC_EANO AND del.DUC_PNUM = duc.DUC_PNUM
			INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
			INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 19 AND del.DVC_IDEN = dap.id_chassi			
		WHERE duc.DUC_DUNO = 2 AND del.DVC_DMAT IS NOT NULL
	OPEN Chassis
	FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdRegisto
		DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
		WHERE id = @IdRegisto
		FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
	END
	CLOSE Chassis
	DEALLOCATE Chassis
END

ALTER TABLE [dbo].[PRO_DUVE] ENABLE TRIGGER [TAD_PRO_DUVE_IMPCAU]
/****** Object:  Trigger [TAI_PRO_DUVE_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_DUVE_IMPCAU] ON [PRO_DUVE] AFTER INSERT AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @TotalVeiculos int, @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @NumVeiculo int
-- obtem os veículos pertencentes às matrículas/chassis inseridos 
	DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.DBT_CODI
		FROM inserted AS ins 			
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM				
		WHERE duc.DUC_DUNO = 2 
		GROUP BY ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, ins.DBT_CODI
	OPEN Chassis
	FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula o n.º de matrículas/chassis do veículo
		SET @TotalVeiculos = ISNULL(
			(SELECT COUNT(*)
			FROM PRO_DUVE WITH(NOLOCK)
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DBT_CODI = @NumVeiculo), 0)
-- atualiza o n.º unidades no veículo
		UPDATE PRO_DUBT SET 
			DBT_NVEI = @TotalVeiculos
		WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao AND DBT_CODI = @NumVeiculo
		FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumVeiculo
	END
	CLOSE Chassis
	DEALLOCATE Chassis			
END

ALTER TABLE [dbo].[PRO_DUVE] ENABLE TRIGGER [TAI_PRO_DUVE_IMPCAU]
/****** Object:  Trigger [TAIU_PRO_DUVE_IMPCAU]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_DUVE_IMPCAU] ON [PRO_DUVE] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis	
	DECLARE @DataAtual datetime, @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int, @Matricula varchar(22), @Chassi varchar(22), @IdChassi bigint, 
		@CodUnidadeMedida varchar(3), @NomeUnidadeMedida varchar(35), @VolsAZeroUnidadeMedida bit, @IdRegisto bigint, @NumProxRegisto int, @IdAdicao int, @IdUtilizador int, 
		@IdPedido int, @NumeroPedido varchar(512)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- se colunas de matrícula ou chassi alteradas, processa a gestão das marcas e volumes associadas às matrículas/chassis inseridas/alteradas nas adições IMP-CAU 
	IF UPDATE(DVC_MATR) OR UPDATE(DVC_CHAS) 
	BEGIN
-- insere/edita a marca e volume no detalhe de marcas e volumes das adições IMP-CAU 
		DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
			SELECT ins.DUC_EANO, ins.DUC_PNUM, ins.DUA_CODI, REPLACE(REPLACE(REPLACE(ins.DVC_MATR, 'I', ''), 'O', ''), 'Q', ''), ins.DVC_CHAS, ins.DVC_IDEN, ume.UME_CODI, 
				ume.UME_NOME, ume.UME_TVOL, dam.D31_IDEN
			FROM inserted AS ins 			
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM		
				INNER JOIN TAB_UMED AS ume WITH(NOLOCK) ON ume.UME_CODI = 'NE' AND ume.UME_IMPT = 1				
				LEFT OUTER JOIN PRO_DU31 AS dam WITH(NOLOCK) ON ins.DUC_EANO = dam.DUC_EANO AND ins.DUC_PNUM = dam.DUC_PNUM AND ins.DUA_CODI = dam.DUA_CODI AND dam.D31_AUTO = 2 AND ins.DVC_IDEN = dam.DVC_IDEN								
			WHERE duc.DUC_DUNO = 2 
		OPEN Chassis
		FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @Matricula, @Chassi, @IdChassi, @CodUnidadeMedida, @NomeUnidadeMedida, @VolsAZeroUnidadeMedida, 
			@IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN				
-- obtem o próximo numero de registo de marcas e volumes da adição IMP-CAU
				SELECT @NumProxRegisto = ISNULL(MAX(D31_CODI), 0) + 1
				FROM PRO_DU31
				WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere a marca e volume no detalhe de marcas e volumes da adição IMP-CAU
				INSERT INTO PRO_DU31(DUC_EANO, DUC_PNUM, DUA_CODI, D31_CODI, D31_MARC, D31_QNTD, UME_CODI, UME_NOME, D31_TTVL, D31_AUTO, DVC_IDEN)
				VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, ISNULL(NULLIF(@Matricula, ''), @Chassi), 1, @CodUnidadeMedida, @NomeUnidadeMedida, 
					@VolsAZeroUnidadeMedida, 2, @IdChassi)
			END
			ELSE
			BEGIN
				UPDATE PRO_DU31 SET
					D31_MARC = ISNULL(NULLIF(@Matricula, ''), @Chassi)
				WHERE D31_IDEN = @IdRegisto
			END
			FETCH NEXT FROM Chassis INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @Matricula, @Chassi, @IdChassi, @CodUnidadeMedida, @NomeUnidadeMedida, @VolsAZeroUnidadeMedida, 
				@IdRegisto
		END
		CLOSE Chassis
		DEALLOCATE Chassis			
	END
-- se coluna da matrícula alterada, processa a gestão do pedido “G1MTV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DVC_MATR)
	BEGIN
-- insere/edita o pedido “G1MTV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DVC_IDEN, NULLIF(ins.DVC_MATR, ''), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1MTV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 18 AND ins.DVC_IDEN = dap.id_chassi								
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DVC_MATR, '') <> '' 
		OPEN Chassis
		FETCH NEXT FROM Chassis INTO @IdChassi, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_chassi)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 18, @IdUtilizador, @DataAtual, @IdChassi)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Chassis INTO @IdChassi, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Chassis
		DEALLOCATE Chassis
-- remove o pedido “G1MTV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da matrícula
		DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DVC_IDEN = del.DVC_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 18 AND ins.DVC_IDEN = dap.id_chassi			
			WHERE duc.DUC_DUNO = 2 AND ISNULL(ins.DVC_MATR, '') = ''
		OPEN Chassis
		FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Chassis
		DEALLOCATE Chassis		
	END
-- se coluna data matrícula alterada, processa a gestão do pedido “G1DMV” no detalhe de pedidos das adições IMP-CAU inseridas/alteradas
	IF UPDATE(DVC_DMAT)
	BEGIN
-- insere/edita o pedido “G1DMV” no detalhe de pedidos da adição IMP-CAU 
		DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DVC_IDEN, CONVERT(varchar(10), ins.DVC_DMAT, 120), adi.DUA_IDEN, uti.UTI_IDTY, tdp.TXM_IDTY, dap.id
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL		
				INNER JOIN TAB_TXML AS tdp WITH(NOLOCK) ON tdp.TXM_CODI = 'G1DMV'
				LEFT OUTER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 19 AND ins.DVC_IDEN = dap.id_chassi								
			WHERE duc.DUC_DUNO = 2 AND ins.DVC_DMAT IS NOT NULL
		OPEN Chassis
		FETCH NEXT FROM Chassis INTO @IdChassi, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_IMP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo, id_chassi)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 19, @IdUtilizador, @DataAtual, @IdChassi)
			END
			ELSE
			BEGIN
				UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET										
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Chassis INTO @IdChassi, @NumeroPedido, @IdAdicao, @IdUtilizador, @IdPedido, @IdRegisto
		END
		CLOSE Chassis
		DEALLOCATE Chassis
-- remove o pedido “G1DMV” existente no detalhe de pedidos da adição mas já não satisfaz a condição da data matrícula
		DECLARE Chassis CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.DVC_IDEN = del.DVC_IDEN
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.DUC_EANO = adi.DUC_EANO AND ins.DUC_PNUM = adi.DUC_PNUM AND ins.DUA_CODI = adi.DUA_CODI
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON ins.DUC_EANO = duc.DUC_EANO AND ins.DUC_PNUM = duc.DUC_PNUM
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(duc.DUC_UALT, duc.DUC_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_IMP_DeclaracoesAdicoesPedidos AS dap WITH(NOLOCK) ON adi.DUA_IDEN = dap.id_adicao AND dap.origem = 19 AND ins.DVC_IDEN = dap.id_chassi			
			WHERE duc.DUC_DUNO = 2 AND ins.DVC_DMAT IS NULL 
		OPEN Chassis
		FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_IMP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_IMP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Chassis INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Chassis
		DEALLOCATE Chassis		
	END
END

ALTER TABLE [dbo].[PRO_DUVE] ENABLE TRIGGER [TAIU_PRO_DUVE_IMPCAU]
/****** Object:  Trigger [TAD_PRO_EXAD]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_EXAD] ON [PRO_EXAD] FOR DELETE AS 
BEGIN
	-- declaracao de variaveis -----------------------------------------------------------------
	DECLARE @cod int
	set nocount on
	-- busca dados a apagar --------------------------------------------------------------------
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT EXA_CHVE
		FROM deleted	
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @cod	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- apagar detalhes das Adições ------------------------------------------------		
		DELETE FROM PRO_EXPS WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXEE WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXDS WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXCR WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXME WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXMV WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXIV WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXRT WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXRR WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXRC WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXRF WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXRP WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXRM WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXBT WHERE EXA_CHVE = @cod 
		DELETE FROM PRO_EXIE WHERE EXA_CHVE = @cod 

		FETCH NEXT FROM Detalhe INTO @cod
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	
	set nocount off
END

ALTER TABLE [dbo].[PRO_EXAD] ENABLE TRIGGER [TAD_PRO_EXAD]
/****** Object:  Trigger [TAD_PRO_EXAD_EXPSAE]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_EXAD_EXPSAE] ON [PRO_EXAD] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @NumeroAdicao int, @SomaAdicoes int, @SomaValorAduaneiro numeric(38, 6)
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- atualiza o numero das adições superiores à adição removida
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.EXM_EANO, del.EXM_CODI, del.EXM_COPE, del.EXA_LINH
		FROM deleted AS del
			INNER JOIN PRO_EXML AS dex WITH(NOLOCK) ON del.EXM_EANO = dex.EXM_EANO AND del.EXM_CODI = dex.EXM_CODI AND del.EXM_COPE = dex.DEC_CODI
		WHERE dex.EXM_CNTX = 1
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumeroAdicao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE PRO_EXAD SET EXA_LINH = EXA_LINH - 1    
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao AND EXA_LINH > @NumeroAdicao
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumeroAdicao
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes   
-- obtem as declarações associadas às adições removidas
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.EXM_EANO, del.EXM_CODI, del.EXM_COPE
		FROM deleted AS del
			INNER JOIN PRO_EXML AS dex WITH(NOLOCK) ON del.EXM_EANO = dex.EXM_EANO AND del.EXM_CODI = dex.EXM_CODI AND del.EXM_COPE = dex.DEC_CODI				
		WHERE dex.EXM_CNTX = 1
		GROUP BY del.EXM_EANO, del.EXM_CODI, del.EXM_COPE
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao 
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula a soma do número de adições e do montante de todas as adições da declaração EXP-SAE
		SELECT @SomaAdicoes = COUNT(*), @SomaValorAduaneiro = SUM(ISNULL(EXA_VALO, 0))
		FROM PRO_EXAD WITH(NOLOCK)
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao
-- atualiza total de adições e valor aduaneiro total na declaração EXP-SAE
		UPDATE PRO_EXML SET 
			EXM_TAD5 = @SomaAdicoes, 
			EXM_VATT = @SomaValorAduaneiro
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodOperadorDeclaracao
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes 
END

ALTER TABLE [dbo].[PRO_EXAD] ENABLE TRIGGER [TAD_PRO_EXAD_EXPSAE]
/****** Object:  Trigger [TAIU_PRO_EXAD_EXPSAE]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_EXAD_EXPSAE] ON [PRO_EXAD] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdRegisto bigint, @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @SomaAdicoes int, 
		@SomaValorAduaneiro numeric(38, 6), @IdUtilizador int
	DECLARE @IdAdicao int, @NumAdicao int, @MassaBrtAdicao numeric(38, 6)
	DECLARE @CodDocumento varchar(5), @NomeDocumento varchar(150), @NumeroDocumento varchar(70), @TipoDocumento tinyint, @IdDocumento int, @CodUnidMedida varchar(3), 
		@NomeUnidMedida varchar(35), @IdUnidMedida int, @IdUnidMedidaVolumes int, @Volumes int
	DECLARE @IdPedido int, @NumeroPedido varchar(512)
	DECLARE @Marca varchar(512), @CodTipoEmbalagem varchar(2), @NomeTipoEmbalagem varchar(35), @VolumesZero bit, @IdStrRegisto varchar(20)	
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- processa automatismos relacionados com a alteração do número de linha
	IF UPDATE(EXA_LINH)
	BEGIN
-- insere as marcas e volumes da 1ª adição configuradas como "Parte" nas adições > 1 caso ainda não existam
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, dam.EXM_MARN, dam.TEM_CODI, dam.TEM_NOME, dam.EXM_TVOL
			FROM inserted AS ins 
				INNER JOIN PRO_EXML AS dex WITH(NOLOCK) ON ins.EXM_EANO = dex.EXM_EANO AND ins.EXM_CODI = dex.EXM_CODI AND ins.EXM_COPE = dex.DEC_CODI
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ins.EXM_EANO = dad.EXM_EANO AND ins.EXM_CODI = dad.EXM_CODI AND ins.EXM_COPE = dad.EXM_COPE AND dad.EXA_LINH = 1
				INNER JOIN PRO_EXMV AS dam WITH(NOLOCK) ON dad.EXA_CHVE = dam.EXA_CHVE AND dam.EXM_PART = 1				
			WHERE dex.EXM_CNTX = 1 AND ins.EXA_LINH > 1
				AND NOT EXISTS(SELECT EXM_CHVE
								FROM PRO_EXMV WITH(NOLOCK)
								WHERE EXA_CHVE = ins.EXA_CHVE AND EXM_AUTO = 1)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @Marca, @CodTipoEmbalagem, @NomeTipoEmbalagem, @VolumesZero
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @IdStrRegisto = REPLACE(LTRIM(STR(CAST(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT() AS numeric(20, 10)) + (CAST(@IdAdicao AS numeric(20, 10)) / 10000000000), 20, 10)), '.', ',')
-- insere a marca e volume no detalhe de marcas e volumes da adição da declaração EXP-SAE
			INSERT INTO PRO_EXMV(EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_TVOL, EXM_IDST, EXM_AUTO, EXM_EANO, EXM_CODI, EXM_COPE)
			VALUES(@IdAdicao, @Marca, @CodTipoEmbalagem, @NomeTipoEmbalagem, 0, 0, @VolumesZero, @IdStrRegisto, 1, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao)	
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @Marca, @CodTipoEmbalagem, @NomeTipoEmbalagem, @VolumesZero
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
	END
-- processa automatismos relacionados com a alteração do número de linha quando o período transitório está ativo
	IF (UPDATE(EXA_LINH)) AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_PTEX = 1))
	BEGIN
-- obtem o documento OEA associado ao exportador (cliente) das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ins.EXA_LINH, doc.DOC_CODI, doc.DOC_NOME, NULLIF(cli.CLI_NAOE, ''), ddo.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON exm.CLI_COD2 = cli.CLI_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cli.DOC_CDOE = doc.DOC_CODI	
				LEFT OUTER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 3									
			WHERE exm.EXM_CNTX = 1 AND ins.EXA_LINH = 1 AND cli.CLI_FXOE IN (0, 2) AND ISNULL(cli.CLI_NAOE, '') <> '' AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4 				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere/atualiza o documento OEA como "Referência Adicional" no detalhe de documentos da 1ª adição da declaração EXP-SAE
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_MONT, EXD_QNTD, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI)
				VALUES(@IdAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, 0, 0, 3, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, 2, @NumAdicao)
			END
			ELSE
			BEGIN
				UPDATE PRO_EXDA SET
					DOC_CODI = @CodDocumento, 
					DOC_NOME = @NomeDocumento, 
					EXD_NREF = @NumeroDocumento			
				WHERE EXD_CHVE = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem o documento OEA existente no detalhe de documentos da 1ª adição das declarações EXP-SAE cuja origem é do OEA exportador mas que já não satisfaz as condições ou não existe no OEA cliente exportador
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 3					
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON exm.CLI_COD2 = cli.CLI_CODI	
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cli.DOC_CDOE = doc.DOC_CODI					
			WHERE exm.EXM_CNTX = 1 AND (ins.EXA_LINH <> 1 OR cli.CLI_FXOE NOT IN (0, 2) OR ISNULL(cli.CLI_NAOE, '') = '' OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 
				OR doc.DOC_IDTY IS NULL) 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o documento OEA existente no detalhe de documentos da 1ª adição da declaração EXP-SAE
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos associados ao exportador (cliente) das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ins.EXA_LINH, doc.DOC_CODI, doc.DOC_NOME, ddo.EXD_CHVE, 			
				ISNULL(NULLIF(cdo.CLD_NDOC, ''), (CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END))	
			FROM inserted AS ins 
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN TAB_CLDO AS cdo WITH(NOLOCK) ON exm.CLI_COD2 = cdo.CLI_CODI				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cdo.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND doc.DOC_CODI = ddo.DOC_CODI AND ddo.EXD_AUTO = 6				
			WHERE exm.EXM_CNTX = 1 AND ins.EXA_LINH = 1 AND cdo.CLD_UEXP = 1 AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4						
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @IdRegisto, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o documento como "Suporte" no detalhe de documentos da 1ª adição da declaração EXP-SAE
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_MONT, EXD_QNTD, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI)
				VALUES(@IdAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, 0, 0, 6, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, 0, @NumAdicao)
			END
			ELSE
			BEGIN
				UPDATE PRO_EXDA SET					
					EXD_NREF = @NumeroDocumento			
				WHERE EXD_CHVE = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @IdRegisto, @NumeroDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
-- obtem os documentos existentes no detalhe de documentos da 1ª adição das declarações EXP-SAE cuja origem é do exportador mas que já não satisfazem as condições ou não existem no detalhe de documentos do cliente exportador
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 6		
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.DOC_CODI = doc.DOC_CODI	
				LEFT OUTER JOIN TAB_CLDO AS cdo WITH(NOLOCK) ON exm.CLI_COD2 = cdo.CLI_CODI AND doc.DOC_CODI = cdo.DOC_CODI				
			WHERE exm.EXM_CNTX = 1 AND (ins.EXA_LINH <> 1 OR cdo.CLD_UEXP = 0 OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR cdo.DOC_CODI IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o documento existente no detalhe de documentos da 1ª adição da declaração EXP-SAE
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem o documento OEA associado ao declarante das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ins.EXA_LINH, doc.DOC_CODI, doc.DOC_NOME, NULLIF(dcl.DEC_NAOE, ''), ddo.EXD_CHVE			
			FROM inserted AS ins 	
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON (CASE exm.EXM_TP14 WHEN 2 THEN dcl.DOC_CDOE ELSE dcl.DOC_CODI2 END) = doc.DOC_CODI	
				LEFT OUTER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 4									
			WHERE exm.EXM_CNTX = 1 AND ins.EXA_LINH = 1 AND dcl.DEC_FXOE IN (0, 2) AND ISNULL(dcl.DEC_NAOE, '') <> '' AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4					
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere/atualiza o documento OEA como "Referência Adicional" no detalhe de documentos da 1ª adição da declaração EXP-SAE
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_MONT, EXD_QNTD, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI)
				VALUES(@IdAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, 0, 0, 4, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, 2, @NumAdicao)
			END
			ELSE
			BEGIN
				UPDATE PRO_EXDA SET
					DOC_CODI = @CodDocumento, 
					DOC_NOME = @NomeDocumento, 
					EXD_NREF = @NumeroDocumento			
				WHERE EXD_CHVE = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem o documento OEA existente no detalhe de documentos da 1ª adição das declaração EXP-SAE cuja origem é do OEA declarante mas que já não satisfaz as condições ou não existe no OEA declarante
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 4					
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON exm.DEC_CO14 = dcl.DEC_CODI
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON (CASE exm.EXM_TP14 WHEN 2 THEN dcl.DOC_CDOE ELSE dcl.DOC_CODI2 END) = doc.DOC_CODI					
			WHERE exm.EXM_CNTX = 1 AND (ins.EXA_LINH <> 1 OR dcl.DEC_FXOE NOT IN (0, 2) OR ISNULL(dcl.DEC_NAOE, '') = '' OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 
				OR doc.DOC_IDTY IS NULL) 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o documento existente no detalhe de documentos da 1ª adição da declaração EXP-SAE
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem o documentos "N821" associado ao par regime/país destino das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ins.EXA_LINH, doc.DOC_CODI, doc.DOC_NOME, doc.DOC_DTRA			
			FROM inserted AS ins 	
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI							
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N821'
				LEFT OUTER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND doc.DOC_CODI = ddo.DOC_CODI AND ddo.EXD_AUTO = 7				
			WHERE exm.EXM_CNTX = 1 AND ins.EXA_LINH = 1 AND LEFT(exm.EXM_REGI, 2) IN ('10', '11', '21', '22', '23') AND exm.EXM_P17A IN ('NO', 'GB', 'CH', 'CY', 'IS', 'LI', 'MK', 'NO', 'RS', 'TR') 
				AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4 AND ddo.EXD_CHVE IS NULL				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento "N821" como "Suporte"/"Transporte" no detalhe de documentos da 1ª adição da declaração EXP-SAE
			INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, /*EXD_NREF, */EXD_MONT, EXD_QNTD, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI)
			VALUES(@IdAdicao, @CodDocumento, @NomeDocumento, /*@NumeroDocumento, */0, 0, 7, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @TipoDocumento, @NumAdicao)					
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos "N821" existentes no detalhe de documentos da 1ª adição das declaração EXP-SAE cuja origem é do par regime/país destino mas que já não satisfazem as condições
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 7							
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N821' AND ddo.DOC_CODI = doc.DOC_CODI
			WHERE exm.EXM_CNTX = 1 AND (ins.EXA_LINH <> 1 OR LEFT(exm.EXM_REGI, 2) NOT IN ('10', '11', '21', '22', '23') OR exm.EXM_P17A NOT IN ('NO', 'GB', 'CH', 'CY', 'IS', 'LI', 'MK', 'NO', 'RS', 'TR') 
				OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR doc.DOC_IDTY IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o documento "N821" existente no detalhe de documentos da 1ª adição da declaração EXP-SAE
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos associados ao tipo de declaração das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ins.EXA_LINH, doc.DOC_CODI, doc.DOC_NOME, 		 
				(CASE 					
					WHEN doc.DOC_TDNU = 1 THEN 'S/N' 
					WHEN doc.DOC_TDNU = 2 THEN 'N/A' 
					WHEN doc.DOC_TDNU = 3 THEN 'DEC' 
					ELSE NULL 
				END)
			FROM inserted AS ins 				
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN TAB_TDED AS tdd WITH(NOLOCK) ON exm.TDE_COD1 = tdd.TDE_CODI	
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON tdd.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND doc.DOC_CODI = ddo.DOC_CODI AND ddo.EXD_AUTO = 8					
			WHERE exm.EXM_CNTX = 1 AND exm.EXM_ASAI = 0 AND ins.EXA_LINH = 1 AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4 AND ddo.EXD_CHVE IS NULL 				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento como "Suporte" no detalhe de documentos da 1ª adição da declaração EXP-SAE
			INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_MONT, EXD_QNTD, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI)
			VALUES(@IdAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, 0, 0, 8, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, 0, @NumAdicao)				
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos existentes no detalhe de documentos da 1ª adição das declaração EXP-SAE cuja origem é do tipo declaração mas que já não satisfazem as condições ou não existem no detalhe de documentos do tipo de declaração
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 8	
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.DOC_CODI = doc.DOC_CODI	
				LEFT OUTER JOIN TAB_TDED AS tdd WITH(NOLOCK) ON exm.TDE_COD1 = tdd.TDE_CODI AND doc.DOC_CODI = tdd.DOC_CODI				
			WHERE exm.EXM_CNTX = 1 AND exm.EXM_ASAI = 0 AND (ins.EXA_LINH <> 1 OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR tdd.DOC_CODI IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o documento existente no detalhe de documentos da 1ª adição da declaração EXP-SAE
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos associados à estância de exportação das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ins.EXA_LINH, doc.DOC_CODI, doc.DOC_NOME, doc.DOC_DTRA, 
				(CASE 
					WHEN doc.DOC_CODI IN ('N704', 'N705', 'N740', 'N821', 'N830') THEN NULLIF(ins.EXM_CPRT, '')
					WHEN doc.DOC_CODI = '9X01' THEN 'Nao aplicavel DL 68/2007'
					WHEN doc.DOC_TDNU = 1 THEN 'S/N' 
					WHEN doc.DOC_TDNU = 2 THEN 'N/A' 
					WHEN doc.DOC_TDNU = 3 THEN 'DEC' 
					ELSE NULL 
				END)
			FROM inserted AS ins 				
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN TAB_EADD AS ead WITH(NOLOCK) ON exm.EAD_CODA = ead.EAD_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ead.DOC_CODI = doc.DOC_CODI				
				LEFT OUTER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND doc.DOC_CODI = ddo.DOC_CODI AND ddo.EXD_AUTO = 9
			WHERE exm.EXM_CNTX = 1 AND ins.EXA_LINH = 1 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4 AND ddo.EXD_CHVE IS NULL 				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento como "Suporte"/"Transporte" no detalhe de documentos da 1ª adição da declaração EXP-SAE
			INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_MONT, EXD_QNTD, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, EXD_NADI)
			VALUES(@IdAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, 0, 0, 9, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @TipoDocumento, @NumAdicao)	
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento, @NumeroDocumento
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
-- obtem os documentos existentes no detalhe de documentos da 1ª adição das declaração EXP-SAE cuja origem é da estância de exportação mas que já não satisfazem as condições ou não existem no detalhe de documentos da estância de exportação
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN PRO_EXDA AS ddo WITH(NOLOCK) ON ins.EXA_CHVE = ddo.EXA_CHVE AND ddo.EXD_AUTO = 9			
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.DOC_CODI = doc.DOC_CODI	
				LEFT OUTER JOIN TAB_EADD AS ead WITH(NOLOCK) ON exm.EAD_CODA = ead.EAD_CODI AND doc.DOC_CODI = ead.DOC_CODI				
			WHERE exm.EXM_CNTX = 1 AND (ins.EXA_LINH <> 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR ead.DOC_CODI IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o documento existente no detalhe de documentos da 1ª adição da declaração EXP-SAE
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos "NMRN" e "NCLE" associados ao tipo declaração adicional das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXA_LINH, ISNULL(ins.EXA_MBRT, 0), doc.DOC_IDTY, ume.UME_IDTY , uti.UTI_IDTY
			FROM inserted AS ins 		
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI					
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE 																				
																				WHEN exm.EXM_TPRO IN ('X', 'Y') THEN 'NMRN'																				
																				WHEN exm.EXM_TPRO = 'Z' THEN 'NCLE'
																				ELSE NULL 
																			END)
				LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesPrecedentes AS dpr WITH(NOLOCK) ON ins.EXA_CHVE = dpr.id_adicao AND doc.DOC_IDTY = dpr.id_documento AND dpr.origem = 1						
				LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON ume.UME_CODI = 'KGM' AND ume.UME_EXPT = 1
			WHERE exm.EXM_CNTX = 1 AND exm.EXM_TPRO IN ('X', 'Y', 'Z') AND ins.EXA_LINH = 1 AND doc.DOC_CA40 = 1 AND LEN(doc.DOC_CODI) = 4 AND doc.DOC_EXPT = 1 AND dpr.id IS NULL
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumAdicao, @MassaBrtAdicao, @IdDocumento, @IdUnidMedida, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			SET @IdUnidMedidaVolumes = NULL
			SET @Volumes = NULL
-- obtem dados dos volumes da adição
			SELECT TOP 1 @Volumes = NULLIF(dam.EXM_NVOL, 0), @IdUnidMedidaVolumes = ume.UME_IDTY
			FROM PRO_EXMV AS dam WITH(NOLOCK)
				LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON dam.TEM_CODI = ume.UME_CODI
			WHERE dam.EXA_CHVE = @IdAdicao
			ORDER BY dam.EXM_CHVE
-- insere o documento "NMRN" ou "NCLE" no detalhe de precedentes da 1ª adição da declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesAdicoesPrecedentes(id_adicao, id_documento, numero, numeroAdicao, id_unidadeMedidaVolumes, volumes, id_unidadeMedidaQualificador, 
				quantidade, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdDocumento, '*****N/A*****', @NumAdicao, @IdUnidMedidaVolumes, @Volumes, @IdUnidMedida, 
				@MassaBrtAdicao, 1, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @NumAdicao, @MassaBrtAdicao, @IdDocumento, @IdUnidMedida, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos "NMRN" e "NCLE" existentes no detalhe de precedentes da 1ª adição das declaração EXP-SAE cuja origem é do tipo declaração adicional mas que já não satisfazem as condições
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpr.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL			
				INNER JOIN tb_EXP_DeclaracoesAdicoesPrecedentes AS dpr WITH(NOLOCK) ON ins.EXA_CHVE = dpr.id_adicao AND dpr.origem = 1							
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY AND doc.DOC_CODI = (CASE 																				
																														WHEN exm.EXM_TPRO IN ('X', 'Y') THEN 'NMRN'																				
																														WHEN exm.EXM_TPRO = 'Z' THEN 'NCLE'
																														ELSE NULL 
																													END)	
			WHERE exm.EXM_CNTX = 1 AND (ins.EXA_LINH <> 1 OR doc.DOC_CA40 = 0 OR LEN(doc.DOC_CODI) <> 4 OR doc.DOC_EXPT = 0 OR doc.DOC_IDTY IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento "NMRN" ou "NCLE" existente no detalhe de precedentes da 1ª adição da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesPrecedentes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento "NMRN" ou "NCLE" existente no detalhe de precedentes da 1ª adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesPrecedentes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
-- obtem o pedido "G1PRO" associado ao estatuto das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, uti.UTI_IDTY, ped.TXM_IDTY, NULLIF(cli.CLI_NDHA, ''), dpe.id
			FROM inserted AS ins 		
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL	
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON exm.CLI_COD2 = cli.CLI_CODI
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'G1PRO'
				LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 1				
			WHERE exm.EXM_CNTX = 1 AND ISNULL(exm.EXM_TP14, 0) = 2 AND ins.EXA_LINH = 1			
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o pedido "G1PRO" no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			IF @IdRegisto IS NULL
			BEGIN				
				INSERT INTO tb_EXP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 1, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesAdicoesPedidos SET
					id_pedido = @IdPedido, 
					numero = @NumeroPedido, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido, @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes				
-- obtem o pedido "G1PRO" existente no detalhe de pedidos da 1ª adição das declaração EXP-SAE cuja origem é do estatuto mas que já não satisfaz a condição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpe.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL		
				INNER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 1									
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.id_pedido = ped.TXM_IDTY				
			WHERE exm.EXM_CNTX = 1 AND (ISNULL(exm.EXM_TP14, 0) <> 2 OR ins.EXA_LINH <> 1 OR ped.TXM_IDTY IS NULL) 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- atualiza o pedido "G1PRO" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o pedido "G1PRO" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
-- obtem os pedidos associados ao tipo declaração das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, uti.UTI_IDTY, ped.TXM_IDTY, SUBSTRING(tdp.TDP_TEXT, 1, 512)			
			FROM inserted AS ins 	
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL				
				INNER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON exm.TDE_COD1 = tdp.TDE_CODI
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON tdp.TXM_CODI = ped.TXM_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 2				
			WHERE exm.EXM_CNTX = 1 AND exm.EXM_ASAI = 0 AND ins.EXA_LINH = 1 AND dpe.id IS NULL	
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o pedido no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 2, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes				
-- obtem os pedidos existentes no detalhe de pedidos da 1ª adição das declaração EXP-SAE cuja origem é do tipo declaração mas que já não existem no detalhe de pedidos do tipo declaração
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpe.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 2	
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.id_pedido = ped.TXM_IDTY
				LEFT OUTER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON exm.TDE_COD1 = tdp.TDE_CODI AND ped.TXM_CODI = tdp.TXM_CODI
			WHERE exm.EXM_CNTX = 1 AND exm.EXM_ASAI = 0 AND (ins.EXA_LINH <> 1 OR tdp.TXM_CODI IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- atualiza o pedido existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o pedido existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
-- obtem o pedido "00100" associado à estância de aperfeiçoamento das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, uti.UTI_IDTY, ped.TXM_IDTY, SUBSTRING(ped.TXM_TEXT, 1, 512)
			FROM inserted AS ins 				
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL					
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = '00100'
				LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 3				
			WHERE exm.EXM_CNTX = 1 AND ISNULL(exm.EAD_CODI1, '') <> '' AND ins.EXA_LINH = 1 AND dpe.id IS NULL		
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o pedido "00100" no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 3, @IdUtilizador, @DataAtual)				
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes				
-- obtem o pedido "00100" existente no detalhe de pedidos da 1ª adição das declaração EXP-SAE cuja origem é da estância de aperfeiçoamento mas que já não satisfaz a condição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpe.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 3							
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.id_pedido = ped.TXM_IDTY
			WHERE exm.EXM_CNTX = 1 AND (ISNULL(exm.EAD_CODI1, '') = '' OR ins.EXA_LINH <> 1 OR ped.TXM_IDTY IS NULL) 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- atualiza o pedido "00100" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o pedido "00100" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem o pedido "E0CCE" associado aos certificados das 1ªs adições inseridas/alteradas pertencentes a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, uti.UTI_IDTY, ped.TXM_IDTY, SUBSTRING(ped.TXM_TEXT, 1, 512)
			FROM inserted AS ins 				
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL					
				INNER JOIN PRO_EXCE AS cce WITH(NOLOCK) ON exm.EXM_EANO = cce.EXM_EANO AND exm.EXM_CODI = cce.EXM_CODI AND exm.DEC_CODI = cce.EXM_COPE AND cce.EXC_LINH = 1
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'E0CCE'
				LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 4
			WHERE exm.EXM_CNTX = 1 AND ins.EXA_LINH = 1 AND cce.EXC_CHVE IS NOT NULL AND dpe.id IS NULL				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o pedido "E0CCE" no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 4, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem o pedido "E0CCE" existente no detalhe de pedidos da 1ª adição das declaração EXP-SAE cuja origem é de certificados mas que já não satisfaz a condição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpe.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON ins.EXM_EANO = exm.EXM_EANO AND ins.EXM_CODI = exm.EXM_CODI AND ins.EXM_COPE = exm.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(exm.EXM_UALT, exm.EXM_UCRI) = uti.UTI_UTIL
				INNER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON ins.EXA_CHVE = dpe.id_adicao AND dpe.origem = 4					
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.id_pedido = ped.TXM_IDTY
				LEFT OUTER JOIN PRO_EXCE AS cce WITH(NOLOCK) ON exm.EXM_EANO = cce.EXM_EANO AND exm.EXM_CODI = cce.EXM_CODI AND exm.DEC_CODI = cce.EXM_COPE AND cce.EXC_LINH = 1
			WHERE exm.EXM_CNTX = 1 AND (ins.EXA_LINH <> 1 OR cce.EXC_CHVE IS NULL OR ped.TXM_IDTY IS NULL) 			
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN			
-- atualiza o pedido "E0CCE" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o pedido "E0CCE" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto			
			FETCH NEXT FROM Adicoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes			
	END
-- processa automatismos relacionados com a alteração do artigo
	IF UPDATE(APA_CO33)
	BEGIN
-- obtem os documentos associados ao artigo das adições inseridas/alteradas associadas a declarações EXP-SAE
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ins.EXA_LINH, doc.DOC_CODI, doc.DOC_NOME, ume.UME_CODI, ume.UME_NOME, 
				(CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END), 
				(CASE LEFT(doc.DOC_CODI, 1) WHEN 'X' THEN 0 ELSE 2 END),
				(CASE LEFT(doc.DOC_CODI, 1) WHEN 'X' THEN ISNULL(ins.EXA_MBRT, 0) ELSE 0 END)
			FROM inserted AS ins 
				INNER JOIN PRO_EXML AS dex WITH(NOLOCK) ON ins.EXM_EANO = dex.EXM_EANO AND ins.EXM_CODI = dex.EXM_CODI AND ins.EXM_COPE = dex.DEC_CODI
				INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON dex.TDE_COD1 = tde.TDE_CODI
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON ins.APA_CO33 = apa.APA_CODI				
				INNER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON apa.APA_CHVE = ado.APA_CHVE
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN PRO_EXDA AS dad WITH(NOLOCK) ON ins.EXA_CHVE = dad.EXA_CHVE AND doc.DOC_CODI = dad.DOC_CODI AND dad.EXD_AUTO = 5					
				LEFT OUTER JOIN TAB_UMED AS ume WITH(NOLOCK) ON ume.UME_CODI = 'KGM' AND LEFT(doc.DOC_CODI, 1) = 'X'
			WHERE dex.EXM_CNTX = 1 AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(doc.DOC_CODI, 1) = 'X') AND ado.ADC_UEXP = 1 AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND doc.DOC_AUTZ = 0 
				AND LEN(doc.DOC_CODI) = 4 AND dad.EXD_CHVE IS NULL 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @CodUnidMedida, @NomeUnidMedida, 
			@NumeroDocumento, @TipoDocumento, @MassaBrtAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento como "Documento de Suporte" ou "Referência Adicional" no detalhe de documentos da adição da declaração EXP-SAE 
			INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_MONT, EXD_QNTD, EXD_AUTO, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, EXD_TIPO, UME_CODI, UME_NOME)
			VALUES(@IdAdicao, @CodDocumento, @NomeDocumento, @NumeroDocumento, 0, @MassaBrtAdicao, 5, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @TipoDocumento, @CodUnidMedida, @NomeUnidMedida)		
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @CodUnidMedida, @NomeUnidMedida, 
				@NumeroDocumento, @TipoDocumento, @MassaBrtAdicao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes
-- obtem os documentos existentes no detalhe de documentos das adições das declarações EXP-SAE cuja origem é do artigo mas que já não satisfazem as condições ou não existem no detalhe de documentos do artigo
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXA_CHVE = del.EXA_CHVE
				INNER JOIN PRO_EXML AS dex WITH(NOLOCK) ON ins.EXM_EANO = dex.EXM_EANO AND ins.EXM_CODI = dex.EXM_CODI AND ins.EXM_COPE = dex.DEC_CODI
				INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON dex.TDE_COD1 = tde.TDE_CODI
				INNER JOIN PRO_EXDA AS dad WITH(NOLOCK) ON ins.EXA_CHVE = dad.EXA_CHVE AND dad.EXD_AUTO = 5		
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.DOC_CODI = doc.DOC_CODI
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON ins.APA_CO33 = apa.APA_CODI	
				LEFT OUTER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON apa.APA_CHVE = ado.APA_CHVE AND doc.DOC_CODI = ado.DOC_CODI				
			WHERE dex.EXM_CNTX = 1 AND (ISNULL(tde.TDE_1CAS, '') <> 'CO' OR LEFT(doc.DOC_CODI, 1) = 'X')
				AND (ado.ADC_UEXP = 0 OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR doc.DOC_AUTZ = 1 OR LEN(doc.DOC_CODI) <> 4 OR ado.ADC_CODI IS NULL)
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- remove o documento existente no detalhe de documentos da adição da declaração EXP-SAE 
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Adicoes INTO @IdRegisto
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	
	END
-- processa automatismos relacionados com a alteração do montante
	IF (ISNULL(CONTEXT_INFO(), 0x0) <> 0x44495341424C4544) AND (UPDATE(EXA_VALO)) --"DISABLED" em binário
	BEGIN
-- obtem as declarações associadas às adições inseridas/editadas
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE
			FROM inserted AS ins
				INNER JOIN PRO_EXML AS dex WITH(NOLOCK) ON ins.EXM_EANO = dex.EXM_EANO AND ins.EXM_CODI = dex.EXM_CODI AND ins.EXM_COPE = dex.DEC_CODI				
			WHERE dex.EXM_CNTX = 1
			GROUP BY ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao 
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a soma do número de adições e do montante de todas as adições da declaração EXP-SAE
			SELECT @SomaAdicoes = COUNT(*), @SomaValorAduaneiro = SUM(ISNULL(EXA_VALO, 0))
			FROM PRO_EXAD WITH(NOLOCK)
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao
-- atualiza total de adições e valor aduaneiro total na declaração EXP-SAE
			UPDATE PRO_EXML SET 
				EXM_TAD5 = @SomaAdicoes, 
				EXM_VATT = @SomaValorAduaneiro
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodOperadorDeclaracao
			FETCH NEXT FROM Adicoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes	 		
	END
END

ALTER TABLE [dbo].[PRO_EXAD] ENABLE TRIGGER [TAIU_PRO_EXAD_EXPSAE]
/****** Object:  Trigger [TAIUD_PRO_EXAD]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_EXAD] ON [PRO_EXAD] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
    if UPDATE(APA_CP33) or UPDATE(PAI_CODI) or UPDATE(EXA_MBRT) or UPDATE(EXA_DESD) or UPDATE(EXA_MLQD) or UPDATE(EXA_QUSU) or UPDATE(EXA_VALO) or UPDATE(EXA_VEST) 
    or UPDATE(EXA_IVEI) or UPDATE(EXA_IRES) or UPDATE(TDE_REGI)
	begin
		insert into LOG_EXAD (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, EXA_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CP33, PAI_CODI, 
			EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, EXA_VALO, EXA_VEST, EXA_IVEI, EXA_IRES, TDE_REGI)
		select NEWID(), (case (select count(*) from deleted where EXA_CHVE = inserted.EXA_CHVE) when 0 then 0 else 1 end), 
			GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), 
			EXA_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CP33, PAI_CODI, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, EXA_VALO, EXA_VEST, EXA_IVEI, EXA_IRES, 
			TDE_REGI
		from inserted
		where ((select count(*) from deleted where EXA_CHVE = inserted.EXA_CHVE) = 0)
			or ((select count(*) from deleted where EXA_CHVE = inserted.EXA_CHVE and ((isnull(APA_CP33, '') <> isnull(inserted.APA_CP33, '')) or 
			(isnull(PAI_CODI, '') <> isnull(inserted.PAI_CODI, '')) or (isnull(EXA_MBRT, -1) <> isnull(inserted.EXA_MBRT, -1)) or 
			(isnull(EXA_DESD, '') <> isnull(inserted.EXA_DESD, '')) or (isnull(EXA_MLQD, -1) <> isnull(inserted.EXA_MLQD, -1)) or 
			(isnull(EXA_QUSU, -1) <> isnull(inserted.EXA_QUSU, -1)) or (isnull(EXA_VALO, -1) <> isnull(inserted.EXA_VALO, -1)) or 
			(isnull(EXA_VEST, -1) <> isnull(inserted.EXA_VEST, -1)) or (isnull(EXA_IVEI, -1) <> isnull(inserted.EXA_IVEI, -1)) or 
			(isnull(EXA_IRES, '') <> isnull(inserted.EXA_IRES, '')) or (isnull(TDE_REGI, '') <> isnull(inserted.TDE_REGI, '')))) > 0)
	end
	else
	begin
		insert into LOG_EXAD (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, EXA_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CP33, PAI_CODI, 
			EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, EXA_VALO, EXA_VEST, EXA_IVEI, EXA_IRES, TDE_REGI)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), EXA_CHVE, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH, APA_CP33, PAI_CODI, EXA_MBRT, EXA_DESD, EXA_MLQD, EXA_QUSU, EXA_VALO, 
			EXA_VEST, EXA_IVEI, EXA_IRES, TDE_REGI
		from deleted
		where (select count(*) from inserted where EXA_CHVE = deleted.EXA_CHVE) = 0
	end
END

ALTER TABLE [dbo].[PRO_EXAD] ENABLE TRIGGER [TAIUD_PRO_EXAD]
/****** Object:  Trigger [TAU_PRO_EXAD]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_EXAD] ON [PRO_EXAD] AFTER UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaracao de variaveis 
	DECLARE @IdAdicao int
-- Se campo do "Valor Estatistico" foi alterado e existe uma adição com o documento "9E06" inserido, coloca "Valor Estatistico Original" no campo do "Valor Estatistico"
	IF UPDATE(EXA_VEST) AND (EXISTS(SELECT EXD_CHVE FROM inserted AS ins INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON ins.EXM_EANO = adi.EXM_EANO AND ins.EXM_CODI = adi.EXM_CODI AND ins.EXM_COPE = adi.EXM_COPE	INNER JOIN PRO_EXDA AS xda WITH(NOLOCK) ON adi.EXA_CHVE = xda.EXA_CHVE WHERE xda.DOC_CODI = '9E06'))
	BEGIN
		UPDATE PRO_EXAD SET EXA_VEST = ins.EXA_VEOR
		FROM PRO_EXAD AS xad WITH(NOLOCK) INNER JOIN inserted AS ins ON xad.EXA_CHVE = ins.EXA_CHVE			
		WHERE ISNULL(ins.EXA_VEOR, 0) > 0 AND EXISTS(SELECT EXD_CHVE FROM inserted AS ins INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON ins.EXM_EANO = adi.EXM_EANO AND ins.EXM_CODI = adi.EXM_CODI AND ins.EXM_COPE = adi.EXM_COPE INNER JOIN PRO_EXDA AS xda WITH(NOLOCK) ON adi.EXA_CHVE = xda.EXA_CHVE WHERE xda.DOC_CODI = '9E06')
	END
-- verifica se campos "Cod. Pautal Artigo", "Massa Líquida", "Qtd. Unidades", "Valor", "Frete", "Seguro" ou "Valor Estatístico" foram alterados e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO" para colocar declarações como pendentes de envio para Portal MyRangel
	IF (UPDATE(APA_CP33) OR UPDATE(EXA_MLQD) OR UPDATE(EXA_QUSU) OR UPDATE(EXA_VALO) OR UPDATE(EXA_VFRE) OR UPDATE(EXA_VSEG) OR UPDATE(EXA_VEST)) 
		AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT EXA_CHVE
			FROM inserted 
			WHERE EXA_PMRP = 0 
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE PRO_EXAD SET 
				EXA_PMRP = 1				
			WHERE EXA_CHVE = @IdAdicao
			FETCH NEXT FROM Adicoes INTO @IdAdicao
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes				
	END
END

ALTER TABLE [dbo].[PRO_EXAD] ENABLE TRIGGER [TAU_PRO_EXAD]
/****** Object:  Trigger [TAD_PRO_EXCE_EXPSAE]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_EXCE_EXPSAE] ON [PRO_EXCE] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @IdRegisto bigint, @DataAtual datetime, @IdUtilizador int
-- processa automatismos relacionados com o pedido "E0CCE" quando o período transitório está ativo
	IF EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_PTEX = 1)
	BEGIN
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem o pedido "E0CCE" existente no detalhe de pedidos da declaração EXP-SAE cuja origem é de certificados mas que já não satisfaz a condição
		DECLARE Certificados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpe.id, uti.UTI_IDTY
			FROM deleted AS del
				INNER JOIN PRO_EXML AS ddg WITH(NOLOCK) ON del.EXM_EANO = ddg.EXM_EANO AND del.EXM_CODI = ddg.EXM_CODI AND del.EXM_COPE = ddg.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ddg.EXM_UALT, ddg.EXM_UCRI) = uti.UTI_UTIL
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ddg.EXM_EANO = dad.EXM_EANO AND ddg.EXM_CODI = dad.EXM_CODI AND ddg.DEC_CODI = dad.EXM_COPE AND dad.EXA_LINH = 1
				INNER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON dad.EXA_CHVE = dpe.id_adicao AND dpe.origem = 4							
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.id_pedido = ped.TXM_IDTY
			WHERE ddg.EXM_CNTX = 1 AND ((NOT EXISTS(SELECT 1 
													FROM PRO_EXCE WITH(NOLOCK) 
													WHERE EXM_EANO = del.EXM_EANO AND EXM_CODI = del.EXM_CODI AND EXM_COPE = del.EXM_COPE)) OR ped.TXM_IDTY IS NULL) 
		OPEN Certificados
		FETCH NEXT FROM Certificados INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN			
-- atualiza o pedido "E0CCE" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesPedidos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o pedido "E0CCE" existente no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesPedidos		
			WHERE id = @IdRegisto			
			FETCH NEXT FROM Certificados INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Certificados
		DEALLOCATE Certificados
	END
	ELSE
	BEGIN
-- obtem o pedido "E0CCE" existente no detalhe de pedidos da declaração EXP-SAE cuja origem é de certificados mas que já não satisfaz a condição
		DECLARE Certificados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT del.EXM_EANO, del.EXM_CODI, del.EXM_COPE, dpe.EXP_CHVE
			FROM deleted AS del
				INNER JOIN PRO_EXML AS ddg WITH(NOLOCK) ON del.EXM_EANO = ddg.EXM_EANO AND del.EXM_CODI = ddg.EXM_CODI AND del.EXM_COPE = ddg.DEC_CODI
				INNER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON del.EXM_EANO = dpe.EXM_EANO AND del.EXM_CODI = dpe.EXM_CODI AND del.EXM_COPE = dpe.EXM_COPE AND dpe.EXP_ORIG = 4							
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.TXM_CODI = ped.TXM_CODI				
			WHERE ddg.EXM_CNTX = 1 AND ((NOT EXISTS(SELECT 1 
													FROM PRO_EXCE WITH(NOLOCK) 
													WHERE EXM_EANO = del.EXM_EANO AND EXM_CODI = del.EXM_CODI AND EXM_COPE = del.EXM_COPE)) OR ped.TXM_IDTY IS NULL) 
		OPEN Certificados
		FETCH NEXT FROM Certificados INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- remove o pedido "E0CCE" existente no detalhe de pedidos da declaração EXP-SAE
			DELETE FROM PRO_EXPA		
			WHERE EXP_CHVE = @IdRegisto
-- atualiza os pedidos posteriores da declaração EXP-SAE
			UPDATE PRO_EXPA SET EXP_LINH = EXP_LINH - 1    
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao AND EXP_CHVE > @IdRegisto
			FETCH NEXT FROM Certificados INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		END
		CLOSE Certificados
		DEALLOCATE Certificados
	END
END

ALTER TABLE [dbo].[PRO_EXCE] ENABLE TRIGGER [TAD_PRO_EXCE_EXPSAE]
/****** Object:  Trigger [TAI_PRO_EXCE_EXPSAE]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_EXCE_EXPSAE] ON [PRO_EXCE] AFTER INSERT AS
BEGIN
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @NumRegisto int, @DataAtual datetime, @IdAdicao int, @IdUtilizador int
	DECLARE @CodPedido varchar(5), @NumeroPedido varchar(512), @IdPedido int
-- processa automatismos relacionados com o pedido "E0CCE" quando o período transitório está ativo
	IF EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_PTEX = 1)
	BEGIN
-- obtem data atual GMT
		SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem o pedido "E0CCE" associado aos certificados das 1ªs adições de declarações EXP-SAE inseridas
		DECLARE Certificados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.EXA_CHVE, uti.UTI_IDTY, ped.TXM_IDTY, SUBSTRING(ped.TXM_TEXT, 1, 512)			
			FROM inserted AS ins 	
				INNER JOIN PRO_EXML AS ddg WITH(NOLOCK) ON ins.EXM_EANO = ddg.EXM_EANO AND ins.EXM_CODI = ddg.EXM_CODI AND ins.EXM_COPE = ddg.DEC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ddg.EXM_UALT, ddg.EXM_UCRI) = uti.UTI_UTIL
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ddg.EXM_EANO = dad.EXM_EANO AND ddg.EXM_CODI = dad.EXM_CODI AND ddg.DEC_CODI = dad.EXM_COPE AND dad.EXA_LINH = 1
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'E0CCE'
				LEFT OUTER JOIN tb_EXP_DeclaracoesAdicoesPedidos AS dpe WITH(NOLOCK) ON dad.EXA_CHVE = dpe.id_adicao AND dpe.origem = 4				
			WHERE ddg.EXM_CNTX = 1 AND ins.EXC_LINH = 1 AND dpe.id IS NULL		
		OPEN Certificados
		FETCH NEXT FROM Certificados INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o pedido "E0CCE" no detalhe de pedidos da 1ª adição da declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesAdicoesPedidos(id_adicao, id_pedido, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdPedido, @NumeroPedido, 4, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Certificados INTO @IdAdicao, @IdUtilizador, @IdPedido, @NumeroPedido
		END
		CLOSE Certificados
		DEALLOCATE Certificados	
	END
	ELSE
	BEGIN
-- obtem o pedido "E0CCE" associado aos certificados das declarações EXP-SAE inseridas
		DECLARE Certificados CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, ped.TXM_CODI, SUBSTRING(ped.TXM_TEXT, 1, 512)
			FROM inserted AS ins 	
				INNER JOIN PRO_EXML AS ddg WITH(NOLOCK) ON ins.EXM_EANO = ddg.EXM_EANO AND ins.EXM_CODI = ddg.EXM_CODI AND ins.EXM_COPE = ddg.DEC_CODI
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'E0CCE'
				LEFT OUTER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON ins.EXM_EANO = dpe.EXM_EANO AND ins.EXM_CODI = dpe.EXM_CODI AND ins.EXM_COPE = dpe.EXM_COPE AND dpe.EXP_ORIG = 4				
			WHERE ddg.EXM_CNTX = 1 AND ins.EXC_LINH = 1 AND dpe.EXP_CHVE IS NULL		
		OPEN Certificados
		FETCH NEXT FROM Certificados INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o pedido "E0CCE" no detalhe de pedidos da declaração EXP-SAE
			SET @NumRegisto = ISNULL((SELECT MAX(EXP_LINH) FROM PRO_EXPA WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao), 0) + 1
			INSERT INTO PRO_EXPA(EXM_EANO, EXM_CODI, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC, EXP_ORIG)
			VALUES(@AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumRegisto, @CodPedido, @NumeroPedido, 4)			
			FETCH NEXT FROM Certificados INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido
		END
		CLOSE Certificados
		DEALLOCATE Certificados	
	END
END

ALTER TABLE [dbo].[PRO_EXCE] ENABLE TRIGGER [TAI_PRO_EXCE_EXPSAE]
/****** Object:  Trigger [TAU_PRO_EXCT]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_EXCT] ON [PRO_EXCT] AFTER UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaracao de variaveis 
	DECLARE @IdContentor int
-- verifica se campo "Contentor" foi alterado e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO" para colocar declarações como pendentes de envio para Portal MyRangel
	IF UPDATE(EXC_CONT) AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT EXC_CHVE
			FROM inserted 
			WHERE EXC_PMRP = 0 
		OPEN Contentores
		FETCH NEXT FROM Contentores INTO @IdContentor
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE PRO_EXCT SET 
				EXC_PMRP = 1				
			WHERE EXC_CHVE = @IdContentor
			FETCH NEXT FROM Contentores INTO @IdContentor
		END
		CLOSE Contentores
		DEALLOCATE Contentores				
	END
END

ALTER TABLE [dbo].[PRO_EXCT] ENABLE TRIGGER [TAU_PRO_EXCT]
/****** Object:  Trigger [TAIU_PRO_EXDA]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_EXDA] ON [PRO_EXDA] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- Declaração de variáveis
	DECLARE @Ano int, @Codigo int, @Operador varchar(6), @AnoConta int, @TipoDocConta varchar(4), @IDConta int, @CodMascara int, @CodCliente varchar(18), 
		@CodNatureza varchar(3), @Observacoes varchar(5000)
-- Se documento "9E06" inserido/editado, processa atualizações em todas as adições da declaração e na propria declaração
	IF (UPDATE(DOC_CODI)) and (EXISTS(SELECT EXD_CHVE FROM inserted WHERE DOC_CODI = '9E06'))
	BEGIN
-- Se documento "9E06" inserido/editado, atualiza o "Valor" e o "Valor Estatistico Original" de todas as adições da declaração
		UPDATE PRO_EXAD SET EXA_VALO = 0, EXA_VEOR = EXA_VEST
		FROM PRO_EXAD AS adc WITH(NOLOCK) INNER JOIN (SELECT adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE
			FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE
			WHERE ins.DOC_CODI = '9E06') as ain ON adc.EXM_EANO = ain.EXM_EANO and adc.EXM_CODI = ain.EXM_CODI and adc.EXM_COPE = ain.EXM_COPE		
		WHERE ISNULL(adc.EXA_VALO, 0) <> 0
-- Se documento "9E06" inserido/editado, atualiza o valor dos campos "Condição Entrega", "Nat. Transação" e "Montante" da declaração
		UPDATE PRO_EXML SET CEN_CO20 = NULL, CEN_NO20 = NULL, EXM_LG20 = NULL, NTR_CO24 = NULL, NTR_NO24 = NULL, EXM_MT22 = 0
		FROM PRO_EXML AS exm WITH(NOLOCK) INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON exm.EXM_EANO = adi.EXM_EANO and exm.EXM_CODI = adi.EXM_CODI and exm.DEC_CODI = adi.EXM_COPE
			INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE
		WHERE ins.DOC_CODI = '9E06'
	END
-- Se documento "N740" inserido/editado na 1ª adição, processa actualizações no SDS Via-Aérea associado (se este existir ou configurações ativas)
	IF (UPDATE(DOC_CODI)) or (UPDATE(EXD_DTEM))
	BEGIN
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE 
			FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE 
				LEFT OUTER JOIN deleted as del ON ins.EXD_CHVE = del.EXD_CHVE
			WHERE adi.EXA_LINH = 1 and (ins.DOC_CODI = 'N740' or del.DOC_CODI = 'N740')
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @Ano, @Codigo, @Operador
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC SP_ExportacaoXML_GeraLinhaSDSViaAerea @Ano, @Codigo, @Operador
			FETCH NEXT FROM Documentos INTO @Ano, @Codigo, @Operador
		END
		CLOSE Documentos
		DEALLOCATE Documentos
	END
-- Se documento inserido/editado na 1ª adição, processa actualizações na Conta associada se configuração o permitir
	IF ((UPDATE(DOC_CODI)) or (UPDATE(EXD_NREF)) or (UPDATE(EXD_DTEM))) and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_BCNR IN (0, 2)))
	BEGIN
		DECLARE Contas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT cdo.CDO_EANO, cdo.CDO_TDOC, cdo.CDO_IDEN, exm.EXM_EANO, exm.EXM_CODI, exm.DEC_CODI, exm.NDE_CODI, exm.CLI_COD2, exm.EXM_MASC
			FROM FAC_CDOC AS cdo WITH(NOLOCK) INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON cdo.CDO_PANO = exm.EXM_EANO and cdo.CDO_NPRO = exm.EXM_NRII and cdo.EXM_OPER = exm.DEC_CODI
				INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON exm.EXM_EANO = adi.EXM_EANO and exm.EXM_CODI = adi.EXM_CODI and exm.DEC_CODI = adi.EXM_COPE		
				INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE 		
				INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''	
			WHERE ((pde.PDE_BCNR = 0) OR ((pde.PDE_BCNR = 2) AND (exm.EXM_ASAI = 0))) AND cdo.CDO_IMEX = 1 AND cdo.CDO_STAT = 0 AND adi.EXA_LINH = 1
		OPEN Contas
		FETCH NEXT FROM Contas INTO @AnoConta, @TipoDocConta, @IDConta, @Ano, @Codigo, @Operador, @CodNatureza, @CodCliente, @CodMascara
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC SP_ObtemObservacoesParaConta @CodMascara, @Ano, @Codigo, @CodCliente, @CodNatureza, @Operador, @Observacoes OUTPUT
			UPDATE FAC_CDOC SET CDO_OBSR = @Observacoes
			WHERE CDO_EANO = @AnoConta and CDO_TDOC = @TipoDocConta and CDO_IDEN = @IDConta
			FETCH NEXT FROM Contas INTO @AnoConta, @TipoDocConta, @IDConta, @Ano, @Codigo, @Operador, @CodNatureza, @CodCliente, @CodMascara
		END
		CLOSE Contas
		DEALLOCATE Contas		
	END		
END

ALTER TABLE [dbo].[PRO_EXDA] ENABLE TRIGGER [TAIU_PRO_EXDA]
/****** Object:  Trigger [TAIUD_PRO_EXDA]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_EXDA] ON [PRO_EXDA] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	if UPDATE(DOC_CODI) or UPDATE(EXD_NREF) or UPDATE(EXD_DTEM) or UPDATE(EXD_DTFV)
	begin
		insert into LOG_EXDA (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, EXD_CHVE, EXA_CHVE, DOC_CODI, EXD_NREF, EXD_DTEM, EXD_DTFV, EXM_EANO, 
			EXM_CODI, EXM_COPE, EXA_LINH)
		select NEWID(), (case (select count(*) from deleted where EXD_CHVE = inserted.EXD_CHVE) when 0 then 0 else 1 end), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), EXD_CHVE, 
			EXA_CHVE, DOC_CODI, EXD_NREF, EXD_DTEM, EXD_DTFV, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH
		from inserted
		where ((select count(*) from deleted where EXD_CHVE = inserted.EXD_CHVE) = 0)
			or ((select count(*) from deleted where EXD_CHVE = inserted.EXD_CHVE and ((DOC_CODI <> inserted.DOC_CODI) or 
			(isnull(EXD_NREF, '') <> isnull(inserted.EXD_NREF, '')) or (isnull(EXD_DTEM, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXD_DTEM, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or 
			(isnull(EXD_DTFV, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXD_DTFV, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())))) > 0)
	end
	else
	begin
		insert into LOG_EXDA (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, EXD_CHVE, EXA_CHVE, DOC_CODI, EXD_NREF, EXD_DTEM, EXD_DTFV, EXM_EANO, 
			EXM_CODI, EXM_COPE, EXA_LINH)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), EXD_CHVE, EXA_CHVE, DOC_CODI, EXD_NREF, EXD_DTEM, EXD_DTFV, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH
		from deleted
		where (select count(*) from inserted where EXD_CHVE = deleted.EXD_CHVE) = 0
	end
END

ALTER TABLE [dbo].[PRO_EXDA] ENABLE TRIGGER [TAIUD_PRO_EXDA]
/****** Object:  Trigger [TAD_PRO_EXDM_EXPSAE]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_EXDM_EXPSAE] ON [PRO_EXDM] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaracao de variaveis 
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @VolsDirty int, @VolsClean int, @VolsScan int
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- obtem os manifestos das declarações EXP-SAE removidas que tenham atribuído Carta de Porte
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.EXM_EANO, del.EXM_CODI, del.EXM_COPE, 
			SUM((CASE del.EXM_TPMN WHEN 'D' THEN 1 ELSE 0 END)), 
			SUM((CASE del.EXM_TPMN WHEN 'C' THEN 1 ELSE 0 END)), 
			SUM((CASE del.EXM_TPMN WHEN 'S' THEN 1 ELSE 0 END)) 
		FROM deleted AS del 
			INNER JOIN PRO_EXML AS ddg WITH(NOLOCK) ON del.EXM_EANO = ddg.EXM_EANO AND del.EXM_CODI = ddg.EXM_CODI AND del.EXM_COPE = ddg.DEC_CODI
		WHERE ddg.EXM_CNTX = 1 AND ISNULL(del.EXM_NCPT, '') <> ''
		GROUP BY del.EXM_EANO, del.EXM_CODI, del.EXM_COPE
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @VolsDirty, @VolsClean, @VolsScan
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- atualiza volumes dirty, clean e scan na declaração EXP-SAE
		UPDATE PRO_EXML SET 
			EXM_VDIR = ISNULL(EXM_VDIR, 0) - @VolsDirty, 
			EXM_VCLE = ISNULL(EXM_VCLE, 0) - @VolsClean, 
			EXM_VSCA = EXM_VSCA - @VolsScan
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodOperadorDeclaracao
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @VolsDirty, @VolsClean, @VolsScan
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER TABLE [dbo].[PRO_EXDM] ENABLE TRIGGER [TAD_PRO_EXDM_EXPSAE]
/****** Object:  Trigger [TAI_PRO_EXDM_EXPSAE]    Script Date: 04-11-2025 10:22:22 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_EXDM_EXPSAE] ON [PRO_EXDM] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaracao de variaveis 
	DECLARE @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @VolsDirty int, @VolsClean int, @VolsScan int
-- processa automatismos relacionados com a alteração do tipo
	IF (ISNULL(CONTEXT_INFO(), 0x0) <> 0x44495341424C4544) AND (UPDATE(EXM_TPMN) OR UPDATE(EXM_NCPT)) --"DISABLED" em binário
	BEGIN
-- obtem os manifestos das declarações EXP-SAE inseridas/alteradas que tenham atribuído Carta de Porte
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE, 
				SUM((CASE WHEN (ins.EXM_TPMN = 'D') AND (ISNULL(ins.EXM_NCPT, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.EXM_TPMN = 'D') AND (ISNULL(del.EXM_NCPT, '') <> '') THEN 1 ELSE 0 END)), 
				SUM((CASE WHEN (ins.EXM_TPMN = 'C') AND (ISNULL(ins.EXM_NCPT, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.EXM_TPMN = 'C') AND (ISNULL(del.EXM_NCPT, '') <> '') THEN 1 ELSE 0 END)), 
				SUM((CASE WHEN (ins.EXM_TPMN = 'S') AND (ISNULL(ins.EXM_NCPT, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.EXM_TPMN = 'S') AND (ISNULL(del.EXM_NCPT, '') <> '') THEN 1 ELSE 0 END)) 
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.EXM_CHVE = del.EXM_CHVE
				INNER JOIN PRO_EXML AS ddg WITH(NOLOCK) ON ins.EXM_EANO = ddg.EXM_EANO AND ins.EXM_CODI = ddg.EXM_CODI AND ins.EXM_COPE = ddg.DEC_CODI
			WHERE ddg.EXM_CNTX = 1 AND ((ISNULL(ins.EXM_NCPT, '') <> '') OR (ISNULL(del.EXM_NCPT, '') <> ''))
			GROUP BY ins.EXM_EANO, ins.EXM_CODI, ins.EXM_COPE
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @VolsDirty, @VolsClean, @VolsScan
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza volumes dirty, clean e scan na declaração EXP-SAE
			UPDATE PRO_EXML SET 
				EXM_VDIR = ISNULL(EXM_VDIR, 0) + @VolsDirty, 
				EXM_VCLE = ISNULL(EXM_VCLE, 0) + @VolsClean, 
				EXM_VSCA = EXM_VSCA + @VolsScan
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND DEC_CODI = @CodOperadorDeclaracao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @VolsDirty, @VolsClean, @VolsScan
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
END

ALTER TABLE [dbo].[PRO_EXDM] ENABLE TRIGGER [TAI_PRO_EXDM_EXPSAE]
/****** Object:  Trigger [TAIU_PRO_EXDS]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_EXDS] ON [PRO_EXDS] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- Se 1ª registo de declaração sumária inserido/editado na 1ª adição, processa actualizações na Conta associada se configuração o permitir
	IF (UPDATE(EXD_DESC)) and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WHERE PDE_BCNR IN (0, 2)))
	BEGIN
		UPDATE FAC_CDOC SET CDO_CTMR = EXD_DESC
		FROM FAC_CDOC as cdo INNER JOIN PRO_EXML as exm ON cdo.CDO_PANO = exm.EXM_EANO and cdo.CDO_NPRO = exm.EXM_NRII and cdo.EXM_OPER = exm.DEC_CODI
			INNER JOIN PRO_EXAD as adi ON exm.EXM_EANO = adi.EXM_EANO and exm.EXM_CODI = adi.EXM_CODI and exm.DEC_CODI = adi.EXM_COPE		
			INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE 		
			INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''	
		WHERE ((pde.PDE_BCNR = 0) OR ((pde.PDE_BCNR = 2) AND (exm.EXM_ASAI = 0))) AND cdo.CDO_IMEX = 1 AND cdo.CDO_STAT = 0 AND adi.EXA_LINH = 1 
			AND ins.EXD_CHVE = (SELECT MIN(EXD_CHVE) FROM PRO_EXDS WHERE EXA_CHVE = ins.EXA_CHVE) 
	END		
END

ALTER TABLE [dbo].[PRO_EXDS] ENABLE TRIGGER [TAIU_PRO_EXDS]
/****** Object:  Trigger [TAI_PRO_EXFI]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_EXFI] ON [PRO_EXFI] AFTER INSERT AS 
BEGIN
	SET NOCOUNT ON;
-- atualiza declaração c/ flag de indicação que possui ficheiros anexados via "Drag & Drop" do email
	UPDATE PRO_EXML SET EXM_DDDM = 1
	FROM PRO_EXML as exm INNER JOIN inserted as ins ON exm.EXM_EANO = ins.EXM_EANO and exm.EXM_CODI = ins.EXM_CODI and exm.DEC_CODI = ins.DEC_CODI
	WHERE exm.EXM_DDDM = 0 and ins.EXF_ODDM = 1
END

ALTER TABLE [dbo].[PRO_EXFI] ENABLE TRIGGER [TAI_PRO_EXFI]
/****** Object:  Trigger [TAD_PRO_EXML]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_EXML] ON [PRO_EXML] FOR DELETE AS 
BEGIN
set nocount on
-- declaracao de variaveis
declare @ano int, @cod int, @ope varchar(6), @codrefint int
-- busca dados a apagar --------------------------------------------------------------------
DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
SELECT EXM_EANO, EXM_CODI, DEC_CODI, EXM_NRII
FROM deleted
OPEN Detalhe
FETCH NEXT FROM Detalhe INTO @ano, @cod, @ope, @codrefint
WHILE @@FETCH_STATUS = 0
BEGIN	
	-- apagar certificados comprovativos de exportação 
	DELETE FROM PRO_EXCE WHERE EXM_EANO = @ano AND EXM_CODI = @cod AND EXM_COPE = @ope
	-- apagar detalhes dos certificados comprovativos de exportação 
	DELETE FROM PRO_EXCD WHERE EXM_EANO = @ano AND EXM_CODI = @cod AND EXM_COPE = @ope
	-- apagar adições 
	DELETE FROM PRO_EXAD WHERE EXM_EANO = @ano AND EXM_CODI = @cod AND EXM_COPE = @ope
	-- apagar anexos à declaração 
	DELETE FROM PRO_EXPA WHERE EXM_EANO = @ano AND EXM_CODI = @cod AND EXM_COPE = @ope
	-- apagar contentores 
	DELETE FROM PRO_EXCT WHERE EXM_EANO = @ano AND EXM_CODI = @cod AND EXM_COPE = @ope
	-- apagar paises do itinerario
	DELETE FROM PRO_EXPI WHERE EXM_EANO = @ano AND EXM_CODI = @cod AND EXM_COPE = @ope
	-- apagar documentos anexos
	DELETE FROM PRO_EXFI WHERE EXM_EANO = @ano AND EXM_CODI = @cod AND DEC_CODI = @ope
	-- apagar informação referênte ao modelo EUR1 ------------------------------------
	DELETE FROM PRO_AEUR WHERE DUC_PNUM = @codrefint AND DUC_EANO = @ano AND DEC_CODI = @ope
	DELETE FROM PRO_EUR1 WHERE DUC_PNUM = @codrefint AND DUC_EANO = @ano AND DEC_CODI = @ope

	FETCH NEXT FROM Detalhe INTO @ano, @cod, @ope, @codrefint
END
CLOSE Detalhe
DEALLOCATE Detalhe
set nocount off
END

ALTER TABLE [dbo].[PRO_EXML] ENABLE TRIGGER [TAD_PRO_EXML]
/****** Object:  Trigger [TAI_PRO_EXML_EXPSAE]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_EXML_EXPSAE] ON [PRO_EXML] AFTER INSERT AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @CodOperador varchar(6)
-- obtem as declarações EXP-SAE inseridas
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT DEC_CODI
		FROM inserted
		WHERE EXM_CNTX = 1
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @CodOperador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- atualiza próximo numero no declarante operador
		UPDATE TAB_DECL SET DEC_NPRO = ISNULL(DEC_NPRO, 1) + 1	
		WHERE DEC_CODI = @CodOperador
		FETCH NEXT FROM Declaracoes INTO @CodOperador
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
END

ALTER TABLE [dbo].[PRO_EXML] ENABLE TRIGGER [TAI_PRO_EXML_EXPSAE]
/****** Object:  Trigger [TAIU_PRO_EXML_EXPSAE]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_EXML_EXPSAE] ON [PRO_EXML] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
	SET DATEFORMAT DMY;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @PeriodoTransitorio bit, @IdDeclaracao bigint, @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @IdUtilizador int, @IdRegisto bigint, 
		@NumRegisto int
	DECLARE @CodFollowUpNatureza int
	DECLARE @IdDocumento int, @NumeroDocumento varchar(70), @TipoDocumento tinyint
	DECLARE @NumeroAutorizacao varchar(35), @TitularAutorizacao varchar(17)
	DECLARE @CodPedido varchar(5), @NumeroPedido varchar(512)	
	DECLARE @IdStatusIncidencia int, @ReleaseHoldStatusIncidencia varchar(1)
	DECLARE @CodPais varchar(2), @NomePais varchar(25)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem configuração do periodo transitório EXP-SAE dos Parâmetros de Despachos
	SELECT TOP 1 @PeriodoTransitorio = PDE_PTEX 
	FROM TAB_PDES WITH(NOLOCK)
-- processa automatismos relacionados com a alteração da natureza
	IF UPDATE(NDE_CODI)
	BEGIN
-- obtem as declarações EXP-SAE inseridas/alteradas cuja natureza tem associado um follow-up de exportação e que valida utilizador
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY , (CASE 
									WHEN ISNULL(ugr.UTI_UTIL, '') <> '' THEN fup.FUP_CODI 
									ELSE ISNULL((SELECT TOP 1 sfu.FUP_CODI
												FROM GIDWIN.dbo.FAP_FWUP AS sfu WITH(NOLOCK) 
													INNER JOIN GIDWIN.dbo.FAP_UGRU AS sug WITH (NOLOCK) ON ins.EXM_UALT = sug.UTI_UTIL AND sfu.GRU_CODI = sug.GRU_CODI
												WHERE sfu.FUP_EXPO = 1 AND sfu.FUP_VUTI = 1 AND sfu.FUP_CODI <> fup.FUP_CODI), fup.FUP_CODI) 
								END)
			FROM inserted AS ins 				
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON ins.NDE_CODI = nde.NDE_CODI
				INNER JOIN GIDWIN.dbo.FAP_FWUP AS fup WITH(NOLOCK) ON nde.FUP_CODI = fup.FUP_CODI
				LEFT OUTER JOIN GIDWIN.dbo.FAP_UGRU AS ugr WITH (NOLOCK) ON ins.EXM_UALT = ugr.UTI_UTIL AND fup.GRU_CODI = ugr.GRU_CODI
			WHERE ins.EXM_CNTX = 1 AND fup.FUP_EXPO = 1 AND fup.FUP_VUTI = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @CodFollowUpNatureza
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza follow-up na declaração EXP-SAE
			UPDATE PRO_EXML SET FUP_CODI = @CodFollowUpNatureza
			WHERE EXM_IDTY = @IdDeclaracao AND ISNULL(FUP_CODI, -1) <> @CodFollowUpNatureza
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @CodFollowUpNatureza
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem as declarações EXP-SAE inseridas/alteradas cuja natureza tem associado um status de incidência/cosmo code
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, uti.UTI_IDTY, ISNULL(sti.SIN_IDTY, cco.COS_IDTY), (CASE WHEN cco.COS_RELI = 1 THEN 'R' WHEN cco.COS_HOLD = 1 THEN 'H' ELSE NULL END)
			FROM inserted AS ins 				
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON ins.NDE_CODI = nde.NDE_CODI		
				LEFT OUTER JOIN TAB_SINC AS sti WITH(NOLOCK) ON nde.SIN_CODI = sti.SIN_CODI
				LEFT OUTER JOIN TAB_COSM AS cco WITH(NOLOCK) ON nde.SIN_CODI = cco.COS_CODE
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL
			WHERE ins.EXM_CNTX = 1 AND (sti.SIN_IDTY IS NOT NULL OR cco.COS_IDTY IS NOT NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia, @ReleaseHoldStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN		
-- insere o status de incidência no detalhe de incidências da declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesIncidencias(id_declaracaoEXP, id_statusIncidencia, dataInicio, dataFim, id_utilizadorCriacao, dataCriacao, releaseHold, origem, id_utilizadorControlo, 
				dataControlo)			
			VALUES(@IdDeclaracao, @IdStatusIncidencia, @DataAtual, @DataAtual, @IdUtilizador, @DataAtual, @ReleaseHoldStatusIncidencia, 1, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia, @ReleaseHoldStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- processa automatismos relacionados com a alteração do exportador (cliente)
	IF UPDATE(CLI_COD2)
	BEGIN
-- obtem as declarações EXP-SAE inseridas/alteradas cujo exportador (cliente) tem associado um cosmo code e este ainda não existe no detalhe de incidências da declaração EXP-SAE
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, uti.UTI_IDTY, cco.COS_IDTY, (CASE WHEN cco.COS_RELI = 1 THEN 'R' WHEN cco.COS_HOLD = 1 THEN 'H' ELSE NULL END)
			FROM inserted AS ins 				
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.CLI_COD2 = cli.CLI_CODI	
				INNER JOIN TAB_COSM AS cco WITH(NOLOCK) ON (CASE RIGHT(ins.EAD_CODA, 3) WHEN '015' THEN cli.COS_CDLS WHEN '020' THEN cli.COS_CDPO ELSE NULL END) = cco.COS_CODE
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL
			WHERE ins.EXM_CNTX = 1 AND NOT EXISTS(SELECT 1 FROM tb_EXP_DeclaracoesIncidencias WITH(NOLOCK) WHERE id_declaracaoEXP = ins.EXM_IDTY AND id_statusIncidencia = cco.COS_IDTY)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia, @ReleaseHoldStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN		
-- insere o cosmo code no detalhe de incidências da declaração EXP-SAE
			INSERT INTO tb_EXP_DeclaracoesIncidencias(id_declaracaoEXP, id_statusIncidencia, dataInicio, dataFim, id_utilizadorCriacao, dataCriacao, releaseHold, origem, id_utilizadorControlo, 
				dataControlo)			
			VALUES(@IdDeclaracao, @IdStatusIncidencia, @DataAtual, @DataAtual, @IdUtilizador, @DataAtual, @ReleaseHoldStatusIncidencia, 2, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia, @ReleaseHoldStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do exportador (cliente) e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND UPDATE(CLI_COD2)
	BEGIN
-- obtem o documento OEA associado ao exportador (cliente) das declarações EXP-SAE inseridas/alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, NULLIF(cli.CLI_NAOE, ''), ddo.id
			FROM inserted AS ins 	
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.CLI_COD2 = cli.CLI_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cli.DOC_CDOE = doc.DOC_CODI	
				LEFT OUTER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 2					
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL
			WHERE ins.EXM_CNTX = 1 AND cli.CLI_FXOE IN (0, 2) AND ISNULL(cli.CLI_NAOE, '') <> '' AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere/atualiza o documento OEA como "Referência Adicional" no detalhe de documentos da declaração EXP-SAE
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 2, @IdDocumento, @NumeroDocumento, 2, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesDocumentos SET
					id_documento = @IdDocumento, 
					numero = @NumeroDocumento, 					
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem o documento OEA existente no detalhe de documentos da declaração EXP-SAE cuja origem é do OEA exportador mas que já não satisfaz as condições ou não existe no OEA cliente exportador
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 2					
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.CLI_COD2 = cli.CLI_CODI	
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cli.DOC_CDOE = doc.DOC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
			WHERE ins.EXM_CNTX = 1 AND (cli.CLI_FXOE NOT IN (0, 2) OR ISNULL(cli.CLI_NAOE, '') = '' OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento OEA existente no detalhe de documentos da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento OEA existente no detalhe de documentos da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- obtem os documentos associados ao exportador (cliente) das declarações EXP-SAE inseridas/alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, ddo.id, 
				ISNULL(NULLIF(cdo.CLD_NDOC, ''), (CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END))	
			FROM inserted AS ins 
				INNER JOIN TAB_CLDO AS cdo WITH(NOLOCK) ON ins.CLI_COD2 = cdo.CLI_CODI				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON cdo.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 3
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL
			WHERE ins.EXM_CNTX = 1 AND cdo.CLD_UEXP = 1 AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @IdRegisto, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o documento como "Suporte" no detalhe de documentos da declaração EXP-SAE
		    IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 0, @IdDocumento, @NumeroDocumento, 3, @IdUtilizador, @DataAtual)				
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesDocumentos SET					
					numero = @NumeroDocumento, 					
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @IdRegisto, @NumeroDocumento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- obtem os documentos existentes no detalhe de documentos da declaração EXP-SAE cuja origem é do exportador mas que já não satisfazem as condições ou não existem no detalhe de documentos do cliente exportador
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 3				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_CLDO AS cdo WITH(NOLOCK) ON ins.CLI_COD2 = cdo.CLI_CODI AND doc.DOC_CODI = cdo.DOC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
			WHERE ins.EXM_CNTX = 1 AND (cdo.CLD_UEXP = 0 OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR cdo.DOC_CODI IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento existente no detalhe de documentos da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento existente no detalhe de documentos da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
	END
-- processa automatismos relacionados com a alteração do exportador (cliente) ou estatuto e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND (UPDATE(CLI_COD2) OR UPDATE(EXM_TP14))
	BEGIN
-- obtem o pedido "G1PRO" associado ao estatuto das declarações EXP-SAE inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, ped.TXM_CODI, NULLIF(cli.CLI_NDHA, ''), dpe.EXP_CHVE
			FROM inserted AS ins 				
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.CLI_COD2 = cli.CLI_CODI
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = 'G1PRO'
				LEFT OUTER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON ins.EXM_EANO = dpe.EXM_EANO AND ins.EXM_CODI = dpe.EXM_CODI AND ins.DEC_CODI = dpe.EXM_COPE AND dpe.EXP_ORIG = 1				
			WHERE ins.EXM_CNTX = 1 AND ISNULL(ins.EXM_TP14, 0) = 2				
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o pedido "G1PRO" no detalhe de pedidos da declaração EXP-SAE
			IF @IdRegisto IS NULL
			BEGIN
				SET @NumRegisto = ISNULL((SELECT MAX(EXP_LINH) FROM PRO_EXPA WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao), 0) + 1
				INSERT INTO PRO_EXPA(EXM_EANO, EXM_CODI, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC, EXP_ORIG)
				VALUES(@AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumRegisto, @CodPedido, @NumeroPedido, 1)
			END
			ELSE
			BEGIN
				UPDATE PRO_EXPA SET
					TXM_CODI = @CodPedido, 
					TXM_DESC = @NumeroPedido
				WHERE EXP_CHVE = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- obtem o pedido "G1PRO" existente no detalhe de pedidos da declaração EXP-SAE cuja origem é do estatuto mas que já não satisfaz a condição
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, dpe.EXP_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON ins.EXM_EANO = dpe.EXM_EANO AND ins.EXM_CODI = dpe.EXM_CODI AND ins.DEC_CODI = dpe.EXM_COPE AND dpe.EXP_ORIG = 1								
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.TXM_CODI = ped.TXM_CODI				
			WHERE ins.EXM_CNTX = 1 AND (ISNULL(ins.EXM_TP14, 0) <> 2 OR ped.TXM_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- remove o pedido "G1PRO" existente no detalhe de pedidos da declaração EXP-SAE
			DELETE FROM PRO_EXPA		
			WHERE EXP_CHVE = @IdRegisto
-- atualiza os pedidos posteriores da declaração EXP-SAE
			UPDATE PRO_EXPA SET EXP_LINH = EXP_LINH - 1    
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao AND EXP_CHVE > @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
	END
-- processa automatismos relacionados com a alteração do declarante ou estatuto e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND (UPDATE(DEC_CO14) OR UPDATE(EXM_TP14))
	BEGIN
-- obtem o documento OEA associado ao declarante das declarações EXP-SAE inseridas/alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, NULLIF(dcl.DEC_NAOE, ''), ddo.id
			FROM inserted AS ins 	
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.DEC_CO14 = dcl.DEC_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON (CASE ins.EXM_TP14 WHEN 2 THEN dcl.DOC_CDOE ELSE dcl.DOC_CODI2 END) = doc.DOC_CODI	
				LEFT OUTER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 4					
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL
			WHERE ins.EXM_CNTX = 1 AND dcl.DEC_FXOE IN (0, 2) AND ISNULL(dcl.DEC_NAOE, '') <> '' AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere/atualiza o documento OEA como "Referência Adicional" no detalhe de documentos da declaração EXP-SAE
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, 2, @IdDocumento, @NumeroDocumento, 4, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesDocumentos SET
					id_documento = @IdDocumento, 
					numero = @NumeroDocumento, 					
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem o documento OEA existente no detalhe de documentos da declaração EXP-SAE cuja origem é do OEA declarante mas que já não satisfaz as condições ou não existe no OEA declarante
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 4					
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.DEC_CO14 = dcl.DEC_CODI
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON (CASE ins.EXM_TP14 WHEN 2 THEN dcl.DOC_CDOE ELSE dcl.DOC_CODI2 END) = doc.DOC_CODI	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
			WHERE ins.EXM_CNTX = 1 AND (dcl.DEC_FXOE NOT IN (0, 2) OR ISNULL(dcl.DEC_NAOE, '') = '' OR doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR doc.DOC_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento OEA existente no detalhe de documentos da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento OEA existente no detalhe de documentos da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do tipo declaração adicional, exportador (cliente), país do exportador ou nif do exportador e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND (UPDATE(EXM_TPRO) OR UPDATE(CLI_COD2) OR UPDATE(CLI_PAI2) OR UPDATE(CLI_NIF2))
	BEGIN
-- obtem os documentos "C512" ou "C514" associados ao tipo declaração adicional das declarações EXP-SAE inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, (ISNULL(ins.CLI_PAI2, '') + ISNULL(ins.CLI_NIF2, '')), uti.UTI_IDTY, doc.DOC_IDTY, ISNULL(NULLIF(cau.CAU_NDOC, ''), '*****N/A*****'), dau.id
			FROM inserted AS ins 								
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL						
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE 
																				WHEN ins.EXM_TPRO IN ('C', 'F', 'U', 'Y') THEN 'C512' 
																				WHEN ins.EXM_TPRO IN ('V', 'Z') THEN 'C514' 
																				ELSE NULL 
																			END)
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.CLI_COD2 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND doc.DOC_IDTY = dau.id_documento AND dau.origem = 3				
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_TPRO IN ('C', 'F', 'U', 'V', 'Y', 'Z') AND doc.DOC_EXPT = 1 AND doc.DOC_AUTZ = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o documento "C513" ou "C514" no detalhe de autorizações da declaração EXP-SAE 
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_EXP_DeclaracoesAutorizacoes(id_declaracaoEXP, id_documento, numero, titular, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, @IdDocumento, @NumeroAutorizacao, @TitularAutorizacao, 3, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesAutorizacoes SET
					id_documento = @IdDocumento, 
					numero = @NumeroAutorizacao, 	
					titular = @TitularAutorizacao, 				
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos "C512" ou "C514" existentes no detalhe de autorizações da declaração EXP-SAE cuja origem é do tipo declaração adicional mas que já não satisfazem as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dau.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
				INNER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND dau.origem = 3					
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dau.id_documento = doc.DOC_IDTY AND doc.DOC_CODI = (CASE 
																														WHEN ins.EXM_TPRO IN ('C', 'F', 'U', 'Y') THEN 'C512' 
																														WHEN ins.EXM_TPRO IN ('V', 'Z') THEN 'C514' 
																														ELSE NULL 
																													END)					
			WHERE ins.EXM_CNTX = 1 AND (doc.DOC_EXPT = 0 OR doc.DOC_AUTZ = 0 OR doc.DOC_IDTY IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento "C512" ou "C514" existente no detalhe de autorizações da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAutorizacoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento "C512" ou "C514" existente no detalhe de autorizações da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAutorizacoes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- processa automatismos relacionados com a alteração do regime, exportador (cliente), país do exportador ou nif do exportador e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND (UPDATE(EXM_REGI) OR UPDATE(CLI_COD2) OR UPDATE(CLI_PAI2) OR UPDATE(CLI_NIF2))
	BEGIN
-- obtem os documentos "C601", "C019", "C516", "C517", "C518", "C519", "C990", "D019" ou "N990" associados ao regime das declarações EXP-SAE inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, (ISNULL(ins.CLI_PAI2, '') + ISNULL(ins.CLI_NIF2, '')), uti.UTI_IDTY, doc.DOC_IDTY, ISNULL(NULLIF(cau.CAU_NDOC, ''), '*****N/A*****'), dau.id
			FROM inserted AS ins 								
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL						
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE 
																				WHEN (LEFT(ins.EXM_REGI, 2) = '11') OR (ISNULL(ins.EXM_REGI, '') = '3151') THEN 'C601' 
																				WHEN LEFT(ins.EXM_REGI, 2) IN ('21', '22') THEN 'C019' 																				
																				WHEN (ISNULL(ins.EXM_REGI, '') = '3171') OR (RIGHT(ins.EXM_REGI, 2) = '76') THEN 'C517'
																				WHEN RIGHT(ins.EXM_REGI, 2) = '44' THEN 'C990'
																				ELSE NULL 
																			END)
															OR doc.DOC_CODI = (CASE 
																				WHEN ISNULL(ins.EXM_REGI, '') = '3151' THEN 'C516'
																				WHEN (ISNULL(ins.EXM_REGI, '') = '3171') OR (RIGHT(ins.EXM_REGI, 2) = '76')  THEN 'C518'
																				WHEN RIGHT(ins.EXM_REGI, 2) = '44' THEN 'D019'
																				ELSE NULL 
																			END)
															OR doc.DOC_CODI = (CASE 																				
																				WHEN (ISNULL(ins.EXM_REGI, '') = '3171') OR (RIGHT(ins.EXM_REGI, 2) = '76')  THEN 'C519'
																				WHEN RIGHT(ins.EXM_REGI, 2) = '44' THEN 'N990'
																				ELSE NULL 
																			END)				
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.CLI_COD2 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND doc.DOC_IDTY = dau.id_documento AND dau.origem = 4		
			WHERE ins.EXM_CNTX = 1 
				AND ((LEFT(ins.EXM_REGI, 2) IN ('11', '21', '22')) OR (ISNULL(ins.EXM_REGI, '') = '3151') OR (ISNULL(ins.EXM_REGI, '') = '3171') OR (RIGHT(ins.EXM_REGI, 2) IN ('44', '76'))) 
				AND doc.DOC_EXPT = 1 AND doc.DOC_AUTZ = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o documento "C601", "C019", "C516", "C517", "C518", "C519", "C990", "D019" ou "N990" no detalhe de autorizações da declaração EXP-SAE 
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_EXP_DeclaracoesAutorizacoes(id_declaracaoEXP, id_documento, numero, titular, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, @IdDocumento, @NumeroAutorizacao, @TitularAutorizacao, 4, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesAutorizacoes SET
					id_documento = @IdDocumento, 
					numero = @NumeroAutorizacao, 	
					titular = @TitularAutorizacao, 				
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos "C601", "C019", "C516", "C517", "C518", "C519", "C990", "D019" ou "N990" existentes no detalhe de autorizações da declaração EXP-SAE cuja origem é do regime mas que já não satisfazem as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dau.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
				INNER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND dau.origem = 4				
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dau.id_documento = doc.DOC_IDTY 
					AND (doc.DOC_CODI = (CASE 
											WHEN (LEFT(ins.EXM_REGI, 2) = '11') OR (ISNULL(ins.EXM_REGI, '') = '3151') THEN 'C601' 
											WHEN LEFT(ins.EXM_REGI, 2) IN ('21', '22') THEN 'C019' 																				
											WHEN (ISNULL(ins.EXM_REGI, '') = '3171') OR (RIGHT(ins.EXM_REGI, 2) = '76') THEN 'C517'
											WHEN RIGHT(ins.EXM_REGI, 2) = '44' THEN 'C990'
											ELSE NULL 
										END)
						OR doc.DOC_CODI = (CASE 
											WHEN ISNULL(ins.EXM_REGI, '') = '3151' THEN 'C516'
											WHEN (ISNULL(ins.EXM_REGI, '') = '3171') OR (RIGHT(ins.EXM_REGI, 2) = '76')  THEN 'C518'
											WHEN RIGHT(ins.EXM_REGI, 2) = '44' THEN 'D019'
											ELSE NULL 
										END)
						OR doc.DOC_CODI = (CASE 																				
											WHEN (ISNULL(ins.EXM_REGI, '') = '3171') OR (RIGHT(ins.EXM_REGI, 2) = '76')  THEN 'C519'
											WHEN RIGHT(ins.EXM_REGI, 2) = '44' THEN 'N990'
											ELSE NULL 
										END))
			WHERE ins.EXM_CNTX = 1 AND (doc.DOC_EXPT = 0 OR doc.DOC_AUTZ = 0 OR doc.DOC_IDTY IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento "C601", "C019", "C516", "C517", "C518", "C519", "C990", "D019" ou "N990" existente no detalhe de autorizações da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAutorizacoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento "C601", "C019", "C516", "C517", "C518", "C519", "C990", "D019" ou "N990" existente no detalhe de autorizações da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAutorizacoes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- processa automatismos relacionados com a alteração da estância de apresentação, exportador (cliente), país do exportador ou nif do exportador e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND (UPDATE(EAD_C29A) OR UPDATE(CLI_COD2) OR UPDATE(CLI_PAI2) OR UPDATE(CLI_NIF2))
	BEGIN
-- obtem o documento "C513" associado à estância de apresentação das declarações EXP-SAE inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, (ISNULL(ins.CLI_PAI2, '') + ISNULL(ins.CLI_NIF2, '')), uti.UTI_IDTY, doc.DOC_IDTY, ISNULL(NULLIF(cau.CAU_NDOC, ''), '*****N/A*****'), dau.id
			FROM inserted AS ins 								
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL						
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C513'
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.CLI_COD2 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND doc.DOC_IDTY = dau.id_documento AND dau.origem = 2					
			WHERE ins.EXM_CNTX = 1 AND ISNULL(ins.EAD_C29A, '') <> '' AND doc.DOC_EXPT = 1 AND doc.DOC_AUTZ = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o documento "C513" no detalhe de autorizações da declaração EXP-SAE 
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_EXP_DeclaracoesAutorizacoes(id_declaracaoEXP, id_documento, numero, titular, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, @IdDocumento, @NumeroAutorizacao, @TitularAutorizacao, 2, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesAutorizacoes SET
					id_documento = @IdDocumento, 
					numero = @NumeroAutorizacao, 	
					titular = @TitularAutorizacao, 				
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem o documento "C513" existente no detalhe de autorizações da declaração EXP-SAE cuja origem é da estância de apresentação mas que já não satisfazem as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dau.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
				INNER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND dau.origem = 2						
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'C513' AND dau.id_documento = doc.DOC_IDTY					
			WHERE ins.EXM_CNTX = 1 AND (ISNULL(ins.EAD_C29A, '') = '' OR doc.DOC_EXPT = 0 OR doc.DOC_AUTZ = 0 OR doc.DOC_IDTY IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento "C513" existente no detalhe de autorizações da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAutorizacoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento "C513" existente no detalhe de autorizações da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAutorizacoes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do NRG, exportador (cliente), país do exportador ou nif do exportador e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND (UPDATE(EXM_NC48) OR UPDATE(CLI_COD2) OR UPDATE(CLI_PAI2) OR UPDATE(CLI_NIF2))
	BEGIN
-- obtem os documentos "C505" e "C506" associados ao NRG das declarações EXP-SAE inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, (ISNULL(ins.CLI_PAI2, '') + ISNULL(ins.CLI_NIF2, '')), uti.UTI_IDTY, doc.DOC_IDTY, ISNULL(NULLIF(cau.CAU_NDOC, ''), '*****N/A*****'), dau.id
			FROM inserted AS ins 								
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL						
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI IN ('C505', 'C506')
				LEFT OUTER JOIN TAB_CLAU AS cau WITH(NOLOCK) ON ins.CLI_COD2 = cau.CLI_CODI AND doc.DOC_CODI = cau.DOC_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND doc.DOC_IDTY = dau.id_documento AND dau.origem = 1					
			WHERE ins.EXM_CNTX = 1 AND ISNULL(ins.EXM_NC48, '') <> '' AND doc.DOC_EXPT = 1 AND doc.DOC_AUTZ = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere/atualiza o documento "C505" e "C506" no detalhe de autorizações da declaração EXP-SAE 
			IF @IdRegisto IS NULL
			BEGIN
				INSERT INTO tb_EXP_DeclaracoesAutorizacoes(id_declaracaoEXP, id_documento, numero, titular, origem, id_utilizadorControlo, dataControlo)
				VALUES(@IdDeclaracao, @IdDocumento, @NumeroAutorizacao, @TitularAutorizacao, 1, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_EXP_DeclaracoesAutorizacoes SET
					id_documento = @IdDocumento, 
					numero = @NumeroAutorizacao, 	
					titular = @TitularAutorizacao, 				
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdRegisto
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TitularAutorizacao, @IdUtilizador, @IdDocumento, @NumeroAutorizacao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos "C505" e "C506" existentes no detalhe de autorizações da declaração EXP-SAE cuja origem é do NRG mas que já não satisfazem as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dau.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
				INNER JOIN tb_EXP_DeclaracoesAutorizacoes AS dau WITH(NOLOCK) ON ins.EXM_IDTY = dau.id_declaracaoEXP AND dau.origem = 1							
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI IN ('C505', 'C506') AND dau.id_documento = doc.DOC_IDTY					
			WHERE ins.EXM_CNTX = 1 AND (ISNULL(ins.EXM_NC48, '') = '' OR doc.DOC_EXPT = 0 OR doc.DOC_AUTZ = 0 OR doc.DOC_IDTY IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento "C505" e "C506" existente no detalhe de autorizações da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAutorizacoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento "C505" e "C506" existente no detalhe de autorizações da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAutorizacoes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do regime ou país destino e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND (UPDATE(EXM_REGI) OR UPDATE(EXM_P17A))
	BEGIN
-- obtem o documentos "N821" associado ao par regime/país destino das declarações EXP-SAE inseridas/alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, doc.DOC_IDTY, doc.DOC_DTRA, uti.UTI_IDTY
			FROM inserted AS ins 								
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N821'
				LEFT OUTER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 5
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL						
			WHERE ins.EXM_CNTX = 1 AND LEFT(ins.EXM_REGI, 2) IN ('10', '11', '21', '22', '23') AND ins.EXM_P17A IN ('NO', 'GB', 'CH', 'CY', 'IS', 'LI', 'MK', 'NO', 'RS', 'TR') 
				AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4 AND ddo.id IS NULL 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento "N821" como "Suporte"/"Transporte" no detalhe de documentos da declaração EXP-SAE 
			INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @TipoDocumento, @IdDocumento, 5, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos "N821" existentes no detalhe de autorizações da declaração EXP-SAE cuja origem é do par regime/país destino mas que já não satisfazem as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 5							
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N821' AND ddo.id_documento = doc.DOC_IDTY	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
			WHERE ins.EXM_CNTX = 1 AND (LEFT(ins.EXM_REGI, 2) NOT IN ('10', '11', '21', '22', '23') OR ins.EXM_P17A NOT IN ('NO', 'GB', 'CH', 'CY', 'IS', 'LI', 'MK', 'NO', 'RS', 'TR') 
				OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR doc.DOC_IDTY IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento "N821" existente no detalhe de documentos da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento "N821" existente no detalhe de documentos da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do tipo de declaração e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND UPDATE(TDE_COD1)
	BEGIN	
-- obtem os documentos associados ao tipo de declaração das declarações EXP-SAE inseridas/alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, doc.DOC_IDTY, uti.UTI_IDTY, 				 
				(CASE 					
					WHEN doc.DOC_TDNU = 1 THEN 'S/N' 
					WHEN doc.DOC_TDNU = 2 THEN 'N/A' 
					WHEN doc.DOC_TDNU = 3 THEN 'DEC' 
					ELSE NULL 
				END)
			FROM inserted AS ins 				
				INNER JOIN TAB_TDED AS tdd WITH(NOLOCK) ON ins.TDE_COD1 = tdd.TDE_CODI	
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON tdd.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 6	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL						
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_ASAI = 0 AND doc.DOC_DTRA = 0 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4 AND ddo.id IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento como "Suporte" no detalhe de documentos da declaração EXP-SAE 
			INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, 0, @IdDocumento, @NumeroDocumento, 6, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador, @NumeroDocumento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos existentes no detalhe de documentos da declaração EXP-SAE cuja origem é do tipo declaração mas que já não satisfazem as condições ou não existem no detalhe de documentos do tipo de declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 6		
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_TDED AS tdd WITH(NOLOCK) ON ins.TDE_COD1 = tdd.TDE_CODI AND doc.DOC_CODI = tdd.DOC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_ASAI = 0 AND (doc.DOC_DTRA = 1 OR doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR tdd.DOC_CODI IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento existente no detalhe de documentos da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento existente no detalhe de documentos da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os pedidos associados ao tipo declaração das declarações EXP-SAE inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, tdp.TXM_CODI, SUBSTRING(tdp.TDP_TEXT, 1, 512)
			FROM inserted AS ins 				
				INNER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON ins.TDE_COD1 = tdp.TDE_CODI
				LEFT OUTER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON ins.EXM_EANO = dpe.EXM_EANO AND ins.EXM_CODI = dpe.EXM_CODI AND ins.DEC_CODI = dpe.EXM_COPE AND dpe.EXP_ORIG = 2				
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_ASAI = 0 AND dpe.EXP_CHVE IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o pedido no detalhe de pedidos da declaração EXP-SAE
			SET @NumRegisto = ISNULL((SELECT MAX(EXP_LINH) FROM PRO_EXPA WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao), 0) + 1
			INSERT INTO PRO_EXPA(EXM_EANO, EXM_CODI, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC, EXP_ORIG)
			VALUES(@AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumRegisto, @CodPedido, @NumeroPedido, 2)
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- obtem os pedidos existentes no detalhe de pedidos da declaração EXP-SAE cuja origem é do tipo declaração mas que já não existem no detalhe de pedidos do tipo declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, dpe.EXP_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON ins.EXM_EANO = dpe.EXM_EANO AND ins.EXM_CODI = dpe.EXM_CODI AND ins.DEC_CODI = dpe.EXM_COPE AND dpe.EXP_ORIG = 2								
				LEFT OUTER JOIN TAB_TDEP AS tdp WITH(NOLOCK) ON ins.TDE_COD1 = tdp.TDE_CODI AND dpe.TXM_CODI = tdp.TXM_CODI
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_ASAI = 0 AND tdp.TXM_CODI IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- remove o pedido existente no detalhe de pedidos da declaração EXP-SAE
			DELETE FROM PRO_EXPA		
			WHERE EXP_CHVE = @IdRegisto
-- atualiza os pedidos posteriores da declaração EXP-SAE
			UPDATE PRO_EXPA SET EXP_LINH = EXP_LINH - 1    
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao AND EXP_CHVE > @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do tipo declaração adicional e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND UPDATE(EXM_TPRO)
	BEGIN
-- obtem os documentos "NMRN" e "NCLE" associados ao tipo declaração adicional das declarações EXP-SAE inseridas/alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, doc.DOC_IDTY, uti.UTI_IDTY
			FROM inserted AS ins 								
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE 																				
																				WHEN ins.EXM_TPRO IN ('X', 'Y') THEN 'NMRN'																				
																				WHEN ins.EXM_TPRO = 'Z' THEN 'NCLE'
																				ELSE NULL 
																			END)
				LEFT OUTER JOIN tb_EXP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) ON ins.EXM_IDTY = dpr.id_declaracaoEXP AND doc.DOC_IDTY = dpr.id_documento AND dpr.origem = 1										
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_TPRO IN ('X', 'Y', 'Z') AND doc.DOC_CA40 = 1 AND LEN(doc.DOC_CODI) = 4 AND doc.DOC_EXPT = 1 AND dpr.id IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento "NMRN" ou "NCLE" no detalhe de precedentes da declaração EXP-SAE 
			INSERT INTO tb_EXP_DeclaracoesPrecedentes(id_declaracaoEXP, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdDocumento, '*****N/A*****', 1, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos "NMRN" e "NCLE" existentes no detalhe de precedentes da declaração EXP-SAE cuja origem é do tipo declaração adicional mas que já não satisfazem as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpr.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
				INNER JOIN tb_EXP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) ON ins.EXM_IDTY = dpr.id_declaracaoEXP AND dpr.origem = 1							
				LEFT OUTER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dpr.id_documento = doc.DOC_IDTY AND doc.DOC_CODI = (CASE 																				
																														WHEN ins.EXM_TPRO IN ('X', 'Y') THEN 'NMRN'																				
																														WHEN ins.EXM_TPRO = 'Z' THEN 'NCLE'
																														ELSE NULL 
																													END)	
			WHERE ins.EXM_CNTX = 1 AND (doc.DOC_CA40 = 0 OR LEN(doc.DOC_CODI) <> 4 OR doc.DOC_EXPT = 0 OR doc.DOC_IDTY IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento "NMRN" ou "NCLE" existente no detalhe de precedentes da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesPrecedentes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento "NMRN" ou "NCLE" existente no detalhe de precedentes da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesPrecedentes		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração da estância de exportação e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND UPDATE(EAD_CODA)
	BEGIN		
-- obtem os documentos associados à estância de exportação das declarações EXP-SAE inseridas/alteradas 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_IDTY, doc.DOC_IDTY, doc.DOC_DTRA, uti.UTI_IDTY, 				 
				(CASE 
					WHEN doc.DOC_CODI IN ('N704', 'N705', 'N740', 'N821', 'N830') THEN NULLIF(ins.EXM_CPRT, '')
					WHEN doc.DOC_CODI = '9X01' THEN 'Nao aplicavel DL 68/2007'
					WHEN doc.DOC_TDNU = 1 THEN 'S/N' 
					WHEN doc.DOC_TDNU = 2 THEN 'N/A' 
					WHEN doc.DOC_TDNU = 3 THEN 'DEC' 
					ELSE NULL 
				END)
			FROM inserted AS ins 				
				INNER JOIN TAB_EADD AS ead WITH(NOLOCK) ON ins.EAD_CODA = ead.EAD_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ead.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 1	
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL						
			WHERE ins.EXM_CNTX = 1 AND doc.DOC_EXPT = 1 AND LEN(doc.DOC_CODI) = 4 AND ddo.id IS NULL 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o documento como "Suporte"/"Transporte" no detalhe de documentos da declaração EXP-SAE 
			INSERT INTO tb_EXP_DeclaracoesDocumentos(id_declaracaoEXP, tipo, id_documento, numero, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @TipoDocumento, @IdDocumento, @NumeroDocumento, 1, @IdUtilizador, @DataAtual)		
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @TipoDocumento, @IdUtilizador, @NumeroDocumento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- obtem os documentos existentes no detalhe de documentos da declaração EXP-SAE cuja origem é da estância de exportação mas que já não satisfazem as condições ou não existem no detalhe de documentos da estância de exportação
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.origem = 1			
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_EADD AS ead WITH(NOLOCK) ON ins.EAD_CODA = ead.EAD_CODI AND doc.DOC_CODI = ead.DOC_CODI
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL			
			WHERE ins.EXM_CNTX = 1 AND (doc.DOC_EXPT = 0 OR LEN(doc.DOC_CODI) <> 4 OR ead.DOC_CODI IS NULL)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o documento existente no detalhe de documentos da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento existente no detalhe de documentos da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos		
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
	END
-- processa automatismos relacionados com a alteração da estância de aperfeiçoamento e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND UPDATE(EAD_CODI1)
	BEGIN
-- obtem o pedido "00100" associado à estância de aperfeiçoamento das declarações EXP-SAE inseridas/alteradas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, ped.TXM_CODI, SUBSTRING(ped.TXM_TEXT, 1, 512)
			FROM inserted AS ins 								
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ped.TXM_CODI = '00100'
				LEFT OUTER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON ins.EXM_EANO = dpe.EXM_EANO AND ins.EXM_CODI = dpe.EXM_CODI AND ins.DEC_CODI = dpe.EXM_COPE AND dpe.EXP_ORIG = 3				
			WHERE ins.EXM_CNTX = 1 AND ISNULL(ins.EAD_CODI1, '') <> '' AND dpe.EXP_CHVE IS NULL		
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o pedido "00100" no detalhe de pedidos da declaração EXP-SAE
			SET @NumRegisto = ISNULL((SELECT MAX(EXP_LINH) FROM PRO_EXPA WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao), 0) + 1
			INSERT INTO PRO_EXPA(EXM_EANO, EXM_CODI, EXM_COPE, EXP_LINH, TXM_CODI, TXM_DESC, EXP_ORIG)
			VALUES(@AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @NumRegisto, @CodPedido, @NumeroPedido, 3)			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPedido, @NumeroPedido
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- obtem o pedido "00100" existente no detalhe de pedidos da declaração EXP-SAE cuja origem é da estância de aperfeiçoamento mas que já não satisfaz a condição
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, dpe.EXP_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN PRO_EXPA AS dpe WITH(NOLOCK) ON ins.EXM_EANO = dpe.EXM_EANO AND ins.EXM_CODI = dpe.EXM_CODI AND ins.DEC_CODI = dpe.EXM_COPE AND dpe.EXP_ORIG = 3							
				LEFT OUTER JOIN TAB_TXML AS ped WITH(NOLOCK) ON dpe.TXM_CODI = ped.TXM_CODI				
			WHERE ins.EXM_CNTX = 1 AND (ISNULL(ins.EAD_CODI1, '') = '' OR ped.TXM_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- remove o pedido "00100" existente no detalhe de pedidos da declaração EXP-SAE
			DELETE FROM PRO_EXPA		
			WHERE EXP_CHVE = @IdRegisto
-- atualiza os pedidos posteriores da declaração EXP-SAE
			UPDATE PRO_EXPA SET EXP_LINH = EXP_LINH - 1    
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao AND EXP_CHVE > @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
	END
-- processa automatismos relacionados com a alteração do país destino ou do anexo B
	IF UPDATE(EXM_P17A) OR UPDATE(EXM_ANXB)
	BEGIN
-- obtem o país destino das declarações EXP-SAE inseridas/alteradas que tem segurança ativa e tem o anexo B como "A2"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, pai.PAI_CODI, pai.PAI_NOME
			FROM inserted AS ins 								
				INNER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON ins.EXM_P17A = pai.PAI_CODI
				LEFT OUTER JOIN PRO_EXPI AS dpr WITH(NOLOCK) ON ins.EXM_EANO = dpr.EXM_EANO AND ins.EXM_CODI = dpr.EXM_CODI AND ins.DEC_CODI = dpr.EXM_COPE AND dpr.EXP_ORIG = 1				
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_SEGU = 2 AND ins.EXM_ANXB = 'A2' AND dpr.EXP_CHVE IS NULL		
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPais, @NomePais
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o país no detalhe de países da rota da declaração EXP-SAE			
			INSERT INTO PRO_EXPI(EXM_EANO, EXM_CODI, EXM_COPE, PAI_CODI, PAI_NOME, EXP_ORIG)
			VALUES(@AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPais, @NomePais, 1)			
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @CodPais, @NomePais
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- obtem o país destino existente no detalhe de países da rota da declaração EXP-SAE cuja origem é do país destino mas que já não satisfazem as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpr.EXP_CHVE
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN PRO_EXPI AS dpr WITH(NOLOCK) ON ins.EXM_EANO = dpr.EXM_EANO AND ins.EXM_CODI = dpr.EXM_CODI AND ins.DEC_CODI = dpr.EXM_COPE AND dpr.EXP_ORIG = 1							
				LEFT OUTER JOIN TAB_PAIS AS pai WITH(NOLOCK) ON ins.EXM_P17A = pai.PAI_CODI
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_SEGU = 2 AND (ins.EXM_ANXB <> 'A2' OR pai.PAI_IDTY IS NULL) 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- remove o país existente no detalhe de países da rota da declaração EXP-SAE
			DELETE FROM PRO_EXPI		
			WHERE EXP_CHVE = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
END

ALTER TABLE [dbo].[PRO_EXML] ENABLE TRIGGER [TAIU_PRO_EXML_EXPSAE]
/****** Object:  Trigger [TAIUD_PRO_EXML]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_EXML] ON [PRO_EXML] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @AnoDec int, @OperadorDec varchar(6), @CodigoDec int
-- verifica alteração de vários campos p/ registar no Histórico de Alterações da Declaração	
	if UPDATE(EXM_TPRO) or UPDATE(NDE_CODI) or UPDATE(EXM_DATA) or UPDATE(EXM_NRII) or UPDATE(EXM_NRIN) or UPDATE(EXM_NRLO) or UPDATE(EXM_STAT) or UPDATE(EXM_CNUM) 
	or UPDATE(EXM_ESTO) or UPDATE(EXM_NVRF) or UPDATE(EXM_DTCD) or UPDATE(EXM_NDGA) or UPDATE(EXM_DDGA) or UPDATE(EXM_VERS) or UPDATE(EXM_REVI) or UPDATE(EXM_PENV) 
	or UPDATE(EAD_CODA) or UPDATE(TDE_COD1) or UPDATE(CLI_NIF2) or UPDATE(EXM_TP2A) or UPDATE(EXM_TAD5) or UPDATE(EXM_TVL6) or UPDATE(FOR_NOM8) or UPDATE(EXM_IROR) 
	or UPDATE(DEC_CO14) or UPDATE(EXM_TP14) or UPDATE(EXM_P15A) or UPDATE(EXM_P17A) or UPDATE(EXM_C17C) or UPDATE(EAD_C17C) or UPDATE(EXM_D17C) or UPDATE(EXM_CT19) 
	or UPDATE(MTR_CO18) or UPDATE(EXM_MT18) or UPDATE(MTR_CO21) or UPDATE(EXM_MT21) or UPDATE(PAI_CO21) or UPDATE(CEN_CO20) or UPDATE(EXM_LG20) or UPDATE(NTR_CO24) 
	or UPDATE(PAI_MO22) or UPDATE(EXM_MT22) or UPDATE(EXM_TX23) or UPDATE(EXM_TFRT) or UPDATE(EXM_TSEG) or UPDATE(EXM_TMLQ) or UPDATE(EXM_TMBR) or UPDATE(EXM_VEUR) 
	or UPDATE(EXM_VATT) or UPDATE(EAD_CO29) or UPDATE(EAD_C29A) or UPDATE(EXM_DTIN) or UPDATE(EXM_HRIN) or UPDATE(EXM_DTFI) or UPDATE(EXM_HRFI) or UPDATE(EAD_CO30) 
	or UPDATE(LEM_CO30) or UPDATE(LME_CO30) or UPDATE(EXM_MR30) or UPDATE(LEM_C30A) or UPDATE(ARM_CO49) or UPDATE(AGE_CO50) or UPDATE(EXM_Q30C) or UPDATE(EXM_CPRT) 
	or UPDATE(EXM_TPCG) or UPDATE(EXM_DTVO) or UPDATE(SIN_CODI) or UPDATE(EXM_INCE) or UPDATE(EXM_NCMR) or UPDATE(EXM_DTMP) or UPDATE(EXM_NRCO) or UPDATE(EXM_DTCO)
	or UPDATE(FUP_CODI)
	begin
		insert into LOG_EXML (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, EXM_EANO, EXM_CODI, DEC_CODI, EXM_TPRO, NDE_CODI, EXM_DATA, EXM_NRII, 
			EXM_NRIN, EXM_NRLO, EXM_STAT, EXM_CNUM, EXM_ESTO, EXM_NVRF, EXM_DTCD, EXM_NDGA, EXM_DDGA, EXM_VERS, EXM_REVI, EXM_PENV, EAD_CODA, TDE_COD1, CLI_NIF2, 
			EXM_TP2A, EXM_TAD5, EXM_TVL6, FOR_NOM8, EXM_IROR, DEC_CO14, EXM_TP14, EXM_P15A, EXM_P17A, EXM_C17C, EAD_C17C, EXM_D17C, EXM_CT19, MTR_CO18, EXM_MT18, 
			MTR_CO21, EXM_MT21, PAI_CO21, CEN_CO20, EXM_LG20, NTR_CO24, PAI_MO22, EXM_MT22, EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, EXM_VEUR, EXM_VATT, 
			EAD_CO29, EAD_C29A, EXM_DTIN, EXM_HRIN, EXM_DTFI, EXM_HRFI, EAD_CO30, LEM_CO30, LME_CO30, EXM_MR30, LEM_C30A, ARM_CO49, AGE_CO50, EXM_Q30C, EXM_CPRT, 
			EXM_TPCG, EXM_DTVO, SIN_CODI, EXM_INCE, EXM_NCMR, EXM_DTMP, EXM_NRCO, EXM_DTCO, FUP_CODI)
		select NEWID(), (case (select count(*) from deleted where EXM_EANO = inserted.EXM_EANO and EXM_CODI = inserted.EXM_CODI and DEC_CODI = inserted.DEC_CODI) when 0 then 0 else 1 end), 
			GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), isnull(HOST_NAME(), 'n.d.'), 
			EXM_EANO, EXM_CODI, DEC_CODI, EXM_TPRO, NDE_CODI, EXM_DATA, EXM_NRII, EXM_NRIN, EXM_NRLO, EXM_STAT, EXM_CNUM, EXM_ESTO, EXM_NVRF, EXM_DTCD, EXM_NDGA, 
			EXM_DDGA, EXM_VERS, EXM_REVI, EXM_PENV, EAD_CODA, TDE_COD1, CLI_NIF2, EXM_TP2A, EXM_TAD5, EXM_TVL6, FOR_NOM8, EXM_IROR, DEC_CO14, EXM_TP14, EXM_P15A, 
			EXM_P17A, EXM_C17C, EAD_C17C, EXM_D17C, EXM_CT19, MTR_CO18, EXM_MT18, MTR_CO21, EXM_MT21, PAI_CO21, CEN_CO20, EXM_LG20, NTR_CO24, PAI_MO22, EXM_MT22, 
			EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, EXM_VEUR, EXM_VATT, EAD_CO29, EAD_C29A, EXM_DTIN, EXM_HRIN, EXM_DTFI, EXM_HRFI, EAD_CO30, LEM_CO30, 
			LME_CO30, EXM_MR30, LEM_C30A, ARM_CO49, AGE_CO50, EXM_Q30C, EXM_CPRT, EXM_TPCG, EXM_DTVO, SIN_CODI, EXM_INCE, EXM_NCMR, EXM_DTMP, EXM_NRCO, EXM_DTCO, 
			FUP_CODI
		from inserted
		where ((select count(*) from deleted where EXM_EANO = inserted.EXM_EANO and EXM_CODI = inserted.EXM_CODI and DEC_CODI = inserted.DEC_CODI) = 0) 
			or ((select count(*) from deleted where EXM_EANO = inserted.EXM_EANO and EXM_CODI = inserted.EXM_CODI and DEC_CODI = inserted.DEC_CODI and (
			(EXM_TPRO <> inserted.EXM_TPRO) or (NDE_CODI <> inserted.NDE_CODI) or (EXM_DATA <> inserted.EXM_DATA) or (EXM_NRII <> inserted.EXM_NRII) or
			(EXM_NRIN <> inserted.EXM_NRIN) or (EXM_NRLO <> inserted.EXM_NRLO) or (EXM_STAT <> inserted.EXM_STAT) or (isnull(EXM_CNUM, -1) <> isnull(inserted.EXM_CNUM, -1)) or
			(isnull(EXM_ESTO, '') <> isnull(inserted.EXM_ESTO, '')) or (isnull(EXM_NVRF, '') <> isnull(inserted.EXM_NVRF, '')) or 
			(isnull(EXM_DTCD, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_DTCD, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (isnull(EXM_NDGA, '') <> isnull(inserted.EXM_NDGA, '')) or 
			(isnull(EXM_DDGA, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_DDGA, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (isnull(EXM_VERS, -1) <> isnull(inserted.EXM_VERS, -1)) or
			(isnull(EXM_REVI, -1) <> isnull(inserted.EXM_REVI, -1)) or (isnull(EXM_PENV, '') <> isnull(inserted.EXM_PENV, '')) or (EAD_CODA <> inserted.EAD_CODA) or
			(TDE_COD1 <> inserted.TDE_COD1) or (isnull(CLI_NIF2, '') <> isnull(inserted.CLI_NIF2, '')) or (isnull(EXM_TP2A, '') <> isnull(inserted.EXM_TP2A, '')) or
			(isnull(EXM_TAD5, -1) <> isnull(inserted.EXM_TAD5, -1)) or (isnull(EXM_TVL6, -1) <> isnull(inserted.EXM_TVL6, -1)) or 
			(isnull(FOR_NOM8, '') <> isnull(inserted.FOR_NOM8, '')) or (EXM_IROR <> inserted.EXM_IROR) or (DEC_CO14 <> inserted.DEC_CO14) or 
			(isnull(EXM_TP14, -1) <> isnull(inserted.EXM_TP14, -1)) or (isnull(EXM_P15A, '') <> isnull(inserted.EXM_P15A, '')) or 
			(isnull(EXM_P17A, '') <> isnull(inserted.EXM_P17A, '')) or (isnull(EXM_C17C, '') <> isnull(inserted.EXM_C17C, '')) or 
			(isnull(EAD_C17C, '') <> isnull(inserted.EAD_C17C, '')) or (isnull(EXM_D17C, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_D17C, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or 
			(isnull(EXM_CT19, -1) <> isnull(inserted.EXM_CT19, -1)) or (isnull(MTR_CO18, '') <> isnull(inserted.MTR_CO18, '')) or
			(isnull(EXM_MT18, '') <> isnull(inserted.EXM_MT18, '')) or (isnull(MTR_CO21, '') <> isnull(inserted.MTR_CO21, '')) or 
			(isnull(EXM_MT21, '') <> isnull(inserted.EXM_MT21, '')) or (isnull(PAI_CO21, '') <> isnull(inserted.PAI_CO21, '')) or 
			(isnull(CEN_CO20, '') <> isnull(inserted.CEN_CO20, '')) or (isnull(EXM_LG20, '') <> isnull(inserted.EXM_LG20, '')) or
			(isnull(NTR_CO24, '') <> isnull(inserted.NTR_CO24, '')) or (isnull(PAI_MO22, '') <> isnull(inserted.PAI_MO22, '')) or 
			(isnull(EXM_MT22, -1) <> isnull(inserted.EXM_MT22, -1)) or (isnull(EXM_TX23, -1) <> isnull(inserted.EXM_TX23, -1)) or 
			(isnull(EXM_TFRT, -1) <> isnull(inserted.EXM_TFRT, -1)) or (isnull(EXM_TSEG, -1) <> isnull(inserted.EXM_TSEG, -1)) or 
			(isnull(EXM_TMLQ, -1) <> isnull(inserted.EXM_TMLQ, -1)) or (isnull(EXM_TMBR, -1) <> isnull(inserted.EXM_TMBR, -1)) or 
			(isnull(EXM_VEUR, -1) <> isnull(inserted.EXM_VEUR, -1)) or (isnull(EXM_VATT, -1) <> isnull(inserted.EXM_VATT, -1)) or 
			(isnull(EAD_CO29, '') <> isnull(inserted.EAD_CO29, '')) or (isnull(EAD_C29A, '') <> isnull(inserted.EAD_C29A, '')) or
			(isnull(EXM_DTIN, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_DTIN, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (isnull(EXM_HRIN, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_HRIN, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or 
			(isnull(EXM_DTFI, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_DTFI, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (isnull(EXM_HRFI, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_HRFI, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or 
			(isnull(EAD_CO30, '') <> isnull(inserted.EAD_CO30, '')) or (isnull(LEM_CO30, '') <> isnull(inserted.LEM_CO30, '')) or 
			(isnull(LME_CO30, '') <> isnull(inserted.LME_CO30, '')) or (isnull(EXM_MR30, '') <> isnull(inserted.EXM_MR30, '')) or 
			(isnull(LEM_C30A, '') <> isnull(inserted.LEM_C30A, '')) or (isnull(ARM_CO49, '') <> isnull(inserted.ARM_CO49, '')) or 
			(isnull(AGE_CO50, '') <> isnull(inserted.AGE_CO50, '')) or (isnull(EXM_Q30C, -1) <> isnull(inserted.EXM_Q30C, -1)) or 
			(isnull(EXM_CPRT, '') <> isnull(inserted.EXM_CPRT, '')) or (isnull(EXM_TPCG, '') <> isnull(inserted.EXM_TPCG, '')) or 
			(isnull(EXM_DTVO, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_DTVO, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (isnull(SIN_CODI, '') <> isnull(inserted.SIN_CODI, '')) or 
			(isnull(EXM_INCE, '') <> isnull(inserted.EXM_INCE, '')) or (isnull(EXM_NCMR, '') <> isnull(inserted.EXM_NCMR, '')) or 
			(isnull(EXM_DTMP, '') <> isnull(inserted.EXM_DTMP, '')) or (isnull(EXM_NRCO, '') <> isnull(inserted.EXM_NRCO, '')) or 
			(isnull(FUP_CODI, -1) <> isnull(inserted.FUP_CODI, -1)) or 
			(isnull(EXM_DTCO, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> isnull(inserted.EXM_DTCO, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())))) > 0)
	end
	else
	begin
		insert into LOG_EXML (LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, EXM_EANO, EXM_CODI, DEC_CODI, EXM_TPRO, NDE_CODI, EXM_DATA, EXM_NRII, 
			EXM_NRIN, EXM_NRLO, EXM_STAT, EXM_CNUM, EXM_ESTO, EXM_NVRF, EXM_DTCD, EXM_NDGA, EXM_DDGA, EXM_VERS, EXM_REVI, EXM_PENV, EAD_CODA, TDE_COD1, CLI_NIF2, 
			EXM_TP2A, EXM_TAD5, EXM_TVL6, FOR_NOM8, EXM_IROR, DEC_CO14, EXM_TP14, EXM_P15A, EXM_P17A, EXM_C17C, EAD_C17C, EXM_D17C, EXM_CT19, MTR_CO18, EXM_MT18, 
			MTR_CO21, EXM_MT21, PAI_CO21, CEN_CO20, EXM_LG20, NTR_CO24, PAI_MO22, EXM_MT22, EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, EXM_VEUR, EXM_VATT, 
			EAD_CO29, EAD_C29A, EXM_DTIN, EXM_HRIN, EXM_DTFI, EXM_HRFI, EAD_CO30, LEM_CO30, LME_CO30, EXM_MR30, LEM_C30A, ARM_CO49, AGE_CO50, EXM_Q30C, EXM_CPRT, 
			EXM_TPCG, EXM_DTVO, SIN_CODI, EXM_INCE, EXM_NCMR, EXM_DTMP, EXM_NRCO, EXM_DTCO, FUP_CODI)
		select NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), isnull(APP_NAME(), 'n.d.'), 
			isnull(HOST_NAME(), 'n.d.'), EXM_EANO, EXM_CODI, DEC_CODI, EXM_TPRO, NDE_CODI, EXM_DATA, EXM_NRII, EXM_NRIN, EXM_NRLO, EXM_STAT, EXM_CNUM, EXM_ESTO, 
			EXM_NVRF, EXM_DTCD, EXM_NDGA, EXM_DDGA, EXM_VERS, EXM_REVI, EXM_PENV, EAD_CODA, TDE_COD1, CLI_NIF2, EXM_TP2A, EXM_TAD5, EXM_TVL6, FOR_NOM8, EXM_IROR, 
			DEC_CO14, EXM_TP14, EXM_P15A, EXM_P17A, EXM_C17C, EAD_C17C, EXM_D17C, EXM_CT19, MTR_CO18, EXM_MT18, MTR_CO21, EXM_MT21, PAI_CO21, CEN_CO20, EXM_LG20, 
			NTR_CO24, PAI_MO22, EXM_MT22, EXM_TX23, EXM_TFRT, EXM_TSEG, EXM_TMLQ, EXM_TMBR, EXM_VEUR, EXM_VATT, EAD_CO29, EAD_C29A, EXM_DTIN, EXM_HRIN, EXM_DTFI, 
			EXM_HRFI, EAD_CO30, LEM_CO30, LME_CO30, EXM_MR30, LEM_C30A, ARM_CO49, AGE_CO50, EXM_Q30C, EXM_CPRT, EXM_TPCG, EXM_DTVO, SIN_CODI, EXM_INCE, EXM_NCMR, 
			EXM_DTMP, EXM_NRCO, EXM_DTCO, FUP_CODI
		from deleted
		where (select count(*) from inserted where EXM_EANO = deleted.EXM_EANO and EXM_CODI = deleted.EXM_CODI and DEC_CODI = deleted.DEC_CODI) = 0
	end
-- verifica alteração do campo "Estado Follow-UP" p/ registar no Histórico de Alterações de Follow-Up da Declaração
	IF UPDATE(FUP_CODI)
	BEGIN
		INSERT INTO PRO_EXFW(EXM_EANO, EXM_CODI, EXM_COPE, EFW_CODI, EFW_DATA, FUP_CODI, UTI_UTIL)
		SELECT EXM_EANO, EXM_CODI, DEC_CODI, ((SELECT COUNT(*) FROM PRO_EXFW WHERE EXM_EANO = inserted.EXM_EANO and EXM_CODI = inserted.EXM_CODI and EXM_COPE = inserted.DEC_CODI) + 1), 
			GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), FUP_CODI, ISNULL((SELECT LOG_UTIL FROM LOG_LOGS WHERE LOG_SPID = @@SPID), SUSER_SNAME())
		FROM inserted
		WHERE FUP_CODI IS NOT NULL and (((SELECT count(*) FROM deleted WHERE EXM_EANO = inserted.EXM_EANO and EXM_CODI = inserted.EXM_CODI and DEC_CODI = inserted.DEC_CODI) = 0) 
			or ((SELECT count(*) FROM deleted WHERE EXM_EANO = inserted.EXM_EANO and EXM_CODI = inserted.EXM_CODI and DEC_CODI = inserted.DEC_CODI and 
			ISNULL(FUP_CODI, -1) <> ISNULL(inserted.FUP_CODI, -1)) > 0))
	END	
-- se campo "Status de Incidência" alterado p/ "A13", gera registo de Linha AWB no Manifesto SDS-Via Aérea de Exportação
	IF UPDATE(SIN_CODI)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT EXM_EANO, EXM_CODI, DEC_CODI
			FROM inserted
			WHERE SIN_CODI = 'A13'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDec, @CodigoDec, @OperadorDec
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			EXEC SP_ExportacaoXML_GeraLinhaSDSViaAerea @AnoDec, @CodigoDec, @OperadorDec
			FETCH NEXT FROM Declaracoes INTO @AnoDec, @CodigoDec, @OperadorDec
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
END

ALTER TABLE [dbo].[PRO_EXML] ENABLE TRIGGER [TAIUD_PRO_EXML]
/****** Object:  Trigger [TAU_PRO_EXML]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_EXML] ON [PRO_EXML] FOR UPDATE AS 
BEGIN
	SET DATEFORMAT DMY
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @AnoDec int, @OperadorDec varchar(6), @NumRefIntDec int, @NumDGADec varchar(25), @DataDGADec datetime, @CodigoDec int, @CodLocalAutorizado varchar(17), @Utilizador varchar(30), 
		@Erro varchar(8000), @TotalVolumes numeric(38, 6)
-- verifica se campos de Num Ordem DGA, Data ou Total Volumes foram alterados
	if UPDATE(EXM_NDGA) or UPDATE(EXM_DDGA) or UPDATE(EXM_TVL6)
	begin
-- busca dados alterados
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			select EXM_EANO, DEC_CODI, EXM_NRII, EXM_NDGA, EXM_DDGA, EXM_TVL6
			from inserted
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDec, @OperadorDec, @NumRefIntDec, @NumDGADec, @DataDGADec, @TotalVolumes
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- actualiza Num Ordem DGA e Data na Conta 
			ALTER TABLE FAC_CDOC DISABLE TRIGGER TAU_FAC_CDOC
			IF UPDATE(EXM_NDGA) or UPDATE(EXM_DDGA)
			BEGIN
				update FAC_CDOC set CDO_NORD = @NumDGADec, CDO_DTAC = @DataDGADec
				where CDO_PANO = @AnoDec and CDO_NPRO = @NumRefIntDec and EXM_OPER = @OperadorDec and CDO_IMEX = 1
			END			
-- actualiza Total Volumes na Conta 			
			IF UPDATE(EXM_TVL6)
			BEGIN
				update FAC_CDOC set CDO_QUNT = @TotalVolumes
				where CDO_PANO = @AnoDec and CDO_NPRO = @NumRefIntDec and EXM_OPER = @OperadorDec and CDO_IMEX = 1
			END
			ALTER TABLE FAC_CDOC ENABLE TRIGGER TAU_FAC_CDOC
			FETCH NEXT FROM Declaracoes INTO @AnoDec, @OperadorDec, @NumRefIntDec, @NumDGADec, @DataDGADec, @TotalVolumes
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	end
-- se campo Carta de Porte alterado, propaga alteração nas Entradas AEX
	IF UPDATE(EXM_CPRT)
	BEGIN
		UPDATE AEX_ENDG SET EDG_REFI = ins.EXM_CPRT
		FROM AEX_ENDG as edg WITH(NOLOCK) 
			INNER JOIN inserted as ins ON edg.EXM_EANO = ins.EXM_EANO and edg.EXM_CODI = ins.EXM_CODI and edg.DEC_CODI = ins.DEC_CODI
	END	
-- se campo Status alterado p/ "Enviado" e campo Local Autorizado configurado como "AEX" e Carta de Porte não existe nas Entradas AEX, gera registo de Entrada AEX se campos adicionais dos Par. Despachos for "FEDEX", "UPS", "DHL" ou "TNT"
	IF (UPDATE(EXM_STAT)) and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI IN (1, 2, 3, 4)))
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, ins.LME_CO30, ins.EXM_UALT
			FROM inserted as ins 
				INNER JOIN TAB_LMER as lme WITH(NOLOCK) ON ins.LME_CO30 = lme.LME_CODI
			WHERE ((ins.EXM_TPRO in ('A', 'B', 'C', 'X', 'Y', 'Z') and ins.EXM_STAT = 1) or (ins.EXM_TPRO in ('D', 'E', 'F') and ins.EXM_STAT = 6)) and lme.LME_GAEX = 1 
				and (NOT EXISTS(SELECT EDG_NUME FROM AEX_ENDG WITH(NOLOCK) WHERE (EDG_EANO = YEAR(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) or EDG_EANO = (YEAR(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) - 1)) and EDG_REFI = ins.EXM_CPRT))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDec, @CodigoDec, @OperadorDec, @CodLocalAutorizado, @Utilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			EXEC SP_EntradasAEX_InsereViaExportacaoXMLouSDSViaAerea 1, @AnoDec, @CodigoDec, @OperadorDec, NULL, @CodLocalAutorizado, @Utilizador, @Erro OUTPUT
			IF ISNULL(@Erro, '') = ''
			BEGIN
				UPDATE PRO_EXML SET EXM_DTVO = CAST(CONVERT(varchar(10), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 105) as datetime)
				WHERE EXM_EANO = @AnoDec and EXM_CODI = @CodigoDec and DEC_CODI = @OperadorDec
			END
			FETCH NEXT FROM Declaracoes INTO @AnoDec, @CodigoDec, @OperadorDec, @CodLocalAutorizado, @Utilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
-- verifica se campos "Status", "Versão", "Revisão" ou "Estado Operação" foram alterados e nos Par. Despachos o valor do campo "Campos Adicionais" for "ENTREPOSTO" para colocar declarações como pendentes de envio para Portal MyRangel
	IF (UPDATE(EXM_STAT) OR UPDATE(EXM_VERS) OR UPDATE(EXM_REVI) OR UPDATE(EXM_ESTO)) AND (EXISTS(SELECT 1 FROM TAB_PDES WITH(NOLOCK) WHERE PDE_CADI = 8)) --Campos Adicionais = "ENTREPOSTO"
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT EXM_EANO, EXM_CODI, DEC_CODI
			FROM inserted 
			WHERE EXM_STAT = 3 OR EXM_VERS > 0 OR EXM_REVI > 0 OR ISNULL(EXM_ESTO, '') <> ''
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO  @AnoDec, @CodigoDec, @OperadorDec
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE PRO_EXML SET 
				EXM_PMRP = 1				
			WHERE EXM_EANO = @AnoDec AND EXM_CODI = @CodigoDec AND DEC_CODI = @OperadorDec
			FETCH NEXT FROM Declaracoes INTO  @AnoDec, @CodigoDec, @OperadorDec
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
	END
END

ALTER TABLE [dbo].[PRO_EXML] ENABLE TRIGGER [TAU_PRO_EXML]
/****** Object:  Trigger [TAU_PRO_EXML_EXPSAE]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_EXML_EXPSAE] ON [PRO_EXML] FOR UPDATE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @PeriodoTransitorio bit, @AnoDeclaracao int, @CodDeclaracao int, @CodOperadorDeclaracao varchar(6), @IdUtilizador int, @IdRegisto bigint
	DECLARE @SQLVariaveis nvarchar(MAX), @SQLAExecutar nvarchar(MAX), @PosIndex int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem configuração do periodo transitório EXP-SAE dos Parâmetros de Despachos
	SELECT TOP 1 @PeriodoTransitorio = PDE_PTEX 
	FROM TAB_PDES WITH(NOLOCK)
-- processa automatismos relacionados com a alteração dos contentores
	IF UPDATE(EXM_CT19)
	BEGIN
-- remove os contentores de todas as adições se mercadoria não for contentorizada
		DECLARE Contentores CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT uti.UTI_IDTY, dac.id
			FROM inserted AS ins 				
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ins.EXM_EANO = dad.EXM_EANO AND ins.EXM_CODI = dad.EXM_CODI AND ins.DEC_CODI = dad.EXM_COPE
				INNER JOIN tb_EXP_DeclaracoesAdicoesContentores AS dac WITH(NOLOCK) ON dad.EXA_CHVE = dac.id_adicao 
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_CT19 = 0
		OPEN Contentores
		FETCH NEXT FROM Contentores INTO @IdUtilizador, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_EXP_DeclaracoesAdicoesContentores SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
			DELETE FROM tb_EXP_DeclaracoesAdicoesContentores
			WHERE id = @IdRegisto
			FETCH NEXT FROM Contentores INTO @IdUtilizador, @IdRegisto
		END
		CLOSE Contentores
		DEALLOCATE Contentores
-- obtem as declarações EXP-SAE alteradas que deixaram de ser com contentores
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI
			FROM inserted AS ins 				
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_CT19 = 0
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove os contentores existentes no detalhe de contentores da declaração EXP-SAE
			DELETE FROM PRO_EXCT
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do país destino ou regime
	IF UPDATE(EXM_P17A) OR UPDATE(EXM_REGI)
	BEGIN
-- obtem as declarações EXP-SAE alteradas que deixaram de ter o país destino como um EUR1 e o regime como "3151" 
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dai.id, uti.UTI_IDTY
			FROM inserted AS ins 				
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ins.EXM_EANO = dad.EXM_EANO AND ins.EXM_CODI = dad.EXM_CODI AND ins.DEC_CODI = dad.EXM_COPE							
				INNER JOIN tb_EXP_DeclaracoesAdicoesImposicoes AS dai WITH(NOLOCK) ON dad.EXA_CHVE = dai.id_adicao
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_P17A NOT IN ('AD', 'AL', 'BA', 'CL', 'DZ', 'EG', 'FO', 'HR', 'IL', 'JO', 'MA', 'ME', 'MK', 'MX', 'PS', 'TN', 'TR', 'XC', 'XL') 
				AND ins.EXM_REGI <> '3151'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza a imposição existente no detalhe de imposições da adição da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesImposicoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove a imposição existente no detalhe de imposições da adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesImposicoes
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração da segurança
	IF UPDATE(EXM_SEGU)
	BEGIN
-- obtem os contentores das declarações EXP-SAE alteradas que deixaram de ter segurança
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT con.EXC_CHVE, uti.UTI_IDTY
			FROM inserted AS ins 				
				INNER JOIN PRO_EXCT AS con WITH(NOLOCK) ON ins.EXM_EANO = con.EXM_EANO AND ins.EXM_CODI = con.EXM_CODI AND ins.DEC_CODI = con.EXM_COPE
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_SEGU = 0
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza os selos associados ao contentor existentes no detalhe de contentores da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesContentoresSelos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id_contentor = @IdRegisto
-- remove os selos associados ao contentor existentes no detalhe de contentores da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesContentoresSelos
			WHERE id_contentor = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os países da rota das declaração EXP-SAE alteradas que deixaram de ter segurança
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpr.EXP_CHVE
			FROM inserted AS ins 				
				INNER JOIN PRO_EXPI AS dpr WITH(NOLOCK) ON ins.EXM_EANO = dpr.EXM_EANO AND ins.EXM_CODI = dpr.EXM_CODI AND ins.DEC_CODI = dpr.EXM_COPE				
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_SEGU <> 2
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN				
-- remove o país da rota da declaração EXP-SAE
			DELETE FROM PRO_EXPI		
			WHERE EXP_CHVE = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
	END
-- processa automatismos relacionados com a alteração do meio de transporte interior
	IF UPDATE(MTR_CO18)
	BEGIN
-- obtem os meios de transporte à partida das declarações EXP-SAE alteradas cujo meio de transporte interior deixou de satisfazer as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dmt.id, uti.UTI_IDTY
			FROM inserted AS ins 								
				INNER JOIN tb_EXP_DeclaracoesMeiosTransportePartida AS dmt WITH(NOLOCK) ON ins.EXM_IDTY = dmt.id_declaracaoEXP
				INNER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON dmt.id_meioTransporte = mtr.MTR_IDTY
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
			WHERE ins.EXM_CNTX = 1 AND ISNULL(LEFT(ins.MTR_CO18, 1), '') <> ISNULL(LEFT(mtr.MTR_CODI, 1), '')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza o meio de transporte à partida existente no detalhe de meios de transporte à partida da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesMeiosTransportePartida SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o meio de transporte à partida existente no detalhe de meios de transporte à partida da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesMeiosTransportePartida
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração da estância de aperfeiçoamento
	IF UPDATE(EAD_CODI1)
	BEGIN
-- obtem os locais de transformação das declarações EXP-SAE alteradas cuja estância de aperfeiçoamento deixou de estar definida
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dlt.id, uti.UTI_IDTY
			FROM inserted AS ins 								
				INNER JOIN tb_EXP_DeclaracoesLocaisTransformacao AS dlt WITH(NOLOCK) ON ins.EXM_IDTY = dlt.id_declaracaoEXP				
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
			WHERE ins.EXM_CNTX = 1 AND ISNULL(ins.EAD_CODI1, '') = ''
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza o local de transformação existente no detalhe de locais de transformação da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesLocaisTransformacao SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o local de transformação existente no detalhe de locais de transformação da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesLocaisTransformacao
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do regime
	IF UPDATE(EXM_REGI)
	BEGIN
-- obtem as declarações EXP-SAE alteradas que deixaram de ter o regime como "10"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI
			FROM inserted AS ins 				
			WHERE ins.EXM_CNTX = 1 AND LEFT(ins.EXM_REGI, 2) <> '10'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove os certificados existentes no detalhe de certificados da declaração EXP-SAE
			DELETE FROM PRO_EXCE
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @CodDeclaracao AND EXM_COPE = @CodOperadorDeclaracao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do tipo declaração
	IF UPDATE(TDE_COD1)
	BEGIN
-- obtem os documentos do tipo "Referência Adicional" das declarações EXP-SAE alteradas cujo tipo declaração deixou de satisfazer as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, uti.UTI_IDTY
			FROM inserted AS ins 							
				INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON ins.TDE_COD1 = tde.TDE_CODI	
				INNER JOIN tb_EXP_DeclaracoesDocumentos AS ddo WITH(NOLOCK) ON ins.EXM_IDTY = ddo.id_declaracaoEXP AND ddo.tipo = 2		
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
			WHERE ins.EXM_CNTX = 1 AND ISNULL(tde.TDE_1CAS, '') = 'CO'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza o documento do tipo "Referência Adicional" existente no detalhe de documentos da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento do tipo "Referência Adicional" existente no detalhe de documentos da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesDocumentos
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos do tipo "Referência Adicional" das adições das declarações EXP-SAE alteradas cujo tipo declaração deixou de satisfazer as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ado.EXD_CHVE
			FROM inserted AS ins 
				INNER JOIN TAB_TDEC AS tde WITH(NOLOCK) ON ins.TDE_COD1 = tde.TDE_CODI
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ins.EXM_EANO = dad.EXM_EANO AND ins.EXM_CODI = dad.EXM_CODI AND ins.DEC_CODI = dad.EXM_COPE								
				INNER JOIN PRO_EXDA AS ado WITH(NOLOCK) ON dad.EXA_CHVE = ado.EXA_CHVE AND ado.EXD_TIPO = 2						
			WHERE ins.EXM_CNTX = 1 AND ISNULL(tde.TDE_1CAS, '') = 'CO'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- remove o documento do tipo "Referência Adicional" existente no detalhe de documentos da adição da declaração EXP-SAE 
			DELETE FROM PRO_EXDA		
			WHERE EXD_CHVE = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do tipo declaração adicional e o período transitório não está ativo
	IF (@PeriodoTransitorio = 0) AND UPDATE(EXM_TPRO)
	BEGIN
-- obtem os documentos precedentes das declarações EXP-SAE alteradas cujo tipo declaração adicional deixou de satisfazer as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dpr.id, uti.UTI_IDTY
			FROM inserted AS ins 								
				INNER JOIN tb_EXP_DeclaracoesPrecedentes AS dpr WITH(NOLOCK) ON ins.EXM_IDTY = dpr.id_declaracaoEXP				
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_TPRO IN ('U', 'V')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza o documento precedente existente no detalhe de precedentes da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesPrecedentes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento precedente existente no detalhe de precedentes da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesPrecedentes
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- obtem os documentos precedentes das adições das declarações EXP-SAE alteradas cujo tipo declaração adicional deixou de satisfazer as condições
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dap.id, uti.UTI_IDTY
			FROM inserted AS ins 	
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ins.EXM_EANO = dad.EXM_EANO AND ins.EXM_CODI = dad.EXM_CODI AND ins.DEC_CODI = dad.EXM_COPE							
				INNER JOIN tb_EXP_DeclaracoesAdicoesPrecedentes AS dap WITH(NOLOCK) ON dad.EXA_CHVE = dap.id_adicao
				INNER JOIN GIDWIN.dbo.FAP_UTIL AS uti WITH(NOLOCK) ON ISNULL(ins.EXM_UALT, ins.EXM_UCRI) = uti.UTI_UTIL	
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_TPRO IN ('X', 'Y', 'Z')
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza o documento precedente existente no detalhe de precedentes da declaração EXP-SAE
			UPDATE tb_EXP_DeclaracoesAdicoesPrecedentes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdRegisto
-- remove o documento precedente existente no detalhe de precedentes da adição da declaração EXP-SAE
			DELETE FROM tb_EXP_DeclaracoesAdicoesPrecedentes
			WHERE id = @IdRegisto
			FETCH NEXT FROM Declaracoes INTO @IdRegisto, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração do tipo declaração, tipo declaração adicional, código destinatário, nome destionatário, país exportação, país destino, natureza transação, fórmula CE, câmbio montante, total frete, total seguro, verbas automaticas, NRUR, metodo pagamento, segurança, código expedidor, nome expedidor, câmbio frete, câmbio seguro, anexo B ou regime
	IF UPDATE(TDE_COD1) OR UPDATE(EXM_TPRO) OR UPDATE(FOR_COD8) OR UPDATE(FOR_NOM8) OR UPDATE(EXM_P15A) OR UPDATE(EXM_P17A) OR UPDATE(NTR_CO24) OR UPDATE(EXM_FR20) OR UPDATE(EXM_TX23) 
	OR UPDATE(EXM_TFRT) OR UPDATE(EXM_TSEG) OR UPDATE(EXM_VRBA) OR UPDATE(EXM_NCMR) OR UPDATE(EXM_DTMP) OR UPDATE(EXM_SEGU) OR UPDATE(CLI_CODI1) OR UPDATE(CLI_NOME1) OR UPDATE(EXM_CFRE) 
	OR UPDATE(EXM_CSEG) OR UPDATE(EXM_ANXB) OR UPDATE(EXM_REGI) 	
	OR ((@PeriodoTransitorio = 1) AND (UPDATE(CLI_COD2) OR UPDATE(DEC_CO14) OR UPDATE(EXM_TP14) OR UPDATE(EAD_CODA) OR UPDATE(EAD_CODI1)))
	BEGIN		
		DECLARE @IdAdicao int, @TotalAdicoes int, @FormulaCondEntrega varchar(70), @TotalMontante numeric(38, 6), @CambioMontante numeric(38, 6), @TotalFrete numeric(38, 6), 
			@TotalSeguro numeric(38, 6), @TotalMassaBrt numeric(38, 6), @CambioFrete numeric(38, 6), @CambioSeguro numeric(38, 6), @Regime varchar(4), @1CasaTipoDeclaracao varchar(5), 
			@DesdobramentoTipoDeclaracao varchar(3), @CodMercPerigosasArtigo varchar(10), @CodCCUSArtigo varchar(9)
-- constroi a lista de variáveis
		SET @SQLVariaveis = '@INIdAdicao int, @INAnoDeclaracao int, @INCodDeclaracao int, @INCodOperadorDeclaracao varchar(6), @INTotalAdicoes int, @INFormulaCondEntrega varchar(70), @INTotalMontante numeric(38, 6), @INCambioMontante numeric(38, 6), @INTotalFrete numeric(38, 6), @INTotalSeguro numeric(38, 6), @INTotalMassaBrt numeric(38, 6), @INCambioFrete numeric(38, 6), @INCambioSeguro numeric(38, 6), @INRegime varchar(4), @IN1CasaTipoDeclaracao varchar(5), @INDesdobramentoTipoDeclaracao varchar(3), @INCodMercPerigosasArtigo varchar(10), @INCodCCUSArtigo varchar(9)'
-- obtem as marcas e volumes editadas
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.EXA_CHVE, ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI, ISNULL(ins.EXM_TAD5, 0), ISNULL(ins.EXM_FR20, ''), ISNULL(ins.EXM_MT22, 0), ISNULL(ins.EXM_TX23, 0), 
				ISNULL(ins.EXM_TFRT, 0), ISNULL(ins.EXM_TSEG, 0), ISNULL(ins.EXM_TMBR, 0), ins.EXM_CFRE, ins.EXM_CSEG, ins.EXM_REGI, tdi.TDE_1CAS, tdi.TDE_DESD, apa.APA_ATAR, apa.APA_CCUS, 
				((CASE WHEN ISNULL(ins.EXM_REGI, '') <> ISNULL(del.EXM_REGI, '') AND ISNULL(ins.EXM_REGI, '') <> ISNULL(dad.TDE_REGI, '') THEN 'TDE_REGI = @INRegime, ' ELSE '' END) 					
					+ (CASE WHEN (ISNULL(tdi.TDE_1CAS, '') <> ISNULL(tdd.TDE_1CAS, '') OR ISNULL(tdi.TDE_DESD, '') <> ISNULL(tdd.TDE_DESD, '') OR ISNULL(ins.EXM_REGI, '') <> ISNULL(del.EXM_REGI, ''))	AND (ISNULL(tdi.TDE_1CAS, '') <> ISNULL(tdd.TDE_1CAS, '') OR ISNULL(ins.EXM_REGI, '') <> ISNULL(dad.TDE_REGI, '') OR ISNULL(tdi.TDE_DESD, '') <> ISNULL(dad.EXA_DESD, '')) THEN 'id_desdobramento = (SELECT TOP 1 id FROM tb_TBL_Desdobramentos WITH(NOLOCK) WHERE tipoDeclaracao = @IN1CasaTipoDeclaracao AND regime = @INRegime AND desdobramento1 = @INDesdobramentoTipoDeclaracao), EXA_DESD = (SELECT TOP 1 desdobramento1 FROM tb_TBL_Desdobramentos WITH(NOLOCK) WHERE tipoDeclaracao = @IN1CasaTipoDeclaracao AND regime = @INRegime AND desdobramento1 = @INDesdobramentoTipoDeclaracao), ' ELSE '' END)					
					+ (CASE WHEN ins.EXM_ANXB <> del.EXM_ANXB AND ins.EXM_ANXB <> 'B1' THEN 'EXA_CCUS = NULL, ' WHEN ins.EXM_ANXB <> del.EXM_ANXB AND ins.EXM_ANXB = 'B1' THEN 'EXA_CCUS = @INCodCCUSArtigo, ' ELSE '' END)
					+ (CASE WHEN ins.EXM_SEGU <> del.EXM_SEGU AND ins.EXM_SEGU = 0 THEN 'EXA_ATAR = NULL, ' WHEN ins.EXM_SEGU <> del.EXM_SEGU AND ins.EXM_SEGU = 2 THEN 'EXA_ATAR = @INCodMercPerigosasArtigo, ' ELSE '' END)
					+ (CASE WHEN (ins.EXM_TPRO <> del.EXM_TPRO OR ISNULL(ins.EXM_REGI, '') <> ISNULL(del.EXM_REGI, '')) AND (ins.EXM_TPRO IN ('C', 'D', 'E', 'F') OR ISNULL(LEFT(ins.EXM_REGI, 2), '') = '76') AND dad.RES_CODI IS NOT NULL THEN 'RES_CODI = NULL, ' ELSE '' END)
					+ (CASE WHEN (ins.EXM_TPRO <> del.EXM_TPRO OR ISNULL(ins.NTR_CO24, '') <> ISNULL(del.NTR_CO24, '')) AND (ins.EXM_TPRO IN ('B', 'C', 'E', 'F') OR ISNULL(ins.NTR_CO24, '') <> '') AND ISNULL(dad.NTR_CODI, '') <> '' THEN 'NTR_CODI = NULL, ' ELSE '' END)					
					+ (CASE WHEN (ins.EXM_SEGU <> del.EXM_SEGU OR ISNULL(ins.EXM_DTMP, '') <> ISNULL(del.EXM_DTMP, '')) AND (ins.EXM_SEGU = 0 OR ISNULL(ins.EXM_DTMP, '') <> '') AND ISNULL(dad.EXA_MPAG, '') <> '' THEN 'EXA_MPAG = NULL, ' ELSE '' END)					
					+ (CASE WHEN ISNULL(ins.EXM_NCMR, '') <> ISNULL(del.EXM_NCMR, '') AND ISNULL(ins.EXM_NCMR, '') <> '' AND ISNULL(dad.EXA_NRUR, '') <> '' THEN 'EXA_NRUR = NULL, ' ELSE '' END)
					+ (CASE WHEN (ins.EXM_SEGU <> del.EXM_SEGU OR ISNULL(tdi.TDE_1CAS, '') <> ISNULL(tdd.TDE_1CAS, '') OR ISNULL(ins.EXM_REGI, '') <> ISNULL(del.EXM_REGI, '') OR ISNULL(ins.CLI_CODI1, '') <> ISNULL(del.CLI_CODI1, '') OR ISNULL(ins.CLI_NOME1, '') <> ISNULL(del.CLI_NOME1, '')) AND (ins.EXM_SEGU = 0 OR ISNULL(tdi.TDE_1CAS, '') = 'CO' OR ISNULL(LEFT(ins.EXM_REGI, 2), '') IN ('21', '22') OR ISNULL(ins.CLI_CODI1, '') <> '' OR ISNULL(ins.CLI_NOME1, '') <> '') AND (ISNULL(dad.CLI_CODI, '') <> '' OR ISNULL(dad.CLI_NOME, '') <> '') THEN 'CLI_CODI = NULL, CLI_NOME = NULL, CLI_MORA = NULL, CLI_LOCA = NULL, CLI_CPOS = NULL, CLI_LPOS = NULL, PAI_CODI1 = NULL, CLI_NIF = NULL, CLI_TNIF = NULL, ' ELSE '' END)
					+ (CASE WHEN ISNULL(ins.EXM_P15A, '') <> ISNULL(del.EXM_P15A, '') AND ISNULL(ins.EXM_P15A, '') <> '' AND ISNULL(dad.PAI_CODI2, '') <> '' THEN 'PAI_CODI2 = NULL, ' WHEN ISNULL(ins.EXM_P15A, '') <> ISNULL(del.EXM_P15A, '') AND ISNULL(ins.EXM_P15A, '') = '' AND ISNULL(dad.PAI_CODI2, '') = '' THEN 'PAI_CODI2 = (SELECT TOP 1 PAI_CODI FROM TAB_PAIS WITH(NOLOCK) WHERE PAI_CODI = ''PT''), ' ELSE '' END)					
					+ (CASE WHEN (ISNULL(ins.FOR_COD8, '') <> ISNULL(del.FOR_COD8, '') OR ISNULL(ins.FOR_NOM8, '') <> ISNULL(del.FOR_NOM8, '')) AND (ISNULL(ins.FOR_COD8, '') <> '' OR ISNULL(ins.FOR_NOM8, '') <> '') AND (ISNULL(dad.FOR_CODI, '') <> '' OR ISNULL(dad.FOR_NOME, '') <> '') THEN 'FOR_CODI = NULL, FOR_NOME = NULL, FOR_MORA = NULL, FOR_LOCA = NULL, FOR_CPOS = NULL, FOR_LPOS = NULL, PAI_CODI3 = NULL, FOR_NIF = NULL, ' ELSE '' END)
					+ (CASE WHEN ISNULL(ins.EXM_P17A, '') <> ISNULL(del.EXM_P17A, '') AND ISNULL(ins.EXM_P17A, '') <> '' AND ISNULL(dad.PAI_CODI4, '') <> '' THEN 'PAI_CODI4 = NULL, ' WHEN ISNULL(ins.EXM_P17A, '') <> ISNULL(del.EXM_P17A, '') AND ISNULL(ins.EXM_P17A, '') = '' AND ISNULL(dad.PAI_CODI4, '') = '' AND ISNULL(dad.PAI_CODI3, '') <> '' THEN 'PAI_CODI4 = PAI_CODI3, ' ELSE '' END)
					+ (CASE WHEN ISNULL(ins.EXM_TFRT, 0) = 0 AND ISNULL(del.EXM_TFRT, 0) <> 0 AND ISNULL(dad.EXA_VFRE, 0) <> 0 THEN '@Frete = EXA_VFRE = 0, ' WHEN ISNULL(ins.EXM_TFRT, 0) > 0 AND ins.EXM_VRBA = 1 AND ((del.EXM_VRBA = 0) OR (ISNULL(ins.EXM_TFRT, 0) <> ISNULL(del.EXM_TFRT, 0))) THEN '@Frete = EXA_VFRE = ROUND((CASE WHEN (@INTotalAdicoes > 1) AND (EXA_LINH = @INTotalAdicoes) THEN (@INTotalFrete - (SELECT SUM(ISNULL(EXA_VFRE, 0)) FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = @INAnoDeclaracao AND EXM_CODI = @INCodDeclaracao AND EXM_COPE = @INCodOperadorDeclaracao AND EXA_CHVE <> @INIdAdicao)) ELSE (ISNULL(EXA_MBRT, 0) * @INTotalFrete / @INTotalMassaBrt) END), 3), ' ELSE '' END)
					+ (CASE WHEN ISNULL(ins.EXM_TSEG, 0) = 0 AND ISNULL(del.EXM_TSEG, 0) <> 0 AND ISNULL(dad.EXA_VSEG, 0) <> 0 THEN '@Seguro = EXA_VSEG = 0, ' WHEN ISNULL(ins.EXM_TSEG, 0) > 0 AND ins.EXM_VRBA = 1 AND ((del.EXM_VRBA = 0) OR (ISNULL(ins.EXM_TSEG, 0) <> ISNULL(del.EXM_TSEG, 0))) THEN '@Seguro = EXA_VSEG = ROUND((CASE WHEN (@INTotalAdicoes > 1) AND (EXA_LINH = @INTotalAdicoes) THEN (@INTotalSeguro - (SELECT SUM(ISNULL(EXA_VSEG, 0)) FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = @INAnoDeclaracao AND EXM_CODI = @INCodDeclaracao AND EXM_COPE = @INCodOperadorDeclaracao AND EXA_CHVE <> @INIdAdicao)) ELSE (ISNULL(EXA_VALO, 0) * @INTotalSeguro / @INTotalMontante) END), 3), ' ELSE '' END) 
					+ (CASE WHEN ISNULL(ins.EXM_FR20, '') <> ISNULL(del.EXM_FR20, '') OR ins.EXM_CFRE <> del.EXM_CFRE OR ins.EXM_CSEG <> del.EXM_CSEG THEN '@Ajustamento = EXA_AJUS = dbo.fn_IMP_CalculaAjustamento(@INFormulaCondEntrega, 0, @INCambioFrete, @INCambioSeguro, @Frete, @Seguro, 0, 0, 0), ' ELSE '' END)
					+ (CASE WHEN ISNULL(ins.EXM_TX23, 0) <> ISNULL(del.EXM_TX23, 0) THEN 'EXA_VEST = dbo.fn_IMP_CalculaValorEstatistico(ROUND(ISNULL(EXA_VALO, 0) / @INCambioMontante, 2), @Ajustamento), ' ELSE '' END)
					+ (CASE WHEN (@PeriodoTransitorio = 1) AND ((ins.CLI_COD2 <> del.CLI_COD2) OR (ins.DEC_CO14 <> del.DEC_CO14) OR (ISNULL(ins.EXM_TP14, 0) <> ISNULL(del.EXM_TP14, 0)) OR (ISNULL(ins.EXM_REGI, '') <> ISNULL(del.EXM_REGI, '')) OR (ISNULL(ins.EXM_P17A, '') <> ISNULL(del.EXM_P17A, '')) OR (ins.TDE_COD1 <> del.TDE_COD1) OR (ins.EXM_TPRO <> del.EXM_TPRO) OR (ins.EAD_CODA <> del.EAD_CODA) OR (ISNULL(ins.EAD_CODI1, '') <> ISNULL(del.EAD_CODI1, ''))) THEN 'EXA_LINH = EXA_LINH, ' ELSE '' END)
				)
			FROM inserted AS ins
				INNER JOIN deleted AS del ON ins.EXM_IDTY = del.EXM_IDTY
				INNER JOIN TAB_TDEC AS tdi WITH(NOLOCK) ON ins.TDE_COD1 = tdi.TDE_CODI
				INNER JOIN TAB_TDEC AS tdd WITH(NOLOCK) ON del.TDE_COD1 = tdd.TDE_CODI
				INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON ins.EXM_EANO = dad.EXM_EANO AND ins.EXM_CODI = dad.EXM_CODI AND ins.DEC_CODI = dad.EXM_COPE
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON dad.APA_CO33 = apa.APA_CODI
			WHERE ins.EXM_CNTX = 1			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @TotalAdicoes, @FormulaCondEntrega, @TotalMontante, @CambioMontante, @TotalFrete, 
			@TotalSeguro, @TotalMassaBrt, @CambioFrete, @CambioSeguro, @Regime, @1CasaTipoDeclaracao, @DesdobramentoTipoDeclaracao, @CodMercPerigosasArtigo, @CodCCUSArtigo, @SQLAExecutar
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF ISNULL(@SQLAExecutar, '') <> ''
			BEGIN				
-- verifica se necessário obter o frete da adição
				IF (CHARINDEX('@Ajustamento = EXA_AJUS = ', @SQLAExecutar) > 0 OR CHARINDEX('@Seguro = EXA_VSEG = ', @SQLAExecutar) > 0) AND (CHARINDEX('@Frete = EXA_VFRE = ', @SQLAExecutar) = 0)
				BEGIN
					IF CHARINDEX('@Seguro = EXA_VSEG = ', @SQLAExecutar) > 0
						SET @PosIndex = CHARINDEX('@Seguro = EXA_VSEG = ', @SQLAExecutar)
					ELSE
						SET @PosIndex = CHARINDEX('@Ajustamento = EXA_AJUS = ', @SQLAExecutar)
					SET @SQLAExecutar = STUFF(@SQLAExecutar, @PosIndex, 0, '@Frete = EXA_VFRE, ')
				END
-- verifica se necessário obter o seguro da adição
				IF (CHARINDEX('@Ajustamento = EXA_AJUS = ', @SQLAExecutar) > 0 OR CHARINDEX('@Frete = EXA_VFRE = ', @SQLAExecutar) > 0) AND (CHARINDEX('@Seguro = EXA_VSEG = ', @SQLAExecutar) = 0)
				BEGIN
					IF CHARINDEX('@Frete = EXA_VFRE = ', @SQLAExecutar) > 0
						SET @PosIndex = CHARINDEX('@Frete = EXA_VFRE = ', @SQLAExecutar)
					ELSE
						SET @PosIndex = CHARINDEX('@Ajustamento = EXA_AJUS = ', @SQLAExecutar)
					SET @SQLAExecutar = STUFF(@SQLAExecutar, @PosIndex, 0, '@Seguro = EXA_VSEG, ')
				END					
-- verifica se necessário obter o ajustamento da adição
				IF (CHARINDEX('@Frete = EXA_VFRE = ', @SQLAExecutar) > 0 OR CHARINDEX('@Seguro = EXA_VSEG = ', @SQLAExecutar) > 0) AND (CHARINDEX('@Ajustamento = EXA_AJUS = ', @SQLAExecutar) = 0)
				BEGIN
					IF CHARINDEX('EXA_VEST = ', @SQLAExecutar) > 0
					BEGIN
						SET @PosIndex = CHARINDEX('EXA_VEST = ', @SQLAExecutar)
						SET @SQLAExecutar = STUFF(@SQLAExecutar, @PosIndex, 0, '@Ajustamento = EXA_AJUS = dbo.fn_IMP_CalculaAjustamento(@INFormulaCondEntrega, 0, @INCambioFrete, @INCambioSeguro, @Frete, @Seguro, 0, 0, 0), ')
					END
					ELSE
						SET @SQLAExecutar = @SQLAExecutar + '@Ajustamento = EXA_AJUS = dbo.fn_IMP_CalculaAjustamento(@INFormulaCondEntrega, 0, @INCambioFrete, @INCambioSeguro, @Frete, @Seguro, 0, 0, 0), '
				END
				ELSE
					IF (CHARINDEX('EXA_VEST = ', @SQLAExecutar) > 0) AND (CHARINDEX('@Ajustamento = EXA_AJUS = ', @SQLAExecutar) = 0)
					BEGIN
						SET @PosIndex = CHARINDEX('EXA_VEST = ', @SQLAExecutar)
						SET @SQLAExecutar = STUFF(@SQLAExecutar, @PosIndex, 0, '@Ajustamento = EXA_AJUS, ')
					END						
-- verifica se necessário obter o valor estatístico da adição
				IF (CHARINDEX('@Ajustamento = EXA_AJUS = ', @SQLAExecutar) > 0) AND (CHARINDEX('EXA_VEST = ', @SQLAExecutar) = 0)
					SET @SQLAExecutar = @SQLAExecutar + 'EXA_VEST = dbo.fn_IMP_CalculaValorEstatistico(ROUND(ISNULL(EXA_VALO, 0) / @INCambioMontante, 2), @Ajustamento), '
-- remove o caracter "," existente no final
				SET @SQLAExecutar = REVERSE(@SQLAExecutar)
				SET @SQLAExecutar = STUFF(@SQLAExecutar, 2, 1, '')
				SET @SQLAExecutar = REVERSE(@SQLAExecutar)
-- constroi o SQL p/ UPDATE da adição
				SET @SQLAExecutar = 'DECLARE @Frete numeric(38, 6), @Seguro numeric(38, 6), @Ajustamento numeric(38, 6) UPDATE PRO_EXAD SET ' + @SQLAExecutar + 'WHERE EXA_CHVE = @INIdAdicao'
-- edita a adição
				EXEC sp_executesql @SQLAExecutar, @SQLVariaveis, @INIdAdicao = @IdAdicao, @INAnoDeclaracao = @AnoDeclaracao, @INCodDeclaracao = @CodDeclaracao, @INCodOperadorDeclaracao = @CodOperadorDeclaracao, 
				@INTotalAdicoes = @TotalAdicoes, @INFormulaCondEntrega = @FormulaCondEntrega, @INTotalMontante = @TotalMontante, @INCambioMontante = @CambioMontante, @INTotalFrete = @TotalFrete, 
				@INTotalSeguro = @TotalSeguro, @INTotalMassaBrt = @TotalMassaBrt, @INCambioFrete = @CambioFrete, @INCambioSeguro = @CambioSeguro, @INRegime = @Regime, 
				@IN1CasaTipoDeclaracao = @1CasaTipoDeclaracao, @INDesdobramentoTipoDeclaracao = @DesdobramentoTipoDeclaracao, @INCodMercPerigosasArtigo = @CodMercPerigosasArtigo, 
				@INCodCCUSArtigo = @CodCCUSArtigo
			END
			FETCH NEXT FROM Declaracoes INTO @IdAdicao, @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao, @TotalAdicoes, @FormulaCondEntrega, @TotalMontante, @CambioMontante, @TotalFrete, 
				@TotalSeguro, @TotalMassaBrt, @CambioFrete, @CambioSeguro, @Regime, @1CasaTipoDeclaracao, @DesdobramentoTipoDeclaracao, @CodMercPerigosasArtigo, @CodCCUSArtigo, @SQLAExecutar
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
-- processa automatismos relacionados com a alteração da autorização de saída
	IF UPDATE(EXM_ASAI)
	BEGIN
-- obtem as declarações EXP-SAE alteradas que passaram a ter autorização de sáida mas cujo status de incidência não é "A13"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.EXM_EANO, ins.EXM_CODI, ins.DEC_CODI
			FROM inserted AS ins 				
			WHERE ins.EXM_CNTX = 1 AND ins.EXM_ASAI = 1 AND ins.SIN_CODI <> 'A13'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- processa a inserção/atualização dos dados AWB no SDS - Via Aérea (se configurado [verificação no SP])
			EXEC SP_ExportacaoXML_GeraLinhaSDSViaAerea @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
			FETCH NEXT FROM Declaracoes INTO @AnoDeclaracao, @CodDeclaracao, @CodOperadorDeclaracao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
END

ALTER TABLE [dbo].[PRO_EXML] ENABLE TRIGGER [TAU_PRO_EXML_EXPSAE]
/****** Object:  Trigger [TAD_PRO_EXMV]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_EXMV] ON [PRO_EXMV] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- Se marca "Parte" da 1ª adição assinalada como "Cópia" removida, atualiza todas as marcas e volumes das outras adições da declaração
	UPDATE PRO_EXMV SET EXM_PART = 0, EXM_REST = 0
	FROM PRO_EXMV as xmv INNER JOIN PRO_EXAD as adc ON xmv.EXA_CHVE = adc.EXA_CHVE
		INNER JOIN PRO_EXAD as adi ON adc.EXM_EANO = adi.EXM_EANO and adc.EXM_CODI = adi.EXM_CODI and adc.EXM_COPE = adi.EXM_COPE		
		INNER JOIN deleted as del ON adi.EXA_CHVE = del.EXA_CHVE		
	WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and del.EXM_PART = 1			
		and adc.EXA_LINH > 1 and xmv.EXM_IDSO = del.EXM_IDST
-- Se marca "Parte" da 1ª adição assinalada como "Cópia" removida, atualiza flag "Cópia" de todas as adições da declaração
    UPDATE PRO_EXAD SET EXA_CPMV = 0
    FROM PRO_EXAD as adc INNER JOIN (SELECT adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE
		FROM PRO_EXAD as adi INNER JOIN deleted as del ON adi.EXA_CHVE = del.EXA_CHVE 
		WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and del.EXM_PART = 1) as adl ON adc.EXM_EANO = adl.EXM_EANO and adc.EXM_CODI = adl.EXM_CODI and adc.EXM_COPE = adl.EXM_COPE
    WHERE adc.EXA_CPMV = 1    
-- Se marca for "Resto" ou não for "Parte" nem "Resto", atualiza "Total Volumes" da declaração
	UPDATE PRO_EXML SET EXM_TVL6 = ISNULL(EXM_TVL6, 0) - ISNULL(del.EXM_NVOL, 0)
	FROM PRO_EXML as exm INNER JOIN PRO_EXAD as adi ON exm.EXM_EANO = adi.EXM_EANO and exm.EXM_CODI = adi.EXM_CODI and exm.DEC_CODI = adi.EXM_COPE		
		INNER JOIN deleted as del ON adi.EXA_CHVE = del.EXA_CHVE
	WHERE exm.EXM_CNTX = 0 AND del.EXM_TVOL = 0 and ((del.EXM_PART = 0 and del.EXM_REST = 0) or (del.EXM_REST = 1))			
END

ALTER TABLE [dbo].[PRO_EXMV] ENABLE TRIGGER [TAD_PRO_EXMV]
/****** Object:  Trigger [TAD_PRO_EXMV_EXPSAE]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_EXMV_EXPSAE] ON [PRO_EXMV] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @CodOperadorDeclaracao varchar(6), @IdRegisto int, @SomaVolumes numeric(38, 6)
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- obtem as marcas e volumes de origem parte das adições > 1 associadas à 1ª adição parte alteradas das declarações EXP-SAE 
	DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dam.EXM_CHVE
		FROM deleted AS del 							
			INNER JOIN PRO_EXML AS dcl WITH(NOLOCK) ON del.EXM_EANO = dcl.EXM_EANO AND del.EXM_CODI = dcl.EXM_CODI AND del.EXM_COPE = dcl.DEC_CODI
			INNER JOIN PRO_EXAD AS dad WITH(NOLOCK) ON dcl.EXM_EANO = dad.EXM_EANO AND dcl.EXM_CODI = dad.EXM_CODI AND dcl.DEC_CODI = dad.EXM_COPE
			INNER JOIN PRO_EXMV AS dam WITH(NOLOCK) ON dad.EXA_CHVE = dam.EXA_CHVE AND dam.EXM_AUTO = 1			
		WHERE dcl.EXM_CNTX = 1 AND del.EXM_PART = 1		
	OPEN MarcasEVolumes
	FETCH NEXT FROM MarcasEVolumes INTO @IdRegisto
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- remove marca e volume					
		DELETE FROM PRO_EXMV
		WHERE EXM_CHVE = @IdRegisto		
		FETCH NEXT FROM MarcasEVolumes INTO @IdRegisto
	END
	CLOSE MarcasEVolumes
	DEALLOCATE MarcasEVolumes		
-- obtem as declarações associadas às marcas e volumes manuais removidas
	DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dcl.EXM_EANO, dcl.EXM_CODI, dcl.DEC_CODI
		FROM deleted AS del			
			INNER JOIN PRO_EXML AS dcl WITH(NOLOCK) ON del.EXM_EANO = dcl.EXM_EANO AND del.EXM_CODI = dcl.EXM_CODI AND del.EXM_COPE = dcl.DEC_CODI
		WHERE dcl.EXM_CNTX = 1 AND del.EXM_AUTO = 0
		GROUP BY dcl.EXM_EANO, dcl.EXM_CODI, dcl.DEC_CODI
	OPEN MarcasEVolumes
	FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @CodOperadorDeclaracao
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula a soma dos volumes das marcas e volumes manuais de todas as adições da declaração EXP-SAE
		SET @SomaVolumes = ISNULL(
			(SELECT SUM(dam.EXM_NVOL)
			FROM PRO_EXMV AS dam WITH(NOLOCK)
				INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON dam.EXA_CHVE = adi.EXA_CHVE			
			WHERE adi.EXM_EANO = @AnoDeclaracao AND adi.EXM_CODI = @NumDeclaracao AND adi.EXM_COPE = @CodOperadorDeclaracao AND dam.EXM_AUTO = 0), 0)
-- atualiza total de volumes na declaração EXP-SAE
		UPDATE PRO_EXML SET 
			EXM_TVL6 = @SomaVolumes				
		WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND DEC_CODI = @CodOperadorDeclaracao
		FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @CodOperadorDeclaracao
	END
	CLOSE MarcasEVolumes
	DEALLOCATE MarcasEVolumes			
END

ALTER TABLE [dbo].[PRO_EXMV] ENABLE TRIGGER [TAD_PRO_EXMV_EXPSAE]
/****** Object:  Trigger [TAIU_PRO_EXMV]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_EXMV] ON [PRO_EXMV] AFTER INSERT, UPDATE AS 
BEGIN	
	SET NOCOUNT ON;
-- Declaração de variáveis
	DECLARE @Ano int, @Codigo int, @Operador varchar(6)		
-- Se existir marca "Parte" da 1ª adição assinalada como "Cópia" inserida/editada, processa atualizações de marcas nas restantes adições da declaração
	IF EXISTS(SELECT adi.EXA_CHVE FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and ins.EXM_PART = 1)
	BEGIN
-- Se marca "Parte" da 1ª adição assinalada como "Cópia" inserida/editada, atualiza flag "Cópia" das restantes adições da declaração			
		UPDATE PRO_EXAD SET EXA_CPMV = 1	
		FROM PRO_EXAD AS adc WITH(NOLOCK) INNER JOIN (SELECT adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE
			FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE
			WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and ins.EXM_PART = 1) as ain ON adc.EXM_EANO = ain.EXM_EANO and ain.EXM_CODI = ain.EXM_CODI and adc.EXM_COPE = ain.EXM_COPE
		WHERE adc.EXA_LINH > 1 and adc.EXA_CPMV = 0	
-- Se marca "Parte" da 1ª adição assinalada como "Cópia" editada, atualiza marcas e volumes das restantes adições da declaração			
		UPDATE PRO_EXMV SET EXM_MARN = ins.EXM_MARN, TEM_CODI = ins.TEM_CODI, TEM_NOME = ins.TEM_NOME, EXM_NVOL = ins.EXM_NVOL, EXM_PART = ins.EXM_PART
		FROM PRO_EXMV AS xmv WITH(NOLOCK) INNER JOIN PRO_EXAD AS adc WITH(NOLOCK) ON xmv.EXA_CHVE = adc.EXA_CHVE
			INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON adc.EXM_EANO = adi.EXM_EANO and adc.EXM_CODI = adi.EXM_CODI and adc.EXM_COPE = adi.EXM_COPE
			INNER JOIN deleted as del ON adi.EXA_CHVE = del.EXA_CHVE
			INNER JOIN inserted as ins ON del.EXM_CHVE = ins.EXM_CHVE
		WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and (del.EXM_PART = 1 or ins.EXM_PART = 1)
			and adc.EXA_LINH > 1 and xmv.EXM_IDSO = del.EXM_IDST
-- Se marca "Parte" da 1ª adição assinalada como "Cópia" inserida/editada, insere marcas e volumes nas restantes adições da declaração se estas ainda não existirem
		INSERT INTO PRO_EXMV (EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_IDST, EXM_IDSO)
		SELECT adc.EXA_CHVE, ins.EXM_MARN, ins.TEM_CODI, ins.TEM_NOME, ins.EXM_NVOL, ins.EXM_PART, 
			(REPLACE(LTRIM(STR(CAST(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT() as numeric(20, 10)) + (CAST(adc.EXA_LINH as numeric(20, 10)) / 10000000000), 20, 10)), '.', ',')), ins.EXM_IDST
		FROM PRO_EXAD AS adc WITH(NOLOCK) INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON adc.EXM_EANO = adi.EXM_EANO and adc.EXM_CODI = adi.EXM_CODI and adc.EXM_COPE = adi.EXM_COPE
			INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE
		WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and ins.EXM_PART = 1 
			and adc.EXA_LINH > 1  and NOT EXISTS(SELECT EXM_CHVE FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = adc.EXA_CHVE and EXM_IDSO = ins.EXM_IDST)
		ORDER BY adc.EXA_CHVE	
-- Se marca "Parte" da 1ª adição assinalada como "Cópia" inserida/editada, atualiza marcas e volumes da última adição da declaração			
		UPDATE PRO_EXMV SET EXM_PART = 0, EXM_REST = 1
		FROM PRO_EXMV AS xmv WITH(NOLOCK) INNER JOIN PRO_EXAD AS adc WITH(NOLOCK) ON xmv.EXA_CHVE = adc.EXA_CHVE
			INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON adc.EXM_EANO = adi.EXM_EANO and adc.EXM_CODI = adi.EXM_CODI and adc.EXM_COPE = adi.EXM_COPE		
			INNER JOIN inserted AS ins WITH(NOLOCK) ON adi.EXA_CHVE = ins.EXA_CHVE
		WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and ins.EXM_PART = 1 
			and adc.EXA_LINH = (SELECT MAX(EXA_LINH) FROM PRO_EXAD WITH(NOLOCK) WHERE EXM_EANO = adc.EXM_EANO and EXM_CODI = adc.EXM_CODI and EXM_COPE = adc.EXM_COPE) 
			and adc.EXA_LINH > 1 and xmv.EXM_IDSO = ins.EXM_IDST	
	END
	ELSE
-- Se existir marca editada de "Parte" p/ "Não Parte" da 1ª adição assinalada como "Cópia", processa atualizações de marcas nas restantes adições da declaração
	IF EXISTS(SELECT adi.EXA_CHVE FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE INNER JOIN deleted as del ON ins.EXM_CHVE = del.EXM_CHVE WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and ins.EXM_PART = 0 and del.EXM_PART = 1)
	BEGIN
-- Se marca editada de "Parte" p/ "Não Parte" da 1ª adição assinalada como "Cópia", atualiza todas as marcas e volumes das outras adições da declaração	
		UPDATE PRO_EXMV SET EXM_PART = 0, EXM_REST = 0
		FROM PRO_EXMV AS xmv WITH(NOLOCK) INNER JOIN PRO_EXAD AS adc WITH(NOLOCK) ON xmv.EXA_CHVE = adc.EXA_CHVE
			INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON adc.EXM_EANO = adi.EXM_EANO and adc.EXM_CODI = adi.EXM_CODI and adc.EXM_COPE = adi.EXM_COPE		
			INNER JOIN deleted as del ON adi.EXA_CHVE = del.EXA_CHVE
			INNER JOIN inserted as ins ON del.EXM_CHVE = ins.EXM_CHVE
		WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and ins.EXM_PART = 0 and del.EXM_PART = 1			
			and adc.EXA_LINH > 1 and xmv.EXM_IDSO = ins.EXM_IDST
-- Se marca editada de "Parte" p/ "Não Parte" da 1ª adição assinalada como "Cópia", atualiza flag "Cópia" de todas as adições da declaração			
		UPDATE PRO_EXAD SET EXA_CPMV = 0	
		FROM PRO_EXAD AS adc WITH(NOLOCK) INNER JOIN (SELECT adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE
			FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE
				INNER JOIN deleted as del ON ins.EXM_CHVE = del.EXM_CHVE 
			WHERE adi.EXA_LINH = 1 and adi.EXA_CPMV = 1 and ins.EXM_PART = 0 and del.EXM_PART = 1) as ain ON adc.EXM_EANO = ain.EXM_EANO and ain.EXM_CODI = ain.EXM_CODI and adc.EXM_COPE = ain.EXM_COPE
		WHERE adc.EXA_CPMV = 1			
	END
-- Se existir marca "Parte" da 1ª adição inserida/editada e o documento "N271" não existir na 1ª adição, processa inserção de documento "N271" na 1ª adição da declaração
	IF EXISTS(SELECT adi.EXA_CHVE FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE WHERE adi.EXA_LINH = 1 and ins.EXM_PART = 1 and NOT EXISTS(SELECT EXD_CHVE FROM PRO_EXDA WITH(NOLOCK) WHERE EXA_CHVE = ins.EXA_CHVE and DOC_CODI = 'N271'))
	BEGIN
-- Se existir marca "Parte" da 1ª adição inserida/editada e o documento "N271" não existir na 1ª adição, insere documento "N271" na 1ª adição da declaração	
		INSERT INTO PRO_EXDA(EXA_CHVE, DOC_CODI, DOC_NOME, EXD_NREF, EXD_DTEM, EXD_MONT, EXD_QNTD, EXM_EANO, EXM_CODI, EXM_COPE, EXA_LINH)
		SELECT adi.EXA_CHVE, doc.DOC_CODI, doc.DOC_NOME, dft.EXD_NREF, dft.EXD_DTEM, 0, 0, adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE, adi.EXA_LINH
		FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE 
			INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = 'N271' and doc.DOC_EXPT = 1
			LEFT OUTER JOIN (SELECT TOP 1 prd.EXA_CHVE, prd.EXD_NREF, prd.EXD_DTEM
				FROM (SELECT exd.EXA_CHVE, NULLIF(exd.EXD_NREF, '') as EXD_NREF, exd.EXD_DTEM, (CASE exd.DOC_CODI WHEN 'N380' THEN 1 WHEN 'N325' THEN 2 WHEN '9E06' THEN 3 WHEN '9E03' THEN 4 WHEN 'N203' THEN 5 WHEN 'N315' THEN 6 WHEN 'N395' THEN 7 WHEN 'N935'  THEN 8 ELSE 999 END) AS EXD_ORDE
					FROM PRO_EXDA AS exd WITH(NOLOCK) INNER JOIN inserted as ins ON exd.EXA_CHVE = ins.EXA_CHVE
					WHERE exd.EXA_LINH = 1 and ins.EXM_PART = 1 and exd.DOC_CODI in ('N380', 'N325', '9E06', '9E03', 'N203', 'N315', 'N395', 'N935')) as prd
				ORDER BY prd.EXD_ORDE) as dft ON adi.EXA_CHVE = dft.EXA_CHVE
		WHERE adi.EXA_LINH = 1 and ins.EXM_PART = 1 			
	END
-- Se campos de "Nº. Volumes", "Total Vols Zero", "Parte" ou "Resto" inseridos/alterados, processa atualização do "Total Volumes" da declaração 
	IF (UPDATE(EXM_NVOL)) or (UPDATE(EXM_TVOL)) or (UPDATE(EXM_PART)) or (UPDATE(EXM_REST))
	BEGIN
-- Se marca for "Resto" ou não for "Parte" nem "Resto", atualiza "Total Volumes" da declaração
		UPDATE PRO_EXML SET EXM_TVL6 = ISNULL((SELECT SUM(ISNULL(emv.EXM_NVOL, 0)) 
			FROM PRO_EXMV AS emv WITH(NOLOCK) INNER JOIN PRO_EXAD AS ead WITH(NOLOCK) ON emv.EXA_CHVE = ead.EXA_CHVE
			WHERE emv.EXM_TVOL = 0 and ((emv.EXM_PART = 0 and emv.EXM_REST = 0) or (emv.EXM_REST = 1)) and 
				ead.EXM_EANO = adi.EXM_EANO and ead.EXM_CODI = adi.EXM_CODI and ead.EXM_COPE = adi.EXM_COPE), 0)
		FROM PRO_EXML AS exm WITH(NOLOCK) INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON exm.EXM_EANO = adi.EXM_EANO and exm.EXM_CODI = adi.EXM_CODI and exm.DEC_CODI = adi.EXM_COPE		
			INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE	
		WHERE exm.EXM_CNTX = 0	
	END		
-- Se 1ª marca e volume inserido/editado na 1ª adição, processa actualizações no SDS Via-Aérea associado (se este existir ou configurações ativas)
	IF (UPDATE(EXM_MARN)) or (UPDATE(TEM_CODI)) or (UPDATE(EXM_NVOL)) or (UPDATE(EXM_TVOL)) or (UPDATE(EXM_PART)) or (UPDATE(EXM_REST))
	BEGIN
		DECLARE Marcas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.EXM_EANO, adi.EXM_CODI, adi.EXM_COPE 
			FROM PRO_EXAD AS adi WITH(NOLOCK) INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE 				
			WHERE adi.EXA_LINH = 1 and ins.EXM_CHVE = (SELECT MIN(EXM_CHVE) FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = ins.EXA_CHVE) 
		OPEN Marcas
		FETCH NEXT FROM Marcas INTO @Ano, @Codigo, @Operador
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC SP_ExportacaoXML_GeraLinhaSDSViaAerea @Ano, @Codigo, @Operador
			FETCH NEXT FROM Marcas INTO @Ano, @Codigo, @Operador
		END
		CLOSE Marcas
		DEALLOCATE Marcas
	END	
-- Se 1ª marca e volume inserido/editado na 1ª adição, processa actualizações na Conta associada se configuração o permitir
	IF ((UPDATE(EXM_MARN)) or (UPDATE(TEM_CODI)) or (UPDATE(EXM_NVOL)) or (UPDATE(EXM_TVOL)) or (UPDATE(EXM_PART)) or (UPDATE(EXM_REST))) 
		and (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_BCNR IN (0, 2)))
	BEGIN
		UPDATE FAC_CDOC SET CDO_MARC = EXM_MARN, CDO_QUAL = TEM_NOME, CDO_QUNT = exm.EXM_TVL6
		FROM FAC_CDOC AS cdo WITH(NOLOCK) INNER JOIN PRO_EXML AS exm WITH(NOLOCK) ON cdo.CDO_PANO = exm.EXM_EANO and cdo.CDO_NPRO = exm.EXM_NRII and cdo.EXM_OPER = exm.DEC_CODI
			INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON exm.EXM_EANO = adi.EXM_EANO and exm.EXM_CODI = adi.EXM_CODI and exm.DEC_CODI = adi.EXM_COPE		
			INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE 
			INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''			
		WHERE ((pde.PDE_BCNR = 0) OR ((pde.PDE_BCNR = 2) AND (exm.EXM_ASAI = 0))) AND cdo.CDO_IMEX = 1 AND cdo.CDO_STAT = 0 AND adi.EXA_LINH = 1 
			AND ins.EXM_CHVE = (SELECT MIN(EXM_CHVE) FROM PRO_EXMV WITH(NOLOCK) WHERE EXA_CHVE = ins.EXA_CHVE) 
	END	
END

ALTER TABLE [dbo].[PRO_EXMV] ENABLE TRIGGER [TAIU_PRO_EXMV]
/****** Object:  Trigger [TAIU_PRO_EXMV_EXPSAE]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_EXMV_EXPSAE] ON [PRO_EXMV] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @CodOperadorDeclaracao varchar(6), @IdAdicao int, @Marca varchar(512), @CodTipoEmbalagem varchar(2), @NomeTipoEmbalagem varchar(35), 
		@Parte bit, @VolumesZero bit, @IdStrRegisto varchar(20), @IdRegisto int, @SomaVolumes numeric(38, 6)
-- processa automatismos relacionados com a alteração da marca, tipo embalagem ou parte
	IF UPDATE(EXM_MARN) OR UPDATE(TEM_CODI) OR UPDATE(EXM_PART)
	BEGIN
-- obtem as marcas e volumes de origem parte das adições > 1 associadas à 1ª adição parte alteradas das declarações EXP-SAE 
		DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adn.EXA_CHVE, adn.EXM_EANO, adn.EXM_CODI, adn.EXM_COPE, ins.EXM_MARN, ins.TEM_CODI, ins.TEM_NOME, ins.EXM_PART, ins.EXM_TVOL, dam.EXM_CHVE
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.EXM_CHVE = del.EXM_CHVE
				INNER JOIN PRO_EXAD AS ad1 WITH(NOLOCK) ON ins.EXA_CHVE = ad1.EXA_CHVE AND ad1.EXA_LINH = 1 
				INNER JOIN PRO_EXML AS dcl WITH(NOLOCK) ON ad1.EXM_EANO = dcl.EXM_EANO AND ad1.EXM_CODI = dcl.EXM_CODI AND ad1.EXM_COPE = dcl.DEC_CODI
				INNER JOIN PRO_EXAD AS adn WITH(NOLOCK) ON dcl.EXM_EANO = adn.EXM_EANO AND dcl.EXM_CODI = adn.EXM_CODI AND dcl.DEC_CODI = adn.EXM_COPE AND adn.EXA_LINH > 1
				LEFT OUTER JOIN PRO_EXMV AS dam WITH(NOLOCK) ON adn.EXA_CHVE = dam.EXA_CHVE AND dam.EXM_AUTO = 1													
			WHERE dcl.EXM_CNTX = 1 AND ((ins.EXM_PART = 1) OR (del.EXM_PART = 1))							
		OPEN MarcasEVolumes
		FETCH NEXT FROM MarcasEVolumes INTO @IdAdicao, @AnoDeclaracao, @NumDeclaracao, @CodOperadorDeclaracao, @Marca, @CodTipoEmbalagem, @NomeTipoEmbalagem, @Parte, @VolumesZero, @IdRegisto
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- insere a marca e volume parte na adição
			IF (@IdRegisto IS NULL) AND (@Parte = 1)
			BEGIN 
				SET @IdStrRegisto = REPLACE(LTRIM(STR(CAST(GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT() AS numeric(20, 10)) + (CAST(@IdAdicao AS numeric(20, 10)) / 10000000000), 20, 10)), '.', ',')
-- insere a marca e volume no detalhe de marcas e volumes da adição da declaração EXP-SAE
				INSERT INTO PRO_EXMV(EXA_CHVE, EXM_MARN, TEM_CODI, TEM_NOME, EXM_NVOL, EXM_PART, EXM_TVOL, EXM_IDST, EXM_AUTO, EXM_EANO, EXM_CODI, EXM_COPE)
				VALUES(@IdAdicao, @Marca, @CodTipoEmbalagem, @NomeTipoEmbalagem, 0, 0, @VolumesZero, @IdStrRegisto, 1, @AnoDeclaracao, @NumDeclaracao, @CodOperadorDeclaracao)			
			END
			ELSE
-- edita a marca e volume parte da adição da declaração EXP-SAE
				IF @Parte = 1
				BEGIN
					UPDATE PRO_EXMV SET											 
						EXM_MARN = @Marca, 						
						TEM_CODI = @CodTipoEmbalagem, 
						TEM_NOME = @NomeTipoEmbalagem, 
						EXM_TVOL = @VolumesZero
					WHERE EXM_CHVE = @IdRegisto
				END
				ELSE
				BEGIN
-- remove marca e volume					
					DELETE FROM PRO_EXMV
					WHERE EXM_CHVE = @IdRegisto
				END
			FETCH NEXT FROM MarcasEVolumes INTO @IdAdicao, @AnoDeclaracao, @NumDeclaracao, @CodOperadorDeclaracao, @Marca, @CodTipoEmbalagem, @NomeTipoEmbalagem, @Parte, @VolumesZero, @IdRegisto
		END
		CLOSE MarcasEVolumes
		DEALLOCATE MarcasEVolumes		
	END
-- processa automatismos relacionados com a alteração do numero volumes
	IF (ISNULL(CONTEXT_INFO(), 0x0) <> 0x44495341424C4544) AND (UPDATE(EXM_NVOL)) --"DISABLED" em binário
	BEGIN
-- obtem as declarações associadas às marcas e volumes manuais inseridas/editadas
		DECLARE MarcasEVolumes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dcl.EXM_EANO, dcl.EXM_CODI, dcl.DEC_CODI
			FROM inserted AS ins
				INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON ins.EXA_CHVE = adi.EXA_CHVE			
				INNER JOIN PRO_EXML AS dcl WITH(NOLOCK) ON adi.EXM_EANO = dcl.EXM_EANO AND adi.EXM_CODI = dcl.EXM_CODI AND adi.EXM_COPE = dcl.DEC_CODI
			WHERE dcl.EXM_CNTX = 1 AND ins.EXM_AUTO = 0
			GROUP BY dcl.EXM_EANO, dcl.EXM_CODI, dcl.DEC_CODI			
		OPEN MarcasEVolumes
		FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @CodOperadorDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a soma dos volumes das marcas e volumes manuais de todas as adições da declaração EXP-SAE
			SET @SomaVolumes = ISNULL(
				(SELECT SUM(dam.EXM_NVOL)
				FROM PRO_EXMV AS dam WITH(NOLOCK)
					INNER JOIN PRO_EXAD AS adi WITH(NOLOCK) ON dam.EXA_CHVE = adi.EXA_CHVE			
				WHERE adi.EXM_EANO = @AnoDeclaracao AND adi.EXM_CODI = @NumDeclaracao AND adi.EXM_COPE = @CodOperadorDeclaracao AND dam.EXM_AUTO = 0), 0)
-- atualiza total de volumes na declaração EXP-SAE
			UPDATE PRO_EXML SET 
				EXM_TVL6 = @SomaVolumes				
			WHERE EXM_EANO = @AnoDeclaracao AND EXM_CODI = @NumDeclaracao AND DEC_CODI = @CodOperadorDeclaracao
			FETCH NEXT FROM MarcasEVolumes INTO @AnoDeclaracao, @NumDeclaracao, @CodOperadorDeclaracao
		END
		CLOSE MarcasEVolumes
		DEALLOCATE MarcasEVolumes		
	END
END

ALTER TABLE [dbo].[PRO_EXMV] ENABLE TRIGGER [TAIU_PRO_EXMV_EXPSAE]
/****** Object:  Trigger [TAI_PRO_EXPS]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_EXPS] ON [PRO_EXPS] AFTER INSERT AS 
BEGIN
	SET NOCOUNT ON;
-- Processa a cópia dos pedidos simplificados inseridos na 1ª adição nas restantes adições da declaração se estes ainda não existirem
	INSERT INTO PRO_EXPS (EXA_CHVE, MIA_CODI, MIA_DESC, MIA_OBRI)
	SELECT adc.EXA_CHVE, ins.MIA_CODI, ins.MIA_DESC, ins.MIA_OBRI
	FROM PRO_EXAD as adc INNER JOIN PRO_EXAD as adi ON adc.EXM_EANO = adi.EXM_EANO and adc.EXM_CODI = adi.EXM_CODI and adc.EXM_COPE = adi.EXM_COPE
		INNER JOIN inserted as ins ON adi.EXA_CHVE = ins.EXA_CHVE
	WHERE adi.EXA_LINH = 1 and adc.EXA_LINH > 1  and NOT EXISTS(SELECT EXP_CHVE FROM PRO_EXPS WHERE EXA_CHVE = adc.EXA_CHVE and MIA_CODI = ins.MIA_CODI)
	ORDER BY adc.EXA_CHVE	
END

ALTER TABLE [dbo].[PRO_EXPS] ENABLE TRIGGER [TAI_PRO_EXPS]
/****** Object:  Trigger [TAD_PRO_IL90]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_IL90] ON [PRO_IL90] FOR DELETE
AS 
	-- declaracao de variaveis -----------------------------------------------------------------
	DECLARE @ano int, @cod int, @num int
	
	set nocount on

	-- busca dados a apagar -----------------------------------------------------------------
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT DUC_EANO, DUC_PNUM
	FROM deleted
	
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @ano, @cod
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- apagar informação das Adições ------------------------------------------------
		DELETE FROM PRO_IL9A WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	

		-- apagar informação da Liquidação Recapitulativa -------------------------------
		DELETE FROM PRO_IL9L WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	

		-- apagar informação referênte às Cauções ---------------------------------------
		DELETE FROM PRO_MCAU WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DUC_TIPO = 2
		DELETE FROM PRO_CCCA WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DUC_TIPO = 2

		FETCH NEXT FROM Detalhe INTO @ano, @cod
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	
	set nocount off

ALTER TABLE [dbo].[PRO_IL90] ENABLE TRIGGER [TAD_PRO_IL90]
/****** Object:  Trigger [TAD_PRO_ILGA]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_ILGA] ON [PRO_ILGA] FOR DELETE
AS 
	-- declaracao de variaveis -----------------------------------------------------------------
	DECLARE @ano int, @cod int, @num int
	
	set nocount on

	-- busca dados a apagar -----------------------------------------------------------------
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
	SELECT DUC_EANO, DUC_PNUM
	FROM deleted
	
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @ano, @cod
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- apagar informação das Adições ------------------------------------------------
		DELETE FROM PRO_ILAD WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	

		-- apagar informação da Liquidação Recapitulativa -------------------------------
		DELETE FROM PRO_ILLR WHERE DUC_PNUM = @cod AND DUC_EANO = @ano	

		-- apagar informação referênte às Cauções ---------------------------------------
		DELETE FROM PRO_MCAU WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DUC_TIPO = 1
		DELETE FROM PRO_CCCA WHERE DUC_PNUM = @cod AND DUC_EANO = @ano AND DUC_TIPO = 1

		FETCH NEXT FROM Detalhe INTO @ano, @cod
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe
	
	set nocount off

ALTER TABLE [dbo].[PRO_ILGA] ENABLE TRIGGER [TAD_PRO_ILGA]
/****** Object:  Trigger [TAD_PRO_MCAU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_MCAU] ON [PRO_MCAU] FOR DELETE AS 
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @MCA_IDEN int, @ALF_ORIG varchar(8), @MCA_ANUL bit, @alfcauc bit
-- busca dados removidos
	DECLARE Registo CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT MCA_IDEN, ALF_ORIG, MCA_ANUL
		FROM deleted
	OPEN Registo
	FETCH NEXT FROM Registo INTO @MCA_IDEN, @ALF_ORIG, @MCA_ANUL
	WHILE @@FETCH_STATUS = 0
	BEGIN		
-- se Mov. Caução não estiver anulado, efectua remoções
		IF @MCA_ANUL = 0 
		BEGIN 
-- busca dados da Alfandega
			SELECT @alfcauc = ALF_PRIN
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE ALF_CODI = @ALF_ORIG	
-- remove Alfandega de Origem
			DELETE FROM PRO_CCCA 
			WHERE CCC_IORI IS NULL AND MCA_IDEN = @MCA_IDEN
-- se Alfandega Origem possui Alfandega Principal, gera outro registo
			IF @alfcauc = 0
			BEGIN
				DELETE FROM PRO_CCCA 
				WHERE CCC_IORI = @MCA_IDEN and MCA_IDEN = @MCA_IDEN
			END
		END
		FETCH NEXT FROM Registo INTO @MCA_IDEN, @ALF_ORIG, @MCA_ANUL
	END
	CLOSE Registo
	DEALLOCATE Registo
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[PRO_MCAU] ENABLE TRIGGER [TAD_PRO_MCAU]
/****** Object:  Trigger [TAI_PRO_MCAU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_PRO_MCAU] ON [PRO_MCAU] FOR INSERT AS 
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @MCA_TENT int, @MCA_ENTI varchar(18), @MCA_NCAU varchar(24), @MCA_CANO varchar(4), @MCA_CTIP varchar(1), @ALF_ORIG varchar(8), @MCA_NDOC varchar(15), @MCA_DATA datetime, @MCA_LIQD bit, @MCA_DBCR int, 
		@MCA_VLTT numeric(38,6), @CAU_CODI varchar(5), @atri bit, @util bit, @vadua numeric(38,6), @vdire numeric(38,6), @alfcauc bit, @alfcodi varchar(8), @MCA_IORI int, @ALF_DEST varchar(8), @MCA_NORD varchar(20), 
		@MCA_DORD datetime, @CLI_DEST varchar(18), @MCA_OBSR varchar(50), @MCA_PROV bit, @DUC_PNUM int, @DUC_EANO int, @DUC_TIPO int, @MCA_IDEN int
-- busca dados inseridos
	DECLARE Registo CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO,	MCA_CTIP, ALF_ORIG, MCA_NDOC, MCA_DATA, MCA_LIQD, MCA_DBCR, MCA_VLTT, CAU_CODI, MCA_IORI, ALF_DEST, MCA_NORD, MCA_DORD, CLI_DEST, MCA_OBSR, MCA_PROV, DUC_PNUM, 
			DUC_EANO, DUC_TIPO, MCA_IDEN
		FROM inserted
	OPEN Registo
	FETCH NEXT FROM Registo INTO @MCA_TENT, @MCA_ENTI, @MCA_NCAU, @MCA_CANO, @MCA_CTIP, @ALF_ORIG, @MCA_NDOC, @MCA_DATA, @MCA_LIQD, @MCA_DBCR, @MCA_VLTT, @CAU_CODI, @MCA_IORI, @ALF_DEST, @MCA_NORD, @MCA_DORD, 
		@CLI_DEST, @MCA_OBSR, @MCA_PROV, @DUC_PNUM, @DUC_EANO, @DUC_TIPO, @MCA_IDEN
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- busca dados da Alfandega
		SELECT @alfcauc = ALF_PRIN, @alfcodi = ALF_APRI
		FROM TAB_ALFA WITH(NOLOCK)
		WHERE ALF_CODI = @ALF_ORIG	
-- busca dados da Caução
		SELECT @atri = CAU_ATRI, @util = CAU_UTIL
		FROM TAB_CAUC WITH(NOLOCK)
		WHERE CAU_CODI = @CAU_CODI
-- conforme dados da Caução, calcula valores
		IF (@atri = 1) and (@util = 0)
			SELECT @vadua = @MCA_VLTT, @vdire = 0
		ELSE 
			IF (@atri = 0) and (@util = 1)
				SELECT @vadua = 0, @vdire = @MCA_VLTT	
			ELSE 
				IF (@atri = 1) and (@util = 1)
					SELECT	@vadua = @MCA_VLTT, @vdire = @MCA_VLTT	
				ELSE
					SELECT	@vadua = 0, @vdire = 0
-- inserir registo da alfândega origem 
		INSERT INTO PRO_CCCA(CCC_TENT, CCC_ENTI, CCC_NCAU, CCC_CANO, CCC_CTIP, ALF_ORIG, CCC_NDOC, CCC_DATA, CCC_LIQD, CCC_DBCR, CCC_VATR, CCC_VUTI, CCC_IORI, ALF_DEST, CAU_CODI, CCC_NORD, CCC_DORD, CLI_DEST, 
			CCC_OBSR, CCC_PROV, DUC_PNUM, DUC_EANO, DUC_TIPO, MCA_IDEN)
		VALUES (@MCA_TENT, @MCA_ENTI, @MCA_NCAU, @MCA_CANO, @MCA_CTIP, @ALF_ORIG, @MCA_NDOC, @MCA_DATA, @MCA_LIQD, @MCA_DBCR, @vadua, @vdire, @MCA_IORI, @ALF_DEST, @CAU_CODI, @MCA_NORD, @MCA_DORD, @CLI_DEST, 
			@MCA_OBSR, @MCA_PROV, @DUC_PNUM, @DUC_EANO, @DUC_TIPO, @MCA_IDEN)
-- se Alfandega Origem possui Alfandega Principal, gera outro registo
		IF @alfcauc = 0
		BEGIN
			SET @MCA_IORI = @MCA_IDEN 
-- inserir registo relacionado com a alfândega principal 
 			INSERT INTO PRO_CCCA(CCC_TENT, CCC_ENTI, CCC_NCAU, CCC_CANO, CCC_CTIP, ALF_ORIG, CCC_NDOC, CCC_DATA, CCC_LIQD, CCC_DBCR, CCC_VATR, CCC_VUTI, CCC_IORI, ALF_DEST, CAU_CODI, CCC_NORD, CCC_DORD, CLI_DEST, 
				CCC_OBSR, CCC_PROV, DUC_PNUM, DUC_EANO, DUC_TIPO, MCA_IDEN)
			VALUES (@MCA_TENT, @MCA_ENTI, @MCA_NCAU, @MCA_CANO, @MCA_CTIP, @alfcodi, @MCA_NDOC, @MCA_DATA, @MCA_LIQD, @MCA_DBCR, @vadua, @vdire, @MCA_IORI, @ALF_DEST, @CAU_CODI, @MCA_NORD, @MCA_DORD, @CLI_DEST, 
				@MCA_OBSR, @MCA_PROV, @DUC_PNUM, @DUC_EANO, @DUC_TIPO, @MCA_IDEN)
		END
		FETCH NEXT FROM Registo INTO @MCA_TENT, @MCA_ENTI, @MCA_NCAU, @MCA_CANO, @MCA_CTIP, @ALF_ORIG, @MCA_NDOC, @MCA_DATA, @MCA_LIQD, @MCA_DBCR, @MCA_VLTT, @CAU_CODI, @MCA_IORI, @ALF_DEST, @MCA_NORD, @MCA_DORD, 
			@CLI_DEST, @MCA_OBSR, @MCA_PROV, @DUC_PNUM, @DUC_EANO, @DUC_TIPO, @MCA_IDEN
	END
	CLOSE Registo
	DEALLOCATE Registo
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[PRO_MCAU] ENABLE TRIGGER [TAI_PRO_MCAU]
/****** Object:  Trigger [TAU_PRO_MCAU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_MCAU] ON [PRO_MCAU] FOR UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- declaracao de variaveis 
	DECLARE @MCA_TENT int, @MCA_ENTI varchar(18), @MCA_NCAU varchar(24), @MCA_CANO varchar(4), @MCA_CTIP varchar(1), @ALF_ORIG varchar(8), @MCA_NDOC varchar(15), @MCA_DATA datetime, @MCA_LIQD bit, @MCA_DBCR int, 
		@MCA_VLTT numeric(38,6), @CAU_CODI varchar(5), @atri bit, @util bit, @vadua numeric(38,6), @vdire numeric(38,6), @alfcauc bit, @alfcodi varchar(8), @MCA_IORI int, @ALF_DEST varchar(8), @MCA_NORD varchar(20), 
		@MCA_DORD datetime, @CLI_DEST varchar(18), @MCA_OBSR varchar(50), @MCA_PROV bit, @MCA_IDEN int, @MCA_ANUL bit, @DUC_PNUM int, @DUC_EANO int, @DUC_TIPO int
-- busca dados alterados
	DECLARE Registo CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT MCA_TENT, MCA_ENTI, MCA_NCAU, MCA_CANO,	MCA_CTIP, ALF_ORIG, MCA_NDOC, MCA_DATA, MCA_LIQD, MCA_DBCR, MCA_VLTT, CAU_CODI, MCA_IORI, ALF_DEST, MCA_NORD, MCA_DORD, CLI_DEST, MCA_OBSR, MCA_PROV, MCA_IDEN, 
			MCA_ANUL, DUC_PNUM, DUC_EANO, DUC_TIPO 
		FROM inserted
	OPEN Registo
	FETCH NEXT FROM Registo INTO @MCA_TENT, @MCA_ENTI, @MCA_NCAU, @MCA_CANO, @MCA_CTIP, @ALF_ORIG, @MCA_NDOC, @MCA_DATA, @MCA_LIQD, @MCA_DBCR, @MCA_VLTT, @CAU_CODI, @MCA_IORI, @ALF_DEST, @MCA_NORD, @MCA_DORD, 
		@CLI_DEST, @MCA_OBSR, @MCA_PROV, @MCA_IDEN, @MCA_ANUL, @DUC_PNUM, @DUC_EANO, @DUC_TIPO
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- se Mov. Caução não estiver anulado, efectua alterações
		IF @MCA_ANUL = 0
		BEGIN
-- busca dados da Alfandega
			SELECT @alfcauc = ALF_PRIN, @alfcodi = ALF_APRI
			FROM TAB_ALFA WITH(NOLOCK)
			WHERE ALF_CODI = @ALF_ORIG	
-- busca dados da Caução
			SELECT @atri = CAU_ATRI, @util = CAU_UTIL
			FROM TAB_CAUC WITH(NOLOCK)
			WHERE CAU_CODI = @CAU_CODI
-- conforme dados da Caução, calcula valores
			if (@atri = 1) and (@util = 0)
				SELECT 	@vadua = @MCA_VLTT, @vdire = 0
			ELSE 
				IF (@atri = 0) and (@util = 1)
					SELECT 	@vadua = 0, @vdire = @MCA_VLTT	
				ELSE 
					IF (@atri = 1) and (@util = 1)
						SELECT 	@vadua = @MCA_VLTT, @vdire = @MCA_VLTT
					ELSE
						SELECT 	@vadua = 0, @vdire = 0			
-- actualizar registo da alfândega origem 
 			UPDATE PRO_CCCA SET CCC_TENT = @MCA_TENT, CCC_ENTI = @MCA_ENTI, CCC_NCAU = @MCA_NCAU, CCC_CANO = @MCA_CANO, CCC_CTIP = @MCA_CTIP, ALF_ORIG = @ALF_ORIG, CCC_NDOC = @MCA_NDOC, CCC_DATA = @MCA_DATA, 
				CCC_LIQD = @MCA_LIQD, CCC_DBCR = @MCA_DBCR, CCC_VATR = @vadua, CCC_VUTI = @vdire, ALF_DEST = @ALF_DEST, CAU_CODI = @CAU_CODI, CCC_NORD = @MCA_NORD, CCC_DORD = @MCA_DORD, CLI_DEST = @CLI_DEST, 
				CCC_OBSR = @MCA_OBSR, CCC_PROV = @MCA_PROV, DUC_PNUM = @DUC_PNUM, DUC_EANO = @DUC_EANO, DUC_TIPO = @DUC_TIPO
			WHERE CCC_IORI IS NULL AND MCA_IDEN = @MCA_IDEN
-- se Alfandega Origem possui Alfandega Principal, gera outro registo
			IF @alfcauc = 0
			BEGIN
				UPDATE PRO_CCCA SET CCC_TENT = @MCA_TENT, CCC_ENTI = @MCA_ENTI, CCC_NCAU = @MCA_NCAU, CCC_CANO = @MCA_CANO, CCC_CTIP = @MCA_CTIP, ALF_ORIG = @alfcodi, CCC_NDOC = @MCA_NDOC, CCC_DATA = @MCA_DATA, 
					CCC_LIQD = @MCA_LIQD, CCC_DBCR = @MCA_DBCR, CCC_VATR = @vadua, CCC_VUTI = @vdire, ALF_DEST = @ALF_DEST, CAU_CODI = @CAU_CODI, CCC_NORD = @MCA_NORD, CCC_DORD = @MCA_DORD, CLI_DEST = @CLI_DEST, 
					CCC_OBSR = @MCA_OBSR, CCC_PROV = @MCA_PROV, DUC_PNUM = @DUC_PNUM, DUC_EANO = @DUC_EANO, DUC_TIPO = @DUC_TIPO
				WHERE CCC_IORI = @MCA_IDEN AND MCA_IDEN = @MCA_IDEN
			END
		END
		FETCH NEXT FROM Registo INTO @MCA_TENT, @MCA_ENTI, @MCA_NCAU, @MCA_CANO, @MCA_CTIP, @ALF_ORIG, @MCA_NDOC, @MCA_DATA, @MCA_LIQD, @MCA_DBCR, @MCA_VLTT, @CAU_CODI, @MCA_IORI, @ALF_DEST, @MCA_NORD, @MCA_DORD, 
			@CLI_DEST, @MCA_OBSR, @MCA_PROV, @MCA_IDEN, @MCA_ANUL, @DUC_PNUM, @DUC_EANO, @DUC_TIPO
	END
	CLOSE Registo
	DEALLOCATE Registo
	SET NOCOUNT OFF
END

ALTER TABLE [dbo].[PRO_MCAU] ENABLE TRIGGER [TAU_PRO_MCAU]
/****** Object:  Trigger [TAD_PRO_NSEL]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_NSEL] ON [PRO_NSEL] FOR DELETE AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- coloca selos no estado de Requisição quando os selos são removidos do detalhe SEL da declaração NSTI
	update PRO_GSSL set SSL_STAT = 0, SSL_UTEN = isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), SSL_DTCE = getdate(), 
		SSL_DTDS = NULL, SSL_DTIN = NULL, SSL_DTSL = NULL, NST_CODI = NULL, NST_EANO = NULL, CLI_OPER = NULL
	from deleted as d INNER JOIN PRO_GSSL as g ON d.NST_CODI = g.NST_CODI and d.NST_EANO = g.NST_EANO and d.CLI_OPER = g.CLI_OPER and d.NSE_IDEN = g.SSL_NSEL
END

ALTER TABLE [dbo].[PRO_NSEL] ENABLE TRIGGER [TAD_PRO_NSEL]
/****** Object:  Trigger [TAIU_PRO_NSTI]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_NSTI] ON  [PRO_NSTI] FOR INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- se colunas de Status ou NRM alterados, processa actualizações nos selos
	if (UPDATE(NST_STAT)) or (UPDATE(NST_NRM1))
	begin
-- coloca selos no estado de Selagem NSTI quando declaração NSTI tem status Integrado e possui NRM
		update PRO_GSSL set SSL_STAT = 3, SSL_DTSL = cast(convert(varchar(10), i.NST_DATA, 105) as datetime), 
			SSL_UTSL = isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), SSL_DTCS = getdate(), NST_CODI = i.NST_CODI, 
			NST_EANO = i.NST_EANO, CLI_OPER = i.CLI_OPER
		from inserted as i INNER JOIN PRO_NSEL as s ON i.NST_CODI = s.NST_CODI and i.NST_EANO = s.NST_EANO and i.CLI_OPER = s.CLI_OPER
			INNER JOIN PRO_GSSL as g ON s.NSE_IDEN = g.SSL_NSEL
		where i.NST_STAT = 2 and isnull(i.NST_NRM1, '') <> ''
-- coloca selos no estado de Requisição quando declaração NSTI tem status Por Enviar ou não possui NRM
		update PRO_GSSL set SSL_STAT = 0, SSL_UTEN = isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), SSL_DTCE = getdate(), 
			SSL_DTDS = NULL, SSL_DTIN = NULL, SSL_DTSL = NULL, NST_CODI = NULL, NST_EANO = NULL, CLI_OPER = NULL
		from inserted as i INNER JOIN PRO_NSEL as s ON i.NST_CODI = s.NST_CODI and i.NST_EANO = s.NST_EANO and i.CLI_OPER = s.CLI_OPER
			INNER JOIN PRO_GSSL as g ON s.NST_CODI = g.NST_CODI and s.NST_EANO = g.NST_EANO and s.CLI_OPER = g.CLI_OPER and s.NSE_IDEN = g.SSL_NSEL
		where i.NST_STAT = 0 or isnull(i.NST_NRM1, '') = ''
-- coloca selos no estado de Inutilização quando declaração NSTI tem status Anulado c/ Inutilização de Selos e possui NRM 
		update PRO_GSSL set SSL_STAT = 2, SSL_DTIN = cast(convert(varchar(10), getdate(), 105) as datetime), 
			SSL_UTIN = isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), SSL_DTCI = getdate()
		from inserted as i INNER JOIN PRO_NSEL as s ON i.NST_CODI = s.NST_CODI and i.NST_EANO = s.NST_EANO and i.CLI_OPER = s.CLI_OPER
			INNER JOIN PRO_GSSL as g ON s.NSE_IDEN = g.SSL_NSEL
		where i.NST_STAT = 3 and i.NST_TASA = 1 and isnull(i.NST_NRM1, '') <> ''
-- coloca selos no estado de Requisição quando declaração NSTI tem status Anulado c/ Reutilização de Selos e possui NRM 
		update PRO_GSSL set SSL_STAT = 0, SSL_UTEN = isnull((select LOG_UTIL from LOG_LOGS where LOG_SPID = @@SPID), SUSER_SNAME()), SSL_DTCE = getdate(), 
			SSL_DTDS = NULL, SSL_DTIN = NULL, SSL_DTSL = NULL, NST_CODI = NULL, NST_EANO = NULL, CLI_OPER = NULL
		from inserted as i INNER JOIN PRO_NSEL as s ON i.NST_CODI = s.NST_CODI and i.NST_EANO = s.NST_EANO and i.CLI_OPER = s.CLI_OPER
			INNER JOIN PRO_GSSL as g ON s.NSE_IDEN = g.SSL_NSEL
		where i.NST_STAT = 3 and i.NST_TASA = 2 and isnull(i.NST_NRM1, '') <> ''
	end
END

ALTER TABLE [dbo].[PRO_NSTI] ENABLE TRIGGER [TAIU_PRO_NSTI]
/****** Object:  Trigger [TAU_PRO_NSTI]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_NSTI] ON [PRO_NSTI] FOR UPDATE AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- se coluna de NRM alterada, processa actualização nas Declarações DUI2
	IF UPDATE(NST_NRM1)
	BEGIN
-- coloca valor de "NRM" do NSTI no campo "T1 Retorno" das Declaração DUI2 associadas
		UPDATE PRO_DUCG SET DUC_T1RE = NULLIF(i.NST_NRM1, '')
		FROM inserted as i INNER JOIN PRO_DUCG as duc ON i.NST_CODI = duc.NST_CODI and i.NST_EANO = duc.NST_EANO and i.CLI_OPER = duc.CLI_OPER
		WHERE ISNULL(i.NST_NRM1, '') <> ISNULL(duc.DUC_T1RE, '')		
	END
END

ALTER TABLE [dbo].[PRO_NSTI] ENABLE TRIGGER [TAU_PRO_NSTI]
/****** Object:  Trigger [TAIUD_PRO_SDSC]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_SDSC] ON [PRO_SDSC] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- verifica alteração de vários campos p/ registar no Histórico de Alterações do MAnifesto SDS - Via Aérea
	IF UPDATE(DSC_TIPO) or UPDATE(EAD_CODI) or UPDATE(DSC_DTVO) or UPDATE(DSC_NCMF) or UPDATE(DSC_NCMV) or UPDATE(DSC_IXML) or UPDATE(DSC_ACTI) 
	BEGIN
		INSERT INTO LOG_SDSC(LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DSC_EANO, DSC_NPRO, DSC_TIPO, EAD_CODI, DSC_DTVO, DSC_NCMF, DSC_NCMV, DSC_IXML, 
			DSC_ACTI)
		SELECT NEWID(), (CASE (SELECT COUNT(*) FROM deleted WHERE DSC_EANO = inserted.DSC_EANO and DSC_NPRO = inserted.DSC_NPRO) WHEN 0 THEN 0 ELSE 1 END), 
			GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), ISNULL((SELECT LOG_UTIL FROM LOG_LOGS WHERE LOG_SPID = @@SPID), SUSER_SNAME()), ISNULL(APP_NAME(), 'n.d.'), ISNULL(HOST_NAME(), 'n.d.'), 
			DSC_EANO, DSC_NPRO, DSC_TIPO, EAD_CODI, DSC_DTVO, DSC_NCMF, DSC_NCMV, DSC_IXML, DSC_ACTI
		FROM inserted
		WHERE ((SELECT COUNT(*) FROM deleted WHERE DSC_EANO = inserted.DSC_EANO and DSC_NPRO = inserted.DSC_NPRO) = 0) 
			or ((SELECT COUNT(*) FROM deleted WHERE DSC_EANO = inserted.DSC_EANO and DSC_NPRO = inserted.DSC_NPRO and ((DSC_TIPO <> inserted.DSC_TIPO) 
			or (EAD_CODI <> inserted.EAD_CODI) or (DSC_DTVO <> inserted.DSC_DTVO) or (DSC_NCMF <> inserted.DSC_NCMF) or (DSC_NCMV <> inserted.DSC_NCMV) 
			or (DSC_IXML <> inserted.DSC_IXML) or (DSC_ACTI <> inserted.DSC_ACTI))) > 0)
	END
	ELSE
	BEGIN
		INSERT INTO LOG_SDSC(LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DSC_EANO, DSC_NPRO, DSC_TIPO, EAD_CODI, DSC_DTVO, DSC_NCMF, DSC_NCMV, DSC_IXML, 
			DSC_ACTI)
		SELECT NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), ISNULL((SELECT LOG_UTIL FROM LOG_LOGS WHERE LOG_SPID = @@SPID), SUSER_SNAME()), ISNULL(APP_NAME(), 'n.d.'), ISNULL(HOST_NAME(), 'n.d.'), 
			DSC_EANO, DSC_NPRO, DSC_TIPO, EAD_CODI, DSC_DTVO, DSC_NCMF, DSC_NCMV, DSC_IXML, DSC_ACTI
		FROM deleted
		WHERE (SELECT COUNT(*) FROM inserted WHERE DSC_EANO = deleted.DSC_EANO and DSC_NPRO = deleted.DSC_NPRO) = 0
	END
END

ALTER TABLE [dbo].[PRO_SDSC] ENABLE TRIGGER [TAIUD_PRO_SDSC]
/****** Object:  Trigger [TAU_PRO_SDSC]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_SDSC] ON [PRO_SDSC] AFTER UPDATE AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaração de variáveis	
	DECLARE @NomeBDParaSDSExportacao varchar(8), @IdContramarca varchar(20), @NumCMFixo varchar(8), @NumCMVar varchar(6), @UtilizadorAlteracao varchar(30), 
		@DataAlteracao datetime, @StatusCM int, @UtilizadorEnvioCMCriacao varchar(30), @DataEnvioCMCriacao datetime, @UtilizadorObterCMCriacao varchar(30), 
		@DataObterCMCriacao datetime, @UtilizadorEnvioCMAlteracao varchar(30), @DataEnvioCMAlteracao datetime, @UtilizadorObterCMAlteracao varchar(30), 
		@DataObterCMAlteracao datetime, @UtilizadorEnvioCMAnulacao varchar(30), @DataEnvioCMAnulacao datetime, @UtilizadorObterCMAnulacao varchar(30), 
		@DataObterCMAnulacao datetime, @EstadoCM varchar(3), @SQLAExecutar nvarchar(4000), @LstVarSQL nvarchar(1000) 
-- obtem o nome da BD de Manifestos SDS de Exportação dos Parâmetros SDS - Via Aérea
	SELECT TOP 1 @NomeBDParaSDSExportacao = ISNULL((CASE PSD_BDEX WHEN 1 THEN (NULLIF(PSD_NBDE, '') + '..') ELSE NULL END), '')
	FROM TAB_PSDS WITH(NOLOCK)
-- processa automatismos relacionados com a alteração dos campos de Contramarca
	IF UPDATE(DSC_NCMF) OR UPDATE(DSC_NCMV) OR UPDATE(DSC_STCM) OR UPDATE(DSC_ESTA)
	BEGIN
-- obtem os Manifestos de Importação alterados
		DECLARE Manifestos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT DSC_IDCM, DSC_NCMF, DSC_NCMV, DSC_UALT, DSC_DALT, DSC_STCM, DSC_UCCM, DSC_DCCM, DSC_UCCR, DSC_DCCR, DSC_UUCM, DSC_DUCM, DSC_UUCR, DSC_DUCR, DSC_UACM, 
				DSC_DACM, DSC_UACR, DSC_DACR, DSC_ESTA
			FROM inserted
			WHERE DSC_TIPO = 0
		OPEN Manifestos
		FETCH NEXT FROM Manifestos INTO @IdContramarca, @NumCMFixo, @NumCMVar, @UtilizadorAlteracao, @DataAlteracao, @StatusCM, @UtilizadorEnvioCMCriacao, @DataEnvioCMCriacao, 
			@UtilizadorObterCMCriacao, @DataObterCMCriacao, @UtilizadorEnvioCMAlteracao, @DataEnvioCMAlteracao, @UtilizadorObterCMAlteracao, @DataObterCMAlteracao, 
			@UtilizadorEnvioCMAnulacao, @DataEnvioCMAnulacao, @UtilizadorObterCMAnulacao, @DataObterCMAnulacao, @EstadoCM
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza os dados da CM no Manifesto SDS de Exportação correspondente na própria BD ou da BD diferente
			SET @SQLAExecutar = N'UPDATE ' + @NomeBDParaSDSExportacao + 'PRO_SDSC SET 			
					DSC_NCMF = @INNumCMFixo, 
					DSC_NCMV = @INNumCMVar,
					DSC_STCM = @INStatusCM, 
					DSC_UCCM = @INUtilizadorEnvioCMCriacao,
					DSC_DCCM = @INDataEnvioCMCriacao,
					DSC_UCCR = @INUtilizadorObterCMCriacao, 
					DSC_DCCR = @INDataObterCMCriacao,
					DSC_UUCM = @INUtilizadorEnvioCMAlteracao,
					DSC_DUCM = @INDataEnvioCMAlteracao,
					DSC_UUCR = @INUtilizadorObterCMAlteracao, 
					DSC_DUCR = @INDataObterCMAlteracao,
					DSC_UACM = @INUtilizadorEnvioCMAnulacao,
					DSC_DACM = @INDataEnvioCMAnulacao,
					DSC_UACR = @INUtilizadorObterCMAnulacao, 
					DSC_DACR = @INDataObterCMAnulacao,		
					DSC_ESTA = @INEstadoCM, 					
					DSC_UALT = @INUtilizadorAlteracao,
					DSC_DALT = @INDataAlteracao		
				WHERE DSC_TIPO = 1 AND DSC_IDCM = @INIdContramarca'			
			SET @LstVarSQL = N'@INIdContramarca varchar(20), @INNumCMFixo varchar(8), @INNumCMVar varchar(6), @INUtilizadorAlteracao varchar(30), @INDataAlteracao datetime, @INStatusCM int, @INUtilizadorEnvioCMCriacao varchar(30), @INDataEnvioCMCriacao datetime, @INUtilizadorObterCMCriacao varchar(30), @INDataObterCMCriacao datetime, @INUtilizadorEnvioCMAlteracao varchar(30), @INDataEnvioCMAlteracao datetime, @INUtilizadorObterCMAlteracao varchar(30), @INDataObterCMAlteracao datetime, @INUtilizadorEnvioCMAnulacao varchar(30), @INDataEnvioCMAnulacao datetime, @INUtilizadorObterCMAnulacao varchar(30), @INDataObterCMAnulacao datetime, @INEstadoCM varchar(3)'
			EXEC sp_executesql @SQLAExecutar, @LstVarSQL, @INIdContramarca = @IdContramarca, @INNumCMFixo = @NumCMFixo, @INNumCMVar = @NumCMVar, @INUtilizadorAlteracao = @UtilizadorAlteracao, @INDataAlteracao = @DataAlteracao, @INStatusCM = @StatusCM, @INUtilizadorEnvioCMCriacao = @UtilizadorEnvioCMCriacao, @INDataEnvioCMCriacao = @DataEnvioCMCriacao, @INUtilizadorObterCMCriacao = @UtilizadorObterCMCriacao, @INDataObterCMCriacao = @DataObterCMCriacao, @INUtilizadorEnvioCMAlteracao = @UtilizadorEnvioCMAlteracao, @INDataEnvioCMAlteracao = @DataEnvioCMAlteracao, @INUtilizadorObterCMAlteracao = @UtilizadorObterCMAlteracao, @INDataObterCMAlteracao = @DataObterCMAlteracao, @INUtilizadorEnvioCMAnulacao = @UtilizadorEnvioCMAnulacao, @INDataEnvioCMAnulacao = @DataEnvioCMAnulacao, @INUtilizadorObterCMAnulacao = @UtilizadorObterCMAnulacao, @INDataObterCMAnulacao = @DataObterCMAnulacao, @INEstadoCM = @EstadoCM 
			FETCH NEXT FROM Manifestos INTO @IdContramarca, @NumCMFixo, @NumCMVar, @UtilizadorAlteracao, @DataAlteracao, @StatusCM, @UtilizadorEnvioCMCriacao, @DataEnvioCMCriacao, 
				@UtilizadorObterCMCriacao, @DataObterCMCriacao, @UtilizadorEnvioCMAlteracao, @DataEnvioCMAlteracao, @UtilizadorObterCMAlteracao, @DataObterCMAlteracao, 
				@UtilizadorEnvioCMAnulacao, @DataEnvioCMAnulacao, @UtilizadorObterCMAnulacao, @DataObterCMAnulacao, @EstadoCM
		END
		CLOSE Manifestos
		DEALLOCATE Manifestos
	END
END

ALTER TABLE [dbo].[PRO_SDSC] ENABLE TRIGGER [TAU_PRO_SDSC]
/****** Object:  Trigger [TAD_PRO_SDSD]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_SDSD] ON [PRO_SDSD] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- atualiza o numero das linhas superiores à linha removida
    UPDATE PRO_SDSD SET DSD_NUME = PRO_SDSD.DSD_NUME - 1
    FROM (SELECT dsd.DSC_EANO, dsd.DSC_NPRO, dsd.DSD_NUME
		FROM deleted AS del INNER JOIN PRO_SDSD AS dsd ON del.DSC_EANO = dsd.DSC_EANO AND del.DSC_NPRO = dsd.DSC_NPRO
		WHERE dsd.DSD_NUME > del.DSD_NUME
		GROUP BY dsd.DSC_EANO, dsd.DSC_NPRO, dsd.DSD_NUME) AS tln
	WHERE PRO_SDSD.DSC_EANO = tln.DSC_EANO and PRO_SDSD.DSC_NPRO = tln.DSC_NPRO and PRO_SDSD.DSD_NUME = tln.DSD_NUME
-- remove as linhas "house" (filhas) da linha "master" (Tipo AWB for "N741") se manifesto SDS for "Exportação"
	DELETE PRO_SDSD 
	FROM (SELECT del.DSD_IDCR
		FROM deleted AS del INNER JOIN PRO_SDSC AS dsc ON del.DSC_EANO = dsc.DSC_EANO AND del.DSC_NPRO = dsc.DSC_NPRO
		WHERE del.DOC_CODI = 'N741' AND dsc.DSC_TIPO = 1
		GROUP BY del.DSD_IDCR) AS tln
	WHERE PRO_SDSD.DSD_CODR = tln.DSD_IDCR
END

ALTER TABLE [dbo].[PRO_SDSD] ENABLE TRIGGER [TAD_PRO_SDSD]
/****** Object:  Trigger [TAIUD_PRO_SDSD]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIUD_PRO_SDSD] ON [PRO_SDSD] AFTER INSERT, DELETE, UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- verifica alteração de vários campos p/ registar no Histórico de Alterações das Linhas AWB do Manifesto SDS - Via Aérea	
    IF UPDATE(DSD_NRMH) or UPDATE(DOC_CODI) or UPDATE(DSD_ORIG) or UPDATE(EXA_CHVE) or UPDATE(DSD_NDAU) or UPDATE(DSD_DTEN) or UPDATE(DSD_ENVI) or UPDATE(DSD_IDFC) 
		or UPDATE(DSD_ASAI) or UPDATE(DSD_ESTA) or UPDATE(DSD_STAT) or UPDATE(DSD_AFRQ) or UPDATE(DSD_EFRQ) or UPDATE(DSD_STRD) or UPDATE(DSD_STMS) or UPDATE(DSD_IDED) 
		or UPDATE(DSD_NOMD) or UPDATE(DSD_PESO) or UPDATE(DSD_VOLS) or UPDATE(DSD_VALO) or UPDATE(DSD_DEPO) or UPDATE(DSD_JUST) or UPDATE(DSD_DERD) or UPDATE(DSD_SIRD) 
		or UPDATE(DSD_DIRD)
	BEGIN
		INSERT INTO LOG_SDSD(LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DSD_ORIG, EXA_CHVE, DSD_NDAU,
			DSD_DTEN, DSD_IDNN, DSD_ENVI, DSD_IDFC, DSD_ASAI, DSD_ESTA, DSD_STAT, DSD_AFRQ, DSD_EFRQ, DSD_STRD, DSD_STMS, DSD_IDED, DSD_NOMD, DSD_PESO, DSD_VOLS, DSD_VALO, 
			DSD_DEPO, DSD_JUST, DSD_DERD, DSD_SIRD, DSD_DIRD)
		SELECT NEWID(), (CASE (SELECT COUNT(*) FROM deleted WHERE DSD_IDNN = inserted.DSD_IDNN) WHEN 0 THEN 0 ELSE 1 END), GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), 
			ISNULL((SELECT LOG_UTIL FROM LOG_LOGS WHERE LOG_SPID = @@SPID), SUSER_SNAME()), ISNULL(APP_NAME(), 'n.d.'), ISNULL(HOST_NAME(), 'n.d.'), 
			DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DSD_ORIG, EXA_CHVE, DSD_NDAU,	DSD_DTEN, DSD_IDNN, DSD_ENVI, DSD_IDFC, DSD_ASAI, DSD_ESTA, DSD_STAT, DSD_AFRQ, 
			DSD_EFRQ, DSD_STRD, DSD_STMS, DSD_IDED, DSD_NOMD, DSD_PESO, DSD_VOLS, DSD_VALO, DSD_DEPO, DSD_JUST, DSD_DERD, DSD_SIRD, DSD_DIRD
		FROM inserted
		WHERE ((SELECT COUNT(*) FROM deleted WHERE DSD_IDNN = inserted.DSD_IDNN) = 0)
			or ((SELECT COUNT(*) FROM deleted WHERE DSD_IDNN = inserted.DSD_IDNN and (DSD_NRMH <> inserted.DSD_NRMH) or (DOC_CODI <> inserted.DOC_CODI) 
			or (DSD_ORIG <> inserted.DSD_ORIG) or (ISNULL(EXA_CHVE, -1) <> ISNULL(inserted.EXA_CHVE, -1)) or (ISNULL(DSD_NDAU, '') <> ISNULL(inserted.DSD_NDAU, '')) 
			or (ISNULL(DSD_DTEN, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> ISNULL(inserted.DSD_DTEN, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) or (DSD_ENVI <> inserted.DSD_ENVI) 
			or (ISNULL(DSD_IDFC, -1) <> ISNULL(inserted.DSD_IDFC, -1)) or (DSD_ASAI <> inserted.DSD_ASAI) or (ISNULL(DSD_ESTA, '') <> ISNULL(inserted.DSD_ESTA, ''))
			or (DSD_STAT <> inserted.DSD_STAT) or (ISNULL(DSD_AFRQ, -1) <> ISNULL(inserted.DSD_AFRQ, -1)) or (DSD_EFRQ <> inserted.DSD_EFRQ) or (DSD_STRD <> inserted.DSD_STRD)
			or (DSD_STMS <> inserted.DSD_STRD) or (ISNULL(DSD_IDED, '') <> ISNULL(inserted.DSD_IDED, '')) or (ISNULL(DSD_NOMD, '') <> ISNULL(inserted.DSD_NOMD, '')) 
			or (DSD_PESO <> inserted.DSD_PESO) or (DSD_VOLS <> inserted.DSD_VOLS) or (DSD_VALO <> inserted.DSD_VALO) or (ISNULL(DSD_DEPO, '') <> ISNULL(inserted.DSD_DEPO, '')) 
			or (ISNULL(DSD_JUST, '') <> ISNULL(inserted.DSD_JUST, '')) or (ISNULL(DSD_DERD, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> ISNULL(inserted.DSD_DERD, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT())) 
			or (DSD_SIRD <> inserted.DSD_SIRD) or (ISNULL(DSD_DIRD, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()) <> ISNULL(inserted.DSD_DIRD, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()))) > 0)
	END
	ELSE
	BEGIN
		INSERT INTO LOG_SDSD(LOG_IDEN, LOG_TIPO, LOG_DATA, LOG_USER, LOG_PROG, LOG_HOST, DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DSD_ORIG, EXA_CHVE, DSD_NDAU,
			DSD_DTEN, DSD_IDNN, DSD_ENVI, DSD_IDFC, DSD_ASAI, DSD_ESTA, DSD_STAT, DSD_AFRQ, DSD_EFRQ, DSD_STRD, DSD_STMS, DSD_IDED, DSD_NOMD, DSD_PESO, DSD_VOLS, DSD_VALO, 
			DSD_DEPO, DSD_JUST, DSD_DERD, DSD_SIRD, DSD_DIRD)
		SELECT NEWID(), 2, GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT(), ISNULL((SELECT LOG_UTIL FROM LOG_LOGS WHERE LOG_SPID = @@SPID), SUSER_SNAME()), ISNULL(APP_NAME(), 'n.d.'), ISNULL(HOST_NAME(), 'n.d.'), 
			DSC_EANO, DSC_NPRO, DSD_NUME, DSD_NRMH, DOC_CODI, DSD_ORIG, EXA_CHVE, DSD_NDAU,	DSD_DTEN, DSD_IDNN, DSD_ENVI, DSD_IDFC, DSD_ASAI, DSD_ESTA, DSD_STAT, DSD_AFRQ, 
			DSD_EFRQ, DSD_STRD, DSD_STMS, DSD_IDED, DSD_NOMD, DSD_PESO, DSD_VOLS, DSD_VALO, DSD_DEPO, DSD_JUST, DSD_DERD, DSD_SIRD, DSD_DIRD
		FROM deleted
		WHERE (SELECT COUNT(*) FROM inserted WHERE DSD_IDNN = deleted.DSD_IDNN) = 0
	END
END

ALTER TABLE [dbo].[PRO_SDSD] ENABLE TRIGGER [TAIUD_PRO_SDSD]
/****** Object:  Trigger [TAU_PRO_SDSD]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_PRO_SDSD] ON [PRO_SDSD] FOR UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- declaração de variáveis
	DECLARE @IDLinhaAWB int, @AltVolumes varchar(50), @AltPeso varchar(50), @AltOutros varchar(50), @AltArtigoFranquia varchar(50)
-- inicia a flag de "Exclusão p/ Manifesto" após alteração de dados nas linhas cuja origem é "Integração ficheiro manifesto" e estão assinaladas p/ "Exclusão p/ Manifesto"
	UPDATE PRO_SDSD SET DSD_PSIM = 0
	FROM (SELECT ins.DSD_IDNN
		FROM inserted AS ins
		WHERE ins.DSD_ORIG = 1 and ins.DSD_PSIM = 1) AS tln
	WHERE PRO_SDSD.DSD_IDNN = tln.DSD_IDNN	
-- se vários campos alterados, actualiza a justificação das linhas AWB
	IF UPDATE(DSD_VOLS) OR UPDATE(DSD_PESO) OR UPDATE(DOC_CODI) OR UPDATE(DSD_LOED) OR UPDATE(DSD_DTED) OR UPDATE(DSD_EEED) OR UPDATE(PAI_CODI) OR UPDATE(DSD_TIPO) 
		OR UPDATE(PAE_CODI) OR UPDATE(PAE_CODI1) OR UPDATE(PAE_CODI2) OR UPDATE(DSD_TCTU) OR UPDATE(DSD_TMEX) OR UPDATE(DSD_EADC) OR UPDATE(DSD_IDOS) OR UPDATE(DSD_NOOS) 
		OR UPDATE(DSD_IDNS) OR UPDATE(DSD_NONS) OR UPDATE(DSD_IDED) OR UPDATE(DSD_NOMD) OR UPDATE(DSD_IDEN) OR UPDATE(DSD_IDEC) OR UPDATE(DSD_DMER) OR UPDATE(DSD_MRNR) 
		OR UPDATE(TEM_CODI) OR UPDATE(DSD_TCAR) OR UPDATE(LME_CODI) OR UPDATE(PAE_CODI3) OR UPDATE(DSD_CAPO) OR UPDATE(DSD_VALO) OR UPDATE(DSD_DEPO) OR UPDATE(DSD_ALTD)
		OR UPDATE(DSD_AFRQ)
	BEGIN
		DECLARE Manifestos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.DSD_IDNN, 
				(CASE WHEN (ins.DSD_VOLS <> del.DSD_VOLS) THEN 'Alteracao Volumes. ' ELSE '' END), 
				(CASE WHEN (ins.DSD_PESO <> del.DSD_PESO) THEN 'Alteracao Peso. ' ELSE '' END),
				(CASE WHEN (ins.DOC_CODI <> del.DOC_CODI) OR (ins.DSD_LOED <> del.DSD_LOED) OR (ins.DSD_DTED <> del.DSD_DTED) OR (ins.DSD_EEED <> del.DSD_EEED) 
					OR (ins.PAI_CODI <> del.PAI_CODI) OR (ins.DSD_TIPO <> del.DSD_TIPO) OR (ins.PAE_CODI <> del.PAE_CODI) OR (ins.PAE_CODI1 <> del.PAE_CODI1) 
					OR (ins.PAE_CODI2 <> del.PAE_CODI2) OR (ins.DSD_TCTU <> del.DSD_TCTU) OR (ins.DSD_TMEX <> del.DSD_TMEX) OR (ins.DSD_EADC <> del.DSD_EADC) 
					OR (ins.DSD_IDOS <> del.DSD_IDOS) OR (ins.DSD_NOOS <> del.DSD_NOOS) OR (ins.DSD_IDNS <> del.DSD_IDNS) OR (ins.DSD_NONS <> del.DSD_NONS) 
					OR (ins.DSD_IDED <> del.DSD_IDED) OR (ins.DSD_NOMD <> del.DSD_NOMD) OR (ins.DSD_IDEN <> del.DSD_IDEN) OR (ins.DSD_IDEC <> del.DSD_IDEC) 
					OR (ins.DSD_DMER <> del.DSD_DMER) OR (ins.DSD_MRNR <> del.DSD_MRNR) OR (ins.TEM_CODI <> del.TEM_CODI) OR (ins.DSD_TCAR <> del.DSD_TCAR) 
					OR (ins.LME_CODI <> del.LME_CODI) OR (ins.PAE_CODI3 <> del.PAE_CODI3) OR (ins.DSD_CAPO <> del.DSD_CAPO) OR (ins.DSD_VALO <> del.DSD_VALO) 
					OR (ins.DSD_DEPO <> del.DSD_DEPO) OR (ins.DSD_ALTD <> del.DSD_ALTD) THEN 'Alteracao Outros. ' ELSE '' END),
				(CASE WHEN (ISNULL(ins.DSD_AFRQ, 0) <> ISNULL(del.DSD_AFRQ, 0)) THEN 'Pedido de Franquia. ' ELSE '' END)
			FROM inserted AS ins INNER JOIN deleted AS del ON ins.DSD_IDNN = del.DSD_IDNN
			WHERE ISNULL(ins.DSD_ESTA, '') <> '' AND ISNULL(ins.DSD_NDGA, '') <> '' AND ins.DSD_ANUL = 0
		OPEN Manifestos
		FETCH NEXT FROM Manifestos INTO @IDLinhaAWB, @AltVolumes, @AltPeso, @AltOutros, @AltArtigoFranquia
		WHILE @@FETCH_STATUS = 0
		BEGIN
			UPDATE PRO_SDSD SET DSD_JUST = LTRIM(RTRIM(@AltVolumes + @AltPeso + @AltOutros + @AltArtigoFranquia))			
			WHERE DSD_IDNN = @IDLinhaAWB
			FETCH NEXT FROM Manifestos INTO @IDLinhaAWB, @AltVolumes, @AltPeso, @AltOutros, @AltArtigoFranquia
		END
		CLOSE Manifestos
		DEALLOCATE Manifestos
	END    
-- se campo Nº. AWB alterado e Linha AWB existe nas Entradas AEX, atualiza registo de Entrada AEX (Dados Gerais)
	IF UPDATE(DSD_NRMH)
	BEGIN
		UPDATE AEX_ENDG SET EDG_REFI = ins.DSD_NRMH, EDG_UALT = sdc.DSC_UALT, EDG_DALT = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()			
		FROM inserted as ins INNER JOIN deleted as del ON ins.DSC_EANO = del.DSC_EANO and ins.DSC_NPRO = del.DSC_NPRO and ins.DSD_NUME = del.DSD_NUME
			INNER JOIN PRO_SDSC as sdc WITH(NOLOCK) ON ins.DSC_EANO = sdc.DSC_EANO and ins.DSC_NPRO = sdc.DSC_NPRO
		WHERE (AEX_ENDG.EDG_EANO = del.DSC_EANO or AEX_ENDG.EDG_EANO = (del.DSC_EANO - 1)) and AEX_ENDG.EDG_REFI = del.DSD_NRMH
	END    
-- se campos Nº. AWB, Est. Carga, Volumes ou Peso Bruto alterados e Linha AWB existe nas Entradas AEX, atualiza registo de Entrada AEX (Linha Mercadoria)
	IF UPDATE(DSD_NRMH) or UPDATE(DSD_EADC) or UPDATE(DSD_VOLS) or UPDATE(DSD_PESO)
	BEGIN		
		UPDATE AEX_ENLN SET ELN_VOLS = ins.DSD_VOLS, ELN_PBRT = ins.DSD_PESO, ELN_LOCA = (CASE WHEN (SELECT TOP 1 PDE_CADI FROM TAB_PDES WITH(NOLOCK)) > 0 THEN ('R' + RIGHT(ins.DSD_NRMH, 1)) ELSE NULL END), 
			ELN_EADU = ins.DSD_EADC, ELN_UALT = sdc.DSC_UALT, ELN_DALT = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
		FROM inserted as ins INNER JOIN PRO_SDSC as sdc WITH(NOLOCK) ON ins.DSC_EANO = sdc.DSC_EANO and ins.DSC_NPRO = sdc.DSC_NPRO
			INNER JOIN AEX_ENDG as edg WITH(NOLOCK) ON (ins.DSC_EANO = edg.EDG_EANO or (ins.DSC_EANO - 1) = edg.EDG_EANO) and ins.DSD_NRMH = edg.EDG_REFI
		WHERE AEX_ENLN.EDG_EANO = edg.EDG_EANO and AEX_ENLN.EDG_NUME = edg.EDG_NUME and edg.EDG_SVOL > 0
	END	    	
END

ALTER TABLE [dbo].[PRO_SDSD] ENABLE TRIGGER [TAU_PRO_SDSD]
/****** Object:  Trigger [TAD_PRO_SSDD]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_PRO_SSDD] ON [PRO_SSDD] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- atualiza o numero das linhas superiores à linha removida
    UPDATE PRO_SSDD SET SDD_NUME = PRO_SSDD.SDD_NUME - 1
    FROM (SELECT sdd.DSC_EANO, sdd.DSC_NPRO, sdd.DSD_NUME, sdd.SDD_NUME
		FROM deleted AS del INNER JOIN PRO_SSDD AS sdd ON del.DSC_EANO = sdd.DSC_EANO AND del.DSC_NPRO = sdd.DSC_NPRO AND del.DSD_NUME = sdd.DSD_NUME
		WHERE sdd.SDD_NUME > del.SDD_NUME
		GROUP BY sdd.DSC_EANO, sdd.DSC_NPRO, sdd.DSD_NUME, sdd.SDD_NUME) AS tln
	WHERE PRO_SSDD.DSC_EANO = tln.DSC_EANO and PRO_SSDD.DSC_NPRO = tln.DSC_NPRO and PRO_SSDD.DSD_NUME = tln.DSD_NUME and PRO_SSDD.SDD_NUME = tln.SDD_NUME
-- incrementa o número de alterações aos documentos na linha AWB
	UPDATE PRO_SDSD SET DSD_ALTD = DSD_ALTD + 1
	FROM (SELECT del.DSC_EANO, del.DSC_NPRO, del.DSD_NUME
		FROM deleted AS del 
		GROUP BY del.DSC_EANO, del.DSC_NPRO, del.DSD_NUME) as tln
	WHERE PRO_SDSD.DSC_EANO = tln.DSC_EANO and PRO_SDSD.DSC_NPRO = tln.DSC_NPRO and PRO_SDSD.DSD_NUME = tln.DSD_NUME
END

ALTER TABLE [dbo].[PRO_SSDD] ENABLE TRIGGER [TAD_PRO_SSDD]
/****** Object:  Trigger [TAIU_PRO_SSDD]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAIU_PRO_SSDD] ON [PRO_SSDD] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;   
-- incrementa o número de alterações aos documentos na linha AWB
	UPDATE PRO_SDSD SET DSD_ALTD = DSD_ALTD + 1
	FROM (SELECT ins.DSC_EANO, ins.DSC_NPRO, ins.DSD_NUME
		FROM inserted AS ins 
		GROUP BY ins.DSC_EANO, ins.DSC_NPRO, ins.DSD_NUME) as tln
	WHERE PRO_SDSD.DSC_EANO = tln.DSC_EANO and PRO_SDSD.DSC_NPRO = tln.DSC_NPRO and PRO_SDSD.DSD_NUME = tln.DSD_NUME
END

ALTER TABLE [dbo].[PRO_SSDD] ENABLE TRIGGER [TAIU_PRO_SSDD]
/****** Object:  Trigger [TAU_TAB_MTRA]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_TAB_MTRA] ON [TAB_MTRA] AFTER UPDATE AS 
BEGIN	
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @id int
-- se campo da gestão automática de optativas foi desselecionado, remove o detalhe de optativas
	IF UPDATE(MTR_OPAU)
	BEGIN
		DECLARE MeiosTransporte CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.MTR_IDTY
			FROM inserted AS ins
				INNER JOIN deleted AS del ON ins.MTR_IDTY = del.MTR_IDTY
			WHERE ins.MTR_OPAU = 0 AND del.MTR_OPAU = 1
		OPEN MeiosTransporte
		FETCH NEXT FROM MeiosTransporte INTO @id
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE TAB_MTRO
			WHERE MTR_IDTY = @id
			FETCH NEXT FROM MeiosTransporte INTO @id
		END
		CLOSE MeiosTransporte
		DEALLOCATE MeiosTransporte
	END
END

ALTER TABLE [dbo].[TAB_MTRA] ENABLE TRIGGER [TAU_TAB_MTRA]
/****** Object:  Trigger [TAU_TAB_PCBE]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAU_TAB_PCBE] ON [TAB_PCBE] FOR UPDATE AS 
BEGIN
	SET NOCOUNT ON
-- se coluna "D." tiver sido alterada, remove os limites da exceção associados aos registos onde "D." ficou a "false"
	IF UPDATE(CBE_UDTL) 
	BEGIN
		DELETE FROM TAB_PCBX
		WHERE CBE_IDEN in (SELECT CBE_IDEN FROM inserted WHERE CBE_UDTL = 0)
	END
END

ALTER TABLE [dbo].[TAB_PCBE] ENABLE TRIGGER [TAU_TAB_PCBE]
/****** Object:  Trigger [TAD_TAB_TDOC]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAD_TAB_TDOC] ON [TAB_TDOC] FOR DELETE
AS 
	--declaracao de variaveis
	DECLARE @tipo int, @cod varchar (4), @ano int

	set nocount on

	-- busca dados a apagar
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT TDO_TDOC, TDO_DOCU
		FROM deleted
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @tipo, @cod

	--busca ano actual
	SET DATEFORMAT dmy
	SELECT @ano = DATEPART(year, GETDATE())

	WHILE @@FETCH_STATUS = 0
	BEGIN
		--apagar informação referênte ao tipo de documento
		DELETE FROM TAB_NUMD WHERE TDO_DOCU = @cod AND NUM_EANO = @ano AND NUM_TDOC = @tipo	

		FETCH NEXT FROM Detalhe INTO @tipo, @cod
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe

	set nocount off

ALTER TABLE [dbo].[TAB_TDOC] ENABLE TRIGGER [TAD_TAB_TDOC]
/****** Object:  Trigger [TAI_TAB_TDOC]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TAI_TAB_TDOC] ON [TAB_TDOC] FOR INSERT
AS 
	--declaracao de variaveis
	DECLARE @tipo int, @cod varchar(4), @ano int

	set nocount on	

	-- busca dados a inserir
	DECLARE Detalhe CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT TDO_TDOC, TDO_DOCU
		FROM inserted
	OPEN Detalhe
	FETCH NEXT FROM Detalhe INTO @tipo, @cod

	--busca ano actual
	SET DATEFORMAT dmy
	SELECT @ano = DATEPART(year, GETDATE())
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--inserir informação referênte ao tipo de documento
		INSERT INTO TAB_NUMD(TDO_DOCU, NUM_TDOC, NUM_EANO, NUM_NUME, NUM_DATA)
		VALUES(@cod, @tipo, @ano, 0, cast('01-01-' + cast(@ano as varchar(4))as datetime))
	
		FETCH NEXT FROM Detalhe INTO @tipo, @cod
	END
	CLOSE Detalhe
	DEALLOCATE Detalhe

	set nocount off
ALTER TABLE [dbo].[TAB_TDOC] ENABLE TRIGGER [TAI_TAB_TDOC]
/****** Object:  Trigger [tr_DeclaracoesDAR_Atualizacoes_U]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDAR_Atualizacoes_U] ON [tb_DeclaracoesDAR] AFTER UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdDeclaracao int, @IdPaisMoedaCustosTransporte int, @CambioCustosTransporte decimal(12, 6), @IdPaisMoedaMontante int, @CambioMontante decimal(12, 6), 
		@IdUtilizador int, @IdAdicao bigint, @TxIVAIsenta decimal(8, 2), @TxIVANormal decimal(8, 2), @TxIVAArtigo decimal(8, 2), @RegimeAdicional varchar(3), @IdStatusIncidencia int, 
		@IdTabela bigint, @NumeroTD int, @IdDocumento int, @MetodoPagamento varchar(1)	
	DECLARE	@IdTipoDoc int, @TipoCliente varchar(3), @Resultado int, @IdDocConta int, @Erro varchar(MAX)
	DECLARE @Ano smallint, @Numero int, @Data datetime, @RegimeIVA tinyint, @NumeroNRM varchar(25), @DataNRM datetime, @CodEstancia varchar(8), @CodCliente varchar(18), 
		@CodDeclarante varchar(6), @Caucao varchar(35), @TotalIVA decimal(18, 2), @NumeroRL varchar(20), @DataRL datetime, @BeneficiarioIVA bit, @DescricaoDeclaracao varchar(15), 
		@AnoCaucao varchar(4), @NumCaucao varchar(24), @TipoCaucao varchar(1), @TipoEntCaucao tinyint, @CodEntCaucao varchar(18)
	DECLARE @MontanteEUR decimal(18, 2), @CustosTransporteEUR decimal(18, 2), @BaseTributacaoIVA decimal(18, 2)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- nas alterações dos países da moeda ou custos de transporte ou respetivos câmbios, atualiza os países das moedas de montante e custos de transporte e respetivos câmbios nas adições 
	IF UPDATE(id_paisMoedaMontante) OR UPDATE(cambioMontante) OR UPDATE(id_paisMoedaCustosTransporte) OR UPDATE(cambioCustosTransporte)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_paisMoedaMontante, ins.cambioMontante, ins.id_paisMoedaCustosTransporte, ins.cambioCustosTransporte, ins.id_utilizadorControlo, adi.id
			FROM inserted AS ins 
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdPaisMoedaMontante, @CambioMontante, @IdPaisMoedaCustosTransporte, @CambioCustosTransporte, @IdUtilizador, @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				id_paisMoedaMontante = @IdPaisMoedaMontante, 
				cambioMontante = @CambioMontante, 
				@MontanteEUR = montanteEUR = ROUND((montante / @CambioMontante), 2), 
				id_paisMoedaCustosTransporte = @IdPaisMoedaCustosTransporte, 
				cambioCustosTransporte = @CambioCustosTransporte,   
				@CustosTransporteEUR = custosTransporteEUR = ROUND((custosTransporte / @CambioCustosTransporte), 2), 
				@BaseTributacaoIVA = baseTributacaoIVA = ROUND((@MontanteEUR + @CustosTransporteEUR + optativas), 2), 
				valorIVA = ROUND((@BaseTributacaoIVA * taxaIVA / 100), 2), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdAdicao
			FETCH NEXT FROM Declaracoes INTO @IdPaisMoedaMontante, @CambioMontante, @IdPaisMoedaCustosTransporte, @CambioCustosTransporte, @IdUtilizador, @IdAdicao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes			
	END
--  nas alterações do regime IVA ou adicional regime, atualiza a taxa de IVA nas adições
	IF UPDATE(regimeIVA) OR UPDATE(regimeAdicional)
	BEGIN
-- obtem as taxas IVA configuradas na aplicação
		SELECT @TxIVAIsenta = PAP_TXIS, @TxIVANormal = PAP_TXNR 
		FROM TAB_PAPL WITH(NOLOCK)
-- atualiza a taxa IVA nas adições para a "Isenta", quando o regime IVA alterou para "IOSS" ou o regime adicional alterou para "C08"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_utilizadorControlo, adi.id
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
			WHERE (ins.regimeIVA = 1 OR ins.regimeAdicional = 'C08') AND (ins.regimeIVA <> del.regimeIVA OR ins.regimeAdicional <> del.regimeAdicional) AND adi.taxaIVA <> @TxIVAIsenta
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				taxaIVA = @TxIVAIsenta, 
				valorIVA = ROUND((baseTributacaoIVA * @TxIVAIsenta / 100), 2), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual			
			WHERE id = @IdAdicao 	
			FETCH NEXT FROM Declaracoes INTO  @IdUtilizador, @IdAdicao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- atualiza a taxa IVA nas adições para a "Normal", quando o regime IVA alterou para "Especial" e o regime adicional não é "C08"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_utilizadorControlo, adi.id
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
			WHERE ins.regimeIVA = 2 AND ins.regimeAdicional <> 'C08' AND (ins.regimeIVA <> del.regimeIVA OR ins.regimeAdicional <> del.regimeAdicional) AND adi.taxaIVA <> @TxIVANormal
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				taxaIVA = @TxIVANormal, 
				valorIVA = ROUND((baseTributacaoIVA * @TxIVANormal / 100), 2), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual			
			WHERE id = @IdAdicao 
			FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- atualiza a taxa IVA nas adições para a taxa IVA definida no artigo, quando o regime IVA alterou para "Geral" e o regime adicional não é "C08"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_utilizadorControlo, adi.id, ISNULL(apa.APA_TIVA, 0)
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
				INNER JOIN TAB_APAU AS apa WITH(NOLOCK) ON adi.id_artigo = apa.APA_IDTY
			WHERE ins.regimeIVA = 3 AND ins.regimeAdicional <> 'C08' AND (ins.regimeIVA <> del.regimeIVA OR ins.regimeAdicional <> del.regimeAdicional) AND adi.taxaIVA <> ISNULL(apa.APA_TIVA, 0)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao, @TxIVAArtigo
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				taxaIVA = @TxIVAArtigo, 
				valorIVA = ROUND((baseTributacaoIVA * @TxIVAArtigo / 100), 2), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdAdicao 
			FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao, @TxIVAArtigo
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- atualiza o adicional regime nas adições para "F48" quando o regime IVA alterou para "IOSS" e o regime adicional alterou para "C07"; para "F49" quando o regime IVA alterou para "Especial" e o regime adicional alterou para "C07"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_utilizadorControlo, adi.id, 
				(CASE ins.regimeIVA 
					WHEN 1 THEN 'F48' 
					WHEN 2 THEN 'F49' 
					ELSE adi.regimeAdicional 
				END)
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
			WHERE ins.regimeIVA IN (1, 2) AND ins.regimeAdicional = 'C07' AND (ins.regimeIVA <> del.regimeIVA OR ins.regimeAdicional <> del.regimeAdicional) 
				AND ISNULL(adi.regimeAdicional, '') <> (CASE ins.regimeIVA 
															WHEN 1 THEN 'F48' 
															WHEN 2 THEN 'F49' 
															ELSE adi.regimeAdicional 
														END)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao, @RegimeAdicional
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				regimeAdicional = @RegimeAdicional,
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual		
			WHERE id = @IdAdicao 
			FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao, @RegimeAdicional
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- atualiza o adicional regime nas adições para "NULL" quando o regime adicional alterou para "C08"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_utilizadorControlo, adi.id
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
			WHERE ins.regimeAdicional = 'C08' AND ins.regimeAdicional <> del.regimeAdicional AND ISNULL(adi.regimeAdicional, '') <> ''
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				regimeAdicional = NULL, 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual				
			WHERE id = @IdAdicao 
			FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes						
	END
-- insere status de incidência em função do estado de operação
	IF UPDATE(estadoOperacao)
	BEGIN
-- insere status de incidência "SC" quando o estado de operação é "SC - Sem Controlo" e não tem caução/garantia definida
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ins.id_utilizadorControlo, inc.SIN_IDTY
			FROM inserted AS ins 
				INNER JOIN TAB_SINC AS inc WITH(NOLOCK) ON ins.estadoOperacao = inc.SIN_CODI					
			WHERE ins.estadoOperacao = 'SC' AND ISNULL(ins.caucao, '') = ''
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARIncidencias(id_declaracaoDAR, id_statusIncidencia, dataInicio, dataFim, id_utilizadorCriacao, dataCriacao, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdStatusIncidencia, @DataAtual, @DataAtual, @IdUtilizador, @DataAtual, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes						
-- insere status de incidência "A00" quando o estado de operação é "AS - Autorização de Saída"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ins.id_utilizadorControlo, inc.SIN_IDTY
			FROM inserted AS ins 
				INNER JOIN TAB_SINC AS inc WITH(NOLOCK) ON inc.SIN_CODI = 'A00'
			WHERE ins.estadoOperacao = 'AS'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			INSERT INTO tb_DeclaracoesDARIncidencias(id_declaracaoDAR, id_statusIncidencia, dataInicio, dataFim, id_utilizadorCriacao, dataCriacao, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdStatusIncidencia, @DataAtual, @DataAtual, @IdUtilizador, @DataAtual, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- insere status de incidência "ND" quando o estado de operação é "ND - Notificação da Dívida"
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ins.id_utilizadorControlo, inc.SIN_IDTY
			FROM inserted AS ins 
				INNER JOIN TAB_SINC AS inc WITH(NOLOCK) ON ins.estadoOperacao = inc.SIN_CODI
			WHERE ins.estadoOperacao = 'ND'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia
		WHILE @@FETCH_STATUS = 0
		BEGIN						
			INSERT INTO tb_DeclaracoesDARIncidencias(id_declaracaoDAR, id_statusIncidencia, dataInicio, dataFim, id_utilizadorCriacao, dataCriacao, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdStatusIncidencia, @DataAtual, @DataAtual, @IdUtilizador, @DataAtual, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @IdStatusIncidencia
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- gere documento "9Z07" e menção "RBVDP" em função do título de depósito
	IF UPDATE(numeroTD)
	BEGIN
-- atualiza documento "9Z07" quando a declaração recebe título de depósito e este já existe
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.numeroTD, ins.id_utilizadorControlo, ddo.id
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id 
				INNER JOIN tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) ON ins.id = ddo.id_declaracaoDAR 
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY				
		WHERE del.numeroTD IS NULL AND ins.numeroTD IS NOT NULL AND doc.DOC_CODI = '9Z07'			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @NumeroTD, @IdUtilizador, @IdTabela
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARDocumentos SET 
				numero = CAST(@NumeroTD AS varchar(20)), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdTabela
			FETCH NEXT FROM Declaracoes INTO @NumeroTD, @IdUtilizador, @IdTabela
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
-- insere documento "9Z07" quando a declaração recebe título de depósito e este ainda não existir
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ins.numeroTD, ins.id_utilizadorControlo, doc.DOC_IDTY
			FROM inserted AS ins INNER JOIN deleted AS del ON ins.id = del.id 
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = '9Z07'
			WHERE del.numeroTD IS NULL AND ins.numeroTD IS NOT NULL AND NOT EXISTS(SELECT id FROM tb_DeclaracoesDARDocumentos WITH(NOLOCK) WHERE id_declaracaoDAR = ins.id AND id_documento = doc.DOC_IDTY)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroTD, @IdUtilizador, @IdDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARDocumentos(id_declaracaoDAR, id_documento, numero, tipo, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdDocumento, CAST(@NumeroTD AS varchar(20)), 0, 5, @IdUtilizador, @DataAtual)			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @NumeroTD, @IdUtilizador, @IdDocumento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- processa a remoção da menção "RBVDP"	quando a declaração recebe título de depósito	
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_utilizadorControlo, dme.id
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARMencoes AS dme WITH(NOLOCK) ON ins.id = dme.id_declaracaoDAR AND dme.origem = 1
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON dme.id_mencao = men.INF_IDTY				
			WHERE ins.numeroTD IS NOT NULL AND del.numeroTD IS NULL AND men.INF_CODI = 'RBVDP'
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdTabela
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARMencoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdTabela
			DELETE FROM tb_DeclaracoesDARMencoes		
			WHERE id = @IdTabela
			FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdTabela
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes			
	END
-- processa geração do documento de conta ao abrigo da "Faturação Automática Ativa"
	IF (UPDATE(autorizacaoSaida)) AND (EXISTS(SELECT FTA_IDEN FROM TAB_PFTA WITH(NOLOCK) WHERE FTA_ACTI = 1))
    BEGIN   		
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ISNULL(ins.id_tipoDocumentoConta, tdo.TDO_IDTY), ins.id_utilizadorControlo, 
				(CASE 
					WHEN pde.PDE_IDCV = 0 THEN NULL 
					WHEN ins.dutyType IN ('A5', 'A6') THEN 'ACC' 
					WHEN ins.dutyType = 'CA' THEN 'COD' 
					WHEN ins.dutyType IN ('D5', 'D6') THEN 'EXB' 
					ELSE NULL 
				END)
			FROM inserted AS ins 
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.id_cliente = cli.CLI_IDTY
				INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON pde.PDE_TDOC = tdo.TDO_DOCU	
				INNER JOIN TAB_PFTA as pft WITH(NOLOCK) ON pft.FTA_ACTI = 1				
			WHERE ins.autorizacaoSaida = 1 AND ins.tipoShipment < 2 AND ins.id_conta IS NULL AND nat.NDE_CRCO = 1 AND ISNULL(nat.NDE_TLCV, 0) <> 1 AND cli.CLI_DUCT = 1
				AND NOT EXISTS(SELECT DVE_IDTY FROM FAC_DVEN WITH(NOLOCK) WHERE DVE_IDAR = ins.id)
				AND (CASE pft.FTA_DUVR 
						WHEN 1 THEN (CASE 
										WHEN ISNULL(ins.numeroVossaReferencia, '') <> '' THEN 1 
										ELSE 0 
									END) 
						WHEN 2 THEN (CASE 
										WHEN ISNULL(ins.numeroVossaReferencia, '') = '' THEN 1 
										ELSE 0 
									END) 
						ELSE 1 END) = 1
				AND (CASE pft.FTA_DDRI 
						WHEN 0 THEN (CASE 
										WHEN ins.regimeIVA = 1 THEN 0 
										ELSE 1 
									END) 						
						ELSE 1 END) = 1
				AND (CASE pft.FTA_DDBI 
						WHEN 0 THEN (CASE 
										WHEN (ins.totalIVA <= 5) AND (cli.CLI_BIVA = 1) THEN 0 
										ELSE 1 
									END) 						
						ELSE 1 END) = 1		
				AND (CASE 
						WHEN (ISNULL(nat.NDE_TLCV, -1) = 0) AND (ins.id_tipoDocumentoConta IS NULL) THEN 0 
						ELSE 1 
					END) = 1			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdTipoDoc, @IdUtilizador, @TipoCliente
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			EXEC @Resultado = sp_DeclaracoesDAR_GeraDocumentoConta @IdDeclaracao, @IdTipoDoc, @TipoCliente, @IdUtilizador, 1, @IdDocConta OUTPUT, @Erro OUTPUT
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdTipoDoc, @IdUtilizador, @TipoCliente
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes 
    END
--  nas alterações da garantia/caução ou beneficiário IVA, atualiza o metodo de pagamento nas adições
	IF UPDATE(caucao) OR UPDATE(beneficiarioIVACliente)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_utilizadorControlo, adi.id,
				(CASE 																	
					WHEN (ins.regimeIVA = 3) AND (ins.beneficiarioIVACliente = 1) THEN 'G' 
					WHEN (ins.regimeIVA = 3) AND (ISNULL(ins.caucao, '') <> '') THEN 'T' 
					WHEN (ins.regimeIVA = 3) AND (ISNULL(ins.caucao, '') = '') THEN  'A' 																	
					ELSE NULL 
				END)
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
			WHERE ISNULL(ins.caucao, '') <> ISNULL(del.caucao, '') OR ins.beneficiarioIVACliente <> del.beneficiarioIVACliente
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao, @MetodoPagamento
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				metodoPagamento = @MetodoPagamento, 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdAdicao
			FETCH NEXT FROM Declaracoes INTO @IdUtilizador, @IdAdicao, @MetodoPagamento
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes								
	END
-- obtem as declarações para efetuar o respetivo lançamento na caução
	IF UPDATE(data) OR UPDATE(regimeIVA) OR UPDATE(regimeAdicional) OR UPDATE(id_natureza) OR UPDATE(numeroNRM) OR UPDATE(dataNRM) OR UPDATE(id_estancia) OR UPDATE(id_cliente) 
	OR UPDATE(id_declarante) OR UPDATE(caucao) OR UPDATE(totalIVA) OR UPDATE(numeroRegistoLiquidacao) OR UPDATE(dataRegistoLiquidacao) OR UPDATE(beneficiarioIVACliente) 
	OR UPDATE(tipoCaucao)
	BEGIN		
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ins.ano, ins.numero, ins.data, ins.regimeIVA, ins.numeroNRM, ins.dataNRM, alf.ALF_CODI, cli.CLI_CODI, dcl.DEC_CODI, ins.caucao, ins.totalIVA, 
				ins.numeroRegistoLiquidacao, ins.dataRegistoLiquidacao, ins.beneficiarioIVACliente, ins.tipoCaucao, 
				(nat.NDE_CODI + '.' + REPLICATE('0', 6 - LEN(CAST(ins.numero AS varchar(10)))) + CAST(ins.numero AS varchar(10)) + '/' + CAST(ins.ano AS varchar(4)))
			FROM inserted AS ins 
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON ins.id_estancia = alf.ALF_IDTY
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.id_cliente = cli.CLI_IDTY
				INNER JOIN TAB_DECL AS dcl WITH(NOLOCK) ON ins.id_declarante = dcl.DEC_IDTY
			WHERE DATEDIFF(MONTH, ISNULL(ins.dataRegistoLiquidacao, @DataAtual), @DataAtual) < 1 
				AND (((SELECT COUNT(*) FROM PRO_MCAU WITH(NOLOCK) WHERE id_declaracaoDAR = ins.id) = (SELECT COUNT(*) FROM PRO_CCCA WITH(NOLOCK) WHERE DUC_PNUM = ins.numero AND DUC_EANO = ins.ano AND DUC_TIPO = 3))
					OR (((SELECT COUNT(*) FROM PRO_MCAU WITH(NOLOCK) WHERE id_declaracaoDAR = ins.id) * 2) = (SELECT COUNT(*) FROM PRO_CCCA WITH(NOLOCK) WHERE DUC_PNUM = ins.numero AND DUC_EANO = ins.ano AND DUC_TIPO = 3)))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @Ano, @Numero, @Data, @RegimeIVA, @NumeroNRM, @DataNRM, @CodEstancia, @CodCliente, @CodDeclarante, @Caucao, @TotalIVA, 
			@NumeroRL, @DataRL, @BeneficiarioIVA, @TipoEntCaucao, @DescricaoDeclaracao
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF (@RegimeIVA = 3) AND (@BeneficiarioIVA = 0) AND (ISNULL(@Caucao, '') <> '') AND (ISNULL(@NumeroRL, '') <> '') 
			BEGIN
				IF CHARINDEX('/', @Caucao) = 0
				BEGIN
					SET @AnoCaucao = ('20' + LEFT(@Caucao, 2))					
					SET @NumCaucao = RIGHT(@Caucao, 7)					
					SET @TipoCaucao = '0'
				END
				ELSE
				BEGIN
					SET @AnoCaucao = SUBSTRING(@Caucao, 1, CHARINDEX('/', @Caucao) - 1)
					SET @Caucao = STUFF(@Caucao, 1, CHARINDEX('/', @Caucao), '')
					SET @NumCaucao = SUBSTRING(@Caucao, 1, CHARINDEX('/', @Caucao) - 1)
					SET @Caucao = STUFF(@Caucao, 1, CHARINDEX('/', @Caucao), '')
					SET @TipoCaucao = @Caucao
				END
				IF @TipoEntCaucao = 1 
					SET @CodEntCaucao = @CodDeclarante
				ELSE
					IF @TipoEntCaucao = 2 
						SET @CodEntCaucao = @CodCliente
					ELSE
						SET @CodEntCaucao = NULL
				SET @TipoEntCaucao = (@TipoEntCaucao - 1)
				EXEC SP_lancaDocUnicoCaucao @TipoEntCaucao, @CodEntCaucao, @NumCaucao, @AnoCaucao, @TipoCaucao, @CodEstancia, @Numero, @Ano, @Data, @DescricaoDeclaracao, @NumeroNRM, @DataNRM, @CodCliente, @TotalIVA, 0, 3, 0, @IdDeclaracao
			END
			ELSE
			BEGIN
				DELETE FROM PRO_MCAU
				WHERE id_declaracaoDAR = @IdDeclaracao
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @Ano, @Numero, @Data, @RegimeIVA, @NumeroNRM, @DataNRM, @CodEstancia, @CodCliente, @CodDeclarante, @Caucao, @TotalIVA, 
				@NumeroRL, @DataRL, @BeneficiarioIVA, @TipoEntCaucao, @DescricaoDeclaracao
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END	
END

ALTER TABLE [dbo].[tb_DeclaracoesDAR] ENABLE TRIGGER [tr_DeclaracoesDAR_Atualizacoes_U]
/****** Object:  Trigger [tr_DeclaracoesDAR_AtualizacoesRecursivas_U]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDAR_AtualizacoesRecursivas_U] ON [tb_DeclaracoesDAR] AFTER UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdDeclaracao int, @TotalMassaBruta decimal(18, 6), @CambioCustosTransporte decimal(12, 6), @TotalCustosTransporte	decimal(18, 2), @CambioMontante	decimal(12, 6), 
		@IdUtilizador int, @IdAdicao bigint, @TotalOptativas decimal(18, 2), @MeioTransporteEVolumes bit
	DECLARE @CustosTransporte decimal(18, 2), @CustosTransporteEUR decimal(18, 2), @BaseTributacaoIVA decimal(18, 2), @Optativas decimal(18, 2)
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- nas alterações do total de custos de transporte, atualiza o custo de transporte nas adições
	IF UPDATE(totalCustosTransporte)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT id, totalMassaBruta, cambioCustosTransporte, totalCustosTransporte, cambioMontante, id_utilizadorControlo
			FROM inserted 
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TotalMassaBruta, @CambioCustosTransporte, @TotalCustosTransporte, @CambioMontante, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				@CustosTransporte = custosTransporte = ROUND((massaBruta * @TotalCustosTransporte / @TotalMassaBruta), 2),   
				@CustosTransporteEUR = custosTransporteEUR = ROUND((@CustosTransporte / @CambioCustosTransporte), 2), 
				@BaseTributacaoIVA = baseTributacaoIVA = ROUND((ROUND((montante / @CambioMontante), 2) + @CustosTransporteEUR + optativas), 2), 
				valorIVA = ROUND((@BaseTributacaoIVA * taxaIVA / 100), 2), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id_declaracaoDAR = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @TotalMassaBruta, @CambioCustosTransporte, @TotalCustosTransporte, @CambioMontante, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
	END
-- nas alterações da massa bruta total, meio de transporte ou total optativas, atualiza os valores de optativas nas adições 
	IF UPDATE(totalMassaBruta) OR UPDATE(id_meioTransporte) OR UPDATE(totalOptativas) 
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.totalMassaBruta, ins.id_utilizadorControlo, ins.totalOptativas, adi.id, (CASE mtr.MTR_VPVL WHEN 2 THEN 1 ELSE 0 END)
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoes AS adi WITH(NOLOCK) ON ins.id = adi.id_declaracaoDAR
				LEFT OUTER JOIN TAB_MTRA AS mtr WITH(NOLOCK) ON ins.id_meioTransporte = mtr.MTR_IDTY
			WHERE ISNULL(ins.id_meioTransporte, -1) <> ISNULL(del.id_meioTransporte, -1) 
				OR (ins.id_meioTransporte IS NOT NULL AND ((ins.totalMassaBruta <> del.totalMassaBruta) OR (ins.totalOptativas <> del.totalOptativas)))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @TotalMassaBruta, @IdUtilizador, @TotalOptativas, @IdAdicao, @MeioTransporteEVolumes
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoes SET 
				@Optativas = optativas = (CASE @MeioTransporteEVolumes 
											WHEN 1 THEN (CASE numeroAdicao WHEN 1 THEN ROUND((volumes * @TotalOptativas), 2) ELSE 0 END)
											ELSE ROUND(((@TotalOptativas * CEILING(@TotalMassaBruta / 100)) * massaBruta / @TotalMassaBruta), 2)
										END), 
				@BaseTributacaoIVA = baseTributacaoIVA = ROUND((montanteEUR + custosTransporteEUR + @Optativas), 2), 
				valorIVA = ROUND((@BaseTributacaoIVA * taxaIVA / 100), 2), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdAdicao
			FETCH NEXT FROM Declaracoes INTO @TotalMassaBruta, @IdUtilizador, @TotalOptativas, @IdAdicao, @MeioTransporteEVolumes
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes			
	END
END

ALTER TABLE [dbo].[tb_DeclaracoesDAR] ENABLE TRIGGER [tr_DeclaracoesDAR_AtualizacoesRecursivas_U]
/****** Object:  Trigger [tr_DeclaracoesDAR_Regras_I]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDAR_Regras_I] ON [tb_DeclaracoesDAR] AFTER INSERT AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @Id int, @Ano smallint, @Numero int, @ProximoNumero int
-- obtem as declarações inseridas quando a numeração é automática
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT ins.id, ins.ano, ins.numero, cdn.proximoNumero
		FROM inserted AS ins INNER JOIN tb_ConfiguracoesDARNumeradores AS cdn ON ins.ano = cdn.ano			
		WHERE cdn.proximoNumero > 0
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @Id, @Ano, @Numero, @ProximoNumero
	WHILE @@FETCH_STATUS = 0
	BEGIN	
-- se número da declaração diferente do próximo numero a atribuir, atualiza numero da declaração
		IF @Numero <> @ProximoNumero
		BEGIN
			UPDATE tb_DeclaracoesDAR SET numero = @ProximoNumero
			WHERE id = @Id
		END
-- atualiza próximo numero nas configurações
		UPDATE tb_ConfiguracoesDARNumeradores SET proximoNumero = proximoNumero + 1
		WHERE ano = @Ano		
		FETCH NEXT FROM Declaracoes INTO @Id, @Ano, @Numero, @ProximoNumero
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes
END

ALTER TABLE [dbo].[tb_DeclaracoesDAR] ENABLE TRIGGER [tr_DeclaracoesDAR_Regras_I]
/****** Object:  Trigger [tr_DeclaracoesDAR_Regras_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDAR_Regras_IU] ON [tb_DeclaracoesDAR] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdDeclaracao int, @IdStatusIncidencia int, @IdUtilizador int, @ReleaseHold varchar(1), @IdDocumento int, @IdTabela bigint, @IdMencao int, 
		@DocTransporte varchar(35), @IdFollowUp int, @IdFollowUpOld int, @IdTipoDoc int, @Resultado int, @IdDocContaFT int, @IdDocContaOR int, @IdDocConta int, 
		@Erro varchar(max)
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- insere status de incidência configurado na natureza
	IF UPDATE(id_natureza)
	BEGIN				
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ISNULL(inc.SIN_IDTY, csc.COS_IDTY), ins.id_utilizadorControlo, (CASE WHEN csc.COS_RELI = 1 THEN 'R' WHEN csc.COS_HOLD = 1 THEN 'H' ELSE NULL END)
			FROM inserted AS ins 
				INNER JOIN TAB_NDES AS nde WITH(NOLOCK) ON ins.id_natureza = nde.NDE_IDTY 
				LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON nde.SIN_CODI = inc.SIN_CODI		
				LEFT OUTER JOIN TAB_COSM AS csc WITH(NOLOCK) ON nde.SIN_CODI = csc.COS_CODE
			WHERE ISNULL(inc.SIN_IDTY, csc.COS_IDTY) IS NOT NULL		
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdStatusIncidencia, @IdUtilizador, @ReleaseHold
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			ALTER TABLE tb_DeclaracoesDARIncidencias DISABLE TRIGGER tr_DeclaracoesDARIncidencias_RegrasRecursivas_IU
			INSERT INTO tb_DeclaracoesDARIncidencias(id_declaracaoDAR, id_statusIncidencia, dataInicio, dataFim, id_utilizadorCriacao, dataCriacao, id_utilizadorControlo, dataControlo, 
				releaseHold)
			VALUES(@IdDeclaracao, @IdStatusIncidencia, @DataAtual, @DataAtual, @IdUtilizador, @DataAtual, @IdUtilizador, @DataAtual, @ReleaseHold)			
			ALTER TABLE tb_DeclaracoesDARIncidencias ENABLE TRIGGER tr_DeclaracoesDARIncidencias_RegrasRecursivas_IU
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdStatusIncidencia, @IdUtilizador, @ReleaseHold
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes			
	END
-- insere documentos e menções configurados na alfândega
	IF UPDATE(id_estancia)
	BEGIN		
-- insere os documentos configurados na alfândega mas ainda não existentes no anexo de documentos da declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, doc.DOC_IDTY, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON ins.id_estancia = alf.ALF_IDTY
				INNER JOIN TAB_ALFD AS ado WITH(NOLOCK) ON alf.ALF_CODI = ado.ALF_CODI
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) ON ins.id = ddo.id_declaracaoDAR AND doc.DOC_IDTY = ddo.id_documento AND ddo.origem = 1
			WHERE doc.DOC_DTRA = 0 AND ddo.id IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARDocumentos(id_declaracaoDAR, id_documento, numero, tipo, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdDocumento, '*****N/A*****', 0, 1, @IdUtilizador, @DataAtual)	
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- remove os documentos existentes no anexo de documentos da declaração mas já não existentes na configuração da alfândega
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) ON ins.id = ddo.id_declaracaoDAR AND ddo.origem = 1
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON ins.id_estancia = alf.ALF_IDTY
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ddo.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_ALFD AS ado WITH(NOLOCK) ON alf.ALF_CODI = ado.ALF_CODI AND doc.DOC_CODI = ado.DOC_CODI
			WHERE ado.DOC_CODI IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdTabela
			DELETE FROM tb_DeclaracoesDARDocumentos		
			WHERE id = @IdTabela
			FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- insere as menções configuradas na alfândega (exceto a "PCEDP") mas ainda não existentes no anexo de menções da declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, men.INF_IDTY, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON ins.id_estancia = alf.ALF_IDTY
				INNER JOIN TAB_ALFM AS ame WITH(NOLOCK) ON alf.ALF_CODI = ame.ALF_CODI
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON ame.INF_CODI = men.INF_CODI
				LEFT OUTER JOIN tb_DeclaracoesDARMencoes AS dme WITH(NOLOCK) ON ins.id = dme.id_declaracaoDAR AND men.INF_IDTY = dme.id_mencao AND dme.origem = 1
			WHERE dme.id IS NULL AND men.INF_CODI <> 'PCEDP'	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdMencao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARMencoes(id_declaracaoDAR, id_mencao, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdMencao, 1, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdMencao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes	
-- remove as menções existentes no anexo de menções da declaração mas já não existentes na configuração da alfândega
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dme.id, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARMencoes AS dme WITH(NOLOCK) ON ins.id = dme.id_declaracaoDAR AND dme.origem = 1
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON ins.id_estancia = alf.ALF_IDTY
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON dme.id_mencao = men.INF_IDTY	
				LEFT OUTER JOIN TAB_ALFM AS ame WITH(NOLOCK) ON alf.ALF_CODI = ame.ALF_CODI AND men.INF_CODI = ame.INF_CODI
			WHERE ame.INF_CODI IS NULL
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARMencoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdTabela
			DELETE FROM tb_DeclaracoesDARMencoes		
			WHERE id = @IdTabela
			FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes								
	END
-- insere o documento fixo relacionado com a alfândega e documento transporte
	IF UPDATE(id_estancia) OR UPDATE(documentoTransporte)
	BEGIN		
-- insere o documento "N740"/"N750" em função da alfândega mas ainda não existente no anexo de documentos da declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, doc.DOC_IDTY, ins.documentoTransporte, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON ins.id_estancia = alf.ALF_IDTY 							
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE RIGHT(alf.ALF_CODI, 3) WHEN '236' THEN 'N750' ELSE 'N740' END)
				LEFT OUTER JOIN tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) ON ins.id = ddo.id_declaracaoDAR AND ddo.origem = 2
			WHERE doc.DOC_DTRA = 1 AND ddo.id IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @DocTransporte, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARDocumentos(id_declaracaoDAR, id_documento, numero, tipo, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdDocumento, @DocTransporte, 1, 2, @IdUtilizador, @DataAtual)	
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocumento, @DocTransporte, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
-- atualiza o documento "N740"/"N750" existente no anexo de documentos da declaração em função da alfândega
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ddo.id, doc.DOC_IDTY, ins.documentoTransporte, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARDocumentos AS ddo WITH(NOLOCK) ON ins.id = ddo.id_declaracaoDAR AND ddo.origem = 2			
				INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON ins.id_estancia = alf.ALF_IDTY 				
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON doc.DOC_CODI = (CASE RIGHT(alf.ALF_CODI, 3) WHEN '236' THEN 'N750' ELSE 'N740' END) 
			WHERE doc.DOC_DTRA = 1 AND ((ins.documentoTransporte <> del.documentoTransporte) OR (ins.id_estancia <> del.id_estancia))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdDocumento, @DocTransporte, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARDocumentos SET id_documento = @IdDocumento, numero = @DocTransporte, id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual
			WHERE id = @IdTabela
			FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdDocumento, @DocTransporte, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- insere a menção fixa relacionada com o estatuto do declarante
	IF UPDATE(estatutoDeclarante)
	BEGIN		
-- insere a menção "DHAB"/"PROC" em função do preenchimento do estatuto do declarante mas ainda não existente no anexo de menções da declaração
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, men.INF_IDTY, ins.id_utilizadorControlo
			FROM inserted AS ins 				
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON men.INF_CODI = (CASE WHEN ins.estatutoDeclarante IS NULL THEN 'DHAB' ELSE 'PROC' END)
				LEFT OUTER JOIN tb_DeclaracoesDARMencoes AS dme WITH(NOLOCK) ON ins.id = dme.id_declaracaoDAR AND dme.origem = 2
			WHERE dme.id IS NULL	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdMencao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARMencoes(id_declaracaoDAR, id_mencao, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdMencao, 2, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdMencao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
-- atualiza a menção "DHAB"/"PROC" existente (que vai ser removida) no anexo de menções da declaração em função do preenchimento do estatuto do declarante
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dme.id, men.INF_IDTY, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARMencoes AS dme WITH(NOLOCK) ON ins.id = dme.id_declaracaoDAR AND dme.origem = 2			
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON men.INF_CODI = (CASE WHEN ins.estatutoDeclarante IS NULL THEN 'DHAB' ELSE 'PROC' END)	
			WHERE ISNULL(ins.estatutoDeclarante, '') <> ISNULL(del.estatutoDeclarante, '')	
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdMencao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARMencoes SET id_mencao = @IdMencao, id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual
			WHERE id = @IdTabela
			FETCH NEXT FROM Declaracoes INTO @IdTabela, @IdMencao, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes				
	END
-- processa atualizações relacionadas c/ o follow-up
	IF UPDATE(id_followUp)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ins.id_followUp, ins.id_utilizadorControlo, del.id_followUp
			FROM inserted AS ins LEFT OUTER JOIN deleted AS del ON ins.id = del.id
			WHERE ins.id_followUp IS NOT NULL AND ((del.id IS NULL) OR ((del.id IS NOT NULL) AND (ISNULL(ins.id_followUp, -1) <> ISNULL(del.id_followUp, -1))))			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdFollowUp, @IdUtilizador, @IdFollowUpOld
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- insere o follow-up no histórico de follow-ups
			INSERT INTO tb_DeclaracoesDARFollowUps(id_declaracaoDAR, id_followUp, id_utilizadorFollowUp, dataFollowUp, id_utilizadorControlo, dataControlo)
			VALUES(@IdDeclaracao, @IdFollowUp, @IdUtilizador, @DataAtual, @IdUtilizador, @DataAtual)
-- em caso de alteração do follow-up, limpa o utilizador nomeado
			IF (@IdFollowUpOld IS NOT NULL) AND (@IdFollowUp <> @IdFollowUpOld)
			BEGIN
				UPDATE tb_DeclaracoesDAR SET id_utilizadorNomeado = NULL			
				WHERE id = @IdDeclaracao AND id_utilizadorNomeado IS NOT NULL
			END
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdFollowUp, @IdUtilizador, @IdFollowUpOld
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- para a "FEDEX/TNT" ou "TNT", processa a alteração do tipo de documento p/ documento de conta
	IF (UPDATE(id_cliente) OR UPDATE(id_natureza) OR UPDATE(totalIVA)) AND (EXISTS(SELECT PDE_CODI FROM TAB_PDES WITH(NOLOCK) WHERE PDE_IDCV = 1 AND PDE_CADI IN (1, 4)))
	BEGIN		
-- obtem tipo de documento configurado como "FT"
		SELECT TOP 1 @IdDocContaFT = tdo.TDO_IDTY
		FROM TAB_PDES AS pde WITH(NOLOCK)
			INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON pde.PDE_TDOC = tdo.TDO_DOCU
-- obtem o tipo de documento de conta "OR"
		SELECT TOP 1 @IdDocContaOR = TDO_IDTY 
		FROM TAB_TDOC WITH(NOLOCK) 
		WHERE TDO_TDOC = 0 AND TDO_TCNT = 0 AND TDO_DCON = 1 AND TDO_EXSF = 1 AND TDO_TDSF = 'OR'
-- obtem as declaraçoes que nao tenham o tipo de documento como "OR" mas satisfaçam o critério para gerar o documento de conta "OR"	
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, (CASE 
					WHEN nat.NDE_CODI IN ('11', '12', '29', '30', 'ZDU') THEN @IdDocContaOR
					WHEN nat.NDE_CODI IN ('45', '55', '60', '62', '65') AND (cli.CLI_CPAG > 0) THEN @IdDocContaOR						
					WHEN nat.NDE_CODI IN ('20', '24', '25', '26', '27', '28') AND ((cli.CLI_TNIF > 0 AND ins.totalIVA <= 50) OR (cli.CLI_TNIF = 0 AND ins.totalIVA <= 1500)) THEN @IdDocContaOR
					WHEN nat.NDE_CODI IN ('20', '24', '25', '26', '27', '28') AND cli.CLI_CPAG > 0 AND ((cli.CLI_TNIF > 0 AND ins.totalIVA > 50) OR (cli.CLI_TNIF = 0 AND ins.totalIVA > 1500)) THEN @IdDocContaOR
					ELSE @IdDocContaFT						
				END)
			FROM inserted AS ins 
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.id_cliente = cli.CLI_IDTY	
			WHERE nat.NDE_TLCV = 0 AND ISNULL(id_tipoDocumentoConta, -1) <> (CASE 
					WHEN nat.NDE_CODI IN ('11', '12', '29', '30', 'ZDU') THEN @IdDocContaOR
					WHEN nat.NDE_CODI IN ('45', '55', '60', '62', '65') AND (cli.CLI_CPAG > 0) THEN @IdDocContaOR						
					WHEN nat.NDE_CODI IN ('20', '24', '25', '26', '27', '28') AND ((cli.CLI_TNIF > 0 AND ins.totalIVA <= 50) OR (cli.CLI_TNIF = 0 AND ins.totalIVA <= 1500)) THEN @IdDocContaOR
					WHEN nat.NDE_CODI IN ('20', '24', '25', '26', '27', '28') AND cli.CLI_CPAG > 0 AND ((cli.CLI_TNIF > 0 AND ins.totalIVA > 50) OR (cli.CLI_TNIF = 0 AND ins.totalIVA > 1500)) THEN @IdDocContaOR
					ELSE @IdDocContaFT						
				END)
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocConta
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDAR SET id_tipoDocumentoConta = @IdDocConta
			WHERE id = @IdDeclaracao
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdDocConta
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
-- processa a inserção ou edição do documento de contas em função das configurações existentes
	IF (UPDATE(ano) OR UPDATE(numero) OR UPDATE(data) OR UPDATE(documentoTransporte) OR UPDATE(numeroNRM) OR UPDATE(dataNRM) OR UPDATE(id_natureza) OR UPDATE(id_fornecedor) 
		OR UPDATE(nomeFornecedor) OR UPDATE(id_cliente) OR UPDATE(nomeCliente) OR UPDATE(moradaCliente) OR UPDATE(localidadeCliente) OR UPDATE(codPostalCliente) 
		OR UPDATE(locPostalCliente) OR UPDATE(nifCliente) OR UPDATE(id_paisCliente) OR UPDATE(id_declarante) OR UPDATE(id_estancia) OR UPDATE(totalVolumes) 
		OR UPDATE(totalMassaBruta) OR UPDATE(totalCustosTransporteParte) OR UPDATE(cambioCustosTransporte) OR UPDATE(totalMontanteEUR) OR UPDATE(totalIVA) 
		OR UPDATE(volumesDirty) OR UPDATE(numeroVossaReferencia) OR UPDATE(numeroRegistoLiquidacao) OR UPDATE(dataRegistoLiquidacao) OR UPDATE(tipoShipment) 
		OR UPDATE(totalMassaBrutaParte) OR UPDATE(totalMontanteEURParte) OR UPDATE(totalIVAParte)) AND (NOT EXISTS(SELECT FTA_IDEN FROM TAB_PFTA WITH(NOLOCK) WHERE FTA_ACTI = 1))
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, ISNULL(ins.id_tipoDocumentoConta, tdo.TDO_IDTY), ins.id_utilizadorControlo
			FROM inserted AS ins LEFT OUTER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.id_cliente = cli.CLI_IDTY
				INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON pde.PDE_TDOC = tdo.TDO_DOCU
			WHERE del.id IS NULL AND pde.PDE_LFCT = 0 AND nat.NDE_CRCO = 1 AND cli.CLI_DUCT = 1 			
			UNION
			SELECT ins.id, ISNULL(ins.id_tipoDocumentoConta, tdo.TDO_IDTY), ins.id_utilizadorControlo
			FROM inserted AS ins INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON ins.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON ins.id_cliente = cli.CLI_IDTY
				INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON pde.PDE_TDOC = tdo.TDO_DOCU
				INNER JOIN FAC_CDOC AS cnt WITH(NOLOCK) ON ins.id_conta = cnt.CDO_IDTY
			WHERE ((pde.PDE_BCNR = 0) OR (pde.PDE_BCNR = 2 AND ins.autorizacaoSaida = 0)) AND cnt.CDO_STAT = 0 
				AND ((pde.PDE_LFCT = 0 AND nat.NDE_CRCO = 1 AND cli.CLI_DUCT = 1) OR (pde.PDE_LFCT = 1 AND pde.PDE_IDCV = 0))
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdTipoDoc, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			EXEC @Resultado = sp_DeclaracoesDAR_GeraDocumentoConta @IdDeclaracao, @IdTipoDoc, NULL, @IdUtilizador, 0, @IdDocConta OUTPUT, @Erro OUTPUT			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdTipoDoc, @IdUtilizador
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes
	END
END

ALTER TABLE [dbo].[tb_DeclaracoesDAR] ENABLE TRIGGER [tr_DeclaracoesDAR_Regras_IU]
/****** Object:  Trigger [tr_DeclaracoesDARAdicoes_Atualizacoes_D]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARAdicoes_Atualizacoes_D] ON [tb_DeclaracoesDARAdicoes] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdDeclaracao int, @IncAdicao tinyint, @IncVolumes int, @IncMontanteEUR decimal(18, 2), @IncCustosTransporteEUR decimal(18, 2), @IncValorIVA decimal(18, 2), 
		@IdUtilizador int	
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- para as adições removidas, decrementa o total de adições e total de volumes da declaração DAR
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT id_declaracaoDAR, COUNT(*), SUM(volumes), SUM(montanteEUR), SUM(custosTransporteEUR), SUM(valorIVA), id_utilizadorControlo
		FROM deleted 			
		GROUP BY id_declaracaoDAR, id_utilizadorControlo
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @IncAdicao, @IncVolumes, @IncMontanteEUR, @IncCustosTransporteEUR, @IncValorIVA, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN						
		SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de UPDATE não ser processado
		UPDATE tb_DeclaracoesDAR SET 
			totalAdicoes = totalAdicoes - @IncAdicao, 
			totalVolumes = totalVolumes - @IncVolumes, 
			totalIVA = totalIVA - @IncValorIVA, 
			totalMontante = totalMontante - (CASE WHEN ISNULL(nomeFornecedor, '') <> '' THEN 0 ELSE @IncMontanteEUR END), 
			totalMontanteEUR = totalMontanteEUR + (CASE WHEN ISNULL(nomeFornecedor, '') <> '' THEN 0 ELSE ROUND((@IncMontanteEUR / cambioMontante), 2) END),   
			totalCustosTransporte = totalCustosTransporte - (CASE WHEN ISNULL(nomeFornecedor, '') <> '' THEN 0 ELSE @IncCustosTransporteEUR END), 
			id_utilizadorControlo = @IdUtilizador, 
			dataControlo = @DataAtual
		WHERE id = @IdDeclaracao
		SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
		FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @IncAdicao, @IncVolumes, @IncMontanteEUR, @IncCustosTransporteEUR, @IncValorIVA, @IdUtilizador
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes
END

ALTER TABLE [dbo].[tb_DeclaracoesDARAdicoes] ENABLE TRIGGER [tr_DeclaracoesDARAdicoes_Atualizacoes_D]
/****** Object:  Trigger [tr_DeclaracoesDARAdicoes_Atualizacoes_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARAdicoes_Atualizacoes_IU] ON [tb_DeclaracoesDARAdicoes] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdDeclaracao int, @IncAdicao tinyint, @IncVolumes int, @IncMontanteEUR decimal(18, 2), @IncCustosTransporteEUR decimal(18, 2), @IncValorIVA decimal(18, 2), 
		@IdUtilizador int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- para as adições inseridas/alteradas, incrementa o total de adições e total de volumes da declaração DAR
	IF UPDATE(volumes) OR UPDATE(valorIVA) OR UPDATE(montanteEUR) OR UPDATE(custosTransporteEUR)
	BEGIN		
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_declaracaoDAR, (CASE WHEN del.id IS NULL THEN 1 ELSE 0 END), SUM(ins.volumes - ISNULL(del.volumes, 0)), SUM((ins.montanteEUR - ISNULL(del.montanteEUR, 0))), 
				SUM((ins.custosTransporteEUR - ISNULL(del.custosTransporteEUR, 0))), SUM(ins.valorIVA - ISNULL(del.valorIVA, 0)), ins.id_utilizadorControlo
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.id = del.id		
			WHERE ins.triggerOff = 0
			GROUP BY ins.id_declaracaoDAR, ins.id_utilizadorControlo, del.id
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @IncAdicao, @IncVolumes, @IncMontanteEUR, @IncCustosTransporteEUR, @IncValorIVA, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN									
			SET CONTEXT_INFO 0x44495341424C4544 --coloca variavel global de sessão com o valor "DISABLED" p/ trigger de UPDATE não ser processado
			UPDATE tb_DeclaracoesDAR SET 
				totalAdicoes = totalAdicoes + @IncAdicao, 
				totalVolumes = totalVolumes + @IncVolumes, 
				totalIVA = totalIVA + @IncValorIVA, 
				totalMontante = totalMontante + (CASE WHEN ISNULL(nomeFornecedor, '') <> '' THEN 0 ELSE @IncMontanteEUR END), 
				totalMontanteEUR = totalMontanteEUR + (CASE WHEN ISNULL(nomeFornecedor, '') <> '' THEN 0 ELSE ROUND((@IncMontanteEUR / cambioMontante), 2) END),   
				totalCustosTransporte = totalCustosTransporte + (CASE WHEN ISNULL(nomeFornecedor, '') <> '' THEN 0 ELSE @IncCustosTransporteEUR END), 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdDeclaracao			
			SET CONTEXT_INFO 0x0 --reset à variavel global de sessão
			FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @IncAdicao, @IncVolumes, @IncMontanteEUR, @IncCustosTransporteEUR, @IncValorIVA, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END	
END

ALTER TABLE [dbo].[tb_DeclaracoesDARAdicoes] ENABLE TRIGGER [tr_DeclaracoesDARAdicoes_Atualizacoes_IU]
/****** Object:  Trigger [tr_DeclaracoesDARAdicoes_Atualizacoes_U]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARAdicoes_Atualizacoes_U] ON [tb_DeclaracoesDARAdicoes] AFTER UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @IdDeclaracao int, @NumeroAdicao smallint, @RegimeAdicional varchar(3)
-- para as adições alteradas, atualiza o adicional regime das adições > 1
	IF UPDATE(regimeAdicional)
	BEGIN
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT id_declaracaoDAR, numeroAdicao, regimeAdicional
			FROM inserted 
			WHERE numeroAdicao = 1
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @NumeroAdicao, @RegimeAdicional
		WHILE @@FETCH_STATUS = 0
		BEGIN	
-- atualiza o adicional regime superiores à 1ª adição alterada
			UPDATE tb_DeclaracoesDARAdicoes SET regimeAdicional = @RegimeAdicional
			WHERE id_declaracaoDAR = @IdDeclaracao AND numeroAdicao > @NumeroAdicao			
			FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @NumeroAdicao, @RegimeAdicional
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
	END
END

ALTER TABLE [dbo].[tb_DeclaracoesDARAdicoes] ENABLE TRIGGER [tr_DeclaracoesDARAdicoes_Atualizacoes_U]
/****** Object:  Trigger [tr_DeclaracoesDARAdicoes_GereNumeracao_D]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARAdicoes_GereNumeracao_D] ON [tb_DeclaracoesDARAdicoes] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @IdDeclaracao int, @NumeroAdicao smallint
-- atualiza o numero das adições superiores à adição removida
	DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT id_declaracaoDAR, numeroAdicao
		FROM deleted 			
	OPEN Adicoes
	FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @NumeroAdicao
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_DeclaracoesDARAdicoes SET numeroAdicao = numeroAdicao - 1    
		WHERE id_declaracaoDAR = @IdDeclaracao AND numeroAdicao > @NumeroAdicao
		FETCH NEXT FROM Adicoes INTO @IdDeclaracao, @NumeroAdicao
	END
	CLOSE Adicoes
	DEALLOCATE Adicoes    
END

ALTER TABLE [dbo].[tb_DeclaracoesDARAdicoes] ENABLE TRIGGER [tr_DeclaracoesDARAdicoes_GereNumeracao_D]
/****** Object:  Trigger [tr_DeclaracoesDARAdicoes_Regras_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARAdicoes_Regras_IU] ON [tb_DeclaracoesDARAdicoes] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdAdicao bigint, @IdDocumento int, @NumeroDocumento varchar(70), @TipoDocumento tinyint, @IdUtilizador int, @IdTabela bigint, @IdMencao int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- insere documentos e menções configurados no artigo
	IF UPDATE(id_artigo)
	BEGIN
-- insere os documentos configurados no artigo mas ainda não existentes no anexo de documentos da adição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, doc.DOC_IDTY, (CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE '*****N/A*****' END), doc.DOC_DTRA, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.id_artigo = art.APA_IDTY
				INNER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON art.APA_CHVE = ado.APA_CHVE
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ado.DOC_CODI = doc.DOC_CODI
				LEFT OUTER JOIN tb_DeclaracoesDARAdicoesDocumentos AS dad WITH(NOLOCK) ON ins.id = dad.id_adicao AND doc.DOC_IDTY = dad.id_documento AND dad.origem = 1
			WHERE ado.ADC_UIMP = 1 AND dad.id IS NULL	
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdDocumento, @NumeroDocumento, @TipoDocumento, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARAdicoesDocumentos(id_adicao, id_documento, numero, tipo, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdDocumento, @NumeroDocumento, @TipoDocumento, 1, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdDocumento, @NumeroDocumento, @TipoDocumento, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
-- remove os documentos existentes no anexo de documentos da adição mas já não existentes na configuração do artigo
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dad.id, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoesDocumentos AS dad WITH(NOLOCK) ON ins.id = dad.id_adicao AND dad.origem = 1
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.id_artigo = art.APA_IDTY
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON dad.id_documento = doc.DOC_IDTY	
				LEFT OUTER JOIN TAB_ADOC AS ado WITH(NOLOCK) ON art.APA_CHVE = ado.APA_CHVE AND doc.DOC_CODI = ado.DOC_CODI
			WHERE ado.DOC_CODI IS NULL OR ado.ADC_UIMP = 0
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdTabela, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoesDocumentos SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdTabela
			DELETE FROM tb_DeclaracoesDARAdicoesDocumentos
			WHERE id = @IdTabela
			FETCH NEXT FROM Adicoes INTO @IdTabela, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes					
-- insere as menções configuradas no artigo mas ainda não existentes no anexo de menções da adição
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id, men.INF_IDTY, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.id_artigo = art.APA_IDTY
				INNER JOIN TAB_AMEN AS ame WITH(NOLOCK) ON art.APA_CHVE = ame.APA_CHVE
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON ame.INF_CODI = men.INF_CODI
				LEFT OUTER JOIN tb_DeclaracoesDARAdicoesMencoes AS dam WITH(NOLOCK) ON ins.id = dam.id_adicao AND men.INF_IDTY = dam.id_mencao AND dam.origem = 1
			WHERE ame.AME_UIMP = 1 AND dam.id IS NULL						
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdMencao, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			INSERT INTO tb_DeclaracoesDARAdicoesMencoes(id_adicao, id_mencao, origem, id_utilizadorControlo, dataControlo)
			VALUES(@IdAdicao, @IdMencao, 1, @IdUtilizador, @DataAtual)
			FETCH NEXT FROM Adicoes INTO @IdAdicao, @IdMencao, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes		
-- remove as menções existentes no anexo de menções da adição mas já não existentes na configuração do artigo
		DECLARE Adicoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dam.id, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoesMencoes AS dam WITH(NOLOCK) ON ins.id = dam.id_adicao AND dam.origem = 1
				INNER JOIN TAB_APAU AS art WITH(NOLOCK) ON ins.id_artigo = art.APA_IDTY
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON dam.id_mencao = men.INF_IDTY	
				LEFT OUTER JOIN TAB_AMEN AS ame WITH(NOLOCK) ON art.APA_CHVE = ame.APA_CHVE AND men.INF_CODI = ame.INF_CODI
			WHERE ame.INF_CODI IS NULL OR ame.AME_UIMP = 0				
		OPEN Adicoes
		FETCH NEXT FROM Adicoes INTO @IdTabela, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoesMencoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdTabela
			DELETE FROM tb_DeclaracoesDARAdicoesMencoes
			WHERE id = @IdTabela
			FETCH NEXT FROM Adicoes INTO @IdTabela, @IdUtilizador
		END
		CLOSE Adicoes
		DEALLOCATE Adicoes							
	END
END

ALTER TABLE [dbo].[tb_DeclaracoesDARAdicoes] ENABLE TRIGGER [tr_DeclaracoesDARAdicoes_Regras_IU]
/****** Object:  Trigger [tr_DeclaracoesDARAdicoesDocumentos_Regras_D]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARAdicoesDocumentos_Regras_D] ON [tb_DeclaracoesDARAdicoesDocumentos] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdTabela bigint, @IdUtilizador int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- remove a menção existente no anexo de menções da adição
	DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT dam.id, del.id_utilizadorControlo
		FROM deleted AS del 
			INNER JOIN tb_DeclaracoesDARAdicoesMencoes AS dam WITH(NOLOCK) ON del.id = dam.id_adicaoDocumento AND dam.origem = 2
	OPEN Documentos
	FETCH NEXT FROM Documentos INTO @IdTabela, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		UPDATE tb_DeclaracoesDARAdicoesMencoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id = @IdTabela
		DELETE FROM tb_DeclaracoesDARAdicoesMencoes
		WHERE id = @IdTabela
		FETCH NEXT FROM Documentos INTO @IdTabela, @IdUtilizador
	END
	CLOSE Documentos
	DEALLOCATE Documentos	
END

ALTER TABLE [dbo].[tb_DeclaracoesDARAdicoesDocumentos] ENABLE TRIGGER [tr_DeclaracoesDARAdicoesDocumentos_Regras_D]
/****** Object:  Trigger [tr_DeclaracoesDARAdicoesDocumentos_Regras_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARAdicoesDocumentos_Regras_IU] ON [tb_DeclaracoesDARAdicoesDocumentos] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdAdicao bigint, @IdMencao int, @IdTabela bigint, @IdUtilizador int, @IdTabelaMencoes bigint
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- insere a menção configurada no documento
	IF UPDATE(id_documento)
	BEGIN
-- insere/edita a menção configurada no documento mas ainda não existente no anexo de menções da adição
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_adicao, men.INF_IDTY, ins.id, ins.id_utilizadorControlo, dam.id
			FROM inserted AS ins 
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ins.id_documento = doc.DOC_IDTY 			
				LEFT OUTER JOIN tb_DeclaracoesDARAdicoesMencoes AS dam WITH(NOLOCK) ON ins.id = dam.id_adicaoDocumento AND dam.origem = 2
				INNER JOIN TAB_INFC AS men WITH(NOLOCK) ON doc.INF_CODI = men.INF_CODI
			WHERE (dam.id IS NULL) OR ((dam.id IS NOT NULL) AND (dam.id_mencao <> men.INF_IDTY) AND (men.INF_IDTY IS NOT NULL))
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @IdAdicao, @IdMencao, @IdTabela, @IdUtilizador, @IdTabelaMencoes
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			IF @IdTabelaMencoes IS NULL
			BEGIN
				INSERT INTO tb_DeclaracoesDARAdicoesMencoes(id_adicao, id_mencao, origem, id_adicaoDocumento, id_utilizadorControlo, dataControlo)
				VALUES(@IdAdicao, @IdMencao, 2, @IdTabela, @IdUtilizador, @DataAtual)
			END
			ELSE
			BEGIN
				UPDATE tb_DeclaracoesDARAdicoesMencoes SET 
					id_mencao = @IdMencao, 
					id_utilizadorControlo = @IdUtilizador, 
					dataControlo = @DataAtual
				WHERE id = @IdTabelaMencoes
			END
			FETCH NEXT FROM Documentos INTO @IdAdicao, @IdMencao, @IdTabela, @IdUtilizador, @IdTabelaMencoes
		END
		CLOSE Documentos
		DEALLOCATE Documentos				
-- remove a menção existente no anexo de menções da adição mas já não existente na configuração do documento	
		DECLARE Documentos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT dam.id, ins.id_utilizadorControlo
			FROM inserted AS ins 
				INNER JOIN deleted AS del ON ins.id = del.id
				INNER JOIN tb_DeclaracoesDARAdicoesMencoes AS dam WITH(NOLOCK) ON ins.id = dam.id_adicaoDocumento AND dam.origem = 2
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ins.id_documento = doc.DOC_IDTY
				LEFT OUTER JOIN TAB_INFC AS men WITH(NOLOCK) ON doc.INF_CODI = men.INF_CODI				
			WHERE men.INF_IDTY IS NULL			
		OPEN Documentos
		FETCH NEXT FROM Documentos INTO @IdTabela, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDARAdicoesMencoes SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
			WHERE id = @IdTabela
			DELETE FROM tb_DeclaracoesDARAdicoesMencoes
			WHERE id = @IdTabela
			FETCH NEXT FROM Documentos INTO @IdTabela, @IdUtilizador
		END
		CLOSE Documentos
		DEALLOCATE Documentos				
	END
END

ALTER TABLE [dbo].[tb_DeclaracoesDARAdicoesDocumentos] ENABLE TRIGGER [tr_DeclaracoesDARAdicoesDocumentos_Regras_IU]
/****** Object:  Trigger [tr_DeclaracoesDARIncidencias_Regras_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARIncidencias_Regras_IU] ON [tb_DeclaracoesDARIncidencias] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE	@IdDeclaracao int, @IdTipoDoc int, @TipoCliente varchar(3), @IdUtilizador int, @Resultado int, @IdDocConta int, @Erro varchar(MAX)
-- processa geração do documento de conta ao abrigo da "Faturação Automática Ativa"
	IF (UPDATE(id_statusIncidencia)) AND (EXISTS(SELECT FTA_IDEN FROM TAB_PFTA WITH(NOLOCK) WHERE FTA_ACTI = 1))
    BEGIN   						
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR			
			SELECT dar.id, ISNULL(dar.id_tipoDocumentoConta, tdo.TDO_IDTY), ins.id_utilizadorControlo, 
				(CASE 
					WHEN pde.PDE_IDCV = 0 THEN NULL 
					WHEN dar.dutyType IN ('A5', 'A6') THEN 'ACC' 
					WHEN dar.dutyType = 'CA' THEN 'COD' 
					WHEN dar.dutyType IN ('D5', 'D6') THEN 'EXB' 
					ELSE NULL 
				END)
			FROM inserted AS ins 
				LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON ins.id_statusIncidencia = inc.SIN_IDTY 
				LEFT OUTER JOIN TAB_COSM AS cco WITH(NOLOCK) ON ins.id_statusIncidencia = cco.COS_IDTY
				INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON ins.id_declaracaoDAR = dar.id
				INNER JOIN TAB_NDES AS nat WITH(NOLOCK) ON dar.id_natureza = nat.NDE_IDTY
				INNER JOIN TAB_CLIE AS cli WITH(NOLOCK) ON dar.id_cliente = cli.CLI_IDTY
				INNER JOIN TAB_PDES AS pde WITH(NOLOCK) ON ISNULL(pde.PDE_TDOC, '') <> ''
				INNER JOIN TAB_TDOC AS tdo WITH(NOLOCK) ON pde.PDE_TDOC = tdo.TDO_DOCU	
				INNER JOIN TAB_PFTA as pft WITH(NOLOCK) ON pft.FTA_ACTI = 1	
			WHERE (inc.SIN_CODI IN ('A13', 'ND') OR cco.COS_CODE IN ('A13', 'ND')) AND dar.autorizacaoSaida = 0 AND dar.tipoShipment < 2 AND dar.id_conta IS NULL AND nat.NDE_CRCO = 1 AND ISNULL(nat.NDE_TLCV, 0) <> 1 AND cli.CLI_DUCT = 1
				AND NOT EXISTS(SELECT DVE_IDTY FROM FAC_DVEN WITH(NOLOCK) WHERE DVE_IDAR = dar.id)
				AND (CASE pft.FTA_DUVR 
						WHEN 1 THEN (CASE 
										WHEN ISNULL(dar.numeroVossaReferencia, '') <> '' THEN 1 
										ELSE 0 
									END) 
						WHEN 2 THEN (CASE 
										WHEN ISNULL(dar.numeroVossaReferencia, '') = '' THEN 1 
										ELSE 0 
									END) 
						ELSE 1 END) = 1
				AND (CASE pft.FTA_DDRI 
						WHEN 0 THEN (CASE 
										WHEN dar.regimeIVA = 1 THEN 0 
										ELSE 1 
									END) 						
						ELSE 1 END) = 1
				AND (CASE pft.FTA_DDBI 
						WHEN 0 THEN (CASE 
										WHEN (dar.totalIVA <= 5) AND (cli.CLI_BIVA = 1) THEN 0 
										ELSE 1 
									END) 						
						ELSE 1 END) = 1						
				AND (CASE 
						WHEN (ISNULL(nat.NDE_TLCV, -1) = 0) AND (dar.id_tipoDocumentoConta IS NULL) THEN 0 
						ELSE 1 
					END) = 1
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdTipoDoc, @IdUtilizador, @TipoCliente
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			EXEC @Resultado = sp_DeclaracoesDAR_GeraDocumentoConta @IdDeclaracao, @IdTipoDoc, @TipoCliente, @IdUtilizador, 1, @IdDocConta OUTPUT, @Erro OUTPUT
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdTipoDoc, @IdUtilizador, @TipoCliente
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes 
    END
END

ALTER TABLE [dbo].[tb_DeclaracoesDARIncidencias] ENABLE TRIGGER [tr_DeclaracoesDARIncidencias_Regras_IU]
/****** Object:  Trigger [tr_DeclaracoesDARIncidencias_RegrasRecursivas_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARIncidencias_RegrasRecursivas_IU] ON [tb_DeclaracoesDARIncidencias] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @DataAtual datetime, @IdDeclaracao int, @IdNatureza int, @IdUtilizador int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- atualiza a natureza da declaração se status de incidência/cosmo code assim estiver configurado
	IF UPDATE(id_statusIncidencia)
	BEGIN
		DECLARE Incidencias CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR						
			SELECT tbl.id_declaracaoDAR, tbl.id_utilizadorControlo, tbl.NDE_IDTY
			FROM (SELECT ins.id_declaracaoDAR, ins.id_utilizadorControlo, dar.id_natureza, 
					ISNULL(nti.NDE_IDTY, (CASE RIGHT(alf.ALF_CODI, 3) WHEN '015' THEN ntl.NDE_IDTY WHEN '020' THEN ntp.NDE_IDTY ELSE NULL END)) AS NDE_IDTY
				FROM inserted AS ins 
					INNER JOIN tb_DeclaracoesDAR AS dar WITH(NOLOCK) ON ins.id_declaracaoDAR = dar.id
					INNER JOIN TAB_ALFA AS alf WITH(NOLOCK) ON dar.id_estancia = alf.ALF_IDTY 
					LEFT OUTER JOIN TAB_SINC AS inc WITH(NOLOCK) ON ins.id_statusIncidencia = inc.SIN_IDTY
					LEFT OUTER JOIN TAB_NDES AS nti WITH(NOLOCK) ON inc.NDE_CODI = nti.NDE_CODI
					LEFT OUTER JOIN TAB_COSM AS csc WITH(NOLOCK) ON ins.id_statusIncidencia = csc.COS_IDTY
					LEFT OUTER JOIN TAB_NDES AS ntl WITH(NOLOCK) ON csc.NDE_CODI = ntl.NDE_CODI
					LEFT OUTER JOIN TAB_NDES AS ntp WITH(NOLOCK) ON csc.NDE_CDPO = ntp.NDE_CODI) AS tbl
			WHERE tbl.NDE_IDTY IS NOT NULL AND tbl.id_natureza <> tbl.NDE_IDTY
			GROUP BY tbl.id_declaracaoDAR, tbl.id_utilizadorControlo, tbl.NDE_IDTY
		OPEN Incidencias
		FETCH NEXT FROM Incidencias INTO @IdDeclaracao, @IdUtilizador, @IdNatureza
		WHILE @@FETCH_STATUS = 0
		BEGIN	
			UPDATE tb_DeclaracoesDAR SET 
				id_natureza = @IdNatureza, 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual
			WHERE id = @IdDeclaracao
			FETCH NEXT FROM Incidencias INTO @IdDeclaracao, @IdUtilizador, @IdNatureza
		END
		CLOSE Incidencias
		DEALLOCATE Incidencias			
	END
END

ALTER TABLE [dbo].[tb_DeclaracoesDARIncidencias] ENABLE TRIGGER [tr_DeclaracoesDARIncidencias_RegrasRecursivas_IU]
/****** Object:  Trigger [tr_DeclaracoesDARManifestos_Regras_D]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARManifestos_Regras_D] ON [tb_DeclaracoesDARManifestos] AFTER DELETE AS
BEGIN
	SET NOCOUNT ON;
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdDeclaracao int, @IdUtilizador int, @VolsDirty int, @VolsClean int, @VolsScan int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- atualiza os volumes Dirty, Clean e Scan da declaração se linhas manifesto tiverem definido o campo "Documento de Transporte"
	DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT id_declaracaoDAR, id_utilizadorControlo, 
			SUM((CASE WHEN (tipoManifesto = 0) THEN 1 ELSE 0 END)), 
			SUM((CASE WHEN (tipoManifesto = 1) THEN 1 ELSE 0 END)), 
			SUM((CASE WHEN (tipoManifesto = 2) THEN 1 ELSE 0 END))
		FROM deleted
		WHERE triggerOff = 0 AND ISNULL(documentoTransporte, '') <> ''
		GROUP BY id_declaracaoDAR, id_utilizadorControlo
	OPEN Declaracoes
	FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @VolsDirty, @VolsClean, @VolsScan
	WHILE @@FETCH_STATUS = 0
	BEGIN
		UPDATE tb_DeclaracoesDAR SET 
			volumesDirty = volumesDirty - @VolsDirty, 
			volumesClean = volumesClean - @VolsClean, 
			volumesScan = volumesScan - @VolsScan, 
			id_utilizadorControlo = @IdUtilizador, 
			dataControlo = @DataAtual
		WHERE id = @IdDeclaracao				
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @VolsDirty, @VolsClean, @VolsScan
	END
	CLOSE Declaracoes
	DEALLOCATE Declaracoes	
END

ALTER TABLE [dbo].[tb_DeclaracoesDARManifestos] ENABLE TRIGGER [tr_DeclaracoesDARManifestos_Regras_D]
/****** Object:  Trigger [tr_DeclaracoesDARManifestos_Regras_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_DeclaracoesDARManifestos_Regras_IU] ON [tb_DeclaracoesDARManifestos] AFTER INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON;
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdDeclaracao int, @IdUtilizador int, @VolsDirty int, @VolsClean int, @VolsScan int
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- atualiza os volumes Dirty, Clean e Scan da declaração se linhas manifesto tiverem definido o campo "Documento de Transporte"
	IF UPDATE(tipoManifesto) OR UPDATE(documentoTransporte)
	BEGIN
		DECLARE Declaracoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_declaracaoDAR, ins.id_utilizadorControlo, 
				SUM((CASE WHEN (ins.tipoManifesto = 0) AND (ISNULL(ins.documentoTransporte, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.tipoManifesto = 0) AND (ISNULL(del.documentoTransporte, '') <> '') THEN 1 ELSE 0 END)), 
				SUM((CASE WHEN (ins.tipoManifesto = 1) AND (ISNULL(ins.documentoTransporte, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.tipoManifesto = 1) AND (ISNULL(del.documentoTransporte, '') <> '') THEN 1 ELSE 0 END)), 
				SUM((CASE WHEN (ins.tipoManifesto = 2) AND (ISNULL(ins.documentoTransporte, '') <> '') THEN 1 ELSE 0 END) - (CASE WHEN (del.tipoManifesto = 2) AND (ISNULL(del.documentoTransporte, '') <> '') THEN 1 ELSE 0 END))
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.id = del.id		
			WHERE ins.triggerOff = 0 AND ((ISNULL(ins.documentoTransporte, '') <> '') OR (ISNULL(del.documentoTransporte, '') <> ''))
			GROUP BY ins.id_declaracaoDAR, ins.id_utilizadorControlo			
		OPEN Declaracoes
		FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @VolsDirty, @VolsClean, @VolsScan
		WHILE @@FETCH_STATUS = 0
		BEGIN
			UPDATE tb_DeclaracoesDAR SET 
				volumesDirty = volumesDirty + @VolsDirty, 
				volumesClean = volumesClean + @VolsClean, 
				volumesScan = volumesScan + @VolsScan, 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual	
			WHERE id = @IdDeclaracao			
			FETCH NEXT FROM Declaracoes INTO @IdDeclaracao, @IdUtilizador, @VolsDirty, @VolsClean, @VolsScan
		END
		CLOSE Declaracoes
		DEALLOCATE Declaracoes		
	END
END

ALTER TABLE [dbo].[tb_DeclaracoesDARManifestos] ENABLE TRIGGER [tr_DeclaracoesDARManifestos_Regras_IU]
/****** Object:  Trigger [tr_EXP_DeclaracoesAdicoesImposicoesTaxas_Atualizacoes_D]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_EXP_DeclaracoesAdicoesImposicoesTaxas_Atualizacoes_D] ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] FOR DELETE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdImposicao bigint, @Montante decimal(18, 2), @IdUtilizador int	
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem as taxas removidas
	DECLARE Taxas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT id_imposicao, montante, id_utilizadorControlo
		FROM deleted 				
	OPEN Taxas
	FETCH NEXT FROM Taxas INTO @IdImposicao, @Montante, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- atualiza o montante total de taxas na imposição
		UPDATE tb_EXP_DeclaracoesAdicoesImposicoes SET 
			montante = montante - @Montante, 
			id_utilizadorControlo = @IdUtilizador, 
			dataControlo = @DataAtual			
		WHERE id = @IdImposicao
		FETCH NEXT FROM Taxas INTO @IdImposicao, @Montante, @IdUtilizador
	END
	CLOSE Taxas
	DEALLOCATE Taxas
END

ALTER TABLE [dbo].[tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ENABLE TRIGGER [tr_EXP_DeclaracoesAdicoesImposicoesTaxas_Atualizacoes_D]
/****** Object:  Trigger [tr_EXP_DeclaracoesAdicoesImposicoesTaxas_Atualizacoes_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_EXP_DeclaracoesAdicoesImposicoesTaxas_Atualizacoes_IU] ON [tb_EXP_DeclaracoesAdicoesImposicoesTaxas] FOR INSERT, UPDATE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdImposicao bigint, @Montante decimal(18, 2), @IdUtilizador int	
-- se variavel global de sessão tem o valor "DISABLED", não processa o trigger
	IF CONTEXT_INFO() = 0x44495341424C4544 --"DISABLED" em binário
		RETURN
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- processa automatismos relacionados com a alteração do montante
	IF UPDATE(montante)
	BEGIN
-- obtem as taxas inseridas/alteradas
		DECLARE Taxas CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_imposicao, (ins.montante - ISNULL(del.montante, 0)), ins.id_utilizadorControlo
			FROM inserted AS ins 
				LEFT OUTER JOIN deleted AS del ON ins.id = del.id
		OPEN Taxas
		FETCH NEXT FROM Taxas INTO @IdImposicao, @Montante, @IdUtilizador
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- atualiza o montante total de taxas na imposição
			UPDATE tb_EXP_DeclaracoesAdicoesImposicoes SET 
				montante = montante + @Montante, 
				id_utilizadorControlo = @IdUtilizador, 
				dataControlo = @DataAtual			
			WHERE id = @IdImposicao
			FETCH NEXT FROM Taxas INTO @IdImposicao, @Montante, @IdUtilizador
		END
		CLOSE Taxas
		DEALLOCATE Taxas
	END
END

ALTER TABLE [dbo].[tb_EXP_DeclaracoesAdicoesImposicoesTaxas] ENABLE TRIGGER [tr_EXP_DeclaracoesAdicoesImposicoesTaxas_Atualizacoes_IU]
/****** Object:  Trigger [tr_EXP_DeclaracoesLocaisTransformacao_GereProdutosTransformados_D]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_EXP_DeclaracoesLocaisTransformacao_GereProdutosTransformados_D] ON [tb_EXP_DeclaracoesLocaisTransformacao] FOR DELETE AS 
BEGIN	
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @DataAtual datetime, @IdDeclaracao bigint, @IdUtilizador int	
-- obtem data atual GMT
	SET @DataAtual = GIDWIN.dbo.FNT_Geral_ObtemDataHoraGMT()
-- obtem os locais de transformação removidos cujo total de registos para a declaração ficou vazio
	DECLARE Locais CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.id_declaracaoEXP, del.id_utilizadorControlo
		FROM deleted AS del 
		WHERE NOT EXISTS(SELECT 1 
						FROM tb_EXP_DeclaracoesLocaisTransformacao WITH(NOLOCK) 
						WHERE id_declaracaoEXP = del.id_declaracaoEXP)
		GROUP BY del.id_declaracaoEXP, del.id_utilizadorControlo		
	OPEN Locais
	FETCH NEXT FROM Locais INTO @IdDeclaracao, @IdUtilizador
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- atualiza os produtos transformados existentes no detalhe de produtos transformados da declaração EXP-SAE
		UPDATE tb_EXP_DeclaracoesProdutosTransformados SET id_utilizadorControlo = @IdUtilizador, dataControlo = @DataAtual			
		WHERE id_declaracaoEXP = @IdDeclaracao
-- remove os produtos transformados existentes no detalhe de produtos transformados da declaração EXP-SAE
		DELETE FROM tb_EXP_DeclaracoesProdutosTransformados
		WHERE id_declaracaoEXP = @IdDeclaracao
		FETCH NEXT FROM Locais INTO @IdDeclaracao, @IdUtilizador
	END
	CLOSE Locais
	DEALLOCATE Locais
END

ALTER TABLE [dbo].[tb_EXP_DeclaracoesLocaisTransformacao] ENABLE TRIGGER [tr_EXP_DeclaracoesLocaisTransformacao_GereProdutosTransformados_D]
/****** Object:  Trigger [tr_IMP_DeclaracoesAdicoesAcrescimosDeducoes_Atualizacoes_D]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_IMP_DeclaracoesAdicoesAcrescimosDeducoes_Atualizacoes_D] ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] AFTER DELETE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @IdAdicao int, @FormulaCondEntrega varchar(70), @TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6), @CambioSeguro numeric(38, 6)
	DECLARE @SomaAcrescimos decimal(18, 2), @SomaDeducoes decimal(18, 2)
	DECLARE @Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @BaseTributacaoDireitos numeric(38, 6), @MontanteDireitos numeric(38, 6), @BaseTributacaoIVA numeric(38, 6)
-- obtem as adições pertencentes aos acréscimos/deduções removidos e não originados de direitos
	DECLARE AcrescimosDeducoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
		SELECT del.id_adicao, ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0), ISNULL(duc.DUC_TXSE, 0)
		FROM deleted AS del
			INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON del.id_adicao = adi.DUA_IDEN
			INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM
		WHERE del.origem = 0
		GROUP BY del.id_adicao, duc.DUC_FR20, duc.DUC_TFDA, duc.DUC_TXFR, duc.DUC_TXSE
	OPEN AcrescimosDeducoes
	FETCH NEXT FROM AcrescimosDeducoes INTO @IdAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro
	WHILE @@FETCH_STATUS = 0
	BEGIN
-- calcula a soma dos acréscimos manuais da adição
		SET @SomaAcrescimos = ISNULL(
			(SELECT SUM(montante)
			FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK)
			WHERE id_adicao = @IdAdicao AND tipo = 0 AND origem = 0), 0)
-- calcula a soma das deduções manuais da adição
		SET @SomaDeducoes = ISNULL(
			(SELECT SUM(montante)
			FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK)
			WHERE id_adicao = @IdAdicao AND tipo = 1 AND origem = 0), 0)
-- atualiza total de acréscimos e total de deduções na adição
		UPDATE PRO_DUAD SET 
			DUA_ACRE = @SomaAcrescimos,
			DUA_DEDU = @SomaDeducoes, 
			@Ajustamento = DUA_AJUS = dbo.fn_IMP_CalculaAjustamento(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro, DUA_VFRE, DUA_VSEG, DUA_VDIR, @SomaAcrescimos, @SomaDeducoes),
			@ValorEstatistico = DUA_VEST = dbo.fn_IMP_CalculaValorEstatistico(DUA_VAEU, @Ajustamento),
			DUA_VATO = @ValorEstatistico,
			@BaseTributacaoDireitos = DUA_BTRI = dbo.fn_IMP_CalculaBaseTributacaoDireitos(DUA_BMAN, DUA_BTRI, DUA_TRIB, DUA_ML38, DUA_US41, @ValorEstatistico, UME_CODI), 
			@MontanteDireitos = DUA_MTRI = dbo.fn_IMP_CalculaMontanteDireitos(DUA_BMAN, DUA_MTRI, (CASE DUA_TXCO WHEN 1 THEN 0 ELSE 1 END), DUA_TXVL, @BaseTributacaoDireitos),
			@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, DUA_VFRE, @Ajustamento, @ValorEstatistico, DUA_VTRA, DUA_VOPT, @MontanteDireitos, DUA_IVAV, DUA_ABTI, DUA_MIVI),
			DUA_VIVA = ROUND(@BaseTributacaoIVA * DUA_TIVA / 100, 2)
		WHERE DUA_IDEN = @IdAdicao
		FETCH NEXT FROM AcrescimosDeducoes INTO @IdAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro
	END
	CLOSE AcrescimosDeducoes
	DEALLOCATE AcrescimosDeducoes			
END

ALTER TABLE [dbo].[tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] ENABLE TRIGGER [tr_IMP_DeclaracoesAdicoesAcrescimosDeducoes_Atualizacoes_D]
/****** Object:  Trigger [tr_IMP_DeclaracoesAdicoesAcrescimosDeducoes_Atualizacoes_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_IMP_DeclaracoesAdicoesAcrescimosDeducoes_Atualizacoes_IU] ON [tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON;
-- declaração de variáveis
	DECLARE @IdAdicao int, @FormulaCondEntrega varchar(70), @TaxaFDA numeric(38, 6), @CambioFrete numeric(38, 6), @CambioSeguro numeric(38, 6)
	DECLARE @SomaAcrescimos decimal(18, 2), @SomaDeducoes decimal(18, 2)
	DECLARE @Ajustamento numeric(38, 6), @ValorEstatistico numeric(38, 6), @BaseTributacaoDireitos numeric(38, 6), @MontanteDireitos numeric(38, 6), @BaseTributacaoIVA numeric(38, 6)
-- se colunas do tipo ou montante alteradas, processa a atualização das adições associadas aos acréscimos/deduções inseridos/alterados
	IF UPDATE(tipo) OR UPDATE(montante)
	BEGIN
-- obtem as adições pertencentes aos acréscimos/deduções inseridos/alterados e não originados de direitos
		DECLARE AcrescimosDeducoes CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT ins.id_adicao, ISNULL(duc.DUC_FR20, ''), ISNULL(duc.DUC_TFDA, 0), ISNULL(duc.DUC_TXFR, 0), ISNULL(duc.DUC_TXSE, 0)
			FROM inserted AS ins 
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.id_adicao = adi.DUA_IDEN
				INNER JOIN PRO_DUCG AS duc WITH(NOLOCK) ON adi.DUC_EANO = duc.DUC_EANO AND adi.DUC_PNUM = duc.DUC_PNUM						
			WHERE ins.origem = 0
			GROUP BY ins.id_adicao, duc.DUC_FR20, duc.DUC_TFDA, duc.DUC_TXFR, duc.DUC_TXSE
		OPEN AcrescimosDeducoes
		FETCH NEXT FROM AcrescimosDeducoes INTO @IdAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- calcula a soma dos acréscimos manuais da adição
			SET @SomaAcrescimos = ISNULL(
				(SELECT SUM(montante)
				FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK)
				WHERE id_adicao = @IdAdicao AND tipo = 0 AND origem = 0), 0)
-- calcula a soma das deduções manuais da adição
			SET @SomaDeducoes = ISNULL(
				(SELECT SUM(montante)
				FROM tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes WITH(NOLOCK)
				WHERE id_adicao = @IdAdicao AND tipo = 1 AND origem = 0), 0)
-- atualiza total de acréscimos e total de deduções na adição
			UPDATE PRO_DUAD SET 
				DUA_ACRE = @SomaAcrescimos,
				DUA_DEDU = @SomaDeducoes,
				@Ajustamento = DUA_AJUS = dbo.fn_IMP_CalculaAjustamento(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro, DUA_VFRE, DUA_VSEG, DUA_VDIR, @SomaAcrescimos, @SomaDeducoes),
				@ValorEstatistico = DUA_VEST = dbo.fn_IMP_CalculaValorEstatistico(DUA_VAEU, @Ajustamento),
				DUA_VATO = @ValorEstatistico,
				@BaseTributacaoDireitos = DUA_BTRI = dbo.fn_IMP_CalculaBaseTributacaoDireitos(DUA_BMAN, DUA_BTRI, DUA_TRIB, DUA_ML38, DUA_US41, @ValorEstatistico, UME_CODI), 
				@MontanteDireitos = DUA_MTRI = dbo.fn_IMP_CalculaMontanteDireitos(DUA_BMAN, DUA_MTRI, (CASE DUA_TXCO WHEN 1 THEN 0 ELSE 1 END), DUA_TXVL, @BaseTributacaoDireitos),
				@BaseTributacaoIVA = DUA_BTIV = dbo.fn_IMP_CalculaBaseTributacaoIVA(@FormulaCondEntrega, @TaxaFDA, @CambioFrete, DUA_VFRE, @Ajustamento, @ValorEstatistico, DUA_VTRA, DUA_VOPT, @MontanteDireitos, DUA_IVAV, DUA_ABTI, DUA_MIVI),
				DUA_VIVA = ROUND(@BaseTributacaoIVA * DUA_TIVA / 100, 2)
			WHERE DUA_IDEN = @IdAdicao
			FETCH NEXT FROM AcrescimosDeducoes INTO @IdAdicao, @FormulaCondEntrega, @TaxaFDA, @CambioFrete, @CambioSeguro
		END
		CLOSE AcrescimosDeducoes
		DEALLOCATE AcrescimosDeducoes		
	END
END

ALTER TABLE [dbo].[tb_IMP_DeclaracoesAdicoesAcrescimosDeducoes] ENABLE TRIGGER [tr_IMP_DeclaracoesAdicoesAcrescimosDeducoes_Atualizacoes_IU]
/****** Object:  Trigger [tr_IMP_DeclaracoesAdicoesPedidos_Regras_IU]    Script Date: 04-11-2025 10:22:23 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [tr_IMP_DeclaracoesAdicoesPedidos_Regras_IU] ON [tb_IMP_DeclaracoesAdicoesPedidos] AFTER INSERT, UPDATE AS 
BEGIN
	SET NOCOUNT ON
	SET DATEFORMAT DMY
-- declaracao de variaveis 
	DECLARE @NumProxRegisto int
	DECLARE @AnoDeclaracao int, @NumDeclaracao int, @NumAdicao int
	DECLARE @CodDocumento varchar(5), @NomeDocumento varchar(150), @NumeroDocumento varchar(70), @TipoDocumento int
-- se coluna do pedido alterada, processa a gestão do documento no detalhe de documentos das adições IMP-CAU associadas aos pedidos inseridos/alterados
	IF UPDATE(id_pedido)
	BEGIN
-- insere o documento como "Suporte" no detalhe de documentos da adição IMP-CAU 
		DECLARE Pedidos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
			SELECT adi.DUC_EANO, adi.DUC_PNUM, adi.DUA_CODI, doc.DOC_CODI, doc.DOC_NOME, doc.DOC_DTRA, 
				(CASE doc.DOC_TDNU WHEN 1 THEN 'S/N' WHEN 2 THEN 'N/A' WHEN 3 THEN 'DEC' ELSE NULL END)				
			FROM inserted AS ins 			
				INNER JOIN PRO_DUAD AS adi WITH(NOLOCK) ON ins.id_adicao = adi.DUA_IDEN				
				INNER JOIN TAB_TXML AS ped WITH(NOLOCK) ON ins.id_pedido = ped.TXM_IDTY
				INNER JOIN TAB_DOCU AS doc WITH(NOLOCK) ON ped.DOC_CODI = doc.DOC_CODI	
				LEFT OUTER JOIN PRO_DDOC AS dad WITH(NOLOCK) ON adi.DUC_EANO = dad.DUC_EANO AND adi.DUC_PNUM = dad.DUC_PNUM AND adi.DUA_CODI = dad.DUA_CODI AND doc.DOC_CODI = dad.DOC_CODI AND dad.DDO_AUTO = 10				
			WHERE doc.DOC_DESP = 1 AND doc.DOC_DTRA = 0 AND LEN(doc.DOC_CODI) <= 4 AND dad.DDO_IDEN IS NULL
		OPEN Pedidos
		FETCH NEXT FROM Pedidos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento, @NumeroDocumento
		WHILE @@FETCH_STATUS = 0
		BEGIN
-- obtem o próximo numero de registo de documentos da adição IMP-CAU
			SELECT @NumProxRegisto = ISNULL(MAX(DDO_CODI), 0) + 1
			FROM PRO_DDOC
			WHERE DUC_EANO = @AnoDeclaracao AND DUC_PNUM = @NumDeclaracao AND DUA_CODI = @NumAdicao
-- insere o documento no detalhe de documentos da adição IMP-CAU
			INSERT INTO PRO_DDOC(DUC_EANO, DUC_PNUM, DUA_CODI, DDO_CODI, DOC_CODI, DOC_NOME, DDO_NUME, DDO_AUTO, DDO_TIPO)
			VALUES(@AnoDeclaracao, @NumDeclaracao, @NumAdicao, @NumProxRegisto, @CodDocumento, @NomeDocumento, @NumeroDocumento, 10, @TipoDocumento)				
			FETCH NEXT FROM Pedidos INTO @AnoDeclaracao, @NumDeclaracao, @NumAdicao, @CodDocumento, @NomeDocumento, @TipoDocumento, @NumeroDocumento
		END
		CLOSE Pedidos
		DEALLOCATE Pedidos	
	END
END

ALTER TABLE [dbo].[tb_IMP_DeclaracoesAdicoesPedidos] ENABLE TRIGGER [tr_IMP_DeclaracoesAdicoesPedidos_Regras_IU]

INSERT INTO TAB_PAPL(PAP_CODI, PAI_CODI, PAP_TAXA, PAP_TXIS, RRE_CDIS, PAP_TXRD, RRE_CDRD, PAP_TXIN, RRE_CDIN, PAP_TXRN, RRE_CDNR, PAP_VRET, PAP_VERS)
VALUES(1, 'EU', 1, 0, 319, 6, 521, 13, 524, 23, 522, 0, '17.4')
GO