/****** Object:  StoredProcedure [dbo].[paWcfUpdateKmVehs]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfUpdateKmVehs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfUpdateKmVehs]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeUpdateItemTrn_TraEspPrograma]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeUpdateItemTrn_TraEspPrograma]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeUpdateItemTrn_TraEspPrograma]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_VencimientosDoc]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_VencimientosDoc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_VencimientosDoc]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_VenceAbonos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_VenceAbonos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_VenceAbonos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspReservasRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspReservasRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspReservasRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspReservasRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspReservasRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspReservasRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspReservasFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspReservasFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspReservasFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspProgramaPers]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspProgramaPers]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspProgramaPers]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPgrRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspPgrRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPgrRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPgrRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspPgrRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPgrRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPgrFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspPgrFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPgrFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPedidoRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspPedidoRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPedidoRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPedidoRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspPedidoRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPedidoRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPedidoFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspPedidoFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPedidoFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOtroSiRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspOtroSiRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOtroSiRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOtroSiFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspOtroSiFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOtroSiFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOrdPagoFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspOrdPagoFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOrdPagoFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOrdenPagoLta]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspOrdenPagoLta]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOrdenPagoLta]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOPagoRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspOPagoRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOPagoRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDetRen]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspOPagoNetoDetRen]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDetRen]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspOPagoNetoDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspNovResFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspNovResFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspNovResFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspListaPasaResFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspListaPasaResFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspListaPasaResFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspListaPasaFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspListaPasaFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspListaPasaFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspLiquidaRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaOtrFmtCauDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspLiquidaOtrFmtCauDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaOtrFmtCauDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspLiquidaFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaEgrFac]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspLiquidaEgrFac]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaEgrFac]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaDedFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspLiquidaDedFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaDedFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspGenRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspGenRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspGenRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspGenRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspGenRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspGenRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspFuecRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspFuecRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspFuecFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecCond]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspFuecCond]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecCond]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFacturasRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspFacturasRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFacturasRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFacturasRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspFacturasRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFacturasRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFacturaFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspFacturaFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFacturaFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevOdpRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevOdpRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevOdpRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevOdpFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevOdpFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevOdpFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevLiquidaFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevLiquidaFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevLiquidaFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevLiqRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevLiqRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevLiqRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevLiq]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevLiq]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevLiq]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevGenRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevGenRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevGenRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevFacturasRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevFacturasRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevFacturasRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevFacFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevFacFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevFacFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevCumFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevCumFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevCumFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevCauRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevCauRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevCauRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevAntRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspDevAntRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevAntRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCumplidosFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspCumplidosFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCumplidosFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspContratoRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspContratoRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspContratoRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspContratoRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspContratoRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspContratoRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspContratoFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspContratoFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspContratoFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspComFacturaNit]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspComFacturaNit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspComFacturaNit]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCausacionLiq]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspCausacionLiq]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCausacionLiq]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCauRelDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspCauRelDet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCauRelDet]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCauRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspCauRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCauRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspAnticiposRel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspAnticiposRel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspAnticiposRel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspAntAbonos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLisTrn_TraEspAntAbonos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLisTrn_TraEspAntAbonos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLis_VehiculosPza]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLis_VehiculosPza]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLis_VehiculosPza]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLis_NovPgr]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLis_NovPgr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLis_NovPgr]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLis_DirTe]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeLis_DirTe]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeLis_DirTe]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehPropietarios]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsVehPropietarios]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsVehPropietarios]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehPolizas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsVehPolizas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsVehPolizas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehiculos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsVehiculos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehConductores]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsVehConductores]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsVehConductores]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVeh_Contrato]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsVeh_Contrato]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsVeh_Contrato]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsUpdateEstadoItem]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsUpdateEstadoItem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsUpdateEstadoItem]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehTraspasos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_VehTraspasos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_VehTraspasos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehNumOrden]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_VehNumOrden]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_VehNumOrden]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehLecturas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_VehLecturas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_VehLecturas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehConductor]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_VehConductor]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_VehConductor]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspSedes]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspSedes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspSedes]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspReservas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspReservas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspReservas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPrograma]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspPrograma]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPrograma]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPicoPlaca]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspPicoPlaca]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPicoPlaca]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPedido]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspPedido]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPedido]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPasajeros]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspPasajeros]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPasajeros]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspOtroSi]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspOtroSi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspOtroSi]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspOrdenPagoGIE]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspOrdenPagoGIE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspOrdenPagoGIE]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspOrdenPago]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspOrdenPago]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspOrdenPago]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspLiquida]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspLiquida]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspLiquida]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspFuec]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspFuec]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspFuec]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevOdpGIE]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspDevOdpGIE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevOdpGIE]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevOdp]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspDevOdp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevOdp]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevLiq]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspDevLiq]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevLiq]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevCum]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspDevCum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevCum]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevCau]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspDevCau]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevCau]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevAnt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspDevAnt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevAnt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspCumplido]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspCumplido]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspCumplido]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspContratos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspContratos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspContratos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspConceptos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspConceptos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspConceptos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspCausacion]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspCausacion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspCausacion]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspAnticipos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_TraEspAnticipos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_TraEspAnticipos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_FcSemanas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_FcSemanas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_FcSemanas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_Facturas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_Facturas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_Facturas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_Factcon]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_Factcon]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_Factcon]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_DevFcr]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_DevFcr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_DevFcr]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_DevFco]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_DevFco]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_DevFco]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_Aprobacion]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTrn_Aprobacion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTrn_Aprobacion]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraFijos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTraFijos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTraFijos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspPolizas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTraEspPolizas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTraEspPolizas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspObjContratos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTraEspObjContratos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTraEspObjContratos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspHorario]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTraEspHorario]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTraEspHorario]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspGruposCol]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTraEspGruposCol]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTraEspGruposCol]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspColegios]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTraEspColegios]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTraEspColegios]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraConcCausac]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTraConcCausac]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTraConcCausac]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposVehFactor]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposVehFactor]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposVehFactor]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposVeh]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposVeh]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposVeh]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposPpt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposPpt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposPpt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposOperac]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposOperac]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposOperac]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposNovPgr]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposNovPgr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposNovPgr]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposNivs]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposNivs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposNivs]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposMot]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposMot]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposMot]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposMod]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposMod]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposMod]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposLub]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposLub]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposLub]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposLla]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposLla]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposLla]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposFuel]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposFuel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposFuel]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposDocumentos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposDocumentos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposDocumentos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCon]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposCon]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposCon]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposComFmt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposComFmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposComFmt]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCol]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposCol]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposCol]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCatLic]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposCatLic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposCatLic]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCalendarPgr]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposCalendarPgr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposCalendarPgr]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposAdm]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTiposAdm]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTiposAdm]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercPropietario]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTercPropietario]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTercPropietario]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTerceros]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTerceros]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTerceros]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndtores]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTercCndtores]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTercCndtores]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndTarjetas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTercCndTarjetas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTercCndTarjetas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndReferencias]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTercCndReferencias]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTercCndReferencias]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndDoc]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTercCndDoc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTercCndDoc]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndContrato]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTercCndContrato]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTercCndContrato]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndCapac]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTercCndCapac]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTercCndCapac]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTarifasEsp]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTarifasEsp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTarifasEsp]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTablaPor]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsTablaPor]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsTablaPor]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Security]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_Security]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_Security]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Report]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_Report]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Modulos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_Modulos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_Modulos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_GruposUsu]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_GruposUsu]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_GruposUsu]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_FmtDoc]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_FmtDoc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_FmtDoc]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Estaciones]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_Estaciones]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_Estaciones]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Cnxextna]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_Cnxextna]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_Cnxextna]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Autoriza]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsSys_Autoriza]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsSys_Autoriza]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsRutas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsRutas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsRutas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsPreFacturas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsPreFacturas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsPreFacturas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsOtroSiFromCOE]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsOtroSiFromCOE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsOtroSiFromCOE]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvTrn_Facturas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMsvTrn_Facturas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMsvTrn_Facturas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvTrn_DevFcr]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMsvTrn_DevFcr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMsvTrn_DevFcr]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvPrograma]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMsvPrograma]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMsvPrograma]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvOrdenPago]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMsvOrdenPago]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMsvOrdenPago]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvLiquidacion]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMsvLiquidacion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMsvLiquidacion]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvFuec]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMsvFuec]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMsvFuec]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMarcasLin]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMarcasLin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMarcasLin]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMarcas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsMarcas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsMarcas]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsLocalidades]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsLocalidades]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsLocalidades]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsListaPasaResProceso]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsListaPasaResProceso]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsListaPasaResProceso]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsListaPasaRes]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsListaPasaRes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsListaPasaRes]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsListaPasajeros]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsListaPasajeros]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsListaPasajeros]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsGruposRot]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsGruposRot]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsGruposRot]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsGruposPro]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsGruposPro]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsGruposPro]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsGruposCli]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsGruposCli]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsGruposCli]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsExpLicencias]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsExpLicencias]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsExpLicencias]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEstadoVeh]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsEstadoVeh]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsEstadoVeh]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEstadoTer]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsEstadoTer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsEstadoTer]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEstadoDoc]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsEstadoDoc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsEstadoDoc]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEdsServicio]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsEdsServicio]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsEdsServicio]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsDocConceptos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsDocConceptos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsDocConceptos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsDepartamentos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsDepartamentos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsDepartamentos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsConceptosFijos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsConceptosFijos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsConceptosFijos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsConceptosDiv]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsConceptosDiv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsConceptosDiv]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCompanias]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsCompanias]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsCompanias]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClasePol]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsClasePol]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsClasePol]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseDocCond]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsClaseDocCond]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsClaseDocCond]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseDiv]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsClaseDiv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsClaseDiv]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseCta]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsClaseCta]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsClaseCta]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseCapac]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsClaseCapac]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsClaseCapac]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCentrosServ]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsCentrosServ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsCentrosServ]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCargos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsCargos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsCargos]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCalndario]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsCalndario]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsCalndario]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsadm_Usuarios]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsadm_Usuarios]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsadm_Usuarios]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsadm_Registro]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsadm_Registro]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsadm_Registro]
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsadm_Opciones]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfSeInsadm_Opciones]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfSeInsadm_Opciones]
GO
/****** Object:  StoredProcedure [dbo].[paWcfGetCTraFijos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[paWcfGetCTraFijos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[paWcfGetCTraFijos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehPropietarios]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeVehPropietarios' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeVehPropietarios]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehPolizas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeVehPolizas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeVehPolizas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehiculos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeVehiculos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeVehiculos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehConductores]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeVehConductores' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeVehConductores]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehAnexo]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeVehAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeVehAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVeh_Contrato]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeVeh_Contrato' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeVeh_Contrato]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeUpdateKmVehs]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeUpdateKmVehs' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeUpdateKmVehs]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Vencimientos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Vencimientos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Vencimientos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VencAbonos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_VencAbonos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_VencAbonos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehTraspasos]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_VehTraspasos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_VehTraspasos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehNumOrden]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_VehNumOrden' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_VehNumOrden]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehLecturas]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_VehLecturas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_VehLecturas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehConductor]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_VehConductor' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_VehConductor]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraTurn]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraTurn' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraTurn]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraTraslados]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraTraslados' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraTraslados]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraTrasladoRem]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraTrasladoRem' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraTrasladoRem]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraReportes]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraReportes' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraReportes]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemMcias]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraRemMcias' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraRemMcias]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemesa]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraRemesa' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraRemesa]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemCntdor]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraRemCntdor' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraRemCntdor]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemAnexo]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraRemAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraRemAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraPedMcias]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraPedMcias' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraPedMcias]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraPedido]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraPedido' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraPedido]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraPedAnexo]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraPedAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraPedAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenServ]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraOrdenServ' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraOrdenServ]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenOper]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraOrdenOper' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraOrdenOper]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraOrdenDet' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraOrdenDet]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenCumDet]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraOrdenCumDet' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraOrdenCumDet]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenCum]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraOrdenCum' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraOrdenCum]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenAnt]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraOrdenAnt' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraOrdenAnt]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenAbo]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraOrdenAbo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraOrdenAbo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraManifRem]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraManifRem' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraManifRem]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraManifiesto]    Script Date: 13/07/2021 10:39:13 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraManifiesto' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraManifiesto]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraManifAnexo]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraManifAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraManifAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraInfViajesOrd]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraInfViajesOrd' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraInfViajesOrd]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraInfViajes]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraInfViajes' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraInfViajes]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspSedes]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspSedes' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspSedes]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspReservaVehLista]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspReservaVehLista' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspReservaVehLista]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspReservas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspReservas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspReservas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspResDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspResDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspResDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspResAnexo]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspResAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspResAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspProgramaPers]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspProgramaPers' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspProgramaPers]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspProgramaDet]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspProgramaDet' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspProgramaDet]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPrograma]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspPrograma' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspPrograma]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPicoPlaca]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspPicoPlaca' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspPicoPlaca]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPedido]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspPedido' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspPedido]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPedDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspPedDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspPedDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPedAnexo]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspPedAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspPedAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPasajeros]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspPasajeros' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspPasajeros]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOtroSiContratos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspOtroSiContratos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspOtroSiContratos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOtroSi]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspOtroSi' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspOtroSi]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOrdenReservas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspOrdenReservas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspOrdenReservas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOrdenProg]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspOrdenProg' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspOrdenProg]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOrdenPago]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspOrdenPago' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspOrdenPago]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspListaPasajeros]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspListaPasajeros' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspListaPasajeros]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquidaOtr]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspLiquidaOtr' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspLiquidaOtr]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquidaOdp]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspLiquidaOdp' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspLiquidaOdp]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquidaDed]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspLiquidaDed' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspLiquidaDed]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquida]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspLiquida' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspLiquida]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuecDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspFuecDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspFuecDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuecCndtores]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspFuecCndtores' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspFuecCndtores]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuecAnexo]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspFuecAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspFuecAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuec]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspFuec' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspFuec]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFacResVehiculos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspFacResVehiculos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspFacResVehiculos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFacReservas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspFacReservas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspFacReservas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevOdp]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspDevOdp' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspDevOdp]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevLiq]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspDevLiq' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspDevLiq]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevCum]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspDevCum' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspDevCum]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevCau]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspDevCau' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspDevCau]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevAnt]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspDevAnt' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspDevAnt]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumReservas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspCumReservas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspCumReservas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumplidoProg]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspCumplidoProg' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspCumplidoProg]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumplido]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspCumplido' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspCumplido]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumFacturas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspCumFacturas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspCumFacturas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoVehLista]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspContratoVehLista' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspContratoVehLista]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspContratos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspContratos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoDet]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspContratoDet' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspContratoDet]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoAnexo]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspContratoAnexo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspContratoAnexo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoAdendos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspContratoAdendos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspContratoAdendos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspConceptos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspConceptos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspConceptos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCausacion]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspCausacion' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspCausacion]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCauDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspCauDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspCauDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspAuxFactura]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspAuxFactura' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspAuxFactura]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspAnticipos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspAnticipos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspAnticipos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspAntAbonos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraEspAntAbonos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraEspAntAbonos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevCum]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraDevCum' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraDevCum]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevCos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraDevCos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraDevCos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevAos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraDevAos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraDevAos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevAnt]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraDevAnt' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraDevAnt]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDespProgram]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraDespProgram' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraDespProgram]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDespachos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraDespachos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraDespachos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumRemesas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraCumRemesas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraCumRemesas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumRadica]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraCumRadica' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraCumRadica]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumRadDoc]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraCumRadDoc' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraCumRadDoc]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumplido]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraCumplido' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraCumplido]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraConceptos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraConceptos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraConceptos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraAnticipos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraAnticipos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraAnticipos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraAntAbonos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_TraAntAbonos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_TraAntAbonos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_RecAfavor]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_RecAfavor' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_RecAfavor]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Pagos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Pagos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Pagos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_NiifDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_NiifDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_NiifDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_NiifCompFMsv]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_NiifCompFMsv' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_NiifCompFMsv]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_NiifComp]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_NiifComp' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_NiifComp]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Kardex]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Kardex' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Kardex]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_FcSemanas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_FcSemanas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_FcSemanas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Facturas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Facturas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Facturas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Factcon]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Factcon' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Factcon]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_EgrFactura]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_EgrFactura' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_EgrFactura]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DocMemo]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_DocMemo' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_DocMemo]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DevFcr]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_DevFcr' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_DevFcr]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DevFco]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_DevFco' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_DevFco]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DetCuentas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_DetCuentas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_DetCuentas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Comprobantes]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Comprobantes' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Comprobantes]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_ComFactura]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_ComFactura' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_ComFactura]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_ComDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_ComDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_ComDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Autoriza]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Autoriza' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Autoriza]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Aprobacion]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTrn_Aprobacion' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTrn_Aprobacion]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraFijos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraFijos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraFijos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspPolizas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraEspPolizas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraEspPolizas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspPolDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraEspPolDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraEspPolDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspObjContratos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraEspObjContratos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraEspObjContratos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspHorario]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraEspHorario' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraEspHorario]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspGruposCol]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraEspGruposCol' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraEspGruposCol]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspColegios]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraEspColegios' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraEspColegios]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraConcCausac]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTraConcCausac' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTraConcCausac]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposVehFactor]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposVehFactor' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposVehFactor]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposVeh]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposVeh' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposVeh]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposPpt]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposPpt' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposPpt]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposOperac]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposOperac' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposOperac]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposNovPgr]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposNovPgr' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposNovPgr]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposNivs]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposNivs' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposNivs]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposMot]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposMot' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposMot]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposMod]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposMod' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposMod]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposLub]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposLub' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposLub]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposLla]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposLla' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposLla]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposFuel]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposFuel' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposFuel]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposDocCons]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposDocCons' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposDocCons]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCon]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposCon' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposCon]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposComFmt]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposComFmt' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposComFmt]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCol]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposCol' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposCol]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCatLic]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposCatLic' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposCatLic]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCalendarPgr]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposCalendarPgr' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposCalendarPgr]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposAdm]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTiposAdm' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTiposAdm]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercPropietario]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTercPropietario' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTercPropietario]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTerceros]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTerceros' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTerceros]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndtores]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTercCndtores' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTercCndtores]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndTarjetas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTercCndTarjetas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTercCndTarjetas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndReferencias]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTercCndReferencias' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTercCndReferencias]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndDoc]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTercCndDoc' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTercCndDoc]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndContrato]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTercCndContrato' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTercCndContrato]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndCapac]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTercCndCapac' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTercCndCapac]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTarifasEsp]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTarifasEsp' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTarifasEsp]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTablaPor]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeTablaPor' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeTablaPor]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_TiposDocCue]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_TiposDocCue' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_TiposDocCue]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_TiposDoc]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_TiposDoc' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_TiposDoc]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Security]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_Security' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_Security]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Report]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_Report' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_Report]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Modulos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_Modulos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_Modulos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_GruposUsu]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_GruposUsu' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_GruposUsu]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_FmtDoc]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_FmtDoc' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_FmtDoc]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Estaciones]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_Estaciones' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_Estaciones]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Cnxextna]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_Cnxextna' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_Cnxextna]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Autoriza]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeSys_Autoriza' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeSys_Autoriza]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasTramos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeRutasTramos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeRutasTramos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasRecorridos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeRutasRecorridos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeRutasRecorridos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasPlan]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeRutasPlan' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeRutasPlan]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasCliente]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeRutasCliente' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeRutasCliente]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeRutas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeRutas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRuta]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeRuta' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeRuta]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeNiifDetalle]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeNiifDetalle' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeNiifDetalle]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeNiifComp]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeNiifComp' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeNiifComp]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeMcia]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeMcia' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeMcia]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeMarcasLin]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeMarcasLin' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeMarcasLin]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeMarcas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeMarcas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeMarcas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeLocalidades]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeLocalidades' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeLocalidades]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeListaPasaResProceso]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeListaPasaResProceso' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeListaPasaResProceso]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeGruposRot]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeGruposRot' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeGruposRot]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeGruposPro]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeGruposPro' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeGruposPro]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeGruposCli]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeGruposCli' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeGruposCli]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos_Veh]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeFijos_Veh' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeFijos_Veh]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos_Cue]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeFijos_Cue' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeFijos_Cue]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos_Cla]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeFijos_Cla' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeFijos_Cla]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeFijos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeFijos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeExpLicencias]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeExpLicencias' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeExpLicencias]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEstadoVeh]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeEstadoVeh' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeEstadoVeh]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEstadoTer]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeEstadoTer' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeEstadoTer]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEstadoDoc]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeEstadoDoc' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeEstadoDoc]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEdsServicio]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeEdsServicio' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeEdsServicio]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeDepartamentos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeDepartamentos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeDepartamentos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCumRemesas]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeCumRemesas' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeCumRemesas]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConceptosCue]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeConceptosCue' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeConceptosCue]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConceptosCia]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeConceptosCia' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeConceptosCia]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConceptos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeConceptos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeConceptos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConcDiversos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeConcDiversos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeConcDiversos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConcDivCue]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeConcDivCue' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeConcDivCue]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConcDivCia]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeConcDivCia' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeConcDivCia]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCompanias]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeCompanias' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeCompanias]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClieContado]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeClieContado' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeClieContado]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClasePol]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeClasePol' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeClasePol]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseDocCond]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeClaseDocCond' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeClaseDocCond]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseDiv]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeClaseDiv' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeClaseDiv]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseCta]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeClaseCta' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeClaseCta]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseCapac]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeClaseCapac' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeClaseCapac]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCentrosServ]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeCentrosServ' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeCentrosServ]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCargos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeCargos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeCargos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCalndario]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeCalndario' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeCalndario]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Usuarios]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeadm_Usuarios' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeadm_Usuarios]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_UOpciones]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeadm_UOpciones' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeadm_UOpciones]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Registro]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeadm_Registro' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeadm_Registro]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_PermisosRoles]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeadm_PermisosRoles' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeadm_PermisosRoles]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Permisos]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeadm_Permisos' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeadm_Permisos]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Opciones]    Script Date: 13/07/2021 10:39:14 ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'dataTypeadm_Opciones' AND ss.name = N'dbo')
DROP TYPE [dbo].[dataTypeadm_Opciones]
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Opciones]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeadm_Opciones] AS TABLE(
	[IdOpc] [varchar](3) NULL,
	[Opcion] [varchar](100) NULL,
	[TipoDato] [varchar](15) NULL,
	[Valor] [varchar](100) NULL,
	[NivUp] [int] NULL,
	[nModulo] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Permisos]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeadm_Permisos] AS TABLE(
	[IdUsuario] [varchar](11) NULL,
	[IdObj] [varchar](10) NULL,
	[Consecutivo] [int] NULL,
	[PerAdd] [bit] NULL,
	[PerUpdate] [bit] NULL,
	[PerDelete] [bit] NULL,
	[PerAnular] [bit] NULL,
	[PerRead] [bit] NULL,
	[PerRename] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_PermisosRoles]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeadm_PermisosRoles] AS TABLE(
	[IdUsuario] [varchar](11) NULL,
	[IdObj] [varchar](10) NULL,
	[IdRole] [varchar](3) NULL,
	[Asignado] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Registro]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeadm_Registro] AS TABLE(
	[IdCia] [char](2) NULL,
	[TipoId] [char](1) NULL,
	[IdEmpresa] [varchar](16) NULL,
	[NitEmpresa] [varchar](16) NULL,
	[DvNit] [char](1) NULL,
	[RazonSocial] [varchar](250) NULL,
	[NitRepLegal] [varchar](16) NULL,
	[RepLegal] [varchar](150) NULL,
	[Descripcion] [varchar](250) NULL,
	[Direccion] [varchar](250) NULL,
	[Telefono] [varchar](20) NULL,
	[Fax] [varchar](20) NULL,
	[IdLocal] [varchar](8) NULL,
	[IdPais] [varchar](8) NULL,
	[e_mail] [varchar](100) NULL,
	[ArchivoLogo] [varchar](30) NULL,
	[NumeroSerial] [varchar](80) NULL,
	[Regimen] [varchar](50) NULL,
	[TipoPersna] [char](1) NULL,
	[Licencia] [varchar](20) NULL,
	[VigenciaLic] [smalldatetime] NULL,
	[Personeria] [varchar](40) NULL,
	[CIIUDane] [varchar](8) NULL,
	[Leyenda] [varchar](250) NULL,
	[FechaRegistro] [smalldatetime] NULL,
	[FechaVence] [smalldatetime] NULL,
	[CurrtyDate] [smalldatetime] NULL,
	[CurDate1] [smalldatetime] NULL,
	[FechaPrest] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_UOpciones]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeadm_UOpciones] AS TABLE(
	[IdUsuario] [varchar](11) NULL,
	[NomOpcion] [varchar](20) NULL,
	[Valor] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeadm_Usuarios]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeadm_Usuarios] AS TABLE(
	[IdUsuario] [varchar](11) NULL,
	[Usuario] [varchar](50) NULL,
	[PwdLog] [varchar](30) NULL,
	[IdGrupo] [int] NULL,
	[IdEstacion] [char](2) NULL,
	[IdCargo] [varchar](4) NULL,
	[Conectado] [bit] NULL,
	[FechaAcc] [smalldatetime] NULL,
	[FechaClave] [smalldatetime] NULL,
	[Caducidad] [int] NULL,
	[LoginSQL] [varchar](20) NULL,
	[PwdSQL] [varchar](20) NULL,
	[ModoSQL] [varchar](3) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCalndario]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeCalndario] AS TABLE(
	[FechaDia] [smalldatetime] NULL,
	[TipoFtvo] [varchar](3) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCargos]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeCargos] AS TABLE(
	[IdCargo] [varchar](4) NOT NULL,
	[Cargo] [varchar](50) NULL,
	[Funciones] [varchar](3000) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCentrosServ]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeCentrosServ] AS TABLE(
	[IdCenSer] [varchar](4) NULL,
	[CentroServ] [varchar](50) NULL,
	[DirCentro] [varchar](100) NULL,
	[IdLocal] [varchar](8) NULL,
	[Telefonos] [varchar](30) NULL,
	[TipoCentro] [varchar](10) NULL,
	[NitResp] [varchar](16) NULL,
	[Respnsable] [varchar](150) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseCapac]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeClaseCapac] AS TABLE(
	[IdClase] [varchar](4) NULL,
	[NomClase] [varchar](150) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseCta]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeClaseCta] AS TABLE(
	[IdClase] [varchar](4) NULL,
	[ClaseCuenta] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseDiv]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeClaseDiv] AS TABLE(
	[IdClase] [varchar](4) NULL,
	[NomClase] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClaseDocCond]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeClaseDocCond] AS TABLE(
	[IdDoc] [varchar](4) NULL,
	[Documento] [varchar](150) NULL,
	[Vigencia] [bit] NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClasePol]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeClasePol] AS TABLE(
	[IdClase] [varchar](4) NULL,
	[ClasePoliza] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeClieContado]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeClieContado] AS TABLE(
	[IdCliente] [varchar](16) NOT NULL,
	[Nombre] [varchar](150) NOT NULL,
	[TipoId] [char](1) NOT NULL,
	[Dv] [char](1) NULL,
	[Direccion] [varchar](150) NULL,
	[IdLocal] [varchar](8) NOT NULL,
	[Telefono] [varchar](20) NOT NULL,
	[email] [varchar](100) NULL,
	[Excento] [bit] NOT NULL,
	[PosIniNom] [int] NOT NULL,
	[Inactivo] [bit] NOT NULL,
	[FechaAdd] [smalldatetime] NOT NULL,
	[FechaUpdate] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCompanias]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeCompanias] AS TABLE(
	[IdCia] [char](2) NULL,
	[Compania] [varchar](50) NULL,
	[DirInterface] [varchar](255) NULL,
	[FechaActual] [smalldatetime] NULL,
	[PeriodoActual] [smalldatetime] NULL,
	[IdCCosto] [varchar](16) NULL,
	[IdSubCos] [varchar](16) NULL,
	[IdTercero] [varchar](16) NULL,
	[CodSucsal] [varchar](10) NULL,
	[DireccSuc] [varchar](250) NULL,
	[TelefSuc] [varchar](20) NULL,
	[FaxSuc] [varchar](20) NULL,
	[IdLocal] [varchar](8) NULL,
	[TipoEDS] [varchar](10) NULL,
	[CodPlanta] [varchar](20) NULL,
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[Inactivo] [bit] NULL,
	[CodBodega] [varchar](4) NULL,
	[FecModPrest] [smalldatetime] NULL,
	[AutoIca] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConcDivCia]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeConcDivCia] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[IdCia] [char](2) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConcDivCue]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeConcDivCue] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[IdClase] [varchar](4) NULL,
	[IdCuenta] [varchar](16) NULL,
	[CdCueDev] [varchar](16) NULL,
	[TipoMov] [char](1) NULL,
	[TipoTerc] [char](1) NULL,
	[FecAdd] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConcDiversos]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeConcDiversos] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[Concepto] [varchar](250) NULL,
	[Grupo] [varchar](20) NULL,
	[EsServicio] [bit] NULL,
	[DeManfsto] [bit] NULL,
	[CdIva] [varchar](4) NULL,
	[CdRet] [varchar](4) NULL,
	[CdIca] [varchar](4) NULL,
	[CdAutoret] [varchar](4) NULL,
	[IdCueDeb] [varchar](16) NULL,
	[IdCueCre] [varchar](16) NULL,
	[Inactivo] [bit] NULL,
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL,
	[OrdenServ] [int] NULL,
	[NovedadNom] [bit] NULL,
	[CdConcDeveng] [varchar](4) NULL,
	[CdConcDed] [varchar](4) NULL,
	[RubroConc] [varchar](50) NULL,
	[MudReajuste] [varchar](50) NULL,
	[CodFEDian] [varchar](20) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConceptos]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeConceptos] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[Concepto] [varchar](100) NULL,
	[IdDoc] [varchar](3) NULL,
	[IdCom] [varchar](3) NULL,
	[Vcmto] [bit] NULL,
	[Imptos] [bit] NULL,
	[Retfte] [bit] NULL,
	[RetIca] [bit] NULL,
	[Observacion] [varchar](150) NULL,
	[Pdterminado] [int] NULL,
	[TrfaSanc] [decimal](14, 4) NULL,
	[RndTotal] [int] NULL,
	[DcmtoEquiv] [bit] NULL,
	[Inactivo] [bit] NULL,
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL,
	[TipoContab] [varchar](10) NULL,
	[CdComNiif] [varchar](3) NULL,
	[CdComFiscal] [varchar](3) NULL,
	[CodCiaTdo] [char](2) NULL,
	[TipoConRev] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConceptosCia]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeConceptosCia] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[IdCia] [char](2) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeConceptosCue]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeConceptosCue] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[IdClase] [int] NULL,
	[Descripcion] [varchar](50) NULL,
	[IdCuenta] [varchar](16) NULL,
	[TipoMov] [char](1) NULL,
	[DetalleMov] [varchar](150) NULL,
	[CdCCosto] [varchar](16) NULL,
	[CdSubCos] [varchar](16) NULL,
	[TipoTerc] [char](1) NULL,
	[FecAdd] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeCumRemesas]    Script Date: 13/07/2021 10:39:14 ******/
CREATE TYPE [dbo].[dataTypeCumRemesas] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('CUM'),
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[TipRem] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[Remesa] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRem] [char](2) NOT NULL DEFAULT ('01'),
	[ItemRem] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeDepartamentos]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeDepartamentos] AS TABLE(
	[IdDep] [varchar](8) NULL,
	[Departamento] [varchar](50) NULL,
	[Codigo] [varchar](4) NULL,
	[IdPais] [varchar](8) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEdsServicio]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeEdsServicio] AS TABLE(
	[IdEstacion] [varchar](4) NULL,
	[EstServicio] [varchar](50) NULL,
	[Direccion] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEstadoDoc]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeEstadoDoc] AS TABLE(
	[IdEstado] [varchar](4) NULL,
	[Estado] [varchar](50) NULL,
	[NColor] [int] NULL,
	[CodDcmto] [varchar](3) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEstadoTer]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeEstadoTer] AS TABLE(
	[IdEstado] [varchar](4) NULL,
	[Estado] [varchar](50) NULL,
	[NColor] [int] NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeEstadoVeh]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeEstadoVeh] AS TABLE(
	[IdEstado] [varchar](4) NULL,
	[Estado] [varchar](50) NULL,
	[NColor] [int] NULL,
	[OutDemand] [bit] NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeExpLicencias]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeExpLicencias] AS TABLE(
	[IdLugar] [varchar](8) NULL,
	[LugarLic] [varchar](50) NULL,
	[CodDpto] [varchar](8) NULL,
	[Dpto] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeFijos] AS TABLE(
	[IdCargo] [varchar](4) NULL,
	[Concepto] [varchar](100) NULL,
	[Obligatorio] [bit] NULL DEFAULT ((0)),
	[TipoAplica] [varchar](10) NULL,
	[DiasSemana] [varchar](20) NULL,
	[DiasMes] [varchar](100) NULL,
	[ValorMensual] [money] NULL DEFAULT ((0)),
	[ValorDiario] [money] NULL,
	[IdCuentaDeb] [varchar](16) NULL,
	[IdCuentaCre] [varchar](16) NULL,
	[IdCueDebVp] [varchar](16) NULL,
	[IdCueCreVp] [varchar](16) NULL,
	[NCuotas] [int] NULL DEFAULT ((0)),
	[DiasVcmto] [varchar](50) NULL,
	[OrdenAbono] [int] NULL DEFAULT ((0)),
	[TipoDcto] [char](1) NULL,
	[DctoPpago] [decimal](14, 4) NULL,
	[VrCargoAdic] [money] NULL DEFAULT ((0)),
	[FecLimiteIni] [smalldatetime] NULL,
	[FecLimiteFin] [smalldatetime] NULL,
	[Inactivo] [bit] NULL DEFAULT ((0)),
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos_Cla]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeFijos_Cla] AS TABLE(
	[IdCargo] [varchar](4) NULL,
	[IdClase] [varchar](4) NULL,
	[ValorMensual] [money] NULL,
	[ValorDiario] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos_Cue]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeFijos_Cue] AS TABLE(
	[IdCargo] [varchar](4) NULL,
	[IdAdmon] [varchar](4) NULL,
	[IdCuentaDeb] [varchar](16) NULL,
	[IdCuentaCre] [varchar](16) NULL,
	[IdCueDebVp] [varchar](16) NULL,
	[IdCueCreVp] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeFijos_Veh]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeFijos_Veh] AS TABLE(
	[IdCargo] [varchar](4) NULL,
	[IdVehiculo] [varchar](10) NULL,
	[ValorMensual] [money] NULL,
	[ValorDiario] [money] NULL,
	[Excluir] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeGruposCli]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeGruposCli] AS TABLE(
	[IdGrupo] [varchar](4) NULL,
	[GrupoClie] [varchar](50) NULL,
	[ModApp] [varchar](10) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeGruposPro]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeGruposPro] AS TABLE(
	[IdGrupo] [varchar](4) NULL,
	[GrupoProp] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeGruposRot]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeGruposRot] AS TABLE(
	[IdGrupo] [varchar](4) NULL,
	[GrupoRot] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeListaPasaResProceso]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeListaPasaResProceso] AS TABLE(
	[IdLista] [int] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[ItemRes] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[IdVehiculo] [varchar](10) NULL,
	[Fecha] [datetime] NULL,
	[IdUsuario] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeLocalidades]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeLocalidades] AS TABLE(
	[IdLocal] [varchar](8) NULL,
	[Localidad] [varchar](50) NULL,
	[IdDep] [varchar](8) NULL,
	[TipLocal] [varchar](20) NULL,
	[Dist_Kmt] [decimal](10, 4) NULL,
	[Time_hh] [varchar](8) NULL,
	[DistSede] [decimal](10, 4) NULL,
	[TimeSede] [varchar](8) NULL,
	[CelRow] [decimal](14, 4) NULL,
	[CelCol] [decimal](14, 4) NULL,
	[CodAlias] [varchar](10) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeMarcas]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeMarcas] AS TABLE(
	[IdMarca] [varchar](4) NULL,
	[Marca] [varchar](50) NULL,
	[TipoMarca] [varchar](20) NULL,
	[CodigoMT] [varchar](10) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeMarcasLin]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeMarcasLin] AS TABLE(
	[IdLinea] [varchar](10) NULL,
	[LineaVeh] [varchar](50) NULL,
	[IdMarca] [varchar](4) NULL,
	[CodMT] [varchar](10) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeMcia]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeMcia] AS TABLE(
	[Item] [int] NOT NULL,
	[NitRemite] [varchar](16) NOT NULL,
	[Remitente] [varchar](250) NOT NULL,
	[DirOrigen] [varchar](250) NOT NULL,
	[NitDestntario] [varchar](16) NOT NULL,
	[Destinatario] [varchar](250) NOT NULL,
	[DirDestino] [varchar](250) NOT NULL,
	[SedeRem] [varchar](10) NOT NULL,
	[SedeDest] [varchar](10) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeNiifComp]    Script Date: 13/07/2021 10:39:15 ******/
CREATE TYPE [dbo].[dataTypeNiifComp] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NULL,
	[TipComCont] [varchar](3) NOT NULL,
	[ComprobanteCont] [int] NOT NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[TipoNiif] [varchar](10) NOT NULL DEFAULT ('NIIF'),
	[CtbTipo] [varchar](3) NULL,
	[CtbNumero] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeNiifDetalle]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeNiifDetalle] AS TABLE(
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NULL,
	[IdCuenta] [varchar](16) NULL,
	[Detalle] [varchar](250) NULL,
	[VrDebito] [money] NULL,
	[VrCredito] [money] NULL,
	[IdTercero] [varchar](16) NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdCCosto] [varchar](16) NULL,
	[IdSubCos] [varchar](16) NULL,
	[VrBase] [money] NULL DEFAULT ((0)),
	[TarifaBase] [decimal](14, 4) NULL,
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NULL,
	[CodConce] [varchar](4) NULL,
	[NitDoc] [varchar](16) NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [varchar](15) NULL,
	[IdCiaFac] [char](2) NULL,
	[ItemFac] [int] NULL DEFAULT ((0)),
	[FecVence] [smalldatetime] NULL,
	[CodCta] [varchar](4) NULL,
	[NumCheque] [varchar](20) NULL,
	[Integrado] [bit] NULL,
	[TipoAplica] [char](1) NULL,
	[Consolida] [bit] NULL,
	[CodCargo] [varchar](4) NULL,
	[NitOtros] [varchar](16) NULL,
	[CodSubgpo] [varchar](8) NULL,
	[CiuOrigen] [varchar](8) NULL,
	[CodAgncia] [varchar](16) NULL,
	[VehPropio] [int] NULL,
	[Referncia] [varchar](50) NULL,
	[TipDocRef] [varchar](3) NULL,
	[DocRef] [int] NULL DEFAULT ((0)),
	[IdCiaRef] [char](2) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[CdConcTrib] [varchar](4) NULL,
	[CdTarifTrib] [varchar](4) NULL,
	[NumEstablec] [varchar](20) NULL,
	[PtoEmision] [varchar](20) NULL,
	[Num_Autoriza] [varchar](50) NULL,
	[FechAutoriza] [smalldatetime] NULL,
	[CodCuentaCG] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRuta]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeRuta] AS TABLE(
	[CdRutaTarif] [varchar](4) NOT NULL,
	[IdLocOrigen] [varchar](8) NOT NULL,
	[IdLocDestino] [varchar](8) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutas]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeRutas] AS TABLE(
	[IdRuta] [varchar](20) NULL,
	[Ruta] [varchar](100) NULL,
	[IdLocOri] [varchar](8) NULL,
	[IdLocDes] [varchar](8) NULL,
	[EsLocal] [bit] NULL,
	[Distkmt] [decimal](14, 4) NULL,
	[TmHoras] [varchar](8) NULL,
	[CodigoMt] [varchar](5) NULL,
	[FleteTon] [money] NULL,
	[Inactivo] [bit] NULL,
	[CdCiaTurno] [char](2) NULL,
	[PuntosRut] [decimal](14, 4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasCliente]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeRutasCliente] AS TABLE(
	[IdRuta] [varchar](4) NULL,
	[IdCliente] [varchar](16) NULL,
	[Ruta] [varchar](100) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasPlan]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeRutasPlan] AS TABLE(
	[IdRuta] [varchar](4) NULL,
	[IdPunto] [int] NULL,
	[Descripcion] [varchar](100) NULL,
	[Distancia] [decimal](14, 4) NULL,
	[Tiempo] [varchar](8) NULL,
	[ClasePto] [varchar](10) NULL,
	[CdPto] [varchar](4) NULL,
	[IdLocal] [varchar](8) NULL,
	[PosLat] [decimal](14, 4) NULL,
	[PosLon] [decimal](14, 4) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasRecorridos]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeRutasRecorridos] AS TABLE(
	[IdRuta] [varchar](4) NULL,
	[NumTramo] [int] NULL DEFAULT ((0)),
	[IdLocal] [varchar](8) NULL,
	[Detalle] [varchar](1000) NULL,
	[kmstramo] [decimal](14, 4) NULL DEFAULT ((0)),
	[kmstotal] [decimal](14, 4) NULL DEFAULT ((0)),
	[Alterno] [bit] NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeRutasTramos]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeRutasTramos] AS TABLE(
	[IdRuta] [varchar](4) NULL,
	[NumTramo] [int] NULL,
	[IdLocal] [varchar](8) NULL,
	[kmstramo] [decimal](14, 4) NULL,
	[kmstotal] [decimal](14, 4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Autoriza]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_Autoriza] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[ConceptoAut] [varchar](150) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Cnxextna]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_Cnxextna] AS TABLE(
	[IdReg] [int] NULL,
	[CnxTipo] [varchar](10) NULL,
	[CnxEngine] [varchar](10) NULL,
	[CnxDso] [varchar](250) NULL,
	[CnxDbname] [varchar](50) NULL,
	[CnxAutentic] [varchar](3) NULL,
	[CnxUid] [varchar](50) NULL,
	[CnxPwd] [varchar](50) NULL,
	[CnxOwner] [varchar](20) NULL,
	[CnxPpties] [varchar](250) NULL,
	[CnxObserv] [varchar](250) NULL,
	[CnxDriver] [varchar](100) NULL,
	[CnxPort] [varchar](30) NULL,
	[CnxTerminal] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Estaciones]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_Estaciones] AS TABLE(
	[IdEstacion] [char](2) NOT NULL,
	[Estacion] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_FmtDoc]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_FmtDoc] AS TABLE(
	[IdDoc] [varchar](3) NULL,
	[IdForma] [char](2) NULL,
	[Descripcion] [varchar](100) NULL,
	[Formato] [varchar](20) NULL,
	[Predtmnado] [bit] NULL,
	[TipoPapel] [int] NULL,
	[Orientacion] [int] NULL,
	[VistaPrevia] [bit] NULL,
	[VerSetup] [bit] NULL,
	[NumCopias] [int] NULL,
	[sp_Nombre] [varchar](50) NULL,
	[Ind_Location] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_GruposUsu]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_GruposUsu] AS TABLE(
	[IdGrupo] [int] NOT NULL DEFAULT ((0)),
	[Grupo] [varchar](50) NULL,
	[Descripcion] [varchar](100) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Modulos]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_Modulos] AS TABLE(
	[IdMod] [varchar](3) NULL,
	[Consecutivo] [int] NULL,
	[Descripcion] [varchar](50) NULL,
	[Valor] [bit] NULL,
	[nModulo] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Report]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_Report] AS TABLE(
	[TipoRep] [varchar](3) NULL,
	[IdRep] [char](2) NULL,
	[Descripcion] [varchar](100) NULL,
	[Formato] [varchar](20) NULL,
	[TipoPapel] [int] NULL,
	[Orientacion] [int] NULL,
	[VistaPrevia] [bit] NULL,
	[VerSetup] [bit] NULL,
	[NumCopias] [int] NULL,
	[sp_Nombre] [varchar](50) NULL,
	[Ind_Location] [varchar](50) NULL,
	[NomRep] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_Security]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_Security] AS TABLE(
	[IdLla] [int] NULL DEFAULT ((0)),
	[Descripcion] [varchar](50) NULL,
	[Pwd] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_TiposDoc]    Script Date: 13/07/2021 10:39:16 ******/
CREATE TYPE [dbo].[dataTypeSys_TiposDoc] AS TABLE(
	[IdDoc] [varchar](3) NULL,
	[TipoDoc] [varchar](50) NULL,
	[ConsUnico] [bit] NULL DEFAULT ((0)),
	[Leyenda] [varchar](250) NULL,
	[Inactivo] [bit] NULL DEFAULT ((0)),
	[IntegraCias] [bit] NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeSys_TiposDocCue]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeSys_TiposDocCue] AS TABLE(
	[IdDoc] [varchar](3) NULL,
	[IdClase] [int] NULL DEFAULT ((0)),
	[ClaseCuenta] [varchar](50) NULL,
	[TipoMov] [char](1) NULL DEFAULT ('N')
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTablaPor]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTablaPor] AS TABLE(
	[IdTarifa] [varchar](4) NULL,
	[Descripcion] [varchar](50) NULL,
	[IdClase] [varchar](4) NULL,
	[Tarifa] [decimal](16, 6) NULL,
	[Simbolo] [char](1) NULL,
	[CdLocdad] [varchar](8) NULL,
	[Minimo] [money] NULL,
	[Maximo] [money] NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTarifasEsp]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTarifasEsp] AS TABLE(
	[Numero] [int] NULL,
	[CdRuta] [varchar](4) NULL,
	[IdOrigen] [varchar](8) NULL,
	[IdDestino] [varchar](8) NULL,
	[TipoTarifa] [varchar](10) NULL,
	[CdTipoVeh] [varchar](4) NULL,
	[TipAfilVeh] [varchar](10) NULL,
	[Kilometros] [decimal](16, 4) NULL,
	[TarifClie] [money] NULL,
	[TarifPago] [money] NULL,
	[IdMneda] [varchar](5) NULL,
	[Inactivo] [bit] NULL DEFAULT ((0)),
	[FechaCrea] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL,
	[VrDia] [money] NULL,
	[Horas] [int] NULL,
	[Nit] [varchar](16) NULL,
	[VrMonitor] [decimal](18, 0) NULL,
	[TarifaXRuta] [bit] NULL DEFAULT ((1))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndCapac]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTercCndCapac] AS TABLE(
	[IdConductor] [varchar](16) NULL,
	[Item] [int] NULL,
	[IdClase] [varchar](4) NULL,
	[Fecha] [smalldatetime] NULL,
	[FecVence] [smalldatetime] NULL,
	[Habilitado] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndContrato]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTercCndContrato] AS TABLE(
	[NumContrato] [int] NULL,
	[IdConductor] [varchar](16) NULL,
	[IdTipCon] [varchar](4) NULL,
	[IdModd] [varchar](4) NULL,
	[FecIngreso] [smalldatetime] NULL,
	[FecRetiro] [smalldatetime] NULL,
	[FecVigencia] [smalldatetime] NULL,
	[Observaciones] [varchar](250) NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndDoc]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTercCndDoc] AS TABLE(
	[IdConductor] [varchar](16) NULL,
	[Item] [int] NULL,
	[IdDoc] [varchar](4) NULL,
	[Fecha] [smalldatetime] NULL,
	[FecVence] [smalldatetime] NULL,
	[Radicado] [bit] NULL,
	[Descripcion] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndReferencias]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTercCndReferencias] AS TABLE(
	[IdConductor] [varchar](16) NULL,
	[Item] [int] NULL,
	[TipoRef] [varchar](10) NULL,
	[EmpresaRef] [varchar](150) NULL,
	[NitRef] [varchar](16) NULL,
	[DireccionRef] [varchar](150) NULL,
	[TelefonoRef] [varchar](30) NULL,
	[ContactoRef] [varchar](150) NULL,
	[EmailRef] [varchar](100) NULL,
	[CargoRef] [varchar](50) NULL,
	[CuentaBanco] [varchar](30) NULL,
	[FechaInicial] [smalldatetime] NULL,
	[FechaFinal] [smalldatetime] NULL,
	[Verificado] [varchar](150) NULL,
	[ObservRef] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndTarjetas]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTercCndTarjetas] AS TABLE(
	[IdConductor] [varchar](16) NULL,
	[Item] [int] NULL,
	[NumeroTarj] [varchar](30) NULL,
	[Secuencia] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[FecVence] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercCndtores]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTercCndtores] AS TABLE(
	[IdConductor] [varchar](16) NULL,
	[IdGrupo] [varchar](4) NULL,
	[IdModd] [varchar](4) NULL,
	[TipoSangre] [char](2) NULL,
	[FactorRh] [char](1) NULL,
	[FecNacmto] [smalldatetime] NULL,
	[LugarNacmto] [varchar](30) NULL,
	[Sexo] [char](1) NULL,
	[IdEstCivil] [varchar](4) NULL,
	[NHijos] [int] NULL,
	[LibMilitar] [varchar](25) NULL,
	[ClaseLib] [int] NULL,
	[FechaLib] [smalldatetime] NULL,
	[DistMil] [varchar](10) NULL,
	[CertJudicial] [varchar](25) NULL,
	[FecJudicial] [smalldatetime] NULL,
	[VigJudicial] [smalldatetime] NULL,
	[Pasporte] [varchar](25) NULL,
	[VigPaspte] [smalldatetime] NULL,
	[Licencia] [varchar](25) NULL,
	[IdLugar] [varchar](8) NULL,
	[CatLicencia] [int] NULL,
	[FecLicencia] [smalldatetime] NULL,
	[VigLicencia] [smalldatetime] NULL,
	[IdClase] [varchar](4) NULL,
	[NumCuenta] [varchar](30) NULL,
	[IdBanco] [varchar](4) NULL,
	[CdLocCue] [varchar](8) NULL,
	[CdFonPen] [varchar](8) NULL,
	[CdFonEps] [varchar](8) NULL,
	[CdFonArp] [varchar](8) NULL,
	[pVehiculo] [varchar](10) NULL,
	[PathFoto] [varchar](30) NULL,
	[PathFirma] [varchar](30) NULL,
	[PathLic] [varchar](30) NULL,
	[Cmntarios] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[Inactivo] [bit] NULL,
	[NumTarjeta] [varchar](30) NULL,
	[EdicTarjeta] [int] NULL,
	[FecTarjeta] [smalldatetime] NULL,
	[VigTarjeta] [smalldatetime] NULL,
	[PasSeguridad] [varchar](30) NULL,
	[FecPasSeg] [smalldatetime] NULL,
	[VigPasSeg] [smalldatetime] NULL,
	[NitEmpTrans] [varchar](16) NULL,
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL,
	[Num_Contrato] [int] NULL,
	[Contrato_Activo] [bit] NULL,
	[CdTipCon] [varchar](4) NULL,
	[Fec_Ingreso] [smalldatetime] NULL,
	[Fec_Retiro] [smalldatetime] NULL,
	[Fec_Vigencia] [smalldatetime] NULL,
	[Fec_IngresoAnt] [smalldatetime] NULL,
	[Fec_UltimoAcc] [smalldatetime] NULL,
	[PasadoJudicial] [varchar](250) NULL,
	[Restriccion] [varchar](50) NULL,
	[FecPagoPen] [smalldatetime] NULL,
	[FecPagoEps] [smalldatetime] NULL,
	[FecPagoArp] [smalldatetime] NULL,
	[CdTipoOper] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTerceros]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTerceros] AS TABLE(
	[IdTercero] [varchar](16) NULL,
	[RazonSocial] [varchar](250) NULL,
	[Codigo] [varchar](16) NULL,
	[TipoId] [char](1) NULL,
	[Dv] [char](1) NULL,
	[NomCial] [varchar](250) NULL,
	[SiglaRaz] [varchar](50) NULL,
	[Direccion] [varchar](250) NULL,
	[IdLocal] [varchar](8) NULL,
	[Telefono] [varchar](20) NULL,
	[Fax] [varchar](20) NULL,
	[TelMovil] [varchar](20) NULL,
	[SitioWeb] [varchar](100) NULL,
	[e_mail] [varchar](100) NULL,
	[EsCliente] [bit] NULL,
	[EsVendedor] [bit] NULL,
	[EsConductor] [bit] NULL,
	[EsPropietario] [bit] NULL,
	[EsProveedor] [bit] NULL,
	[EsEmpleado] [bit] NULL,
	[EsOperario] [bit] NULL,
	[EsAccnista] [bit] NULL,
	[EsCiaAseg] [bit] NULL,
	[EsCliePres] [bit] NULL,
	[IdSector] [varchar](8) NULL,
	[IdProf] [varchar](4) NULL,
	[IdRegimen] [varchar](4) NULL,
	[TipEnte] [char](1) NULL,
	[IdLugarCed] [varchar](8) NULL,
	[FecExpCed] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IniStgNom] [int] NULL,
	[IdEstado] [varchar](4) NULL,
	[Inactivo] [bit] NULL,
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL,
	[ImgFoto] [varchar](30) NULL,
	[ImgFirma] [varchar](30) NULL,
	[ImagenDoc1] [varchar](50) NULL,
	[ImagenDoc2] [varchar](50) NULL,
	[ImagenDoc3] [varchar](50) NULL,
	[FechaNac] [smalldatetime] NULL,
	[IdEstOper] [varchar](4) NULL,
	[IdLocUbic] [varchar](8) NULL,
	[DescUbicac] [varchar](150) NULL,
	[CdGrupoTerc] [varchar](4) NULL,
	[RegimenFE] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTercPropietario]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTercPropietario] AS TABLE(
	[IdPropietario] [varchar](16) NULL,
	[IdGrupo] [varchar](4) NULL,
	[CupoCredito] [money] NULL,
	[SaldoActual] [money] NULL,
	[Avala] [bit] NULL,
	[IdAdmon] [varchar](4) NULL,
	[IdTipCon] [varchar](4) NULL,
	[ContratoActivo] [bit] NULL,
	[FecIngreso] [smalldatetime] NULL,
	[FecRetiro] [smalldatetime] NULL,
	[FecVigencia] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposAdm]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTiposAdm] AS TABLE(
	[IdAdmon] [varchar](4) NULL,
	[TipoAdmon] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCalendarPgr]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTiposCalendarPgr] AS TABLE(
	[Codigo] [varchar](3) NULL,
	[Dias] [varchar](100) NULL,
	[Inactivo] [bit] NULL,
	[IncFestivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCatLic]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTiposCatLic] AS TABLE(
	[IdCateg] [int] NULL DEFAULT ((0)),
	[CategMT] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCol]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTiposCol] AS TABLE(
	[IdColor] [varchar](4) NULL,
	[NomColor] [varchar](50) NULL,
	[NColor] [int] NULL,
	[Inactivo] [bit] NULL,
	[CodigoMT] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposComFmt]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTiposComFmt] AS TABLE(
	[IdCom] [varchar](3) NULL,
	[IdForma] [char](2) NULL,
	[Descripcion] [varchar](100) NULL,
	[Formato] [varchar](20) NULL,
	[Predtmnado] [bit] NULL,
	[TipoPapel] [int] NULL,
	[Orientacion] [int] NULL,
	[VistaPrevia] [bit] NULL,
	[VerSetup] [bit] NULL,
	[NumCopias] [int] NULL,
	[sp_Nombre] [varchar](50) NULL,
	[Ind_Location] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposCon]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTiposCon] AS TABLE(
	[IdTipCon] [varchar](4) NULL,
	[TipoContrato] [varchar](100) NULL,
	[Duracion] [int] NULL,
	[Inactivo] [bit] NULL,
	[VincLabUgpp] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposDocCons]    Script Date: 13/07/2021 10:39:17 ******/
CREATE TYPE [dbo].[dataTypeTiposDocCons] AS TABLE(
	[IdDoc] [varchar](3) NULL,
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[LDesde] [int] NULL DEFAULT ((0)),
	[LHasta] [int] NULL DEFAULT ((0)),
	[Resolucion] [varchar](30) NULL,
	[RangoNum] [varchar](50) NULL,
	[FechaRes] [smalldatetime] NULL,
	[Prefijo] [varchar](5) NULL,
	[Numero] [int] NULL DEFAULT ((0)),
	[NumManual] [bit] NULL DEFAULT ((0)),
	[IntLotes] [bit] NULL DEFAULT ((0)),
	[ConfigFecha] [varchar](10) NULL,
	[Formato] [varchar](20) NULL,
	[TipoPapel] [int] NULL DEFAULT ((1)),
	[Orientacion] [int] NULL DEFAULT ((1)),
	[VistaPrevia] [bit] NULL DEFAULT ((0)),
	[VerSetup] [bit] NULL DEFAULT ((0)),
	[NumCopias] [int] NULL DEFAULT ((1)),
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[FechaVigRes] [smalldatetime] NULL,
	[ClaveTecDian] [varchar](250) NULL,
	[CodResol] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposFuel]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposFuel] AS TABLE(
	[IdCom] [varchar](4) NULL,
	[TipoComb] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposLla]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposLla] AS TABLE(
	[IdTlla] [varchar](4) NULL,
	[TipoLlanta] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposLub]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposLub] AS TABLE(
	[IdLub] [varchar](4) NULL,
	[TipoLub] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposMod]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposMod] AS TABLE(
	[IdModd] [varchar](4) NULL,
	[Modalidad] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposMot]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposMot] AS TABLE(
	[IdTipoMot] [varchar](4) NULL,
	[TipoMotor] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposNivs]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposNivs] AS TABLE(
	[IdNiv] [varchar](4) NULL,
	[NivelServicio] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposNovPgr]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposNovPgr] AS TABLE(
	[IdNovedad] [varchar](4) NULL,
	[Novedad] [varchar](50) NULL,
	[Tipo] [varchar](20) NULL,
	[IdEstado] [varchar](4) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposOperac]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposOperac] AS TABLE(
	[IdTipoOper] [varchar](4) NULL,
	[TipoOperacion] [varchar](50) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposPpt]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposPpt] AS TABLE(
	[IdPpd] [varchar](4) NULL,
	[TipoProp] [varchar](50) NULL,
	[VehPropio] [bit] NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposVeh]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposVeh] AS TABLE(
	[IdTipoVeh] [varchar](4) NULL,
	[TipoVehiculo] [varchar](50) NULL,
	[Configuracion] [varchar](6) NULL,
	[Ejes] [int] NULL,
	[Llantas] [int] NULL,
	[CapacPeso] [decimal](14, 4) NULL,
	[UndCapac] [varchar](10) NULL,
	[CapacVol] [decimal](14, 4) NULL,
	[UndCapVol] [varchar](10) NULL,
	[CubAlto] [decimal](14, 4) NULL,
	[CubLargo] [decimal](14, 4) NULL,
	[CubAncho] [decimal](14, 4) NULL,
	[PesoBruto] [decimal](14, 4) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTiposVehFactor]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTiposVehFactor] AS TABLE(
	[IdTipoVeh] [varchar](4) NULL,
	[nSemana] [int] NULL,
	[TarifaFc] [decimal](14, 4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraConcCausac]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTraConcCausac] AS TABLE(
	[IdConcepto] [varchar](4) NULL,
	[Concepto] [varchar](250) NULL,
	[IdCuenta] [varchar](16) NULL,
	[TipoConc] [varchar](10) NULL DEFAULT ('CTACOBRAR'),
	[Inactivo] [bit] NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspColegios]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTraEspColegios] AS TABLE(
	[IdColegio] [varchar](4) NULL,
	[NomColegio] [varchar](500) NULL,
	[IdGrupo] [varchar](4) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspGruposCol]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTraEspGruposCol] AS TABLE(
	[IdGrupo] [varchar](4) NULL,
	[Grupo] [varchar](250) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspHorario]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTraEspHorario] AS TABLE(
	[IdHorario] [varchar](3) NULL,
	[Item] [int] NULL,
	[Inicio] [varchar](5) NULL,
	[Final] [varchar](5) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspObjContratos]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTraEspObjContratos] AS TABLE(
	[IdObj] [varchar](4) NULL,
	[Objeto] [varchar](500) NULL,
	[Predtminado] [bit] NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspPolDetalle]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTraEspPolDetalle] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('CPL'),
	[NumDoc] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Item] [int] NULL,
	[IdVehiculo] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraEspPolizas]    Script Date: 13/07/2021 10:39:18 ******/
CREATE TYPE [dbo].[dataTypeTraEspPolizas] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('CPL'),
	[NumDoc] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NULL,
	[FechaExp] [smalldatetime] NULL,
	[FechaVence] [smalldatetime] NULL,
	[TipoPol] [varchar](3) NULL,
	[IdProv] [varchar](16) NULL,
	[NumPoliza] [varchar](16) NULL DEFAULT ('0'),
	[VrPoliza] [money] NULL DEFAULT ((0)),
	[VrCobro] [money] NULL DEFAULT ((0)),
	[IdTipoVeh] [varchar](4) NULL,
	[TipoAfil] [varchar](10) NULL,
	[Todos] [bit] NULL DEFAULT ((0)),
	[OnlyActivos] [bit] NULL DEFAULT ((0)),
	[IdVehiculo] [varchar](10) NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipCom] [varchar](3) NOT NULL DEFAULT ('0'),
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL DEFAULT ('00'),
	[NCuotasOtros] [int] NOT NULL DEFAULT ((0)),
	[NCuotasSocios] [int] NOT NULL DEFAULT ((0)),
	[IdMneda] [varchar](5) NULL DEFAULT ('COP'),
	[OrigenAdd] [varchar](10) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL,
	[Inactivo] [bit] NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTraFijos]    Script Date: 13/07/2021 10:39:19 ******/
CREATE TYPE [dbo].[dataTypeTraFijos] AS TABLE(
	[Numero] [int] NULL DEFAULT ((0)),
	[IdConcepto] [varchar](4) NULL,
	[DescConc] [varchar](250) NULL,
	[TipoConc] [varchar](10) NULL,
	[Tarifa] [decimal](14, 4) NULL DEFAULT ((0)),
	[TipoTarif] [char](1) NULL DEFAULT ('%'),
	[TipoAfilVeh] [varchar](10) NULL DEFAULT ('0'),
	[CdTipoVeh] [varchar](4) NULL DEFAULT ('0'),
	[TipoTerc] [char](1) NULL DEFAULT ('N'),
	[Anulado] [bit] NULL DEFAULT ((0)),
	[CdCiuOrigen] [varchar](8) NULL,
	[CdCiuDestino] [varchar](8) NULL,
	[pVehiculo] [varchar](10) NULL,
	[CedConductor] [varchar](16) NULL,
	[CdRuta] [varchar](4) NULL,
	[TipoVigencia] [char](1) NULL,
	[FechaInicial] [smalldatetime] NULL,
	[FechaFinal] [smalldatetime] NULL,
	[NitCliente] [varchar](16) NULL,
	[CdMercancia] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Aprobacion]    Script Date: 13/07/2021 10:39:20 ******/
CREATE TYPE [dbo].[dataTypeTrn_Aprobacion] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Aprobacion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[TipoPed] [varchar](3) NULL,
	[Pedido] [int] NULL,
	[IdCiaPed] [char](2) NULL,
	[FecPedido] [smalldatetime] NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL,
	[pVehiculo] [varchar](10) NULL,
	[VrCupoCred] [money] NULL,
	[VrSaldoAct] [money] NULL,
	[ChequesDev] [bit] NULL,
	[ClienteMora] [bit] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[Anulado] [bit] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[Tabla] [varchar](250) NULL,
	[ColTabla] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Autoriza]    Script Date: 13/07/2021 10:39:20 ******/
CREATE TYPE [dbo].[dataTypeTrn_Autoriza] AS TABLE(
	[TipAut] [varchar](3) NULL,
	[Autoriza] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[NumAutoriza] [int] NULL,
	[IdUsuarioAut] [varchar](11) NULL,
	[IdEstacion] [char](2) NULL,
	[NitTercero] [varchar](16) NULL,
	[pVehiculo] [varchar](10) NULL,
	[TipoDoc] [varchar](3) NULL,
	[Documento] [int] NULL,
	[IdCiaDoc] [char](2) NULL,
	[FechaDoc] [smalldatetime] NULL,
	[DocRef] [int] NULL DEFAULT ((0)),
	[OrigenAdd] [varchar](10) NULL,
	[Anulado] [bit] NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[VrAprobado] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_ComDetalle]    Script Date: 13/07/2021 10:39:20 ******/
CREATE TYPE [dbo].[dataTypeTrn_ComDetalle] AS TABLE(
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NOT NULL,
	[IdCuenta] [varchar](16) NOT NULL,
	[Detalle] [varchar](250) NOT NULL,
	[VrDebito] [money] NOT NULL DEFAULT ((0)),
	[VrCredito] [money] NOT NULL DEFAULT ((0)),
	[IdTercero] [varchar](16) NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL DEFAULT ('0'),
	[IdCCosto] [varchar](16) NOT NULL,
	[IdSubCos] [varchar](16) NOT NULL,
	[VrBase] [money] NOT NULL DEFAULT ((0)),
	[TarifaBase] [decimal](10, 4) NOT NULL DEFAULT ((0)),
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NULL DEFAULT ('01'),
	[CodConce] [varchar](4) NULL,
	[NitDoc] [varchar](16) NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [varchar](15) NULL,
	[IdCiaFac] [char](2) NULL DEFAULT ('01'),
	[ItemFac] [int] NOT NULL DEFAULT ((0)),
	[FecVence] [smalldatetime] NOT NULL,
	[CodCta] [varchar](4) NULL,
	[NumCheque] [varchar](20) NULL,
	[Integrado] [bit] NOT NULL DEFAULT ((0)),
	[TipoAplica] [char](1) NOT NULL DEFAULT ('N'),
	[Consolida] [bit] NOT NULL DEFAULT ((0)),
	[CodCargo] [varchar](4) NULL,
	[NitOtros] [varchar](16) NULL,
	[CodSubgpo] [varchar](8) NULL,
	[CiuOrigen] [varchar](8) NULL,
	[CodAgncia] [varchar](16) NOT NULL DEFAULT ('0'),
	[VehPropio] [int] NOT NULL DEFAULT ((0)),
	[Referncia] [varchar](50) NULL,
	[TipDocRef] [varchar](3) NULL,
	[DocRef] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRef] [char](2) NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL,
	[CdConcTrib] [varchar](4) NULL,
	[CdTarifTrib] [varchar](4) NULL,
	[NumEstablec] [varchar](20) NULL,
	[PtoEmision] [varchar](20) NULL,
	[Num_Autoriza] [varchar](50) NULL,
	[FechAutoriza] [smalldatetime] NULL,
	[CdCuentaNiif] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_ComFactura]    Script Date: 13/07/2021 10:39:21 ******/
CREATE TYPE [dbo].[dataTypeTrn_ComFactura] AS TABLE(
	[TipFac] [varchar](3) NULL,
	[Factura] [varchar](15) NULL,
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Item] [int] NULL DEFAULT ((1)),
	[IdProveedor] [varchar](16) NULL,
	[IdCuenta] [varchar](16) NULL,
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NULL DEFAULT ('01'),
	[FecEmision] [smalldatetime] NULL,
	[FecVence] [smalldatetime] NULL,
	[VrFactura] [money] NULL DEFAULT ((0)),
	[VrAbonado] [money] NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL DEFAULT ((0)),
	[ItemCom] [int] NULL DEFAULT ((0)),
	[Referencia] [varchar](50) NULL,
	[Detalle] [varchar](100) NULL,
	[pVehiculo] [varchar](10) NULL,
	[VehPropio] [bit] NULL DEFAULT ((0)),
	[TipRef] [varchar](3) NULL,
	[DocRef] [int] NULL DEFAULT ((0)),
	[IdCiaRef] [char](2) NULL,
	[EstadoApr] [int] NULL DEFAULT ((0)),
	[MontoAprob] [money] NOT NULL DEFAULT ((0)),
	[FecProgPago] [smalldatetime] NULL,
	[ObservAprob] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Comprobantes]    Script Date: 13/07/2021 10:39:22 ******/
CREATE TYPE [dbo].[dataTypeTrn_Comprobantes] AS TABLE(
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdTercero] [varchar](16) NOT NULL,
	[VrTotal] [money] NOT NULL DEFAULT ((0)),
	[IdCta] [varchar](4) NOT NULL,
	[EnEfectivo] [bit] NOT NULL DEFAULT ((0)),
	[NumCheque] [varchar](20) NULL,
	[FecCheque] [smalldatetime] NULL,
	[TipDoc] [varchar](3) NOT NULL,
	[Documento] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NOT NULL,
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[NumDev] [int] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[TipEgr] [varchar](3) NULL,
	[NEgreso] [int] NOT NULL DEFAULT ((0)),
	[pVehiculo] [varchar](10) NULL,
	[VehPropio] [int] NOT NULL DEFAULT ((0)),
	[CedCondtor] [varchar](16) NULL,
	[CodConce] [varchar](4) NULL,
	[Beneficiario] [varchar](150) NULL,
	[VrDivisa1] [money] NOT NULL DEFAULT ((0)),
	[VrDivisa2] [money] NOT NULL DEFAULT ((0)),
	[VrDivisa3] [money] NOT NULL DEFAULT ((0)),
	[PermEditar] [bit] NOT NULL DEFAULT ((0)),
	[Integrado] [bit] NOT NULL DEFAULT ((0)),
	[EsEgreso] [bit] NOT NULL DEFAULT ((0)),
	[Anticipo] [bit] NOT NULL DEFAULT ((0)),
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[Propddes] [varchar](50) NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL,
	[CdSustento] [varchar](4) NULL,
	[Tipo_Pago] [varchar](10) NULL,
	[Establec] [varchar](20) NULL,
	[PEmision] [varchar](20) NULL,
	[Autorizac] [varchar](50) NULL,
	[FechaAut] [smalldatetime] NULL,
	[NiifTipo] [varchar](3) NULL,
	[NiifNumero] [int] NOT NULL DEFAULT ((0)),
	[FisTipo] [varchar](3) NULL,
	[FisNumero] [int] NOT NULL DEFAULT ((0)),
	[DocSoporte] [int] NOT NULL DEFAULT ((0)),
	[CodRes] [varchar](4) NULL,
	[DescServicio] [varchar](500) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DetCuentas]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_DetCuentas] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL,
	[IdCia] [char](2) NULL,
	[Concepto] [varchar](10) NULL,
	[Item] [int] NULL,
	[IdCuenta] [varchar](16) NULL,
	[Valor] [money] NULL,
	[Detalle] [varchar](150) NULL,
	[IdTercero] [varchar](16) NULL,
	[CodAgncia] [varchar](16) NULL,
	[CdCCosto] [varchar](16) NULL,
	[CdSubCos] [varchar](16) NULL,
	[pVehiculo] [varchar](10) NULL,
	[VrBase] [money] NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [varchar](15) NULL,
	[IdCiaFac] [char](2) NULL,
	[ItemFac] [int] NULL,
	[FecVence] [smalldatetime] NULL,
	[Cheque] [varchar](20) NULL,
	[CiuOrigen] [varchar](8) NULL,
	[Referencia] [varchar](50) NULL,
	[VrTarifa] [decimal](14, 4) NULL,
	[TipoTarif] [char](1) NULL,
	[CodConc] [varchar](4) NULL,
	[CodTarif] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DevFco]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_DevFco] AS TABLE(
	[TipDev] [varchar](3) NULL,
	[Devolucion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipDoc] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaDoc] [char](2) NULL,
	[FecDoc] [smalldatetime] NULL,
	[nClieCon] [varchar](16) NULL,
	[VrSubTotal] [money] NULL,
	[VrDescuento] [money] NULL,
	[VrImpuesto] [money] NULL,
	[VrRetencion] [money] NULL,
	[VrReteICA] [money] NULL,
	[VrReteIVA] [money] NULL,
	[VrFletes] [money] NULL,
	[VrCargos] [money] NULL,
	[VrOtrDcto] [money] NULL,
	[VrCostos] [money] NULL,
	[VrNeto] [money] NULL,
	[VrEfectivo] [money] NULL,
	[VrPagosOtr] [money] NULL,
	[Cantidad] [decimal](14, 4) NULL,
	[CantPuntos] [decimal](14, 4) NULL,
	[BaseImp] [money] NULL,
	[BaseRet] [money] NULL,
	[IdCajero] [varchar](11) NULL,
	[IdVend] [varchar](16) NULL,
	[TarifaCom] [decimal](14, 4) NULL,
	[CodTarCom] [varchar](4) NULL,
	[NitCliente] [varchar](16) NULL,
	[CdAgencia] [varchar](16) NULL,
	[IdCCosto] [varchar](16) NULL,
	[IdSubCos] [varchar](16) NULL,
	[IdLocal] [varchar](8) NULL,
	[EnEfectivo] [bit] NULL,
	[Pedido] [int] NULL,
	[IdCiaPed] [char](2) NULL,
	[Remision] [int] NULL,
	[IdCiaRem] [char](2) NULL,
	[FecPedido] [smalldatetime] NULL,
	[Modalidad] [varchar](10) NULL,
	[ModdDev] [varchar](10) NULL,
	[NumAutoriza] [int] NULL,
	[PlacaVehic] [varchar](10) NULL,
	[KmtVehic] [int] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[VrImpCons] [money] NULL,
	[VrReteCREE] [money] NULL,
	[TarifaRtc] [decimal](14, 4) NULL,
	[CodTarRtc] [varchar](4) NULL,
	[BaseIvaObsq] [money] NULL,
	[VrIvaObsequio] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DevFcr]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_DevFcr] AS TABLE(
	[TipDev] [varchar](3) NULL,
	[Devolucion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipDoc] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaDoc] [char](2) NULL,
	[FecDoc] [smalldatetime] NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL,
	[VrSubTotal] [money] NULL,
	[VrDescuento] [money] NULL,
	[VrImpuesto] [money] NULL,
	[VrRetencion] [money] NULL,
	[VrReteICA] [money] NULL,
	[VrReteIVA] [money] NULL,
	[VrFletes] [money] NULL,
	[VrOtros] [money] NULL,
	[VrCargos] [money] NULL,
	[VrOtrDcto] [money] NULL,
	[VrCostos] [money] NULL,
	[VrSobretasa] [money] NULL,
	[VrImpGlobal] [money] NULL,
	[VrFaltantes] [money] NULL,
	[VrAnticipos] [money] NULL,
	[VrNeto] [money] NULL,
	[Cantidad] [decimal](14, 4) NULL,
	[CantPuntos] [decimal](14, 4) NULL,
	[BaseImp] [money] NULL,
	[BaseRet] [money] NULL,
	[IdCCosto] [varchar](16) NULL,
	[IdSubCos] [varchar](16) NULL,
	[IdVend] [varchar](16) NULL,
	[TarifaCom] [decimal](14, 4) NULL,
	[CodTarCom] [varchar](4) NULL,
	[IdLocEnv] [varchar](8) NULL,
	[Pedido] [int] NULL,
	[IdCiaPed] [char](2) NULL,
	[Remision] [int] NULL,
	[IdCiaRem] [char](2) NULL,
	[Cotizacion] [int] NULL,
	[IdCiaCot] [char](2) NULL,
	[FecPedido] [smalldatetime] NULL,
	[Modalidad] [varchar](10) NULL,
	[ModdDev] [varchar](10) NULL,
	[PlacaVehic] [varchar](10) NULL,
	[KmtVehic] [int] NULL,
	[ZonaFrontera] [int] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[VrImpCons] [money] NULL,
	[VrReteCREE] [money] NULL,
	[TarifaRtc] [decimal](14, 4) NULL,
	[CodTarRtc] [varchar](4) NULL,
	[BaseIvaObsq] [money] NULL,
	[VrIvaObsequio] [money] NULL,
	[VrImpCarbono] [money] NULL,
	[DevMasivo] [int] NULL,
	[NumRecibo] [int] NULL,
	[CdCiaRec] [char](2) NULL,
	[CdMotDev] [varchar](4) NULL,
	[BaseIvaIgp] [money] NULL,
	[VrIvaIngProd] [money] NULL,
	[TarifaArf] [decimal](14, 4) NULL,
	[VrAutRetFte] [money] NULL,
	[TarifaAri] [decimal](14, 4) NULL,
	[VrAutRetIca] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_DocMemo]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_DocMemo] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL,
	[IdCia] [char](2) NULL,
	[Comentarios] [varchar](6500) NULL,
	[Nota1] [varchar](500) NULL,
	[Nota2] [varchar](500) NULL,
	[Nota3] [varchar](500) NULL,
	[CantImp] [int] NULL,
	[ArchivoImg] [varchar](150) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_EgrFactura]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_EgrFactura] AS TABLE(
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [varchar](15) NULL,
	[IdCiaFac] [char](2) NULL,
	[ItemFac] [int] NULL,
	[IdProveedor] [varchar](16) NULL,
	[IdCuenta] [varchar](16) NULL,
	[VrAbono] [money] NULL,
	[EsEgreso] [bit] NULL,
	[ItemCom] [int] NULL,
	[pVehiculo] [varchar](10) NULL,
	[VehPropio] [bit] NULL,
	[TipDev] [varchar](3) NULL,
	[NumDev] [int] NULL,
	[DetAbono] [varchar](100) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Factcon]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_Factcon] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[nClieCon] [varchar](16) NULL,
	[VrSubTotal] [money] NULL,
	[VrDescuento] [money] NULL,
	[VrImpuesto] [money] NULL,
	[VrRetencion] [money] NULL,
	[VrReteICA] [money] NULL,
	[VrReteIVA] [money] NULL,
	[VrFletes] [money] NULL,
	[VrCargos] [money] NULL,
	[VrOtrDcto] [money] NULL,
	[VrCostos] [money] NULL,
	[VrNeto] [money] NULL,
	[VrEfectivo] [money] NULL,
	[VrPagosOtr] [money] NULL,
	[Cantidad] [decimal](14, 4) NULL,
	[CantPuntos] [decimal](14, 4) NULL,
	[PuntosAcum] [decimal](14, 4) NULL,
	[BaseImp] [money] NULL,
	[BaseRet] [money] NULL,
	[BaseIca] [money] NULL,
	[BaseRiv] [money] NULL,
	[TarifaIva] [decimal](14, 4) NULL,
	[TarifaRet] [decimal](14, 4) NULL,
	[TarifaIca] [decimal](14, 4) NULL,
	[TarifaRiv] [decimal](14, 4) NULL,
	[CodTarIva] [varchar](4) NULL,
	[CodTarRet] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[CodTarRiv] [varchar](4) NULL,
	[IdCajero] [varchar](11) NULL,
	[IdVend] [varchar](16) NULL,
	[TarifaCom] [decimal](14, 4) NULL,
	[CodTarCom] [varchar](4) NULL,
	[NitCliente] [varchar](16) NULL,
	[CdAgencia] [varchar](16) NULL,
	[IdCCosto] [varchar](16) NULL,
	[IdSubCos] [varchar](16) NULL,
	[IdLocal] [varchar](8) NULL,
	[EnEfectivo] [bit] NULL,
	[CdForma] [varchar](4) NULL,
	[NumForma] [varchar](20) NULL,
	[DetallePago] [varchar](250) NULL,
	[Referncia1] [varchar](50) NULL,
	[Referncia2] [varchar](50) NULL,
	[CdBanco] [varchar](4) NULL,
	[TipPed] [varchar](3) NULL,
	[Pedido] [int] NULL,
	[IdCiaPed] [char](2) NULL,
	[TipRem] [varchar](3) NULL,
	[Remision] [int] NULL,
	[IdCiaRem] [char](2) NULL,
	[FecPedido] [smalldatetime] NULL,
	[Modalidad] [varchar](10) NULL,
	[PlacaVehic] [varchar](10) NULL,
	[KmtVehic] [int] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Anulado] [bit] NULL,
	[NumDev] [int] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[VrImpCons] [money] NULL,
	[VrReteCREE] [money] NULL,
	[TarifaRtc] [decimal](14, 4) NULL,
	[CodTarRtc] [varchar](4) NULL,
	[BaseIvaObsq] [money] NULL,
	[VrIvaObsequio] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Facturas]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_Facturas] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL,
	[FechaVence] [smalldatetime] NULL,
	[VrSubTotal] [money] NULL,
	[VrDescuento] [money] NULL,
	[VrImpuesto] [money] NULL,
	[VrRetencion] [money] NULL,
	[VrReteICA] [money] NULL,
	[VrReteIVA] [money] NULL,
	[VrFletes] [money] NULL,
	[VrOtros] [money] NULL,
	[VrCargos] [money] NULL,
	[VrOtrDcto] [money] NULL,
	[VrCostos] [money] NULL,
	[VrSobretasa] [money] NULL,
	[VrImpGlobal] [money] NULL,
	[VrFaltantes] [money] NULL,
	[VrAnticipos] [money] NULL,
	[VrNeto] [money] NULL,
	[VrAplicado] [money] NULL,
	[Cantidad] [decimal](14, 4) NULL,
	[CantPuntos] [decimal](14, 4) NULL,
	[PuntosAcum] [decimal](14, 4) NULL,
	[BaseImp] [money] NULL,
	[BaseRet] [money] NULL,
	[BaseIca] [money] NULL,
	[BaseRiv] [money] NULL,
	[TarifaIva] [decimal](14, 4) NULL,
	[TarifaRet] [decimal](14, 4) NULL,
	[TarifaIca] [decimal](14, 4) NULL,
	[TarifaRiv] [decimal](14, 4) NULL,
	[CodTarIva] [varchar](4) NULL,
	[CodTarRet] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[CodTarRiv] [varchar](4) NULL,
	[IdCCosto] [varchar](16) NULL,
	[IdSubCos] [varchar](16) NULL,
	[IdVend] [varchar](16) NULL,
	[TarifaCom] [decimal](14, 4) NULL,
	[CodTarCom] [varchar](4) NULL,
	[DirEnvio] [varchar](250) NULL,
	[IdLocEnv] [varchar](8) NULL,
	[DiasEntraga] [int] NULL,
	[NitContac] [varchar](16) NULL,
	[NomContac] [varchar](150) NULL,
	[TelContac] [varchar](20) NULL,
	[emlContac] [varchar](100) NULL,
	[CargoContac] [varchar](50) NULL,
	[IdForma] [varchar](4) NULL,
	[DetallePago] [varchar](100) NULL,
	[MulPlazos] [bit] NULL,
	[IdPlazo] [varchar](4) NULL,
	[CdMney] [varchar](5) NULL,
	[NitEmpTrans] [varchar](16) NULL,
	[EmpTrans] [varchar](150) NULL,
	[pVehiculo] [varchar](10) NULL,
	[CdConductor] [varchar](16) NULL,
	[CdRuta] [varchar](4) NULL,
	[TipPed] [varchar](3) NULL,
	[Pedido] [int] NULL,
	[IdCiaPed] [char](2) NULL,
	[TipRem] [varchar](3) NULL,
	[Remision] [int] NULL,
	[IdCiaRem] [char](2) NULL,
	[TipCot] [varchar](3) NULL,
	[Cotizacion] [int] NULL,
	[IdCiaCot] [char](2) NULL,
	[FecPedido] [smalldatetime] NULL,
	[AutzaMora] [int] NULL,
	[AutzaCupo] [int] NULL,
	[Modalidad] [varchar](10) NULL,
	[KmtVehic] [int] NULL,
	[ZonaFrontera] [int] NULL,
	[PesoTotal] [decimal](14, 4) NULL,
	[UnidTotal] [decimal](14, 4) NULL,
	[VolTotal] [decimal](14, 4) NULL,
	[CantFalt] [decimal](14, 4) NULL,
	[VrCostoRem] [money] NULL,
	[VrCostoAfi] [money] NULL,
	[CodAutoRet] [varchar](4) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Anulado] [bit] NULL,
	[NumDev] [int] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[VrImpCons] [money] NULL,
	[VrReteCREE] [money] NULL,
	[TarifaRtc] [decimal](14, 4) NULL,
	[CodTarRtc] [varchar](4) NULL,
	[Parqueadero] [bit] NULL,
	[FecCuotaParq] [smalldatetime] NULL,
	[BaseIvaObsq] [money] NULL,
	[VrIvaObsequio] [money] NULL,
	[VrImpCarbono] [money] NULL,
	[TipoFE] [varchar](3) NULL,
	[FechaFE] [smalldatetime] NULL,
	[BaseIvaIgp] [money] NULL,
	[VrIvaIngProd] [money] NULL,
	[CodigoPreFact] [varchar](3) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_FcSemanas]    Script Date: 13/07/2021 10:39:24 ******/
CREATE TYPE [dbo].[dataTypeTrn_FcSemanas] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[nSemana] [int] NULL DEFAULT ((0)),
	[NumCargue] [int] NULL DEFAULT ((0)),
	[CiaCargue] [char](2) NULL DEFAULT ('01'),
	[TipoSem] [int] NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NULL,
	[FecVence] [smalldatetime] NULL,
	[VrCargo] [money] NULL DEFAULT ((0)),
	[VrOtros] [money] NULL DEFAULT ((0)),
	[VrPagado] [money] NULL DEFAULT ((0)),
	[TipRec] [varchar](3) NULL,
	[Recibo] [int] NULL DEFAULT ((0)),
	[IdCiaRec] [char](2) NULL DEFAULT ('00'),
	[FechaPago] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[FecSemIni] [smalldatetime] NULL,
	[FecSemFin] [smalldatetime] NULL,
	[TimeSys] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Kardex]    Script Date: 13/07/2021 10:39:25 ******/
CREATE TYPE [dbo].[dataTypeTrn_Kardex] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL,
	[Documento] [int] NOT NULL,
	[IdCia] [char](2) NOT NULL,
	[Item] [int] NOT NULL,
	[Fecha] [smalldatetime] NOT NULL,
	[IdProducto] [varchar](16) NOT NULL,
	[IdBodega] [varchar](4) NOT NULL,
	[CdTanque] [varchar](4) NULL,
	[Entradas] [decimal](14, 4) NOT NULL,
	[Salidas] [decimal](14, 4) NOT NULL,
	[IdUnd] [varchar](4) NOT NULL,
	[VrUnitario] [money] NOT NULL,
	[VrPrecio] [money] NOT NULL,
	[VrCostProm] [money] NOT NULL,
	[TarifaIva] [decimal](14, 4) NOT NULL,
	[VrIvaEnt] [money] NOT NULL,
	[VrIvaSal] [money] NOT NULL,
	[TarifaDct] [decimal](14, 4) NOT NULL,
	[VrDctoEnt] [money] NOT NULL,
	[VrDctoSal] [money] NOT NULL,
	[VrCostoEnt] [money] NOT NULL,
	[VrCostoSal] [money] NOT NULL,
	[TarifaRet] [decimal](14, 4) NOT NULL,
	[VrReteEnt] [money] NOT NULL,
	[VrReteSal] [money] NOT NULL,
	[TarifaIca] [decimal](14, 4) NOT NULL,
	[VrIcaEnt] [money] NOT NULL,
	[VrIcaSal] [money] NOT NULL,
	[VrBruto] [money] NOT NULL,
	[CdUbic] [varchar](10) NULL,
	[NumLote] [varchar](30) NULL,
	[FechLote] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[IdTercero] [varchar](16) NOT NULL,
	[CdAgencia] [varchar](16) NULL,
	[CdCCosto] [varchar](16) NULL,
	[CdSubCos] [varchar](16) NULL,
	[CdLocal] [varchar](8) NOT NULL,
	[CdSzona] [varchar](4) NULL,
	[pVehiculo] [varchar](10) NULL,
	[IdVend] [varchar](16) NOT NULL,
	[Comision] [decimal](14, 4) NOT NULL,
	[CdOperario] [varchar](16) NULL,
	[ComisnOper] [decimal](14, 4) NOT NULL,
	[Referencia] [varchar](50) NULL,
	[Descripcion] [varchar](250) NULL,
	[Comptmntos] [varchar](50) NULL,
	[CdProdEquiv] [varchar](16) NULL,
	[TipOrd] [varchar](3) NOT NULL,
	[NumOrden] [int] NOT NULL,
	[IdCiaOrd] [char](2) NOT NULL,
	[Cotizacion] [int] NOT NULL,
	[IdCiaCot] [char](2) NOT NULL,
	[Remision] [int] NOT NULL,
	[IdCiaRem] [char](2) NOT NULL,
	[Factura] [varchar](15) NULL,
	[TipDocDev] [varchar](3) NOT NULL,
	[NumDocDev] [int] NOT NULL,
	[CdMngra] [varchar](10) NULL,
	[NumInicial] [decimal](14, 4) NOT NULL,
	[NumFinal] [decimal](14, 4) NOT NULL,
	[Sobretasa] [decimal](14, 4) NOT NULL,
	[TasaNac] [decimal](14, 4) NOT NULL,
	[TasaDep] [decimal](14, 4) NOT NULL,
	[TasaMun] [decimal](14, 4) NOT NULL,
	[Soldicom] [decimal](14, 4) NOT NULL,
	[ImpGlobal] [decimal](14, 4) NOT NULL,
	[OtroImpto] [decimal](14, 4) NOT NULL,
	[Unidades] [decimal](14, 4) NOT NULL,
	[ItemCombo] [int] NOT NULL,
	[Servcios] [bit] NOT NULL,
	[NoVentas] [int] NOT NULL,
	[EsCombo] [bit] NOT NULL,
	[EsProdBase] [int] NOT NULL,
	[CodTarDct] [varchar](4) NULL,
	[CodTarIva] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[CodTarRet] [varchar](4) NULL,
	[CodTarCom] [varchar](4) NULL,
	[CodTarCmc] [varchar](4) NULL,
	[ListaPrec] [char](1) NOT NULL,
	[VrBase] [money] NOT NULL,
	[CdMoneda] [varchar](5) NOT NULL,
	[VrTasaCamb] [money] NOT NULL,
	[VrDivisa1] [money] NOT NULL,
	[VrDivisa2] [money] NOT NULL,
	[VrDivisa3] [money] NOT NULL,
	[Referencia2] [varchar](50) NULL,
	[FecOrden] [smalldatetime] NULL,
	[galsbruto] [decimal](14, 4) NULL,
	[galsneto] [decimal](14, 4) NULL,
	[Temperatura] [decimal](14, 4) NULL,
	[UmTemp] [varchar](3) NULL,
	[Densidad] [decimal](14, 4) NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[IdUsuario] [varchar](11) NOT NULL,
	[Rec_Costo] [decimal](14, 4) NOT NULL,
	[MgenCont] [decimal](14, 4) NOT NULL,
	[VrImvCosto] [decimal](16, 4) NOT NULL,
	[TarifaIco] [decimal](14, 4) NOT NULL,
	[VrImpCon] [decimal](16, 4) NOT NULL,
	[CantObseq] [decimal](14, 4) NOT NULL,
	[VrIvaObseq] [money] NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_NiifComp]    Script Date: 13/07/2021 10:39:25 ******/
CREATE TYPE [dbo].[dataTypeTrn_NiifComp] AS TABLE(
	[TipComCont] [varchar](3) NOT NULL,
	[ComprobanteCont] [int] NOT NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[TipoNiif] [varchar](10) NOT NULL DEFAULT ('NIIF'),
	[CtbTipo] [varchar](3) NULL,
	[CtbNumero] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_NiifCompFMsv]    Script Date: 13/07/2021 10:39:25 ******/
CREATE TYPE [dbo].[dataTypeTrn_NiifCompFMsv] AS TABLE(
	[TipComCont] [varchar](3) NOT NULL,
	[ComprobanteCont] [int] NOT NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[TipoNiif] [varchar](10) NOT NULL DEFAULT ('NIIF'),
	[CtbTipo] [varchar](3) NULL,
	[CtbNumero] [int] NOT NULL DEFAULT ((0)),
	[Documento] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_NiifDetalle]    Script Date: 13/07/2021 10:39:26 ******/
CREATE TYPE [dbo].[dataTypeTrn_NiifDetalle] AS TABLE(
	[TipComCont] [varchar](3) NOT NULL,
	[ComprobanteCont] [int] NOT NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[IdCuenta] [varchar](16) NOT NULL,
	[Detalle] [varchar](250) NOT NULL,
	[VrDebito] [money] NOT NULL DEFAULT ((0)),
	[VrCredito] [money] NOT NULL DEFAULT ((0)),
	[IdTercero] [varchar](16) NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL DEFAULT ('0'),
	[IdCCosto] [varchar](16) NOT NULL,
	[IdSubCos] [varchar](16) NOT NULL,
	[Referncia] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Pagos]    Script Date: 13/07/2021 10:39:26 ******/
CREATE TYPE [dbo].[dataTypeTrn_Pagos] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL,
	[Documento] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NOT NULL,
	[IdForma] [varchar](4) NOT NULL DEFAULT ('EFE'),
	[Detalle] [varchar](150) NOT NULL,
	[VrPagado] [money] NOT NULL DEFAULT ((0)),
	[VrCambio] [money] NOT NULL DEFAULT ((0)),
	[EsCaja] [bit] NOT NULL DEFAULT ((1)),
	[IdBanco] [varchar](4) NOT NULL,
	[NitCliente] [varchar](16) NOT NULL DEFAULT ('0'),
	[CdAgencia] [varchar](16) NOT NULL DEFAULT ('0'),
	[NumForma] [varchar](20) NULL,
	[FecForma] [smalldatetime] NULL,
	[CtaForma] [varchar](30) NULL,
	[Beneficiario] [varchar](150) NULL,
	[Referncia1] [varchar](50) NULL,
	[Referncia2] [varchar](50) NULL,
	[CdLocal] [varchar](8) NOT NULL DEFAULT ('0'),
	[NumAutoriza] [varchar](30) NULL,
	[VrDenom] [money] NOT NULL DEFAULT ((0)),
	[Cantidad] [int] NOT NULL DEFAULT ((0)),
	[TipDenom] [char](1) NOT NULL DEFAULT ('B'),
	[TipRef] [varchar](3) NOT NULL DEFAULT ('0'),
	[DocRef] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRef] [char](2) NOT NULL DEFAULT ('00'),
	[ItemDoc] [int] NOT NULL DEFAULT ((0)),
	[CdCta] [varchar](4) NULL,
	[IdUsuario] [varchar](11) NOT NULL,
	[CdProducto] [varchar](16) NULL,
	[FE_Ticket] [bit] NOT NULL DEFAULT ((0)),
	[Cant_Gals] [decimal](14, 4) NULL,
	[PrecioBase] [money] NOT NULL DEFAULT ((0)),
	[PrecioUnit] [money] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_RecAfavor]    Script Date: 13/07/2021 10:39:28 ******/
CREATE TYPE [dbo].[dataTypeTrn_RecAfavor] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Recibo] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[VrAFavor] [money] NULL,
	[VrOtrosDb] [money] NULL,
	[VrAbono] [money] NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL,
	[IdVend] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraAntAbonos]    Script Date: 13/07/2021 10:39:28 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraAntAbonos] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('ODP'),
	[Documento] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NOT NULL,
	[TipAnt] [varchar](3) NOT NULL DEFAULT ('ANT'),
	[Anticipo] [int] NOT NULL DEFAULT ((0)),
	[IdCiaAnt] [char](2) NOT NULL,
	[VrAbono] [money] NOT NULL DEFAULT ((0)),
	[TipoAplica] [varchar](10) NOT NULL DEFAULT ('OPAGO'),
	[Detalle] [varchar](100) NULL,
	[CdCuentaAnt] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraAnticipos]    Script Date: 13/07/2021 10:39:28 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraAnticipos] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('ANT'),
	[Anticipo] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[TipMuc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCiaMuc] [char](2) NOT NULL DEFAULT ('01'),
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdPoseedor] [varchar](16) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[VrAnticipo] [money] NOT NULL DEFAULT ((0)),
	[VrAbonado] [money] NOT NULL DEFAULT ((0)),
	[Modalidad] [varchar](10) NOT NULL DEFAULT ('EGRESO'),
	[TipoPago] [varchar](10) NOT NULL DEFAULT ('EFECTIVO'),
	[NumCheque] [varchar](20) NULL,
	[FecCheque] [smalldatetime] NULL,
	[IdCta] [varchar](4) NOT NULL DEFAULT ('0'),
	[IdCuenta] [varchar](16) NOT NULL,
	[Beneficiario] [varchar](150) NULL,
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[FechaVence] [smalldatetime] NULL,
	[NumPresAnt] [int] NOT NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NOT NULL DEFAULT ('0'),
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL DEFAULT ('00'),
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[NumDev] [int] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[OrigenAdd] [varchar](10) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL,
	[CedBenef] [varchar](16) NULL,
	[PreAnticipo] [int] NOT NULL DEFAULT ((0)),
	[NumCargue] [int] NOT NULL DEFAULT ((0)),
	[CiaCargue] [char](2) NULL DEFAULT ('00')
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraConceptos]    Script Date: 13/07/2021 10:39:30 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraConceptos] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL,
	[Documento] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[Descripcion] [varchar](250) NOT NULL,
	[Tarifa] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[TipoConc] [varchar](10) NOT NULL DEFAULT ('DEDUCCION'),
	[RubroConcep] [varchar](20) NOT NULL,
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[VrUnitario] [money] NOT NULL DEFAULT ((0)),
	[TarifIva] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[IdConcepto] [varchar](4) NOT NULL,
	[CdCuenta] [varchar](16) NOT NULL DEFAULT ('0'),
	[NitTercero] [varchar](16) NULL DEFAULT ('0'),
	[CdTipoEsc] [varchar](4) NULL,
	[FechaNov] [smalldatetime] NULL,
	[VrBase] [money] NOT NULL DEFAULT ((0)),
	[TipoTarif] [char](1) NOT NULL DEFAULT ('$'),
	[RefConc] [varchar](50) NULL,
	[Fijos] [bit] NOT NULL DEFAULT ((0)),
	[IncBaseRet] [int] NOT NULL DEFAULT ((0)),
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumplido]    Script Date: 13/07/2021 10:39:31 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraCumplido] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('CUM'),
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[TipMuc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCiaMuc] [char](2) NOT NULL DEFAULT ('01'),
	[IdVehiculo] [varchar](10) NOT NULL,
	[Modalidad] [varchar](10) NOT NULL DEFAULT ('TOTAL'),
	[DiasPlazo] [int] NOT NULL DEFAULT ((0)),
	[FecPago] [smalldatetime] NOT NULL,
	[TipoMargen] [varchar](10) NOT NULL DEFAULT ('UNIDAD'),
	[MargenFalt] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndCalcFalt] [varchar](10) NULL DEFAULT ('PESO'),
	[TarifFaltPago] [money] NOT NULL DEFAULT ((0)),
	[TarifFaltCobro] [money] NOT NULL DEFAULT ((0)),
	[NRadicaDoc] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRadic] [char](2) NULL,
	[CdCiaOfic] [char](2) NULL,
	[FecRadic] [smalldatetime] NULL,
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](1000) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[OrigenAdd] [varchar](10) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL,
	[CdRuta] [varchar](4) NULL,
	[CdOrigen] [varchar](8) NULL,
	[CdDestino] [varchar](8) NULL,
	[TipoComp] [varchar](3) NULL,
	[NumComp] [int] NOT NULL DEFAULT ((0)),
	[CodConcepto] [varchar](4) NULL,
	[TipoCumpMT] [varchar](3) NULL,
	[MotivoSusp] [varchar](3) NULL,
	[ConsecSusp] [varchar](3) NULL,
	[VrAdicCargue] [decimal](16, 4) NOT NULL DEFAULT ((0)),
	[VrAdicDescargue] [decimal](16, 4) NOT NULL DEFAULT ((0)),
	[VrAdicFlete] [decimal](16, 4) NOT NULL DEFAULT ((0)),
	[MotivoVrAdic] [varchar](3) NULL,
	[VrDctoFlete] [decimal](16, 4) NOT NULL DEFAULT ((0)),
	[MotivoVrDcto] [varchar](3) NULL,
	[VrAdicAnticipo] [decimal](16, 4) NOT NULL DEFAULT ((0)),
	[FecEntregaDoc] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumRadDoc]    Script Date: 13/07/2021 10:39:33 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraCumRadDoc] AS TABLE(
	[NumRadica] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NOT NULL,
	[NitCliente] [varchar](16) NOT NULL,
	[ItemDoc] [int] NOT NULL DEFAULT ((0)),
	[Descripcion] [varchar](250) NULL,
	[Radicado] [bit] NOT NULL DEFAULT ((0)),
	[Referencia] [varchar](50) NULL,
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumRadica]    Script Date: 13/07/2021 10:39:33 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraCumRadica] AS TABLE(
	[NumRadica] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[TipMuc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCiaMuc] [char](2) NOT NULL DEFAULT ('01'),
	[CdCiaRad] [char](2) NOT NULL DEFAULT ('01'),
	[DocAnexos] [varchar](1000) NULL,
	[CantDoc] [int] NOT NULL DEFAULT ((0)),
	[FormaEnvio] [varchar](50) NULL,
	[NomRadica] [varchar](150) NULL,
	[CedRadica] [varchar](16) NULL,
	[Funcionario] [varchar](150) NULL,
	[Observacion] [varchar](2000) NULL,
	[NumeroCum] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCum] [char](2) NOT NULL DEFAULT ('00'),
	[FechaCum] [smalldatetime] NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraCumRemesas]    Script Date: 13/07/2021 10:39:34 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraCumRemesas] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('CUM'),
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[TipRem] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[Remesa] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRem] [char](2) NOT NULL DEFAULT ('01'),
	[ItemRem] [int] NOT NULL DEFAULT ((0)),
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[PesoNeto] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndMed] [varchar](10) NOT NULL,
	[Volumen] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndVol] [varchar](10) NOT NULL,
	[Cases] [int] NOT NULL DEFAULT ((0)),
	[Cajas] [int] NOT NULL DEFAULT ((0)),
	[Palets] [int] NOT NULL DEFAULT ((0)),
	[TarifClie] [money] NOT NULL DEFAULT ((0)),
	[TarifPago] [money] NOT NULL DEFAULT ((0)),
	[UndTarifClie] [varchar](10) NOT NULL DEFAULT ('PESO'),
	[UndTarifPago] [varchar](10) NOT NULL DEFAULT ('PESO'),
	[CantCargue] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[PesoCargue] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[VolCargue] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[CasesCargue] [int] NOT NULL DEFAULT ((0)),
	[CajasCargue] [int] NOT NULL DEFAULT ((0)),
	[PaletsCargue] [int] NOT NULL DEFAULT ((0)),
	[EstadoCump] [int] NOT NULL DEFAULT ((1)),
	[Remision] [decimal](18, 2) NOT NULL DEFAULT ((0)),
	[DocCliente] [varchar](30) NULL,
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[Detalle] [varchar](250) NULL,
	[TarifFlete] [money] NOT NULL DEFAULT ((0)),
	[TipoCumRemesa] [varchar](3) NULL,
	[MotivoSuspRem] [varchar](3) NULL,
	[HoraLlegaCargue] [smalldatetime] NULL,
	[HoraEntraCargue] [smalldatetime] NULL,
	[HoraSaleCargue] [smalldatetime] NULL,
	[HoraLlegaDescargue] [smalldatetime] NULL,
	[HoraEntraDescargue] [smalldatetime] NULL,
	[HoraSaleDescargue] [smalldatetime] NULL,
	[CodCCosto] [varchar](16) NULL,
	[CodSubCos] [varchar](16) NULL,
	[NitClieRem] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDespachos]    Script Date: 13/07/2021 10:39:36 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraDespachos] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[FecCargue] [smalldatetime] NOT NULL,
	[FecDespacho] [smalldatetime] NOT NULL,
	[IdOrigen] [varchar](8) NOT NULL,
	[IdDestino] [varchar](8) NOT NULL,
	[IdRuta] [varchar](4) NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[IdPoseedor] [varchar](16) NOT NULL,
	[NitRemite] [varchar](16) NOT NULL,
	[Remitente] [varchar](250) NOT NULL,
	[NitDestntario] [varchar](16) NOT NULL,
	[Destinatario] [varchar](250) NOT NULL DEFAULT ('varios'),
	[DescMcia] [varchar](150) NULL,
	[PesoTotal] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[NumOrden] [int] NOT NULL DEFAULT ((0)),
	[IdCiaOrd] [char](2) NOT NULL DEFAULT ('00'),
	[Remesa] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRem] [char](2) NOT NULL DEFAULT ('00'),
	[Estado] [int] NOT NULL DEFAULT ((0)),
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDespProgram]    Script Date: 13/07/2021 10:39:36 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraDespProgram] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[CdRuta] [varchar](4) NOT NULL,
	[IdPunto] [int] NOT NULL DEFAULT ((0)),
	[HoraProg] [smalldatetime] NOT NULL,
	[TipoProg] [int] NOT NULL DEFAULT ((0)),
	[IdUsuario] [varchar](11) NOT NULL,
	[FechaCrea] [smalldatetime] NOT NULL,
	[ObservProg] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevAnt]    Script Date: 13/07/2021 10:39:37 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraDevAnt] AS TABLE(
	[TipDev] [varchar](3) NOT NULL DEFAULT ('DVA'),
	[Devolucion] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('ANT'),
	[Anticipo] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NOT NULL DEFAULT ('01'),
	[FecDoc] [smalldatetime] NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdPoseedor] [varchar](16) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[VrDevolucion] [money] NOT NULL DEFAULT ((0)),
	[CdCta] [varchar](4) NOT NULL DEFAULT ('0'),
	[CdCuenta] [varchar](16) NOT NULL,
	[ModdDev] [varchar](10) NOT NULL DEFAULT ('TOTAL'),
	[OrigenAdd] [varchar](10) NOT NULL,
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevAos]    Script Date: 13/07/2021 10:39:38 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraDevAos] AS TABLE(
	[TipDev] [varchar](3) NOT NULL,
	[Devolucion] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[TipDoc] [varchar](3) NOT NULL,
	[Anticipo] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NOT NULL DEFAULT ('01'),
	[FecDoc] [smalldatetime] NOT NULL,
	[VrDevolucion] [money] NOT NULL DEFAULT ((0)),
	[CdCta] [varchar](4) NOT NULL DEFAULT ('0'),
	[CdCuenta] [varchar](16) NOT NULL,
	[ModdDev] [varchar](10) NOT NULL DEFAULT ('TOTAL'),
	[OrigenAdd] [varchar](10) NOT NULL,
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevCos]    Script Date: 13/07/2021 10:39:38 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraDevCos] AS TABLE(
	[TipDev] [varchar](3) NOT NULL,
	[Devolucion] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[TipDoc] [varchar](3) NOT NULL,
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NOT NULL DEFAULT ('01'),
	[FecDoc] [smalldatetime] NOT NULL,
	[ModdDev] [varchar](10) NOT NULL DEFAULT ('TOTAL'),
	[OrigenAdd] [varchar](10) NOT NULL,
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL,
	[Observacion] [varchar](250) NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraDevCum]    Script Date: 13/07/2021 10:39:39 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraDevCum] AS TABLE(
	[TipDev] [varchar](3) NOT NULL DEFAULT ('DCU'),
	[Devolucion] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('CUM'),
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NOT NULL DEFAULT ('01'),
	[FecDoc] [smalldatetime] NOT NULL,
	[ModdDev] [varchar](10) NOT NULL DEFAULT ('TOTAL'),
	[OrigenAdd] [varchar](10) NOT NULL,
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL,
	[Observacion] [varchar](250) NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspAntAbonos]    Script Date: 13/07/2021 10:39:40 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspAntAbonos] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Item] [int] NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NULL,
	[TipAnt] [varchar](3) NULL DEFAULT ('ANE'),
	[Anticipo] [int] NULL DEFAULT ((0)),
	[IdCiaAnt] [char](2) NULL,
	[VrAbono] [money] NULL DEFAULT ((0)),
	[TipoAplica] [varchar](10) NULL,
	[Detalle] [varchar](100) NULL,
	[CdCuentaAnt] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspAnticipos]    Script Date: 13/07/2021 10:39:40 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspAnticipos] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('ANE'),
	[Anticipo] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipRes] [varchar](3) NULL DEFAULT ('RES'),
	[Reserva] [int] NULL DEFAULT ((0)),
	[IdCiaRes] [char](2) NULL DEFAULT ('01'),
	[ItemRes] [int] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[VrAnticipo] [money] NULL DEFAULT ((0)),
	[VrAbonado] [money] NULL DEFAULT ((0)),
	[Modalidad] [varchar](10) NULL DEFAULT ('EGRESO'),
	[TipoPago] [varchar](10) NULL DEFAULT ('EFECTIVO'),
	[NumCheque] [varchar](20) NULL,
	[FecCheque] [smalldatetime] NULL,
	[IdCta] [varchar](4) NULL DEFAULT ('0'),
	[IdCuenta] [varchar](16) NULL,
	[Beneficiario] [varchar](150) NULL,
	[CedBenef] [varchar](16) NULL,
	[Cantidad] [decimal](14, 4) NULL DEFAULT ((0)),
	[FechaVence] [smalldatetime] NULL,
	[NumPresAnt] [int] NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NULL DEFAULT ('0'),
	[Comprobante] [int] NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NULL DEFAULT ('00'),
	[Anulado] [bit] NULL DEFAULT ((0)),
	[NumDev] [int] NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NULL,
	[PreAnticipo] [int] NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspAuxFactura]    Script Date: 13/07/2021 10:39:42 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspAuxFactura] AS TABLE(
	[TipFac] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaFac] [char](2) NULL,
	[Resolucion] [varchar](30) NULL,
	[Rango] [varchar](50) NULL,
	[FechaResl] [smalldatetime] NULL,
	[Prefijo] [varchar](5) NULL,
	[TipDocPf] [varchar](3) NULL,
	[PreFactura] [int] NULL,
	[IdCiaPf] [char](2) NULL,
	[CodigoPreFact] [varchar](3) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCauDetalle]    Script Date: 13/07/2021 10:39:42 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspCauDetalle] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Causacion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[IdConcepto] [varchar](4) NULL,
	[Descripcion] [varchar](250) NULL,
	[TipoConc] [varchar](10) NULL,
	[VrDebito] [money] NULL,
	[VrCredito] [money] NULL,
	[CdCuenta] [varchar](16) NULL,
	[NitTercero] [varchar](16) NULL,
	[CdCCosto] [varchar](16) NULL,
	[CdSubCos] [varchar](16) NULL,
	[pVehiculo] [varchar](10) NULL,
	[TipoAfiVehic] [varchar](10) NULL,
	[VrBase] [money] NULL,
	[TarifBase] [decimal](14, 4) NULL,
	[Referencia] [varchar](50) NULL,
	[TipDocRef] [varchar](3) NULL,
	[DocRef] [int] NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [varchar](15) NULL,
	[IdCiaFac] [char](2) NULL,
	[ItemFac] [int] NULL,
	[FecVence] [smalldatetime] NULL,
	[EstadoReg] [int] NULL,
	[TipoLiq] [varchar](3) NULL,
	[NumLiquida] [int] NULL,
	[CiaLiquida] [char](2) NULL,
	[VrAbonado] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCausacion]    Script Date: 13/07/2021 10:39:42 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspCausacion] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Causacion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[IdProv] [varchar](16) NULL,
	[Factura] [varchar](20) NULL,
	[VrTotal] [money] NULL,
	[VrOtros] [money] NULL,
	[VrNeto] [money] NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Anulado] [bit] NULL,
	[NumDev] [int] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspConceptos]    Script Date: 13/07/2021 10:39:42 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspConceptos] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Item] [int] NULL DEFAULT ((0)),
	[Descripcion] [varchar](250) NULL,
	[Tarifa] [decimal](14, 4) NULL DEFAULT ((0)),
	[TipoConc] [varchar](10) NULL DEFAULT ('DEDUCCION'),
	[RubroConcep] [varchar](20) NULL,
	[Cantidad] [decimal](14, 4) NULL DEFAULT ((0)),
	[VrUnitario] [money] NULL DEFAULT ((0)),
	[TarifIva] [decimal](14, 4) NULL DEFAULT ((0)),
	[IdConcepto] [varchar](4) NULL,
	[CdCuenta] [varchar](16) NULL DEFAULT ('0'),
	[NitTercero] [varchar](16) NULL DEFAULT ('0'),
	[CdTipoEsc] [varchar](4) NULL,
	[FechaNov] [smalldatetime] NULL,
	[VrBase] [money] NULL DEFAULT ((0)),
	[TipoTarif] [char](1) NULL DEFAULT ('$'),
	[RefConc] [varchar](50) NULL,
	[Fijos] [bit] NULL DEFAULT ((0)),
	[IncBaseRet] [int] NULL DEFAULT ((0)),
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[Cliente] [bit] NULL,
	[Conductor] [bit] NULL,
	[Vehiculo] [bit] NULL,
	[ItemDoc] [int] NULL DEFAULT ((0)),
	[IdVehiculo] [varchar](10) NULL DEFAULT ('0')
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoAdendos]    Script Date: 13/07/2021 10:39:43 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspContratoAdendos] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Adendo] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[TipCont] [varchar](3) NULL,
	[Contrato] [int] NULL,
	[IdCiaCont] [char](2) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoAnexo]    Script Date: 13/07/2021 10:39:43 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspContratoAnexo] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Contrato] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[TipContrato] [varchar](150) NULL,
	[IdContrato] [varchar](20) NULL,
	[IdObjCOE] [varchar](4) NULL,
	[ObjContrato] [varchar](1000) NULL,
	[NomCliente] [varchar](250) NULL,
	[TelCliente] [varchar](100) NULL,
	[emlCliente] [varchar](150) NULL,
	[DireccionCli] [varchar](250) NULL,
	[Observacion] [varchar](100) NULL,
	[NombArchivo] [varchar](100) NULL,
	[DescripCarga] [varchar](250) NULL,
	[Clausulas] [varchar](2500) NULL,
	[Responsable] [varchar](16) NULL,
	[NombreResp] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoDet]    Script Date: 13/07/2021 10:39:43 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspContratoDet] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Contrato] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[IdHorario] [varchar](3) NULL,
	[TipPed] [varchar](3) NULL,
	[Pedido] [int] NULL DEFAULT ((0)),
	[CiaPed] [char](2) NULL DEFAULT ('01'),
	[ItemPed] [int] NULL,
	[TipRes] [varchar](3) NULL,
	[NumRes] [int] NULL DEFAULT ((0)),
	[IdCiaRes] [char](2) NULL DEFAULT ('00'),
	[ItemRes] [int] NULL DEFAULT ((0)),
	[IdVehiculo] [varchar](10) NULL,
	[CdTipVeh] [varchar](4) NULL,
	[NumPasajeros] [int] NULL,
	[PesoNeto] [decimal](12, 4) NULL,
	[VrUnitario] [money] NULL,
	[VrPago] [money] NULL,
	[IdRuta] [varchar](4) NULL,
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[EsRutaCliente] [bit] NULL,
	[CdCiuOrigen] [varchar](8) NULL,
	[DirOrigen] [varchar](max) NULL,
	[FecOrigen] [datetime] NULL,
	[CdCiuDestino] [varchar](8) NULL,
	[DirDestino] [varchar](max) NULL,
	[FecDestino] [datetime] NULL,
	[DiasDisp] [int] NULL DEFAULT ((0)),
	[VrDia] [money] NULL DEFAULT ((0)),
	[Parada] [varchar](10) NULL,
	[CdTipRuta] [varchar](15) NULL,
	[CdTipServicio] [varchar](20) NULL,
	[CantVeh] [int] NULL,
	[Retorno] [bit] NULL,
	[VrMonitor] [decimal](14, 4) NULL,
	[CantMonitor] [int] NULL,
	[VrMaxRec] [decimal](14, 4) NULL,
	[NumDias] [int] NULL,
	[TipoTarifa] [varchar](10) NULL,
	[IdColegio] [varchar](4) NULL,
	[Codigo] [varchar](3) NULL,
	[Itinerario] [varchar](1000) NULL,
	[VLargo] [bit] NULL,
	[IdOtroSi] [int] NULL,
	[ItemAnuladoOS] [bit] NULL,
	[EsItemPME] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratos]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspContratos] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Contrato] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[FechaInicio] [smalldatetime] NULL,
	[FechaFin] [smalldatetime] NULL,
	[IdCliente] [varchar](16) NULL,
	[IdVend] [varchar](16) NULL,
	[IdTarifCom] [varchar](4) NULL,
	[IdForma] [varchar](4) NULL,
	[Plazos] [bit] NULL,
	[TipoPago] [varchar](10) NULL,
	[Modalidad] [varchar](10) NULL,
	[TipoLiquid] [varchar](8) NULL,
	[CodTarRet] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[VrPresupuesto] [money] NULL,
	[VrSaldoPresup] [money] NULL,
	[VrCobro] [money] NULL,
	[VrCargos] [money] NULL,
	[VrRetencion] [money] NULL,
	[VrReteIca] [money] NULL,
	[VrDctos] [money] NULL,
	[Cantidad] [decimal](14, 4) NULL,
	[Peso] [decimal](14, 4) NULL,
	[NumAprob] [int] NULL,
	[IdCiaApr] [char](2) NULL,
	[FecAprob] [smalldatetime] NULL,
	[TipOdp] [varchar](3) NULL,
	[NumOdp] [int] NULL,
	[IdCiaOdp] [char](2) NULL,
	[FechaOdp] [smalldatetime] NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaFac] [char](2) NULL,
	[FechaFac] [smalldatetime] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[EsLicitacion] [bit] NULL,
	[Anulado] [bit] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](1000) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[CdCarga] [varchar](15) NULL,
	[IdAgencia] [varchar](16) NULL,
	[IdMneda] [varchar](5) NULL,
	[VrIva] [money] NULL,
	[CantPasajeros] [decimal](14, 4) NULL,
	[CdDescuento] [varchar](4) NULL,
	[UnionTemporal] [varchar](250) NULL,
	[IdGrupo] [varchar](4) NULL,
	[IdRutaG] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspContratoVehLista]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspContratoVehLista] AS TABLE(
	[IdLista] [int] NULL,
	[TipDoc] [varchar](3) NULL,
	[Contrato] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[Fecha] [datetime] NULL,
	[IdEstado] [varchar](4) NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumFacturas]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspCumFacturas] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Cumplido] [int] NULL,
	[IdCia] [char](2) NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaFac] [char](2) NULL,
	[IdCliente] [varchar](16) NULL,
	[VrIngreso] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumplido]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspCumplido] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Cumplido] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaFac] [char](2) NULL,
	[IdClieFac] [varchar](16) NULL,
	[CdRuta] [varchar](4) NULL,
	[CdOrigen] [varchar](8) NULL,
	[CdDestino] [varchar](8) NULL,
	[Anulado] [bit] NULL,
	[NumDev] [int] NULL,
	[FecDev] [smalldatetime] NULL,
	[TipoComp] [varchar](3) NULL,
	[NumComp] [int] NULL,
	[CodConcepto] [varchar](4) NULL,
	[Observacion] [varchar](1000) NULL,
	[IdEstado] [varchar](4) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[ObservAnulado] [varchar](250) NULL,
	[CdCenCosto] [varchar](16) NULL,
	[CdSubCenCos] [varchar](16) NULL,
	[VrPago] [money] NULL,
	[VrCobro] [money] NULL,
	[VrAfiliados] [money] NULL,
	[VrPropios] [money] NULL,
	[VrTotalServ] [money] NULL,
	[VrTotalPagos] [money] NULL,
	[CodTarRtc] [varchar](4) NULL,
	[BaseRet] [money] NULL,
	[VrReteCree] [money] NULL,
	[VrNeto] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumplidoProg]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspCumplidoProg] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Cumplido] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[TipPgr] [varchar](3) NULL,
	[Programa] [int] NULL,
	[IdCiaPgr] [char](2) NULL,
	[ItemPgr] [int] NULL,
	[VrRecorrido] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspCumReservas]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspCumReservas] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Cumplido] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[EstadoItemRes] [varchar](20) NULL,
	[VrRecorridos] [money] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[TipoAfil] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevAnt]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspDevAnt] AS TABLE(
	[TipDev] [varchar](3) NULL DEFAULT ('DAE'),
	[Devolucion] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipDoc] [varchar](3) NULL DEFAULT ('ANE'),
	[Anticipo] [int] NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NULL DEFAULT ('01'),
	[FecDoc] [smalldatetime] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[VrDevolucion] [money] NULL DEFAULT ((0)),
	[CdCta] [varchar](4) NULL DEFAULT ('0'),
	[CdCuenta] [varchar](16) NULL,
	[ModdDev] [varchar](10) NULL DEFAULT ('TOTAL'),
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevCau]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspDevCau] AS TABLE(
	[TipDev] [varchar](3) NULL,
	[Devolucion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipDoc] [varchar](3) NULL,
	[Causacion] [int] NULL,
	[IdCiaDoc] [char](2) NULL,
	[FecDoc] [smalldatetime] NULL,
	[IdProv] [varchar](16) NULL,
	[Factura] [varchar](20) NULL,
	[VrTotal] [money] NULL,
	[VrOtros] [money] NULL,
	[VrNeto] [money] NULL,
	[ModdDev] [varchar](10) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevCum]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspDevCum] AS TABLE(
	[TipDev] [varchar](3) NULL,
	[Devolucion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipDoc] [varchar](3) NULL,
	[Cumplido] [int] NULL,
	[IdCiaDoc] [char](2) NULL,
	[FecDoc] [smalldatetime] NULL,
	[ModdDev] [varchar](10) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Observacion] [varchar](250) NULL,
	[TimeSys] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevLiq]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspDevLiq] AS TABLE(
	[TipDev] [varchar](3) NULL,
	[Devolucion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipDoc] [varchar](3) NULL,
	[Liquidacion] [int] NULL,
	[IdCiaDoc] [char](2) NULL,
	[FecDoc] [smalldatetime] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[VrTotal] [money] NULL,
	[ModdDev] [varchar](10) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspDevOdp]    Script Date: 13/07/2021 10:39:44 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspDevOdp] AS TABLE(
	[TipDev] [varchar](3) NOT NULL,
	[Devolucion] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[TipDoc] [varchar](3) NOT NULL,
	[OrdPago] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDoc] [char](2) NOT NULL DEFAULT ('01'),
	[FecDoc] [smalldatetime] NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdPoseedor] [varchar](16) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[CxPagar] [bit] NOT NULL DEFAULT ((0)),
	[ModdDev] [varchar](10) NOT NULL DEFAULT ('TOTAL'),
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[OrigenAdd] [varchar](10) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFacReservas]    Script Date: 13/07/2021 10:39:45 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspFacReservas] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipoReg] [int] NULL,
	[FechaFact] [smalldatetime] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[FecReserva] [smalldatetime] NULL,
	[Descripcion] [varchar](250) NULL,
	[Cantidad] [decimal](14, 4) NULL,
	[VrServicio] [money] NULL,
	[VrUnitario] [money] NULL,
	[VrCosto] [money] NULL,
	[TarifaIva] [decimal](14, 4) NULL,
	[VrImpuesto] [money] NULL,
	[TarifaDct] [decimal](14, 4) NULL,
	[VrDescuento] [money] NULL,
	[DocCliente] [varchar](30) NULL,
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[CdConcepto] [varchar](4) NULL,
	[CdCCosto] [varchar](16) NULL,
	[CdSubCos] [varchar](16) NULL,
	[NitTercero] [varchar](16) NULL,
	[CdAgencia] [varchar](16) NULL,
	[pVehiculo] [varchar](10) NULL,
	[TipoAfiVehic] [varchar](10) NULL,
	[IdOrigen] [varchar](8) NULL,
	[IdDestino] [varchar](8) NULL,
	[Anulado] [int] NULL,
	[TipDocRef] [varchar](3) NULL,
	[NumDocRef] [int] NULL,
	[IdCiaRef] [char](2) NULL,
	[FecDocRef] [smalldatetime] NULL,
	[CodTarDct] [varchar](4) NULL,
	[CodTarRet] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[TarifaRet] [decimal](14, 4) NULL,
	[VrRetencion] [money] NULL,
	[TarifaIca] [decimal](14, 4) NULL,
	[VrReteIca] [money] NULL,
	[EstadoItem] [varchar](20) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFacResVehiculos]    Script Date: 13/07/2021 10:39:45 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspFacResVehiculos] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[TipoAfil] [varchar](10) NULL,
	[VrRecorrido] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuec]    Script Date: 13/07/2021 10:39:45 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspFuec] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('FUE'),
	[Fuec] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Numero] [varchar](21) NULL,
	[Fecha] [datetime] NULL,
	[FechaInicio] [smalldatetime] NULL,
	[FechaFin] [smalldatetime] NULL,
	[CdCarga] [varchar](15) NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdConductor] [varchar](16) NULL,
	[IdConductor2] [varchar](16) NULL,
	[IdConductor3] [varchar](16) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdRuta] [varchar](4) NULL,
	[CdTipRuta] [varchar](15) NULL,
	[IdOrigen] [varchar](8) NULL,
	[IdDestino] [varchar](8) NULL,
	[Modalidad] [varchar](10) NULL,
	[CantPasajeros] [decimal](14, 4) NULL DEFAULT ((0)),
	[CodTarRet] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[VrPresupuesto] [money] NULL DEFAULT ((0)),
	[VrCobro] [money] NULL DEFAULT ((0)),
	[VrPagos] [money] NULL DEFAULT ((0)),
	[VrCargos] [money] NULL DEFAULT ((0)),
	[VrDctos] [money] NULL DEFAULT ((0)),
	[VrIva] [money] NULL DEFAULT ((0)),
	[VrRetencion] [money] NULL DEFAULT ((0)),
	[VrReteIca] [money] NULL DEFAULT ((0)),
	[Cantidad] [decimal](14, 4) NULL DEFAULT ((0)),
	[Peso] [decimal](14, 4) NULL DEFAULT ((0)),
	[TipDocPgr] [varchar](3) NULL DEFAULT ('0'),
	[NumPgr] [int] NULL DEFAULT ((0)),
	[IdCiaPgr] [char](2) NULL DEFAULT ('00'),
	[ItemPgr] [int] NULL DEFAULT ((0)),
	[TipDocCnt] [varchar](3) NULL,
	[Contrato] [int] NULL,
	[CiaCnt] [char](2) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[Anulado] [bit] NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NULL,
	[Consecutivo] [int] NULL,
	[Itinerario] [varchar](1000) NULL,
	[FuecParcial] [bit] NULL DEFAULT ((0)),
	[ComenParcial] [varchar](500) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuecAnexo]    Script Date: 13/07/2021 10:39:47 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspFuecAnexo] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('FUE'),
	[Fuec] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[TipContrato] [varchar](150) NULL,
	[IdContrato] [varchar](20) NULL,
	[ObjContrato] [varchar](1000) NULL,
	[DescripCarga] [varchar](250) NULL,
	[Observacion] [varchar](1000) NULL,
	[RespViaje] [varchar](300) NULL,
	[VehConvenio] [bit] NULL DEFAULT ((0)),
	[EmpresaVehCon] [varchar](16) NULL DEFAULT ('0')
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuecCndtores]    Script Date: 13/07/2021 10:39:47 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspFuecCndtores] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('FUE'),
	[Fuec] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('02'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[IdConductor] [varchar](16) NOT NULL DEFAULT ('0')
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspFuecDetalle]    Script Date: 13/07/2021 10:39:47 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspFuecDetalle] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('FUE'),
	[Fuec] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Item] [int] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL DEFAULT ((0)),
	[IdCiaRes] [char](2) NULL DEFAULT ('00'),
	[ItemRes] [int] NULL DEFAULT ((0)),
	[NumPasajeros] [int] NULL,
	[PesoNeto] [decimal](12, 4) NULL,
	[VrCobro] [money] NULL DEFAULT ((0)),
	[VrPagos] [money] NULL DEFAULT ((0)),
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[CdTipServicio] [varchar](20) NULL,
	[EsRutaCliente] [bit] NULL,
	[Kilometros] [decimal](14, 4) NULL,
	[DirOrigen] [varchar](max) NULL,
	[FecOrigen] [datetime] NULL,
	[DirDestino] [varchar](max) NULL,
	[FecDestino] [datetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquida]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspLiquida] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Liquidacion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[VrTotal] [money] NULL,
	[CxPagar] [bit] NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Anulado] [bit] NULL,
	[NumDev] [int] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[FecIniCau] [smalldatetime] NULL,
	[FecFinCau] [smalldatetime] NULL,
	[FecIniOdp] [smalldatetime] NULL,
	[FecFinOdp] [smalldatetime] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[ModLiquida] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquidaDed]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspLiquidaDed] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Liquidacion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipCau] [varchar](3) NULL,
	[Causacion] [int] NULL,
	[IdCiaCau] [char](2) NULL,
	[ItemCau] [int] NULL,
	[FechaCau] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[Descripcion] [varchar](250) NULL,
	[VrAbono] [money] NULL,
	[NitPoseedor] [varchar](16) NULL,
	[pVehiculo] [varchar](10) NULL,
	[EsVence] [bit] NULL,
	[TipOdp] [varchar](3) NULL,
	[OrdenPago] [int] NULL,
	[IdCiaOdp] [char](2) NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[VrSaldoOrden] [money] NULL,
	[CdCuenta] [varchar](16) NULL,
	[CdCuePagar] [varchar](16) NULL,
	[NumFactura] [varchar](20) NULL,
	[CdCCosto] [varchar](16) NULL,
	[CdSubCos] [varchar](16) NULL,
	[TipoFac] [varchar](3) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquidaOdp]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspLiquidaOdp] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Liquidacion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipOdp] [varchar](3) NULL,
	[OrdPago] [int] NULL,
	[IdCiaOdp] [char](2) NULL,
	[VrAbonado] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspLiquidaOtr]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspLiquidaOtr] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Liquidacion] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipCau] [varchar](3) NULL,
	[Causacion] [int] NULL,
	[IdCiaCau] [char](2) NULL,
	[ItemCau] [int] NULL,
	[Factura] [varchar](15) NULL,
	[ItemFac] [int] NULL,
	[IdProveedor] [varchar](16) NULL,
	[pVehiculo] [varchar](10) NULL,
	[VrAbono] [money] NULL,
	[TipFac] [varchar](3) NULL,
	[VrFactura] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspListaPasajeros]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspListaPasajeros] AS TABLE(
	[IdLista] [int] NULL,
	[Documento] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOrdenPago]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspOrdenPago] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[OrdPago] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[IdConcepto] [varchar](4) NULL,
	[Cantidad] [int] NULL,
	[Modalidad] [varchar](10) NULL,
	[LiqReservas] [bit] NULL,
	[CxPagar] [bit] NULL,
	[MulPlazos] [bit] NULL,
	[IdPlazo] [varchar](4) NULL,
	[FechaVence] [smalldatetime] NULL,
	[TipCom] [varchar](3) NULL,
	[Comprobante] [int] NULL,
	[IdCiaCom] [char](2) NULL,
	[Anulado] [bit] NULL,
	[NumDev] [int] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOrdenProg]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspOrdenProg] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[OrdPago] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[TipPgr] [varchar](3) NULL,
	[Programa] [int] NOT NULL,
	[IdCiaPgr] [char](2) NULL,
	[ItemPgr] [int] NULL,
	[VrRecorrido] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOrdenReservas]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspOrdenReservas] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[OrdPago] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[TipRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdConductor] [varchar](16) NULL,
	[IdPropietario] [varchar](16) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[VrServicio] [money] NULL,
	[VrDescuento] [money] NULL,
	[VrRetencion] [money] NULL,
	[VrReteIca] [money] NULL,
	[VrReteCREE] [money] NULL,
	[VrAnticipos] [money] NULL,
	[VrOtrosDctos] [money] NULL,
	[VrImpuestos] [money] NULL,
	[VrOtrosPagos] [money] NULL,
	[VrNeto] [money] NULL,
	[BaseRet] [money] NULL,
	[BaseIca] [money] NULL,
	[BaseCree] [money] NULL,
	[TarifaRet] [decimal](14, 4) NULL,
	[TarifaIca] [decimal](14, 4) NULL,
	[TarifaRtc] [decimal](14, 4) NULL,
	[CodTarRet] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[CodTarRtc] [varchar](4) NULL,
	[TipEgr] [varchar](3) NULL,
	[Egreso] [int] NULL,
	[IdCiaEgr] [char](2) NULL,
	[FechaEgr] [smalldatetime] NULL,
	[NumCheque] [varchar](20) NULL,
	[Referencia] [varchar](50) NULL,
	[VrConcPagos] [money] NULL,
	[VrConcDctos] [money] NULL,
	[VrConcFondo] [money] NULL,
	[VrConcSeguro] [money] NULL,
	[VrConcAporte] [money] NULL,
	[VrConcImpuesto] [money] NULL,
	[VrRecCaja] [money] NULL,
	[CdForma] [varchar](4) NULL,
	[CdCenCosto] [varchar](16) NULL,
	[CdSubCenCos] [varchar](16) NULL,
	[VrSeguros] [money] NOT NULL DEFAULT ((0)),
	[VrFondos] [money] NOT NULL DEFAULT ((0)),
	[VrAportes] [money] NOT NULL DEFAULT ((0)),
	[EdoLiqCausac] [int] NOT NULL DEFAULT ((0)),
	[EstadoItem] [varchar](20) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOtroSi]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspOtroSi] AS TABLE(
	[IdOtroSi] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[Adicion] [bit] NULL,
	[CFecha] [bit] NULL,
	[Items] [bit] NULL,
	[Aplicado] [bit] NULL,
	[TimeSys] [smalldatetime] NULL,
	[Observacion] [varchar](500) NULL,
	[IdUsuario] [varchar](11) NULL,
	[Anulado] [bit] NULL,
	[FecDev] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspOtroSiContratos]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspOtroSiContratos] AS TABLE(
	[IdOtroSi] [int] NULL,
	[TipDocCnt] [varchar](3) NULL,
	[Contrato] [int] NULL,
	[IdCiaCnt] [char](2) NULL,
	[FechaFinAnt] [smalldatetime] NULL,
	[FechaFinNew] [smalldatetime] NULL,
	[VrPpto] [money] NULL,
	[VrSaldoPpo] [money] NULL,
	[VrAdicionPpto] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPasajeros]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspPasajeros] AS TABLE(
	[TipId] [varchar](2) NOT NULL,
	[Documento] [varchar](16) NOT NULL,
	[Apellidos] [varchar](250) NULL,
	[Nombres] [varchar](250) NULL,
	[Cargo] [varchar](250) NULL,
	[EsMonitor] [bit] NULL,
	[Telefono] [varchar](20) NULL,
	[Observacion] [varchar](250) NULL,
	[EsEstudiante] [bit] NULL,
	[IdResponsable] [varchar](16) NULL,
	[Porcentaje] [decimal](14, 4) NULL,
	[VrPago] [decimal](14, 4) NULL,
	[IdColegio] [varchar](4) NULL,
	[CdEstudiante] [varchar](16) NULL,
	[Jornada] [varchar](250) NULL,
	[Sede] [varchar](4) NULL,
	[Inactivo] [bit] NULL,
	[FechaNac] [smalldatetime] NULL,
	[IncluirPeriodo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPedAnexo]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspPedAnexo] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Pedido] [int] NULL,
	[IdCia] [char](2) NULL,
	[NomCliente] [varchar](150) NULL,
	[DirCliente] [varchar](250) NULL,
	[NomContacto] [varchar](150) NULL,
	[TelContacto] [varchar](30) NULL,
	[emlContacto] [varchar](100) NULL,
	[emlCliente] [varchar](100) NULL,
	[DescripCarga] [varchar](250) NULL,
	[Clausulas] [varchar](2500) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPedDetalle]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspPedDetalle] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Pedido] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[CdTipVeh] [varchar](4) NULL,
	[NumPasajeros] [int] NULL,
	[Parada] [varchar](10) NULL,
	[PesoNeto] [decimal](12, 4) NULL,
	[VrUnitario] [money] NULL,
	[IdRuta] [varchar](4) NULL,
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[EsRutaCliente] [bit] NULL,
	[CdCiuOrigen] [varchar](8) NULL,
	[DirOrigen] [varchar](max) NULL,
	[FecOrigen] [datetime] NULL,
	[CdCiuDestino] [varchar](8) NULL,
	[DirDestino] [varchar](max) NULL,
	[FecDestino] [datetime] NULL,
	[CdTipRuta] [varchar](15) NULL,
	[CdTipServicio] [varchar](20) NULL,
	[DiasDisp] [int] NULL,
	[VrDia] [money] NULL,
	[TipCtn] [varchar](3) NULL,
	[NumCnt] [int] NULL,
	[IdCiaCnt] [char](2) NULL,
	[ItemCnt] [int] NULL,
	[CantVeh] [int] NULL,
	[Retorno] [bit] NULL,
	[VrMonitor] [decimal](14, 4) NULL,
	[CantMonitor] [int] NULL,
	[TipoTarifa] [varchar](10) NULL,
	[Dias] [int] NULL,
	[Itinerario] [varchar](1000) NULL,
	[VLargo] [bit] NULL,
	[ItemPpalRet] [int] NULL,
	[CiaPpalRet] [char](2) NULL,
	[VrPago] [money] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPedido]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspPedido] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Pedido] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [smalldatetime] NULL,
	[FechaVence] [smalldatetime] NULL,
	[FecInicio] [smalldatetime] NULL,
	[FecFinal] [smalldatetime] NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL,
	[IdVend] [varchar](16) NULL,
	[IdTarifCom] [varchar](4) NULL,
	[TipoContrato] [varchar](10) NULL,
	[TipoPago] [varchar](10) NULL,
	[Modalidad] [varchar](10) NULL,
	[Vigencia] [varchar](10) NULL,
	[VrCobro] [money] NULL,
	[VrPagos] [money] NULL,
	[VrCargos] [money] NULL,
	[VrDctos] [money] NULL,
	[VrIva] [money] NULL,
	[CdDescuento] [varchar](4) NULL,
	[Presupuesto] [money] NULL,
	[CantPasajeros] [decimal](14, 4) NULL,
	[Cantidad] [decimal](14, 4) NULL,
	[Peso] [decimal](14, 4) NULL,
	[IdMneda] [varchar](5) NULL,
	[NumAprob] [int] NULL,
	[IdCiaApr] [char](2) NULL,
	[FecAprob] [smalldatetime] NULL,
	[EsLicitacion] [bit] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[Anulado] [bit] NULL,
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](1000) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL,
	[CdCarga] [varchar](15) NULL,
	[VrEditado] [money] NULL,
	[CantDias] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPicoPlaca]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspPicoPlaca] AS TABLE(
	[IdLocal] [varchar](8) NULL,
	[Fecha] [datetime] NULL,
	[UltimoDig] [varchar](50) NULL,
	[Observacion] [varchar](250) NULL,
	[ClaseMat] [varchar](250) NULL,
	[IdTipoVeh] [varchar](250) NULL,
	[Horas] [varchar](250) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspPrograma]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspPrograma] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Programa] [int] NULL,
	[IdCia] [char](2) NULL,
	[Fecha] [datetime] NULL,
	[OrigenAdd] [varchar](10) NULL,
	[Anulado] [bit] NULL,
	[FecDev] [smalldatetime] NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspProgramaDet]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspProgramaDet] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Programa] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[FechaInicio] [datetime] NULL,
	[FechaFin] [datetime] NULL,
	[TipDocRes] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCiaRes] [char](2) NULL,
	[ItemRes] [int] NULL,
	[IdOrigen] [varchar](8) NULL,
	[IdDestino] [varchar](8) NULL,
	[IdVehiculo] [varchar](10) NULL,
	[CdTipVeh] [varchar](4) NULL,
	[IdConductor] [varchar](16) NULL,
	[NumPasajeros] [int] NULL,
	[TipDocFuec] [varchar](3) NULL,
	[NumFuec] [int] NULL,
	[IdCiaFuec] [char](2) NULL,
	[TipDocOdp] [varchar](3) NULL,
	[NumOdp] [int] NULL,
	[IdCiaOdp] [char](2) NULL,
	[FechaOdp] [smalldatetime] NULL,
	[IdNovedad] [varchar](4) NULL,
	[Novedad] [varchar](250) NULL,
	[Cumplido] [bit] NULL,
	[FecIniCump] [datetime] NULL,
	[FecFinCump] [datetime] NULL,
	[VrCobro] [money] NULL,
	[VrPagos] [money] NULL,
	[DiasDisp] [int] NULL,
	[Parada] [varchar](10) NULL,
	[CdTipServicio] [varchar](20) NULL,
	[DirOrigen] [varchar](max) NULL,
	[DirDestino] [varchar](max) NULL,
	[IdRuta] [varchar](4) NULL,
	[CdTipRuta] [varchar](15) NULL,
	[PesoNeto] [decimal](12, 4) NULL,
	[EstadoItem] [bit] NULL,
	[VrMonitor] [decimal](14, 4) NULL,
	[CantMonitor] [int] NULL,
	[VrRecorrido] [decimal](14, 4) NULL,
	[Observacion] [varchar](max) NULL,
	[VLargo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspProgramaPers]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspProgramaPers] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Programa] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[Nit] [varchar](16) NULL,
	[IdNovedad] [varchar](4) NULL,
	[Novedad] [varchar](250) NULL,
	[Cumplido] [bit] NULL,
	[IdRuta] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspResAnexo]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspResAnexo] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCia] [char](2) NULL,
	[NomCliente] [varchar](250) NULL,
	[TelCliente] [varchar](100) NULL,
	[emlCliente] [varchar](150) NULL,
	[DireccionCli] [varchar](100) NULL,
	[Observacion] [varchar](1000) NULL,
	[NombArchivo] [varchar](100) NULL,
	[DescripCarga] [varchar](250) NULL,
	[Clausulas] [varchar](2500) NULL,
	[Responsable] [varchar](100) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspResDetalle]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspResDetalle] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Reserva] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[ItemCnt] [int] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[CdTipVeh] [varchar](4) NULL,
	[IdConductor] [varchar](16) NULL,
	[IdRuta] [varchar](4) NULL,
	[CdTipRuta] [varchar](15) NULL,
	[NumPasajeros] [int] NULL,
	[PesoNeto] [decimal](12, 4) NULL,
	[VrCobro] [money] NULL,
	[VrPagos] [money] NULL,
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[EsRutaCliente] [bit] NULL,
	[CdCiuOrigen] [varchar](8) NULL,
	[DirOrigen] [varchar](max) NULL,
	[FecOrigen] [datetime] NULL,
	[CdCiuDestino] [varchar](8) NULL,
	[DirDestino] [varchar](max) NULL,
	[FecDestino] [datetime] NULL,
	[DiasDisp] [int] NULL,
	[VrDia] [money] NULL,
	[Parada] [varchar](10) NULL,
	[CdTipServicio] [varchar](20) NULL,
	[EstadoItem] [varchar](20) NULL,
	[VrMonitor] [decimal](14, 4) NULL,
	[CantMonitor] [int] NULL,
	[VrRecorrido] [decimal](14, 4) NULL,
	[NumDias] [int] NULL,
	[TipoTarifa] [varchar](10) NULL,
	[IdColegio] [varchar](4) NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaFac] [char](2) NULL,
	[FechaFac] [smalldatetime] NULL,
	[TipCum] [varchar](3) NULL,
	[Cumplido] [int] NULL,
	[IdCiaCum] [char](2) NULL,
	[FechaCum] [smalldatetime] NULL,
	[Codigo] [varchar](3) NULL,
	[Itinerario] [varchar](1000) NULL,
	[VLargo] [bit] NULL,
	[IdOtroSi] [int] NULL,
	[EsItemPME] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspReservas]    Script Date: 13/07/2021 10:39:48 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspReservas] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('RES'),
	[Reserva] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Fecha] [datetime] NULL,
	[FechaInicio] [datetime] NULL,
	[FechaFin] [datetime] NULL,
	[TipDocCnt] [varchar](3) NULL,
	[Contrato] [int] NULL,
	[IdCiaCnt] [char](2) NULL,
	[EstadoRes] [varchar](20) NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL DEFAULT ('0'),
	[IdMneda] [varchar](5) NULL DEFAULT ('COP'),
	[CdCarga] [varchar](15) NULL,
	[Modalidad] [varchar](10) NULL,
	[TipoLiquid] [varchar](8) NULL,
	[TipFac] [varchar](3) NULL,
	[Factura] [int] NULL DEFAULT ((0)),
	[IdCiaFac] [char](2) NULL DEFAULT ('00'),
	[FechaFac] [smalldatetime] NULL,
	[TipFuec] [varchar](3) NULL,
	[NumFuec] [int] NULL DEFAULT ((0)),
	[IdCiaFuec] [char](2) NULL DEFAULT ('00'),
	[VrCobro] [money] NULL DEFAULT ((0)),
	[VrPagos] [money] NULL DEFAULT ((0)),
	[OrigenAdd] [varchar](10) NULL,
	[Anulado] [bit] NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NULL,
	[IdGrupo] [varchar](4) NULL,
	[IdRutaG] [varchar](4) NULL,
	[NoRequiereGIE] [bit] NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspReservaVehLista]    Script Date: 13/07/2021 10:39:49 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspReservaVehLista] AS TABLE(
	[IdLista] [int] NOT NULL,
	[TipDoc] [varchar](3) NOT NULL,
	[Reserva] [int] NOT NULL,
	[IdCia] [char](2) NOT NULL,
	[Item] [int] NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[Fecha] [datetime] NOT NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NOT NULL,
	[IdListaCOE] [int] NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraEspSedes]    Script Date: 13/07/2021 10:39:49 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraEspSedes] AS TABLE(
	[IdColegio] [varchar](4) NULL,
	[IdSede] [varchar](4) NULL,
	[NomSede] [varchar](250) NULL,
	[Inactivo] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraInfViajes]    Script Date: 13/07/2021 10:39:49 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraInfViajes] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('OCV'),
	[NumViaje] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[IdOrigen] [varchar](8) NOT NULL,
	[IdDestino] [varchar](8) NOT NULL,
	[IdRuta] [varchar](4) NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdPoseedor] [varchar](16) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[nRemolque] [varchar](10) NULL,
	[TipoAfiVehic] [varchar](10) NOT NULL DEFAULT ('TERCEROS'),
	[VrFletes] [money] NOT NULL DEFAULT ((0)),
	[PesoTotal] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[NumManif] [int] NOT NULL DEFAULT ((0)),
	[IdCiaManif] [char](2) NOT NULL DEFAULT ('00'),
	[NumMintrans] [decimal](14, 2) NOT NULL DEFAULT ((0)),
	[MvoAnulacion] [varchar](5) NULL,
	[OrigenAdd] [varchar](10) NOT NULL,
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraInfViajesOrd]    Script Date: 13/07/2021 10:39:50 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraInfViajesOrd] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('OCV'),
	[NumViaje] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[TipOrden] [varchar](3) NOT NULL DEFAULT ('OCT'),
	[NumOrden] [int] NOT NULL DEFAULT ((0)),
	[IdCiaOrd] [char](2) NOT NULL DEFAULT ('01'),
	[ItemOrd] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraManifAnexo]    Script Date: 13/07/2021 10:39:51 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraManifAnexo] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[kmsTotal] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[VrFleteTon] [money] NOT NULL DEFAULT ((0)),
	[TipoRuta] [varchar](10) NULL DEFAULT ('URBANO'),
	[CdLocTrao] [varchar](8) NULL,
	[CdLocTrad] [varchar](8) NULL,
	[KmsTraOri] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[KmsTraDes] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[IdMneda] [varchar](5) NOT NULL DEFAULT ('COP'),
	[VrTasa] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[NomRemite] [varchar](150) NULL,
	[NomDestino] [varchar](150) NULL,
	[LugarFletes] [varchar](100) NULL,
	[NumAnticipo] [int] NOT NULL DEFAULT ((0)),
	[NumCheque] [varchar](20) NULL,
	[TipoMintrans] [varchar](10) NULL DEFAULT ('GENERAL'),
	[MucMintrans] [int] NOT NULL DEFAULT ((0)),
	[ContIntegral] [int] NOT NULL DEFAULT ((0)),
	[VolumenCarga] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[NumPoliza] [varchar](30) NULL,
	[CdBodDtno] [varchar](4) NULL,
	[TipoTrslado] [int] NULL DEFAULT ((0)),
	[MvoAnulacion] [varchar](5) NULL,
	[MvoSuspension] [varchar](5) NULL,
	[WsSeguro] [bit] NULL DEFAULT ((0)),
	[NumRadSeguro] [decimal](18, 2) NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraManifiesto]    Script Date: 13/07/2021 10:39:52 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraManifiesto] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[FecDespacho] [smalldatetime] NOT NULL,
	[FecEntrega] [smalldatetime] NULL,
	[IdOrigen] [varchar](8) NOT NULL,
	[IdDestino] [varchar](8) NOT NULL,
	[IdRuta] [varchar](4) NOT NULL,
	[IdRutaFle] [varchar](4) NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[nRemolque] [varchar](10) NULL,
	[TipoAfiVehic] [varchar](10) NOT NULL DEFAULT ('TERCEROS'),
	[IdPropietario] [varchar](16) NOT NULL,
	[IdPoseedor] [varchar](16) NOT NULL,
	[VrFletes] [money] NOT NULL DEFAULT ((0)),
	[VrRetencion] [money] NOT NULL DEFAULT ((0)),
	[VrReteIca] [money] NOT NULL DEFAULT ((0)),
	[VrDescuento] [money] NOT NULL DEFAULT ((0)),
	[VrAnticipo] [money] NOT NULL DEFAULT ((0)),
	[VrAntAdic] [money] NOT NULL DEFAULT ((0)),
	[VrNeto] [money] NOT NULL DEFAULT ((0)),
	[VrPagos] [money] NOT NULL DEFAULT ((0)),
	[VrCargos] [money] NOT NULL DEFAULT ((0)),
	[VrDctos] [money] NOT NULL DEFAULT ((0)),
	[TarifaFlete] [money] NOT NULL DEFAULT ((0)),
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[PesoTotal] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[BaseRet] [money] NOT NULL DEFAULT ((0)),
	[TarifaRet] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[TarifaIca] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[CodTarRet] [varchar](4) NULL,
	[CodTarIca] [varchar](4) NULL,
	[IdLocFletes] [varchar](8) NOT NULL,
	[FechaPago] [smalldatetime] NULL,
	[PagoCargue] [varchar](50) NOT NULL,
	[PagoDescargue] [varchar](50) NOT NULL,
	[NumMintrans] [decimal](14, 2) NOT NULL DEFAULT ((0)),
	[EdoMintrans] [varchar](5) NULL,
	[Remesa] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRem] [char](2) NOT NULL DEFAULT ('00'),
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCump] [char](2) NOT NULL DEFAULT ('00'),
	[FechaCump] [smalldatetime] NULL,
	[EstCumplido] [int] NOT NULL DEFAULT ((0)),
	[TipOdp] [varchar](3) NOT NULL DEFAULT ('0'),
	[OrdPago] [int] NOT NULL DEFAULT ((0)),
	[IdCiaOdp] [char](2) NOT NULL DEFAULT ('00'),
	[FechaOdp] [smalldatetime] NULL,
	[EstOrden] [int] NOT NULL DEFAULT ((0)),
	[OrigenAdd] [varchar](10) NOT NULL,
	[TipCom] [varchar](3) NOT NULL DEFAULT ('0'),
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL DEFAULT ('00'),
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL,
	[VrFleteNeto] [money] NOT NULL DEFAULT ((0)),
	[TipInfVia] [varchar](3) NULL,
	[NumViaje] [int] NOT NULL DEFAULT ((0)),
	[CiaInfViaje] [char](2) NULL,
	[CdCatPeaje] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraManifRem]    Script Date: 13/07/2021 10:39:55 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraManifRem] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[TipRem] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[Remesa] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRem] [char](2) NOT NULL DEFAULT ('01'),
	[ItemRem] [int] NOT NULL DEFAULT ((0)),
	[TarifTabla] [money] NOT NULL DEFAULT ((0)),
	[TarifPago] [money] NOT NULL DEFAULT ((0)),
	[RemMintrans] [decimal](14, 2) NOT NULL DEFAULT ((0)),
	[EdoRemMin] [varchar](5) NULL,
	[CodBodDtno] [varchar](4) NULL,
	[TipTraslado] [int] NULL DEFAULT ((0)),
	[HorasCargue] [decimal](14, 4) NULL DEFAULT ((0)),
	[HorasDesc] [decimal](14, 4) NULL DEFAULT ((0)),
	[FecInicioCargue] [smalldatetime] NULL,
	[FecFinCargue] [smalldatetime] NULL,
	[FecIniciodesc] [smalldatetime] NULL,
	[FecFindesc] [smalldatetime] NULL,
	[TiempoCargue] [decimal](14, 4) NULL DEFAULT ((0)),
	[TiempoDesc] [decimal](14, 4) NULL DEFAULT ((0)),
	[FecLlegCargue] [smalldatetime] NULL,
	[FecSalidaCargue] [smalldatetime] NULL,
	[FecLlegdesc] [smalldatetime] NULL,
	[FecSalidadesc] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenAbo]    Script Date: 13/07/2021 10:39:56 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraOrdenAbo] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Documento] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Item] [int] NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NULL,
	[TipAnt] [varchar](3) NULL DEFAULT ('AOS'),
	[Anticipo] [int] NULL DEFAULT ((0)),
	[IdCiaAnt] [char](2) NULL,
	[VrAbono] [money] NULL DEFAULT ((0)),
	[TipoAplica] [varchar](10) NULL DEFAULT ('OPAGO'),
	[Observacion] [varchar](250) NULL,
	[CodCuenta] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenAnt]    Script Date: 13/07/2021 10:39:57 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraOrdenAnt] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('AOS'),
	[Anticipo] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipOds] [varchar](3) NULL DEFAULT ('OSA'),
	[NumOrden] [int] NULL DEFAULT ((0)),
	[IdCiaOds] [char](2) NULL DEFAULT ('01'),
	[VrAnticipo] [money] NULL DEFAULT ((0)),
	[VrAbonado] [money] NULL DEFAULT ((0)),
	[TipoPago] [varchar](10) NOT NULL DEFAULT ('EFECTIVO'),
	[NumCheque] [varchar](20) NULL,
	[FecCheque] [smalldatetime] NULL,
	[IdCta] [varchar](4) NULL DEFAULT ('0'),
	[IdCuenta] [varchar](16) NULL,
	[Beneficiario] [varchar](150) NULL,
	[CedBenef] [varchar](16) NULL,
	[FechaVence] [smalldatetime] NULL,
	[TipCom] [varchar](3) NULL DEFAULT ('0'),
	[Comprobante] [int] NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NULL DEFAULT ('00'),
	[Anulado] [bit] NULL DEFAULT ((0)),
	[NumDev] [int] NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenCum]    Script Date: 13/07/2021 10:39:58 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraOrdenCum] AS TABLE(
	[TipDoc] [varchar](3) NULL DEFAULT ('COS'),
	[Cumplido] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NULL,
	[TipOds] [varchar](3) NULL,
	[NumOrden] [int] NULL DEFAULT ((0)),
	[IdCiaOds] [char](2) NULL DEFAULT ('01'),
	[TipoAfiVehic] [varchar](10) NULL DEFAULT ('TERCEROS'),
	[FecDespacho] [smalldatetime] NULL,
	[FecRecibo] [smalldatetime] NULL,
	[FecIngCertif] [smalldatetime] NULL,
	[FecCertificado] [smalldatetime] NULL,
	[DescServicio] [varchar](100) NULL,
	[Cantidad] [decimal](14, 4) NULL DEFAULT ((0)),
	[VrTotal] [money] NULL DEFAULT ((0)),
	[VrCosto] [money] NULL DEFAULT ((0)),
	[RemCliente] [varchar](30) NULL,
	[Funcionario] [varchar](150) NULL,
	[TipCom] [varchar](3) NULL DEFAULT ('0'),
	[Comprobante] [int] NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NULL DEFAULT ('00'),
	[Anulado] [bit] NULL DEFAULT ((0)),
	[NumDev] [int] NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](1000) NULL,
	[IdEstado] [varchar](4) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NULL,
	[CdTarIva] [varchar](4) NULL,
	[CdTarRiv] [varchar](4) NULL,
	[CdTarRet] [varchar](4) NULL,
	[CdTarIca] [varchar](4) NULL,
	[CdTarRtc] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenCumDet]    Script Date: 13/07/2021 10:39:59 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraOrdenCumDet] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('COS'),
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[IdMercancia] [varchar](16) NOT NULL,
	[Descripcion] [varchar](250) NOT NULL,
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndMed] [varchar](10) NOT NULL,
	[VrUnitario] [money] NOT NULL DEFAULT ((0)),
	[TarifaPago] [money] NOT NULL DEFAULT ((0)),
	[DocCliente] [varchar](30) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenDet]    Script Date: 13/07/2021 10:40:00 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraOrdenDet] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('OST'),
	[NumOrden] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[IdMercancia] [varchar](16) NOT NULL,
	[Descripcion] [varchar](250) NOT NULL,
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndMed] [varchar](10) NOT NULL,
	[VrUnitario] [money] NOT NULL DEFAULT ((0)),
	[TarifaPago] [money] NOT NULL DEFAULT ((0)),
	[CantCump] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[TarifaCump] [money] NOT NULL DEFAULT ((0)),
	[PagoCump] [money] NOT NULL DEFAULT ((0)),
	[DocCliente] [varchar](30) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenOper]    Script Date: 13/07/2021 10:40:00 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraOrdenOper] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[NumOrden] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Item] [int] NULL DEFAULT ((0)),
	[IdOperario] [varchar](16) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraOrdenServ]    Script Date: 13/07/2021 10:40:00 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraOrdenServ] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[NumOrden] [int] NULL DEFAULT ((0)),
	[IdCia] [char](2) NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NULL,
	[FecDespacho] [smalldatetime] NULL,
	[FecRecibo] [smalldatetime] NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL DEFAULT ('0'),
	[IdVehiculo] [varchar](10) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[nRemolque] [varchar](10) NULL,
	[TipoAfiVehic] [varchar](10) NOT NULL DEFAULT ('TERCEROS'),
	[Modalidad] [varchar](10) NULL,
	[VrTotal] [money] NULL DEFAULT ((0)),
	[VrCosto] [money] NULL DEFAULT ((0)),
	[Cantidad] [decimal](14, 4) NULL DEFAULT ((0)),
	[VrAnticipo] [money] NULL DEFAULT ((0)),
	[IdDestino] [varchar](8) NULL,
	[TipoOrden] [varchar](10) NULL,
	[IdEstacion] [varchar](4) NULL,
	[NomEstacion] [varchar](50) NULL,
	[TipoResiduo] [varchar](100) NULL,
	[RemCliente] [varchar](30) NULL,
	[NomRecibido] [varchar](150) NULL,
	[FecIngCertif] [smalldatetime] NULL,
	[FecCertificado] [smalldatetime] NULL,
	[NumRemesa] [int] NULL DEFAULT ((0)),
	[CdCiaRem] [char](2) NULL DEFAULT ('00'),
	[EstCumplido] [int] NULL DEFAULT ((0)),
	[EstFactura] [int] NULL DEFAULT ((0)),
	[TipFact] [varchar](3) NULL,
	[NumFactura] [int] NULL DEFAULT ((0)),
	[CdCiaFact] [char](2) NULL,
	[kmtInicial] [int] NULL DEFAULT ((0)),
	[kmtFinal] [int] NULL DEFAULT ((0)),
	[EstOrden] [int] NULL DEFAULT ((0)),
	[TipLiq] [varchar](3) NULL,
	[NumLiquida] [int] NULL DEFAULT ((0)),
	[CdCiaLiq] [char](2) NULL,
	[OrigenAdd] [varchar](10) NULL,
	[Anulado] [bit] NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](1000) NULL,
	[IdEstado] [varchar](4) NULL,
	[TimeSys] [smalldatetime] NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NULL,
	[NumAprob] [int] NULL DEFAULT ((0)),
	[IdCiaApr] [char](2) NULL DEFAULT ('00'),
	[FecAprob] [smalldatetime] NULL,
	[UsuAprob] [varchar](11) NULL,
	[ObservAprob] [varchar](250) NULL,
	[CdRuta] [varchar](4) NULL,
	[IdOrigen] [varchar](8) NULL,
	[Cantkms] [int] NULL DEFAULT ((0)),
	[NumCump] [int] NULL DEFAULT ((0)),
	[CdCiaCum] [char](2) NULL,
	[CdTarIva] [varchar](4) NULL,
	[CdTarRiv] [varchar](4) NULL,
	[CdTarRet] [varchar](4) NULL,
	[CdTarIca] [varchar](4) NULL,
	[CdTarRtc] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraPedAnexo]    Script Date: 13/07/2021 10:40:02 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraPedAnexo] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('PDT'),
	[Pedido] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[NomCliente] [varchar](150) NULL,
	[NomRemite] [varchar](150) NULL,
	[NomDestino] [varchar](150) NULL,
	[LugarCargue] [varchar](150) NULL,
	[LugarDescargue] [varchar](150) NULL,
	[NomContacto] [varchar](150) NULL,
	[TelContacto] [varchar](30) NULL,
	[emlContacto] [varchar](100) NULL,
	[ContacDestino] [varchar](150) NULL,
	[TelContacDest] [varchar](30) NULL,
	[emlContacDest] [varchar](100) NULL,
	[PolizaEsp] [bit] NOT NULL DEFAULT ((0)),
	[NumPolizaEsp] [varchar](50) NULL,
	[NitCiaPoliza] [varchar](16) NULL,
	[NomCiaPoliza] [varchar](150) NULL,
	[FecVencePol] [smalldatetime] NULL,
	[VrLimiteDesp] [money] NOT NULL DEFAULT ((0)),
	[Seguros] [varchar](10) NOT NULL DEFAULT ('EMPRESA'),
	[Cargue] [varchar](20) NOT NULL DEFAULT ('CLIENTE'),
	[Descargue] [varchar](20) NOT NULL DEFAULT ('CLIENTE'),
	[CdTipoEsc] [varchar](4) NULL DEFAULT ('0'),
	[NitSIA] [varchar](16) NULL,
	[NombreSIA] [varchar](150) NULL,
	[ContactoSIA] [varchar](150) NULL,
	[TelContacSIA] [varchar](30) NULL,
	[TipoRuta] [varchar](10) NOT NULL DEFAULT ('NACIONAL'),
	[TipoTrans] [varchar](10) NOT NULL DEFAULT ('GENERAL'),
	[Embarque] [varchar](10) NOT NULL DEFAULT ('SUELTA'),
	[CdTipCarga] [varchar](4) NULL,
	[DevContenedor] [bit] NOT NULL DEFAULT ((0)),
	[IdLocCont] [varchar](8) NULL,
	[PatioCont] [varchar](50) NULL,
	[CdTipoVeh] [varchar](4) NOT NULL DEFAULT ('0'),
	[MargenFalt] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[TipoMargen] [varchar](10) NOT NULL DEFAULT ('UNIDAD'),
	[UndCalcFalt] [varchar](10) NULL DEFAULT ('PESO'),
	[TarifFaltPago] [money] NOT NULL DEFAULT ((0)),
	[TarifFaltCobro] [money] NOT NULL DEFAULT ((0)),
	[EmbAdicional] [varchar](150) NULL,
	[CdRutaTarif] [varchar](4) NULL,
	[TipoServicio] [varchar](10) NULL,
	[CodTipoOper] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraPedido]    Script Date: 13/07/2021 10:40:04 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraPedido] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('PDT'),
	[Pedido] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[FechaVence] [smalldatetime] NOT NULL,
	[FecDespacho] [smalldatetime] NOT NULL,
	[FecEntrega] [smalldatetime] NULL,
	[IdCliente] [varchar](16) NOT NULL,
	[IdAgencia] [varchar](16) NOT NULL DEFAULT ('0'),
	[IdClieFact] [varchar](16) NOT NULL,
	[IdRemitente] [varchar](16) NOT NULL,
	[IdDestinatario] [varchar](16) NOT NULL,
	[IdLocOrigen] [varchar](8) NOT NULL,
	[IdLocDestino] [varchar](8) NOT NULL,
	[IdVend] [varchar](16) NOT NULL,
	[IdTarifCom] [varchar](4) NOT NULL DEFAULT ('0'),
	[Modalidad] [varchar](10) NOT NULL,
	[Vigencia] [varchar](10) NOT NULL DEFAULT ('NORMAL'),
	[TipoTarifa] [varchar](10) NOT NULL DEFAULT ('PEDIDO'),
	[VrCobro] [money] NOT NULL DEFAULT ((0)),
	[VrPagos] [money] NOT NULL DEFAULT ((0)),
	[VrFletes] [money] NOT NULL DEFAULT ((0)),
	[VrCargue] [money] NOT NULL DEFAULT ((0)),
	[VrDesCargue] [money] NOT NULL DEFAULT ((0)),
	[VrEscolta] [money] NOT NULL DEFAULT ((0)),
	[VrDevContdor] [money] NOT NULL DEFAULT ((0)),
	[VrTraUrbano] [money] NOT NULL DEFAULT ((0)),
	[VrEmbalajes] [money] NOT NULL DEFAULT ((0)),
	[VrCargos] [money] NOT NULL DEFAULT ((0)),
	[VrDctos] [money] NOT NULL DEFAULT ((0)),
	[VrDeclarado] [money] NOT NULL DEFAULT ((0)),
	[VrSeguro] [money] NOT NULL DEFAULT ((0)),
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[CantDesp] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[IdMneda] [varchar](5) NOT NULL DEFAULT ('COP'),
	[VrTasa] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[Cotizacion] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCot] [char](2) NOT NULL DEFAULT ('00'),
	[NumAprob] [int] NOT NULL DEFAULT ((0)),
	[IdCiaApr] [char](2) NOT NULL DEFAULT ('01'),
	[FecAprob] [smalldatetime] NULL,
	[TipOdc] [varchar](3) NOT NULL DEFAULT ('OCT'),
	[OCargue] [int] NOT NULL DEFAULT ((0)),
	[IdCiaOdc] [char](2) NOT NULL DEFAULT ('01'),
	[FechaOdc] [smalldatetime] NULL,
	[TipRem] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[Remesa] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRem] [char](2) NOT NULL DEFAULT ('01'),
	[FechaRem] [smalldatetime] NULL,
	[TipFac] [varchar](3) NOT NULL DEFAULT ('FCR'),
	[Factura] [int] NOT NULL DEFAULT ((0)),
	[IdCiaFac] [char](2) NOT NULL DEFAULT ('00'),
	[FechaFac] [smalldatetime] NULL,
	[OrigenAdd] [varchar](10) NOT NULL,
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraPedMcias]    Script Date: 13/07/2021 10:40:06 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraPedMcias] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('PDT'),
	[Pedido] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[IdMercancia] [varchar](16) NOT NULL,
	[DescripMcias] [varchar](250) NOT NULL,
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[PesoNeto] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndMed] [varchar](10) NOT NULL,
	[dmsAlto] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[dmsAncho] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[dmsLargo] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[Volumen] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndVol] [varchar](10) NOT NULL,
	[IdUnd] [varchar](4) NOT NULL,
	[IdEmp] [varchar](4) NOT NULL DEFAULT ('0'),
	[IdNat] [varchar](4) NOT NULL,
	[IdMnjo] [varchar](4) NOT NULL,
	[IdTmcia] [varchar](4) NOT NULL,
	[CdRango] [varchar](4) NULL,
	[Cases] [int] NOT NULL DEFAULT ((0)),
	[Cajas] [int] NOT NULL DEFAULT ((0)),
	[Palets] [int] NOT NULL DEFAULT ((0)),
	[NitRemite] [varchar](16) NOT NULL,
	[Remitente] [varchar](250) NOT NULL,
	[DirOrigen] [varchar](250) NOT NULL,
	[IdOrigen] [varchar](8) NOT NULL,
	[NitDestntario] [varchar](16) NOT NULL,
	[Destinatario] [varchar](250) NOT NULL DEFAULT ('varios'),
	[DirDestino] [varchar](250) NOT NULL,
	[IdDestino] [varchar](8) NOT NULL,
	[TarifClie] [money] NOT NULL DEFAULT ((0)),
	[TarifPago] [money] NOT NULL DEFAULT ((0)),
	[TarifTabla] [money] NOT NULL DEFAULT ((0)),
	[VrDeclarado] [money] NOT NULL DEFAULT ((0)),
	[VrSeguro] [money] NOT NULL DEFAULT ((0)),
	[TarifSeguro] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Contenedor1] [varchar](50) NULL,
	[Contenedor2] [varchar](50) NULL,
	[UndTarifa] [varchar](10) NOT NULL DEFAULT ('PESO'),
	[UndTarifPago] [varchar](10) NOT NULL DEFAULT ('PESO'),
	[DocCliente] [varchar](30) NULL,
	[Referencia3] [varchar](50) NULL,
	[CdTipoVehic] [varchar](4) NULL,
	[Tipo_Servicio] [varchar](10) NULL,
	[SedeRem] [varchar](10) NULL,
	[SedeDest] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemAnexo]    Script Date: 13/07/2021 10:40:08 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraRemAnexo] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[NumOrden] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[IdVend] [varchar](16) NOT NULL,
	[IdTarifCom] [varchar](4) NOT NULL DEFAULT ('0'),
	[NomCliente] [varchar](150) NULL,
	[NomRemite] [varchar](150) NULL,
	[NomDestino] [varchar](150) NULL,
	[LugarCargue] [varchar](150) NULL,
	[LugarDescargue] [varchar](150) NULL,
	[NomContacto] [varchar](150) NULL,
	[TelContacto] [varchar](30) NULL,
	[emlContacto] [varchar](100) NULL,
	[ContacDestino] [varchar](150) NULL,
	[TelContacDest] [varchar](30) NULL,
	[emlContacDest] [varchar](100) NULL,
	[TomadorPoliza] [char](1) NOT NULL DEFAULT ('N'),
	[PolizaSeguro] [varchar](50) NULL,
	[NitCiaPoliza] [varchar](16) NULL,
	[NomCiaPoliza] [varchar](150) NULL,
	[FecVencePol] [smalldatetime] NULL,
	[ManifMintrans] [decimal](14, 2) NOT NULL DEFAULT ((0)),
	[RemMintrans] [decimal](14, 2) NOT NULL DEFAULT ((0)),
	[TipSal] [varchar](3) NULL,
	[NumSalida] [int] NOT NULL DEFAULT ((0)),
	[IdCiaSal] [char](2) NULL DEFAULT ('00'),
	[NumInvent] [int] NOT NULL DEFAULT ((0)),
	[IdCiaInv] [char](2) NULL DEFAULT ('00'),
	[TipoRuta] [varchar](10) NOT NULL DEFAULT ('URBANO'),
	[TipoMintrans] [varchar](10) NULL DEFAULT ('GENERAL'),
	[NitEmpTransp] [varchar](16) NULL,
	[NumFactEmp] [varchar](20) NULL,
	[MvoAnulacion] [varchar](3) NULL,
	[PactoCargue] [bit] NOT NULL DEFAULT ((0)),
	[HorasPactoCargue] [int] NOT NULL DEFAULT ((0)),
	[MinPactoCargue] [int] NOT NULL DEFAULT ((0)),
	[HoraCitaCargue] [smalldatetime] NULL,
	[HoraLlegaCargue] [smalldatetime] NULL,
	[HoraEntraCargue] [smalldatetime] NULL,
	[HoraSaleCargue] [smalldatetime] NULL,
	[PactoDescargue] [bit] NOT NULL DEFAULT ((0)),
	[HorasPactoDescargue] [int] NOT NULL DEFAULT ((0)),
	[MinPactoDescargue] [int] NOT NULL DEFAULT ((0)),
	[HoraCitaDescargue] [smalldatetime] NULL,
	[HoraLlegaDescargue] [smalldatetime] NULL,
	[HoraEntraDescargue] [smalldatetime] NULL,
	[HoraSaleDescargue] [smalldatetime] NULL,
	[TipoDevRemesa] [varchar](3) NULL,
	[CodCiuTransb] [varchar](8) NULL,
	[MvoTransbordo] [varchar](3) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemCntdor]    Script Date: 13/07/2021 10:40:09 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraRemCntdor] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[NumOrden] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[IdTipoCon] [varchar](4) NULL,
	[NumContdor] [varchar](50) NULL,
	[PesoNeto] [decimal](14, 4) NULL,
	[IdTipoPre] [varchar](4) NULL,
	[NumPrecinto] [varchar](30) NULL,
	[ColorPrecinto] [varchar](20) NULL,
	[Sellos] [varchar](150) NULL,
	[Peligroso] [bit] NULL,
	[Perecedero] [bit] NULL,
	[Toxico] [bit] NULL,
	[Inflamable] [bit] NULL,
	[Difmanejo] [bit] NULL,
	[Fragil] [bit] NULL,
	[DevCont] [bit] NULL,
	[CdLocCont] [varchar](8) NULL,
	[PatioCont] [varchar](50) NULL,
	[Observacion] [varchar](150) NULL,
	[NumSalidaSello] [int] NULL,
	[CdCiaSalSello] [char](2) NULL,
	[ItemSalSello] [int] NULL,
	[CdProdSalida] [varchar](16) NULL,
	[NumSerialSello] [varchar](30) NULL,
	[NumComodato] [varchar](50) NULL,
	[FecVenceCom] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemesa]    Script Date: 13/07/2021 10:40:09 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraRemesa] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[NumOrden] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[FecDespacho] [smalldatetime] NOT NULL,
	[FecEntrega] [smalldatetime] NULL,
	[HoraLlegada] [smalldatetime] NULL,
	[IdCliente] [varchar](16) NOT NULL,
	[IdAgencia] [varchar](16) NOT NULL DEFAULT ('0'),
	[IdClieFact] [varchar](16) NOT NULL,
	[IdRemitente] [varchar](16) NOT NULL,
	[IdDestinatario] [varchar](16) NOT NULL,
	[IdLocOrigen] [varchar](8) NOT NULL,
	[IdLocDestino] [varchar](8) NOT NULL,
	[IdLocFletes] [varchar](8) NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[nRemolque] [varchar](10) NULL,
	[TipoAfiVehic] [varchar](10) NOT NULL DEFAULT ('TERCEROS'),
	[Modalidad] [varchar](10) NOT NULL,
	[TipoTarifa] [varchar](10) NOT NULL DEFAULT ('TABLA'),
	[VrCobro] [money] NOT NULL DEFAULT ((0)),
	[VrPagos] [money] NOT NULL DEFAULT ((0)),
	[VrFletes] [money] NOT NULL DEFAULT ((0)),
	[VrCargue] [money] NOT NULL DEFAULT ((0)),
	[VrDesCargue] [money] NOT NULL DEFAULT ((0)),
	[VrEscolta] [money] NOT NULL DEFAULT ((0)),
	[VrDevContdor] [money] NOT NULL DEFAULT ((0)),
	[VrTraUrbano] [money] NOT NULL DEFAULT ((0)),
	[VrEmbalajes] [money] NOT NULL DEFAULT ((0)),
	[VrCargos] [money] NOT NULL DEFAULT ((0)),
	[VrDctos] [money] NOT NULL DEFAULT ((0)),
	[VrDeclarado] [money] NOT NULL DEFAULT ((0)),
	[VrSeguro] [money] NOT NULL DEFAULT ((0)),
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[PesoTotal] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[Items] [int] NOT NULL DEFAULT ((0)),
	[IdMneda] [varchar](5) NOT NULL DEFAULT ('COP'),
	[VrTasa] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[NumPedido] [int] NOT NULL DEFAULT ((0)),
	[IdCiaPed] [char](2) NOT NULL DEFAULT ('01'),
	[FechaPed] [smalldatetime] NULL,
	[TipDcm] [varchar](3) NOT NULL DEFAULT ('0'),
	[NumDocmto] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDcm] [char](2) NOT NULL DEFAULT ('01'),
	[FechaDcm] [smalldatetime] NULL,
	[NumManif] [int] NOT NULL DEFAULT ((0)),
	[IdCiaManif] [char](2) NOT NULL DEFAULT ('00'),
	[EstCumplido] [int] NOT NULL DEFAULT ((0)),
	[EstFactura] [int] NOT NULL DEFAULT ((0)),
	[CdConcepto] [varchar](4) NOT NULL DEFAULT ('0'),
	[CdRutaTarif] [varchar](4) NULL,
	[SerieGuia] [char](2) NOT NULL DEFAULT ('00'),
	[NumGuia] [int] NOT NULL DEFAULT ((0)),
	[CdForma] [varchar](4) NULL,
	[NumCausac] [int] NOT NULL DEFAULT ((0)),
	[CdCiaCausac] [char](2) NULL,
	[EdoCausac] [int] NOT NULL DEFAULT ((0)),
	[TipCom] [varchar](3) NOT NULL,
	[Comprobante] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCom] [char](2) NOT NULL,
	[OrigenAdd] [varchar](10) NOT NULL,
	[Anulado] [bit] NOT NULL DEFAULT ((0)),
	[FecDev] [smalldatetime] NULL,
	[Observacion] [varchar](250) NULL,
	[IdEstado] [varchar](4) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL,
	[CdBodega] [varchar](4) NULL,
	[VigenciaOdc] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraRemMcias]    Script Date: 13/07/2021 10:40:12 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraRemMcias] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[NumOrden] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[IdMercancia] [varchar](16) NOT NULL,
	[DescripMcias] [varchar](250) NOT NULL,
	[Cantidad] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[PesoNeto] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndMed] [varchar](10) NOT NULL,
	[dmsAlto] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[dmsAncho] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[dmsLargo] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[Volumen] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndVol] [varchar](10) NOT NULL,
	[IdUnd] [varchar](4) NOT NULL,
	[IdEmp] [varchar](4) NOT NULL,
	[IdNat] [varchar](4) NOT NULL,
	[IdTmcia] [varchar](4) NOT NULL,
	[IdMnjo] [varchar](4) NOT NULL,
	[CdRango] [varchar](4) NULL,
	[Cases] [int] NOT NULL DEFAULT ((0)),
	[Cajas] [int] NOT NULL DEFAULT ((0)),
	[Palets] [int] NOT NULL DEFAULT ((0)),
	[NitRemite] [varchar](16) NOT NULL,
	[Remitente] [varchar](250) NOT NULL,
	[DirOrigen] [varchar](250) NOT NULL,
	[IdOrigen] [varchar](8) NOT NULL,
	[NitDestntario] [varchar](16) NOT NULL,
	[Destinatario] [varchar](250) NOT NULL DEFAULT ('varios'),
	[DirDestino] [varchar](250) NOT NULL,
	[IdDestino] [varchar](8) NOT NULL,
	[TarifClie] [money] NOT NULL DEFAULT ((0)),
	[TarifPago] [money] NOT NULL DEFAULT ((0)),
	[TarifTabla] [money] NOT NULL DEFAULT ((0)),
	[VrDeclarado] [money] NOT NULL DEFAULT ((0)),
	[VrSeguro] [money] NOT NULL DEFAULT ((0)),
	[TarifSeguro] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[UndTarifa] [varchar](10) NOT NULL DEFAULT ('PESO'),
	[UndTarifPago] [varchar](10) NOT NULL DEFAULT ('PESO'),
	[Remision] [decimal](18, 2) NOT NULL DEFAULT ((0)),
	[DocCliente] [varchar](30) NOT NULL DEFAULT ('0'),
	[Referencia1] [varchar](50) NULL,
	[Referencia2] [varchar](50) NULL,
	[Referencia3] [varchar](50) NULL,
	[Contenedor1] [varchar](50) NULL,
	[Contenedor2] [varchar](50) NULL,
	[CdAgencia] [varchar](16) NOT NULL DEFAULT ('0'),
	[Cumplido] [int] NOT NULL DEFAULT ((0)),
	[IdCiaCump] [char](2) NOT NULL DEFAULT ('01'),
	[FechaCump] [smalldatetime] NULL,
	[DetalleCump] [varchar](250) NULL,
	[CantidadCump] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[PesoCump] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[VolCump] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[CasesCump] [int] NOT NULL DEFAULT ((0)),
	[CajasCump] [int] NOT NULL DEFAULT ((0)),
	[PaletsCump] [int] NOT NULL DEFAULT ((0)),
	[TarifCump] [money] NOT NULL DEFAULT ((0)),
	[PagoCump] [money] NOT NULL DEFAULT ((0)),
	[UndTarCump] [varchar](10) NOT NULL DEFAULT ('PESO'),
	[UndTarPagoCump] [varchar](10) NULL DEFAULT ('PESO'),
	[TipFac] [varchar](3) NOT NULL DEFAULT ('FCR'),
	[Factura] [int] NOT NULL DEFAULT ((0)),
	[IdCiaFac] [char](2) NOT NULL DEFAULT ('00'),
	[FechaFac] [smalldatetime] NULL,
	[TarifClieFac] [money] NOT NULL DEFAULT ((0)),
	[TipOdp] [varchar](3) NOT NULL DEFAULT ('0'),
	[NumeroOdp] [int] NOT NULL DEFAULT ((0)),
	[IdCiaOdp] [char](2) NOT NULL DEFAULT ('00'),
	[TarifOdp] [money] NOT NULL DEFAULT ((0)),
	[PesoCont] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[SedeRem] [varchar](10) NULL,
	[SedeDest] [varchar](10) NULL,
	[TipDocInv] [varchar](3) NULL,
	[NumDocInv] [int] NOT NULL DEFAULT ((0)),
	[IdCiaDocInv] [char](2) NULL DEFAULT ('00'),
	[ItemDocInv] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraReportes]    Script Date: 13/07/2021 10:40:16 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraReportes] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('MUC'),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[CdRuta] [varchar](4) NOT NULL,
	[IdPunto] [int] NOT NULL DEFAULT ((0)),
	[FecReporte] [smalldatetime] NOT NULL,
	[TipoRep] [varchar](10) NOT NULL,
	[EstadoRep] [int] NOT NULL DEFAULT ((0)),
	[IdUsuario] [varchar](11) NOT NULL,
	[FechaCrea] [smalldatetime] NOT NULL,
	[CdNovedad] [varchar](4) NULL,
	[ObservRep] [varchar](250) NULL,
	[TipoPunto] [varchar](10) NULL,
	[CdPuesto] [varchar](4) NULL,
	[NomConductor] [varchar](150) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraTrasladoRem]    Script Date: 13/07/2021 10:40:17 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraTrasladoRem] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('TRR'),
	[Traslado] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Item] [int] NOT NULL DEFAULT ((0)),
	[TipRem] [varchar](3) NOT NULL DEFAULT ('RMT'),
	[Remesa] [int] NOT NULL DEFAULT ((0)),
	[IdCiaRem] [char](2) NOT NULL DEFAULT ('01'),
	[ItemRem] [int] NOT NULL DEFAULT ((0)),
	[CdBodega] [varchar](4) NOT NULL,
	[EdoRecibido] [int] NOT NULL DEFAULT ((0)),
	[Comentarios] [varchar](250) NULL,
	[CdNovedad] [varchar](4) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraTraslados]    Script Date: 13/07/2021 10:40:17 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraTraslados] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL DEFAULT ('TRR'),
	[Traslado] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('01'),
	[Fecha] [smalldatetime] NOT NULL,
	[FecDespacho] [smalldatetime] NOT NULL,
	[TipoTraslado] [int] NOT NULL DEFAULT ((0)),
	[IdBodega] [varchar](4) NOT NULL,
	[IdBodDtno] [varchar](4) NOT NULL,
	[IdVehiculo] [varchar](10) NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[Cantidad] [int] NOT NULL DEFAULT ((0)),
	[PesoTotal] [decimal](14, 4) NOT NULL DEFAULT ((0)),
	[Manifiesto] [int] NOT NULL DEFAULT ((0)),
	[CdCiaMuc] [char](2) NULL,
	[EstadoRec] [int] NOT NULL DEFAULT ((0)),
	[FechaRec] [smalldatetime] NULL,
	[CedRecibido] [varchar](16) NULL,
	[NomRecibido] [varchar](150) NULL,
	[Observacion] [varchar](1000) NULL,
	[OrigenAdd] [varchar](10) NOT NULL,
	[TimeSys] [smalldatetime] NOT NULL,
	[IdCiaCrea] [char](2) NOT NULL DEFAULT ('01'),
	[IdUsuario] [varchar](11) NOT NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_TraTurn]    Script Date: 13/07/2021 10:40:18 ******/
CREATE TYPE [dbo].[dataTypeTrn_TraTurn] AS TABLE(
	[Numero] [int] NOT NULL DEFAULT ((0)),
	[IdCia] [char](2) NOT NULL DEFAULT ('00'),
	[IdVehiculo] [varchar](10) NOT NULL,
	[IndTurno] [int] NOT NULL DEFAULT ((0)),
	[Fecha] [smalldatetime] NOT NULL,
	[IdConductor] [varchar](16) NOT NULL,
	[nRemolque] [varchar](10) NULL,
	[Estado] [int] NOT NULL DEFAULT ((0)),
	[TipOrd] [varchar](3) NULL DEFAULT ('0'),
	[NumOrden] [int] NOT NULL DEFAULT ((0)),
	[IdCiaOrd] [char](2) NULL,
	[FecOrden] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NOT NULL,
	[FechaCrea] [smalldatetime] NULL,
	[NitCliente] [varchar](16) NULL,
	[SedeClie] [varchar](10) NULL,
	[Autorizac] [int] NOT NULL DEFAULT ((0))
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehConductor]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeTrn_VehConductor] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[Numero] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[IdPropietario] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[IdCondNuevo] [varchar](16) NULL,
	[Observacion] [varchar](150) NULL,
	[TimeSys] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehLecturas]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeTrn_VehLecturas] AS TABLE(
	[TipDoc] [varchar](3) NULL,
	[Numero] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[TipoUnidad] [varchar](3) NULL,
	[pVehiculo] [varchar](10) NULL,
	[KmsAnterior] [int] NULL,
	[KmsActual] [int] NULL,
	[Kms2Anterior] [int] NULL,
	[Kms2Actual] [int] NULL,
	[TipoLectura] [varchar](10) NULL,
	[Observacion] [varchar](250) NULL,
	[TimeSys] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehNumOrden]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeTrn_VehNumOrden] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[Numero] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[NumOrden] [varchar](10) NULL,
	[NuevoNum] [varchar](10) NULL,
	[Observacion] [varchar](250) NULL,
	[TimeSys] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VehTraspasos]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeTrn_VehTraspasos] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[Numero] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[IdPpd] [varchar](4) NULL,
	[IdPropietario] [varchar](16) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdPropNuevo] [varchar](16) NULL,
	[IdPoseeNuevo] [varchar](16) NULL,
	[IdNewPpd] [varchar](4) NULL,
	[IdGrupo] [varchar](4) NULL,
	[VrComercial] [money] NULL,
	[VrCupo] [money] NULL,
	[VrAsegurado] [money] NULL,
	[Observacion] [varchar](150) NULL,
	[TipoAfil] [varchar](10) NULL,
	[TipoAfilNew] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_VencAbonos]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeTrn_VencAbonos] AS TABLE(
	[TipRec] [varchar](3) NULL,
	[Recibo] [int] NULL,
	[IdCia] [char](2) NULL,
	[Item] [int] NULL,
	[Fecha] [smalldatetime] NULL,
	[TipDoc] [varchar](3) NULL,
	[Factura] [int] NULL,
	[IdCiaFac] [char](2) NULL,
	[ItemFac] [int] NULL,
	[VrAbono] [money] NULL,
	[VrDescto] [money] NULL,
	[VrBaseCms] [money] NULL,
	[IdCliente] [varchar](16) NULL,
	[IdAgencia] [varchar](16) NULL,
	[IdVend] [varchar](16) NULL,
	[Comision] [decimal](14, 4) NULL,
	[Detalle] [varchar](150) NULL,
	[FecPago] [smalldatetime] NULL,
	[TipoAplica] [varchar](10) NULL,
	[TimeSys] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeTrn_Vencimientos]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeTrn_Vencimientos] AS TABLE(
	[TipDoc] [varchar](3) NOT NULL,
	[Factura] [int] NOT NULL,
	[IdCia] [char](2) NOT NULL,
	[Item] [int] NOT NULL,
	[Fecha] [smalldatetime] NOT NULL,
	[FechaVence] [smalldatetime] NOT NULL,
	[VrFactura] [money] NOT NULL,
	[VrAbonado] [money] NOT NULL,
	[IdCliente] [varchar](16) NOT NULL,
	[IdAgencia] [varchar](16) NOT NULL,
	[IdVend] [varchar](16) NOT NULL,
	[Comision] [decimal](14, 4) NOT NULL,
	[TarifDcto] [decimal](14, 4) NOT NULL,
	[TipoDcto] [char](1) NOT NULL,
	[TipoBase] [varchar](10) NOT NULL,
	[FecLmtDcto] [smalldatetime] NULL,
	[IdConcepto] [varchar](4) NOT NULL,
	[Referencia] [varchar](50) NULL,
	[Detalle] [varchar](150) NULL,
	[TipRef] [varchar](3) NOT NULL,
	[DocRef] [int] NOT NULL,
	[IdCiaRef] [char](2) NOT NULL,
	[FecUltPago] [smalldatetime] NULL,
	[NumNota] [int] NOT NULL,
	[IdCiaNot] [char](2) NOT NULL,
	[TarifInt] [decimal](14, 4) NOT NULL,
	[FecLiqMora] [smalldatetime] NULL,
	[FecPlazoCal] [smalldatetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeUpdateKmVehs]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeUpdateKmVehs] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[KmActual] [int] NULL,
	[FechaUpdate] [datetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVeh_Contrato]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeVeh_Contrato] AS TABLE(
	[NumContrato] [int] NULL,
	[IdVehiculo] [varchar](10) NULL,
	[IdAdmon] [varchar](4) NULL,
	[IdTipCon] [varchar](4) NULL,
	[FecIngreso] [smalldatetime] NULL,
	[FecRetiro] [smalldatetime] NULL,
	[FecVigencia] [smalldatetime] NULL,
	[Observaciones] [varchar](250) NULL,
	[NumPagare] [varchar](20) NULL,
	[ArchPagare] [varchar](50) NULL,
	[FecUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehAnexo]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeVehAnexo] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[PolizaRCE] [varchar](30) NULL,
	[FecEmisionRCE] [smalldatetime] NULL,
	[FecVigenciaRCE] [smalldatetime] NULL,
	[appPyP] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehConductores]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeVehConductores] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[Item] [int] NULL,
	[CedConductor] [varchar](16) NULL,
	[TipoCond] [varchar](10) NULL,
	[FechaIng] [smalldatetime] NULL,
	[EstadoCond] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehiculos]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeVehiculos] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[NumVeh] [varchar](10) NULL,
	[ClaseVeh] [varchar](10) NULL,
	[IdTipoVeh] [varchar](4) NULL,
	[IdMarca] [varchar](4) NULL,
	[IdLinea] [varchar](10) NULL,
	[IdColor] [varchar](4) NULL,
	[IdTipoMot] [varchar](4) NULL,
	[IdCrceria] [varchar](4) NULL,
	[Modelo] [varchar](4) NULL,
	[FecRep] [smalldatetime] NULL,
	[Config] [varchar](5) NULL,
	[VehArtic] [bit] NULL,
	[NumLlan] [int] NULL,
	[NumLlans] [int] NULL,
	[IdCat] [varchar](4) NULL,
	[CdCatv] [varchar](4) NULL,
	[ClaseMat] [varchar](10) NULL,
	[Cilind] [decimal](14, 4) NULL,
	[CapTanq] [decimal](14, 4) NULL,
	[IdCom] [varchar](4) NULL,
	[IdLub] [varchar](4) NULL,
	[IdTlla] [varchar](4) NULL,
	[IdMarlla] [varchar](4) NULL,
	[PesoVacio] [decimal](14, 4) NULL,
	[PesoMax] [decimal](14, 4) NULL,
	[NumMotor] [varchar](30) NULL,
	[SerieChasis] [varchar](30) NULL,
	[NumSerie] [varchar](30) NULL,
	[CdRemque] [varchar](10) NULL,
	[Longitud] [decimal](14, 4) NULL,
	[CarrAlto] [decimal](14, 4) NULL,
	[CarrAncho] [decimal](14, 4) NULL,
	[CarrLargo] [decimal](14, 4) NULL,
	[CarrCapac] [decimal](14, 4) NULL,
	[UndCapc] [varchar](10) NULL,
	[Comptmtos] [int] NULL,
	[CapComp] [varchar](50) NULL,
	[PasjerosPie] [int] NULL,
	[PasjerosSen] [int] NULL,
	[NitEmpresa] [varchar](16) NULL,
	[IdPropietario] [varchar](16) NULL,
	[IdPoseedor] [varchar](16) NULL,
	[IdConductor] [varchar](16) NULL,
	[IdPpd] [varchar](4) NULL,
	[TipoAfil] [varchar](10) NULL,
	[Adquisc] [varchar](10) NULL,
	[NitProv] [varchar](16) NULL,
	[FecCompra] [smalldatetime] NULL,
	[VrComcial] [money] NULL,
	[VrAseg] [money] NULL,
	[VrAvaludo] [money] NULL,
	[VidaUtil] [int] NULL,
	[FecSalida] [smalldatetime] NULL,
	[NContrato] [int] NULL,
	[IdAdmon] [varchar](4) NULL,
	[IdNiv] [varchar](4) NULL,
	[IdGrupo] [varchar](4) NULL,
	[CdGrupR] [varchar](4) NULL,
	[CdTarifa] [varchar](4) NULL,
	[FecIngreso] [smalldatetime] NULL,
	[FecVigencia] [smalldatetime] NULL,
	[FecRetiro] [smalldatetime] NULL,
	[NumSoat] [varchar](30) NULL,
	[FecSoat] [smalldatetime] NULL,
	[VigSoat] [smalldatetime] NULL,
	[NitEmpSoat] [varchar](16) NULL,
	[TarjProp] [varchar](30) NULL,
	[FecTProp] [smalldatetime] NULL,
	[VigTProp] [smalldatetime] NULL,
	[CdLugTp] [varchar](8) NULL,
	[Ulttramite] [varchar](150) NULL,
	[RespCivil] [varchar](30) NULL,
	[FecRCivil] [smalldatetime] NULL,
	[VigRCivil] [smalldatetime] NULL,
	[RegNalCarga] [varchar](30) NULL,
	[FecRegNal] [smalldatetime] NULL,
	[VigRegNal] [smalldatetime] NULL,
	[RevTecMec] [varchar](30) NULL,
	[FecTecMec] [smalldatetime] NULL,
	[VigTecMec] [smalldatetime] NULL,
	[CertGases] [varchar](30) NULL,
	[FecCertGas] [smalldatetime] NULL,
	[VigCertGas] [smalldatetime] NULL,
	[TarjOper] [varchar](30) NULL,
	[FecTarjOper] [smalldatetime] NULL,
	[VigTarjOper] [smalldatetime] NULL,
	[KmInicial] [int] NULL,
	[KmActual] [int] NULL,
	[Km2Actual] [int] NULL,
	[Regtradora] [bit] NULL,
	[CentInicial] [int] NULL,
	[CentFinal] [int] NULL,
	[VrLmtCred] [money] NULL,
	[VrSaldoAct] [money] NULL,
	[Descripcion] [varchar](100) NULL,
	[Observacion] [varchar](250) NULL,
	[CdCenSer] [varchar](4) NULL,
	[CdLocal] [varchar](8) NULL,
	[Ubicacion] [varchar](100) NULL,
	[PathFoto] [varchar](30) NULL,
	[FecPriServ] [smalldatetime] NULL,
	[FecUltServ] [smalldatetime] NULL,
	[FecUltAcc] [smalldatetime] NULL,
	[TieneAcc] [bit] NULL,
	[FecPagImp] [smalldatetime] NULL,
	[IdEstado] [varchar](4) NULL,
	[Inactivo] [bit] NULL,
	[FechaAdd] [smalldatetime] NULL,
	[FechaUpdate] [smalldatetime] NULL,
	[IdUsuario] [varchar](11) NULL,
	[ValorCupo] [money] NULL,
	[ObligaTProd] [bit] NULL,
	[GarantiaAcc] [bit] NULL,
	[DocCompleta] [bit] NULL,
	[CertMovilizacion] [varchar](20) NULL,
	[FecCertMovil] [smalldatetime] NULL,
	[VigCertMovil] [smalldatetime] NULL,
	[CdRutaHab] [varchar](4) NULL,
	[DeclaracImp] [varchar](50) NULL,
	[TipoIngreso] [varchar](4) NULL,
	[IdOrgTra] [varchar](8) NULL,
	[GPSoperador] [varchar](250) NULL,
	[GPSUsuario] [varchar](50) NULL,
	[GPSClave] [varchar](50) NULL,
	[CantFiltros] [decimal](14, 4) NULL,
	[GPSIdOper] [varchar](16) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehPolizas]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeVehPolizas] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[IdClase] [varchar](4) NULL,
	[Numero] [varchar](30) NULL,
	[FecEmision] [smalldatetime] NULL,
	[FecVigencia] [smalldatetime] NULL,
	[NitCompania] [varchar](16) NULL,
	[Valor] [money] NULL,
	[Comntarios] [varchar](100) NULL,
	[DiasAviso] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[dataTypeVehPropietarios]    Script Date: 13/07/2021 10:40:19 ******/
CREATE TYPE [dbo].[dataTypeVehPropietarios] AS TABLE(
	[IdVehiculo] [varchar](10) NULL,
	[Item] [int] NULL,
	[NitPropietario] [varchar](16) NULL,
	[PorcPartic] [decimal](14, 4) NULL,
	[FechaIng] [smalldatetime] NULL,
	[EstadoProp] [int] NULL
)
GO
/****** Object:  StoredProcedure [dbo].[paWcfGetCTraFijos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: John Jairo Roa Castañeda
-- Create date(dd/MM/yyyy): 16/08/2017
-- Description: Obtiene los registros de conceptos fijos de transporte que conciden con los filtros de acuerdo tipo de afiliación, tipo vehiculo, ruta, vehículo, conductor 
-- =============================================
CREATE PROCEDURE [dbo].[paWcfGetCTraFijos]
 @TipoAfilVeh varchar(10) = null, 
 @CdTipoVeh varchar(4) = null,
 @pVehiculo varchar(10) = null,
 @CedConductor varchar(16) = null,
 --@CedPropietario varchar(16) = null,
 @CdRuta varchar(4)=null
 AS
 BEGIN
 SELECT
 @TipoAfilVeh= CASE WHEN @TipoAfilVeh IS NULL  OR @TipoAfilVeh='' THEN '0' ELSE @TipoAfilVeh END, 
 @CdTipoVeh= CASE WHEN @CdTipoVeh IS NULL OR @CdTipoVeh='' THEN '0' ELSE @CdTipoVeh END,
 @pVehiculo= CASE WHEN @pVehiculo IS NULL  OR @pVehiculo='' THEN '0' ELSE @pVehiculo END,
 @CedConductor= CASE WHEN @CedConductor IS NULL OR @CedConductor='' THEN '0' ELSE @CedConductor END,
 --@CedPropietario= CASE WHEN @CedPropietario IS NULL OR  @CedPropietario='0' OR @CedPropietario='' THEN NULL ELSE @CedPropietario END,
 @CdRuta= CASE WHEN @CdRuta IS NULL OR @CdRuta='' THEN '0' ELSE @CdRuta END

SELECT 
TF.Numero, TF.IdConcepto, CD.IdCueDeb,CD.IdCueCre, TF.DescConc, TF.TipoConc, TF.Tarifa, TF.TipoTarif, TF.TipoAfilVeh, TF.CdTipoVeh, TF.TipoTerc, TF.Anulado, 
TF.CdCiuOrigen, TF.CdCiuDestino, TF.pVehiculo, TF.CedConductor, TF.CdRuta,TF.TipoVigencia,TF.FechaInicial,TF.FechaFinal
FROM            
(
	SELECT 
		TF.Numero, TF.IdConcepto, TF.DescConc, TF.TipoConc, TF.Tarifa, TF.TipoTarif, TF.TipoTerc, TF.Anulado, 
		TF.CdCiuOrigen, TF.CdCiuDestino,
		CASE WHEN TipoAfilVeh = '' or TipoAfilVeh = '0' THEN '0' ELSE TipoAfilVeh END AS TipoAfilVeh,
		CASE WHEN CdTipoVeh = '' or CdTipoVeh = '0' THEN '0' ELSE CdTipoVeh END AS CdTipoVeh,
		CASE WHEN pVehiculo = '' or pVehiculo = '0' THEN '0' ELSE pVehiculo END AS pVehiculo,
		CASE WHEN CedConductor = '' or CedConductor = '0' THEN '0' ELSE CedConductor END AS CedConductor,
		CASE WHEN CdRuta = '' or CdRuta = '0' THEN '0' ELSE CdRuta END AS CdRuta,
		TipoVigencia,
		FechaInicial,
		FechaFinal
	FROM
		TraFijos TF
	WHERE
		TF.Anulado = 0 AND TF.TipoConc<> 'SEGURO' AND TF.TipoConc<> 'IMPUESTO'
) AS TF 
JOIN ConcDiversos AS CD ON TF.IdConcepto = CD.IdConcepto 
WHERE 
	TipoAfilVeh = CASE WHEN TipoAfilVeh<>'0' THEN @TipoAfilVeh ELSE TipoAfilVeh END AND
	CdTipoVeh = CASE WHEN CdTipoVeh<>'0' THEN @CdTipoVeh ELSE CdTipoVeh END AND
	pVehiculo = CASE WHEN pVehiculo<>'0' THEN @pVehiculo ELSE pVehiculo END AND
	CedConductor = CASE WHEN CedConductor<>'0' THEN @CedConductor ELSE CedConductor END AND
	CdRuta = CASE WHEN CdRuta<>'0' THEN @CdRuta ELSE CdRuta END
ORDER BY TF.Numero

END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsadm_Opciones]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 20/04/2016
-- Description:	Insertar/Actualizar/Eliminar adm_Opciones.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsadm_Opciones]
	@adm_Opciones dataTypeadm_Opciones READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @adm_Opciones))
			begin
			 UPDATE adm_Opciones
			 SET IdOpc = T2.IdOpc, Opcion = T2.Opcion,TipoDato = T2.TipoDato,Valor = T2.Valor,NivUp = T2.NivUp,nModulo = T2.nModulo
			 FROM adm_Opciones T1
			 JOIN @adm_Opciones T2 ON T1.IdOpc = T2.IdOpc
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @adm_Opciones))
			BEGIN
			 INSERT INTO adm_Opciones(
			 IdOpc, Opcion,TipoDato,Valor,NivUp,nModulo)
			 SELECT 
			 IdOpc, Opcion,TipoDato,Valor,NivUp,nModulo
			 FROM @adm_Opciones
			 WHERE IdOpc NOT IN(SELECT IdOpc FROM adm_Opciones)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(3)
			 SELECT @id = IdOpc FROM @adm_Opciones
			 DELETE FROM adm_Opciones WHERE IdOpc = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsadm_Registro]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 19/04/2016
-- Description:	Insertar/Actualizar adm_Registro.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsadm_Registro]
	@adm_Registro dataTypeadm_Registro READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE adm_Registro
			 SET 
			 IdCia = t2.IdCia,TipoId = t2.TipoId,IdEmpresa = t2.IdEmpresa,
			 NitEmpresa = t2.NitEmpresa, DvNit = t2.DvNit, RazonSocial = t2.RazonSocial, NitRepLegal = t2.NitRepLegal, RepLegal = t2.RepLegal,
			 Descripcion = t2.Descripcion, Direccion = t2.Direccion, Telefono = t2.Telefono, Fax = t2.Fax, IdLocal = t2.IdLocal, IdPais = t2.IdPais,
			 e_mail = t2.e_mail, ArchivoLogo = t2.ArchivoLogo, NumeroSerial = t2.NumeroSerial, Regimen = t2.Regimen,TipoPersna = t2.TipoPersna,
			 Licencia = t2.Licencia, VigenciaLic = t2.VigenciaLic, Personeria = t2.Personeria, CIIUDane = t2.CIIUDane, Leyenda = t2.Leyenda, 
			 FechaRegistro = t2.FechaRegistro, FechaVence = t2.FechaVence, CurrtyDate = t2.CurrtyDate, CurDate1 = t2.CurDate1, FechaPrest = t2.FechaPrest
		     FROM adm_Registro t1
			 JOIN @adm_Registro t2 ON t1.IdEmpresa = t2.IdEmpresa and t1.NitEmpresa = t2.NitEmpresa
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO adm_Registro(
			 IdCia,TipoId,IdEmpresa,NitEmpresa,DvNit,RazonSocial,NitRepLegal,RepLegal,Descripcion,Direccion,Telefono,Fax,IdLocal,
			 IdPais,e_mail,ArchivoLogo,NumeroSerial,Regimen,TipoPersna,Licencia,VigenciaLic,Personeria,CIIUDane,Leyenda,FechaRegistro,
			 FechaVence,CurrtyDate,CurDate1,FechaPrest
			 )
			 SELECT 
			 IdCia,TipoId,IdEmpresa,NitEmpresa,DvNit,RazonSocial,NitRepLegal,RepLegal,Descripcion,Direccion,Telefono,Fax,IdLocal,
			 IdPais,e_mail,ArchivoLogo,NumeroSerial,Regimen,TipoPersna,Licencia,VigenciaLic,Personeria,CIIUDane,Leyenda,FechaRegistro,
			 FechaVence,CurrtyDate,CurDate1,FechaPrest
			 FROM @adm_Registro
			 WHERE IdEmpresa NOT IN(SELECT IdEmpresa FROM adm_Registro)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id char(2)
			 SELECT @id = IdEmpresa FROM @adm_Registro
			 DELETE FROM adm_Registro WHERE IdEmpresa = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsadm_Usuarios]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 19/04/2016
-- Description:	Insertar/Actualizar/Eliminar adm_Usuarios.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsadm_Usuarios]
	@adm_Usuarios dataTypeadm_Usuarios READONLY, 
	@adm_Permisos dataTypeadm_Permisos READONLY,
	@adm_UOpciones dataTypeadm_UOpciones READONLY,
	@adm_PermisosRoles dataTypeadm_PermisosRoles READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @adm_Usuarios))
			begin
			 UPDATE adm_Usuarios
			 SET 
			 IdUsuario = t2.IdUsuario, Usuario = t2.Usuario, PwdLog = t2.PwdLog, IdGrupo = t2.IdGrupo, IdEstacion = t2.IdEstacion,
			 IdCargo = t2.IdCargo, Conectado = t2.Conectado, FechaAcc = t2.FechaAcc, FechaClave = t2.FechaClave, Caducidad = t2.Caducidad,
			 LoginSQL = t2.LoginSQL, PwdSQL = t2.PwdSQL, ModoSQL = t2.ModoSQL, Inactivo = t2.Inactivo
			 FROM adm_Usuarios t1
			 JOIN @adm_Usuarios t2 ON t1.IdUsuario = t2.IdUsuario
			 WHERE t1.IdUsuario = t2.IdUsuario
			end

			IF(EXISTS(SELECT TOP 1 * FROM @adm_Permisos))
			begin
			 --Actualizar los que existen
			 UPDATE adm_Permisos
			 SET 
			 IdUsuario = t2.IdUsuario, IdObj = t2.IdObj, Consecutivo = t2.Consecutivo,PerAdd = t2.PerAdd,
			 PerUpdate = t2.PerUpdate,PerDelete = t2.PerDelete,PerAnular = t2.PerAnular,PerRead = t2.PerRead,
			 PerRename = t2.PerRename
			 FROM adm_Permisos t1
			 JOIN @adm_Permisos t2 ON t1.IdUsuario = t2.IdUsuario and t1.IdObj = t2.IdObj
			 WHERE t1.IdUsuario = t2.IdUsuario and t1.IdObj = t2.IdObj
			 --Inserta los que no existen
			 INSERT INTO adm_Permisos(
			 IdUsuario,IdObj,Consecutivo,PerAdd,PerUpdate,PerDelete,PerAnular,PerRead,PerRename)
			 SELECT 
			 IdUsuario,IdObj,Consecutivo,PerAdd,PerUpdate,PerDelete,PerAnular,PerRead,PerRename
			 FROM @adm_Permisos
			 WHERE (IdUsuario+IdObj) NOT IN(SELECT (IdUsuario+IdObj) FROM adm_Permisos)
			end

			IF(EXISTS(SELECT TOP 1 * FROM @adm_UOpciones))
			begin
			 --Actualizar los que existen
			 UPDATE adm_UOpciones
			 SET IdUsuario = T2.IdUsuario,NomOpcion = T2.NomOpcion,Valor = T2.Valor
			 FROM adm_UOpciones T1
			 JOIN @adm_UOpciones T2 ON T1.IdUsuario = T2.IdUsuario and t1.NomOpcion = T2.NomOpcion
			 --Inserta los que no existen
			 INSERT INTO adm_UOpciones(IdUsuario,NomOpcion,Valor)
			 SELECT IdUsuario,NomOpcion,Valor FROM @adm_UOpciones
			 WHERE (IdUsuario+NomOpcion) NOT IN(SELECT (IdUsuario+NomOpcion) FROM adm_UOpciones)
			end

			IF(EXISTS(SELECT TOP 1 * FROM @adm_PermisosRoles))
			begin
			 --Actualiza los que existen
			 UPDATE adm_PermisosRoles
			 SET IdUsuario = t2.IdUsuario, IdObj = t2.IdObj, IdRole = t2.IdRole, Asignado = t2.Asignado FROM adm_PermisosRoles T1
			 JOIN @adm_PermisosRoles T2 ON T1.IdUsuario = T2.IdUsuario and T1.IdObj = T2.IdObj and T1.IdRole = t2.IdRole
			 WHERE T1.IdUsuario = T2.IdUsuario and T1.IdObj = T2.IdObj and T1.IdRole = t2.IdRole
			 --Inserta los que no existen
			 INSERT INTO adm_PermisosRoles(IdUsuario,IdObj,IdRole,Asignado)
			 SELECT IdUsuario,IdObj,IdRole,Asignado FROM @adm_PermisosRoles
			 WHERE (IdUsuario+IdObj+IdRole) NOT IN(SELECT (IdUsuario+IdObj+IdRole) FROM adm_PermisosRoles)
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @adm_Usuarios))
			BEGIN
			 INSERT INTO adm_Usuarios(
			 IdUsuario, Usuario, PwdLog, IdGrupo, IdEstacion, IdCargo, Conectado, FechaAcc, FechaClave,
			 Caducidad, LoginSQL, PwdSQL, ModoSQL, Inactivo)
			 SELECT 
			 IdUsuario,Usuario,PwdLog,IdGrupo,IdEstacion,IdCargo,Conectado,FechaAcc,FechaClave,
			 Caducidad,LoginSQL,PwdSQL,ModoSQL,Inactivo			 
			 FROM @adm_Usuarios
			 WHERE IdUsuario NOT IN(SELECT IdUsuario FROM adm_Usuarios)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @adm_Permisos))
			BEGIN
			 INSERT INTO adm_Permisos(
			 IdUsuario,IdObj,Consecutivo,PerAdd,PerUpdate,PerDelete,PerAnular,PerRead,PerRename)
			 SELECT 
			 IdUsuario,IdObj,Consecutivo,PerAdd,PerUpdate,PerDelete,PerAnular,PerRead,PerRename
			 FROM @adm_Permisos
			 WHERE (IdUsuario+IdObj) NOT IN(SELECT (IdUsuario+IdObj) FROM adm_Permisos)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @adm_UOpciones))
			BEGIN
			 INSERT INTO adm_UOpciones(
			 IdUsuario,NomOpcion,Valor
			 )
			 SELECT 
			 IdUsuario,NomOpcion,Valor
			 FROM @adm_UOpciones
			 WHERE (IdUsuario+NomOpcion) NOT IN(SELECT (IdUsuario+NomOpcion) FROM adm_UOpciones)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @adm_PermisosRoles))
			BEGIN
			 INSERT INTO adm_PermisosRoles(
			 IdUsuario,IdObj,IdRole,Asignado
			 )
			 SELECT 
			 IdUsuario,IdObj,IdRole,Asignado
			 FROM @adm_PermisosRoles
			 WHERE (IdUsuario+IdObj+IdRole) NOT IN(SELECT (IdUsuario+IdObj+IdRole) FROM adm_PermisosRoles)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id VARCHAR (11)
			 SELECT @id = IdUsuario FROM @adm_Usuarios

			 DELETE FROM adm_Permisos WHERE IdUsuario = @id			
			 DELETE FROM adm_Usuarios WHERE IdUsuario = @id
			 DELETE FROM adm_PermisosRoles WHERE IdUsuario = @id
			 DELETE FROM adm_UOpciones WHERE IdUsuario = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCalndario]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar/Eliminar Calndario.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsCalndario]
	@Calndario dataTypeCalndario READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		DECLARE @id smalldatetime

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN

			 --Eliminar el mes que se va a actualizar
		     SELECT @id = FechaDia FROM @Calndario
			 DELETE FROM Calndario WHERE (MONTH(FechaDia) = MONTH(@id)) AND (YEAR(FechaDia) = YEAR(@id))

			 --Insertar el mes que se actualiza
			 INSERT INTO Calndario( FechaDia, TipoFtvo )
			 SELECT FechaDia, TipoFtvo FROM @Calndario WHERE FechaDia NOT IN(SELECT FechaDia FROM Calndario)

			 --UPDATE Calndario
			 --SET 
			 --FechaDia = t2.FechaDia, TipoFtvo = t2.TipoFtvo
		  --   FROM Calndario t1
			 --JOIN @Calndario t2 ON t1.FechaDia = t2.FechaDia
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Calndario( FechaDia, TipoFtvo )
			 SELECT FechaDia, TipoFtvo FROM @Calndario WHERE FechaDia NOT IN(SELECT FechaDia FROM Calndario)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 SELECT @id = FechaDia FROM @Calndario
			 DELETE FROM Calndario WHERE (MONTH(FechaDia) = MONTH(@id)) AND (YEAR(FechaDia) = YEAR(@id))
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCargos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 12/05/2016
-- Description:	Insertar/Actualizar/Eliminar Cargos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsCargos]
	@Cargos dataTypeCargos READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Cargos
			 SET 
				IdCargo = t2.IdCargo,
				Cargo = t2.Cargo,
				Funciones = t2.Funciones,
				Inactivo = t2.Inactivo
		     FROM Cargos t1
			 JOIN @Cargos t2 ON t1.IdCargo = t2.IdCargo
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Cargos(
			 IdCargo,Cargo,Funciones,Inactivo
			 )
			 SELECT 
			 IdCargo,Cargo,Funciones,Inactivo
			 FROM @Cargos
			 WHERE IdCargo NOT IN(SELECT IdCargo FROM Cargos)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdCargo FROM @Cargos
			 DELETE FROM Cargos WHERE IdCargo = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCentrosServ]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 27/04/2016
-- Description:	Insertar/Actualizar/Eliminar CentrosServ.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsCentrosServ]
	@CentrosServ dataTypeCentrosServ READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE CentrosServ
			 SET 
			 IdCenSer = t2.IdCenSer, CentroServ = t2.CentroServ, DirCentro = t2.DirCentro, 
			 IdLocal = t2.IdLocal, Telefonos = t2.Telefonos, TipoCentro = t2.TipoCentro,
			 NitResp = t2.NitResp, Respnsable = t2.Respnsable, Inactivo = t2.Inactivo
		     FROM CentrosServ t1
			 JOIN @CentrosServ t2 ON t1.IdCenSer = t2.IdCenSer
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO CentrosServ(
			 IdCenSer,CentroServ,DirCentro,IdLocal,Telefonos,TipoCentro,NitResp,Respnsable,Inactivo
			 )
			 SELECT 
			 IdCenSer,CentroServ,DirCentro,IdLocal,Telefonos,TipoCentro,NitResp,Respnsable,Inactivo
			 FROM @CentrosServ
			 WHERE IdCenSer NOT IN(SELECT IdCenSer FROM CentrosServ)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdCenSer FROM @CentrosServ
			 DELETE FROM CentrosServ WHERE IdCenSer = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseCapac]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/08/2016
-- Description:	Insertar/Actualizar ClaseCapac.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsClaseCapac]
	@ClaseCapac dataTypeClaseCapac READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE ClaseCapac
			 SET 
			 IdClase = t2.IdClase,NomClase = t2.NomClase,Inactivo = t2.Inactivo
		     FROM ClaseCapac t1
			 JOIN @ClaseCapac t2 ON t1.IdClase = t2.IdClase
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO ClaseCapac(
			 IdClase,NomClase,Inactivo
			 )
			 SELECT 
			 IdClase,NomClase,Inactivo	
			 FROM @ClaseCapac
			 WHERE IdClase NOT IN(SELECT IdClase FROM ClaseCapac)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdClase FROM @ClaseCapac
			 DELETE FROM ClaseCapac WHERE IdClase = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseCta]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 13/05/2016
-- Description:	Insertar/Actualizar/Eliminar ClaseCta.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsClaseCta]
	@ClaseCta dataTypeClaseCta READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @ClaseCta))
			begin
			 UPDATE ClaseCta
			 SET 
			 IdClase = t2.IdClase, ClaseCuenta = t2.ClaseCuenta, Inactivo = t2.Inactivo
			 FROM ClaseCta T1
			 JOIN @ClaseCta T2 ON T1.IdClase = T2.IdClase
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @ClaseCta))
			BEGIN
			 INSERT INTO ClaseCta(
			 IdClase,ClaseCuenta,Inactivo
			 )
			 SELECT 
			 IdClase,ClaseCuenta,Inactivo
			 FROM @ClaseCta
			 WHERE IdClase NOT IN(SELECT IdClase FROM ClaseCta)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdClase FROM @ClaseCta
			 DELETE FROM ClaseCta WHERE IdClase = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseDiv]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21¿6/04/2016
-- Description:	Insertar/Actualizar/Eliminar ClaseDiv.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsClaseDiv]
	@ClaseDiv dataTypeClaseDiv READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE ClaseDiv
			 SET 
			 IdClase = t2.IdClase,NomClase = t2.NomClase,Inactivo = t2.Inactivo
		     FROM ClaseDiv t1
			 JOIN @ClaseDiv t2 ON t1.IdClase = t2.IdClase
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO ClaseDiv(
			 IdClase,NomClase,Inactivo
			 )
			 SELECT 
			 IdClase,NomClase,Inactivo
			 FROM @ClaseDiv
			 WHERE IdClase NOT IN(SELECT IdClase FROM ClaseDiv)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdClase FROM @ClaseDiv
			 DELETE FROM ClaseDiv WHERE IdClase = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClaseDocCond]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/08/2016
-- Description:	Insertar/Actualizar ClaseDocCond.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsClaseDocCond]
	@ClaseDocCond dataTypeClaseDocCond READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE ClaseDocCond
			 SET 
			 IdDoc = t2.IdDoc,Documento = t2.Documento,Vigencia = t2.Vigencia,Inactivo = t2.Inactivo
		     FROM ClaseDocCond t1
			 JOIN @ClaseDocCond t2 ON t1.IdDoc = t2.IdDoc
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO ClaseDocCond(
			 IdDoc,Documento,Vigencia,Inactivo
			 )
			 SELECT 
			 IdDoc,Documento,Vigencia,Inactivo
			 FROM @ClaseDocCond
			 WHERE IdDoc NOT IN(SELECT IdDoc FROM ClaseDocCond)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdDoc FROM @ClaseDocCond
			 DELETE FROM ClaseDocCond WHERE IdDoc = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsClasePol]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar ClasePol.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsClasePol]
	@ClasePol dataTypeClasePol READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE ClasePol
			 SET 
			 IdClase = t2.IdClase,ClasePoliza = t2.ClasePoliza,Inactivo = t2.Inactivo
		     FROM ClasePol t1
			 JOIN @ClasePol t2 ON t1.IdClase = t2.IdClase
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO ClasePol(
			 IdClase,ClasePoliza,Inactivo
			 )
			 SELECT 
			 IdClase,ClasePoliza,Inactivo
			 FROM @ClasePol
			 WHERE IdClase NOT IN(SELECT IdClase FROM ClasePol)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdClase FROM @ClasePol
			 DELETE FROM ClasePol WHERE IdClase = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsCompanias]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 20/04/2016
-- Description:	Insertar/Actualizar/Eliminar Companias.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsCompanias]
	@Companias dataTypeCompanias READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Companias))
			begin
			 UPDATE Companias
			 SET 
			 IdCia = t2.IdCia,Compania = t2.Compania,DirInterface = t2.DirInterface,FechaActual = t2.FechaActual,
			 PeriodoActual = t2.PeriodoActual,IdCCosto = t2.IdCCosto,IdSubCos = t2.IdSubCos,IdTercero = t2.IdTercero,
			 CodSucsal = t2.CodSucsal,DireccSuc = t2.DireccSuc,TelefSuc = t2.TelefSuc,FaxSuc = t2.FaxSuc,
			 IdLocal = t2.IdLocal,TipoEDS = t2.TipoEDS,CodPlanta = t2.CodPlanta,FechaAdd = t2.FechaAdd,
			 FechaUpdate = t2.FechaUpdate,Inactivo = t2.Inactivo,CodBodega = t2.CodBodega,FecModPrest = t2.FecModPrest,
			 AutoIca = t2.AutoIca
			 FROM Companias T1
			 JOIN @Companias T2 ON T1.IdCia = T2.IdCia
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Companias))
			BEGIN
			 INSERT INTO Companias(
			 IdCia,Compania,DirInterface,FechaActual,PeriodoActual,IdCCosto,IdSubCos,IdTercero,CodSucsal,DireccSuc,TelefSuc,FaxSuc,IdLocal,
			 TipoEDS,CodPlanta,FechaAdd,FechaUpdate,Inactivo,CodBodega,FecModPrest,AutoIca
			 )
			 SELECT 
			 IdCia,Compania,DirInterface,FechaActual,PeriodoActual,IdCCosto,IdSubCos,IdTercero,CodSucsal,DireccSuc,TelefSuc,FaxSuc,IdLocal,
			 TipoEDS,CodPlanta,FechaAdd,FechaUpdate,Inactivo,CodBodega,FecModPrest,AutoIca
			 FROM @Companias
			 WHERE IdCia NOT IN(SELECT IdCia FROM Companias)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id char(2)
			 SELECT @id = IdCia FROM @Companias
			 DELETE FROM Companias WHERE IdCia = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsConceptosDiv]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 12/07/2016
-- Description:	Insertar/Actualizar/Eliminar ConceptosDiversos y ConceptosDivCue.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsConceptosDiv]
	@ConcDiversos dataTypeConcDiversos READONLY, 
	@ConcDivCue dataTypeConcDivCue READONLY,
	@ConcDivCia dataTypeConcDivCia READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @ConcDiversos))
			begin
			 UPDATE ConcDiversos
			 SET
			  IdConcepto = t2.IdConcepto,Concepto = t2.Concepto,Grupo = t2.Grupo,EsServicio = t2.EsServicio,
			  DeManfsto = t2.DeManfsto,CdIva = t2.CdIva,CdRet = t2.CdRet,CdIca = t2.CdIca,CdAutoret = t2.CdAutoret,
			  IdCueDeb = t2.IdCueDeb,IdCueCre = t2.IdCueCre,Inactivo = t2.Inactivo,FechaAdd = t2.FechaAdd,
			  FechaUpdate = t2.FechaUpdate,IdUsuario = t2.IdUsuario,OrdenServ = t2.OrdenServ,NovedadNom = t2.NovedadNom,
			  CdConcDeveng = t2.CdConcDeveng,CdConcDed = t2.CdConcDed,RubroConc = t2.RubroConc,MudReajuste=t2.MudReajuste,
			  CodFEDian = t2.CodFEDian
			 FROM ConcDiversos t1
			 JOIN @ConcDiversos t2 ON t1.IdConcepto = t2.IdConcepto
			 WHERE t1.IdConcepto = t2.IdConcepto
			end

			IF(EXISTS(SELECT TOP 1 * FROM @ConcDivCia))
			begin
			  declare @id varchar(4) 
			  select top 1 @id = IdConcepto from @ConcDivCia
				delete from ConcDivCia where IdConcepto = @id
				
				insert into ConcDivCia(
				IdConcepto,IdCia )
				select 
				IdConcepto,IdCia
				from @ConcDivCia 
				where (IdConcepto+Idcia) NOT IN(SELECT (IdConcepto+Idcia) FROM ConcDivCia) 
			end

			IF(EXISTS(SELECT TOP 1 * FROM @ConcDivCue))
			begin
			 --Actualizar los que existen
			 UPDATE ConcDivCue
			 SET 
			  IdConcepto = t2.IdConcepto,IdClase = t2.IdClase,
			  IdCuenta = t2.IdCuenta,CdCueDev = t2.CdCueDev,
			  TipoMov = t2.TipoMov,TipoTerc = t2.TipoTerc,
			  FecAdd = t2.FecAdd,FecUpdate = t2.FecUpdate
			 FROM ConcDivCue t1
			 JOIN @ConcDivCue t2 ON t1.IdConcepto = t2.IdConcepto and t1.IdClase = t2.IdClase
			 WHERE t1.IdConcepto = t2.IdConcepto and t1.IdClase = t2.IdClase
			 --Inserta los que no existen
			 INSERT INTO ConcDivCue(
			  IdConcepto,IdClase,IdCuenta,CdCueDev,TipoMov,TipoTerc,FecAdd,FecUpdate
			 )
			 SELECT 
			  IdConcepto,IdClase,IdCuenta,CdCueDev,TipoMov,TipoTerc,FecAdd,FecUpdate
			 FROM @ConcDivCue
			 WHERE (IdConcepto+IdClase) NOT IN(SELECT (IdConcepto+IdClase) FROM ConcDivCue)
			end					
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @ConcDiversos))
			BEGIN
			INSERT INTO ConcDiversos(
			IdConcepto,Concepto,Grupo,EsServicio,DeManfsto,CdIva,CdRet,CdIca,CdAutoret,
			IdCueDeb,IdCueCre,Inactivo,FechaAdd,FechaUpdate,IdUsuario,OrdenServ,NovedadNom,
			CdConcDeveng,CdConcDed,RubroConc,MudReajuste,CodFEDian
			)
			SELECT 
			IdConcepto,Concepto,Grupo,EsServicio,DeManfsto,CdIva,CdRet,CdIca,CdAutoret,
			IdCueDeb,IdCueCre,Inactivo,FechaAdd,FechaUpdate,IdUsuario,OrdenServ,NovedadNom,
			CdConcDeveng,CdConcDed,RubroConc,MudReajuste,CodFEDian
			FROM @ConcDiversos
			WHERE IdConcepto NOT IN(SELECT IdConcepto FROM ConcDiversos)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @ConcDivCia))
			BEGIN
			INSERT INTO ConcDivCia(
			IdConcepto,IdCia)
			SELECT 
			IdConcepto,IdCia
			FROM @ConcDivCia 
			WHERE (IdConcepto+Idcia) NOT IN(SELECT (IdConcepto+Idcia) FROM ConcDivCia)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @ConcDivCue))
			BEGIN
			INSERT INTO ConcDivCue(
			IdConcepto,IdClase,IdCuenta,CdCueDev,TipoMov,TipoTerc,FecAdd,FecUpdate)
			SELECT 
			IdConcepto,IdClase,IdCuenta,CdCueDev,TipoMov,TipoTerc,FecAdd,FecUpdate
			FROM @ConcDivCue
			WHERE (IdConcepto+IdClase) NOT IN(SELECT (IdConcepto+IdClase) FROM ConcDivCue)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @_id VARCHAR(4)
			 DECLARE @idcl int
			 
			 IF(EXISTS(SELECT TOP 1 * FROM @ConcDiversos))	
			 BEGIN
				SELECT @_id = IdConcepto FROM @ConcDiversos
				DELETE FROM ConcDivCue WHERE IdConcepto = @_id
				DELETE FROM ConcDivCia WHERE IdConcepto = @_id
				DELETE FROM ConcDiversos WHERE IdConcepto = @_id	
			 END

			 IF(EXISTS(SELECT TOP 1 * FROM @ConcDivCue))
			 BEGIN
				if((SELECT TOP 1 IdClase FROM @ConcDivCue) > 0)
				begin 
				 SELECT @_id = IdConcepto, @idcl = IdClase FROM @ConcDivCue
				 DELETE FROM ConcDivCue WHERE IdConcepto = @_id and IdClase = @idcl
				end
				else 
				begin
				 SELECT @_id = IdConcepto FROM @ConcDivCue
				 DELETE FROM ConcDivCue WHERE IdConcepto = @_id
				end
			 END
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsConceptosFijos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 29/07/2016
-- Description:	Insertar/Actualizar/Eliminar Conceptos de Cargos Fijos
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsConceptosFijos]
	@Fijos dataTypeFijos READONLY, 
	@Fijos_Cue dataTypeFijos_Cue READONLY,
	@Fijos_Veh dataTypeFijos_Veh READONLY,
	@Fijos_Cla dataTypeFijos_Cla READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos))
			begin
			 UPDATE Fijos
			 SET
			  IdCargo = t2.IdCargo, Concepto = t2.Concepto, Obligatorio = t2.Obligatorio,
			  TipoAplica = t2.TipoAplica, DiasSemana = t2.DiasSemana, DiasMes = t2.DiasMes, ValorMensual = t2.ValorMensual,
			  ValorDiario = t2.ValorDiario, IdCuentaDeb = t2.IdCuentaDeb, IdCuentaCre = t2.IdCuentaCre, IdCueDebVp = t2.IdCueDebVp,
			  IdCueCreVp = t2.IdCueCreVp,NCuotas = t2.NCuotas,DiasVcmto = t2.DiasVcmto,OrdenAbono = t2.OrdenAbono,
			  TipoDcto = t2.TipoDcto,DctoPpago = t2.DctoPpago,VrCargoAdic = t2.VrCargoAdic,FecLimiteIni = t2.FecLimiteIni,
			  FecLimiteFin = t2.FecLimiteFin,Inactivo = t2.Inactivo,FechaAdd = t2.FechaAdd,FechaUpdate = t2.FechaUpdate,IdUsuario = t2.IdUsuario
			 FROM Fijos t1
			 JOIN @Fijos t2 ON t1.IdCargo = t2.IdCargo
			 WHERE t1.IdCargo = t2.IdCargo
			end

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Cue))
			begin
			  declare @id varchar(4) 
			  select top 1 @id = IdCargo from @Fijos_Cue
				delete from Fijos_Cue where IdCargo = @id
				
				insert into Fijos_Cue(
				IdCargo,IdAdmon,IdCuentaDeb,IdCuentaCre,IdCueDebVp,IdCueCreVp)
				select 
				IdCargo,IdAdmon,IdCuentaDeb,IdCuentaCre,IdCueDebVp,IdCueCreVp
				from @Fijos_Cue 
				where (IdCargo+IdAdmon) NOT IN(SELECT (IdCargo+IdAdmon) FROM Fijos_Cue) 
			end

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Veh))
			begin
			 --Actualizar los que existen
			 UPDATE Fijos_Veh
			 SET 
			  IdCargo = t2.IdCargo,IdVehiculo = t2.IdVehiculo,ValorMensual = t2.ValorMensual,
			  ValorDiario = t2.ValorDiario,Excluir = t2.Excluir
			 FROM Fijos_Veh t1
			 JOIN @Fijos_Veh t2 ON t1.IdCargo = t2.IdCargo and t1.IdVehiculo = t2.IdVehiculo
			 WHERE t1.IdCargo = t2.IdCargo and t1.IdVehiculo = t2.IdVehiculo
			 --Inserta los que no existen
			 INSERT INTO Fijos_Veh(
			  IdCargo,IdVehiculo,ValorMensual,ValorDiario,Excluir)
			 SELECT 
			  IdCargo,IdVehiculo,ValorMensual,ValorDiario,Excluir
			 FROM @Fijos_Veh
			 WHERE (IdCargo+IdVehiculo) NOT IN(SELECT (IdCargo+IdVehiculo) FROM Fijos_Veh)
			end		

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Cla))
			begin
			 --Actualizar los que existen
			 UPDATE Fijos_Cla
			 SET 
			  IdCargo = t2.IdCargo,IdClase = t2.IdClase,ValorMensual = t2.ValorMensual,ValorDiario = t2.ValorDiario
			 FROM Fijos_Cla t1
			 JOIN @Fijos_Cla t2 ON t1.IdCargo = t2.IdCargo and t1.IdClase = t2.IdClase
			 WHERE t1.IdCargo = t2.IdCargo and t1.IdClase = t2.IdClase
			 --Inserta los que no existen
			 INSERT INTO Fijos_Cla(
			  IdCargo,IdClase,ValorMensual,ValorDiario)
			 SELECT 
			  IdCargo,IdClase,ValorMensual,ValorDiario
			 FROM @Fijos_Cla
			 WHERE (IdCargo+IdClase) NOT IN(SELECT (IdCargo+IdClase) FROM Fijos_Cla)
			end					
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos))
			BEGIN
			INSERT INTO Fijos(
			IdCargo,Concepto,Obligatorio,TipoAplica,DiasSemana,DiasMes,ValorMensual,
			ValorDiario,IdCuentaDeb,IdCuentaCre,IdCueDebVp,IdCueCreVp,NCuotas,DiasVcmto,
			OrdenAbono,TipoDcto,DctoPpago,VrCargoAdic,FecLimiteIni,FecLimiteFin,Inactivo,
			FechaAdd,FechaUpdate,IdUsuario
			)
			SELECT 
			IdCargo,Concepto,Obligatorio,TipoAplica,DiasSemana,DiasMes,ValorMensual,
			ValorDiario,IdCuentaDeb,IdCuentaCre,IdCueDebVp,IdCueCreVp,NCuotas,DiasVcmto,
			OrdenAbono,TipoDcto,DctoPpago,VrCargoAdic,FecLimiteIni,FecLimiteFin,Inactivo,
			FechaAdd,FechaUpdate,IdUsuario
			FROM @Fijos
			WHERE IdCargo NOT IN(SELECT IdCargo FROM Fijos)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Cue))
			BEGIN
			INSERT INTO Fijos_Cue(
			IdCargo,IdAdmon,IdCuentaDeb,IdCuentaCre,IdCueDebVp,IdCueCreVp
			)
			SELECT 
			IdCargo,IdAdmon,IdCuentaDeb,IdCuentaCre,IdCueDebVp,IdCueCreVp
			FROM @Fijos_Cue 
			WHERE (IdCargo+IdAdmon) NOT IN(SELECT (IdCargo+IdAdmon) FROM Fijos_Cue)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Veh))
			BEGIN
			INSERT INTO Fijos_Veh(
			IdCargo,IdVehiculo,ValorMensual,ValorDiario,Excluir)
			SELECT 
			IdCargo,IdVehiculo,ValorMensual,ValorDiario,Excluir
			FROM @Fijos_Veh
			WHERE (IdCargo+IdVehiculo) NOT IN(SELECT (IdCargo+IdVehiculo) FROM Fijos_Veh)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Cla))
			BEGIN
			INSERT INTO Fijos_Cla(
			IdCargo,IdClase,ValorMensual,ValorDiario)
			SELECT 
			IdCargo,IdClase,ValorMensual,ValorDiario
			FROM @Fijos_Cla
			WHERE (IdCargo+IdClase) NOT IN(SELECT (IdCargo+IdClase) FROM Fijos_Cla)
			END

		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @_id VARCHAR (4)
			 DECLARE @idcl int
			 
			 IF(EXISTS(SELECT TOP 1 * FROM @Fijos))	
			 BEGIN
				SELECT @_id = IdCargo FROM @Fijos
				DELETE FROM Fijos_Cue WHERE IdCargo = @_id
				DELETE FROM Fijos_Cla WHERE IdCargo = @_id
				DELETE FROM Fijos_Veh WHERE IdCargo = @_id
				DELETE FROM Fijos WHERE IdCargo = @_id	
			 END

			 IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Cla))
			 BEGIN
				if((SELECT TOP 1 IdClase FROM @Fijos_Cla) > 0)
				begin 
				 SELECT @_id = IdCargo, @idcl = IdClase FROM @Fijos_Cla
				 DELETE FROM Fijos_Cla WHERE IdCargo = @_id and IdClase = @idcl
				end
				else 
				begin
				 SELECT @_id = IdCargo FROM @Fijos_Cla
				 DELETE FROM Fijos_Cla WHERE IdCargo = @_id
				end
			 END

			 IF(EXISTS(SELECT TOP 1 * FROM @Fijos_Veh))
			 BEGIN				
				 SELECT @_id = IdCargo, @idcl = IdVehiculo  FROM @Fijos_Veh
				 DELETE FROM Fijos_Veh WHERE IdCargo = @_id and IdVehiculo = @idcl
			 END

		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsDepartamentos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar/Eliminar Departamentos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsDepartamentos]
	@Departamentos dataTypeDepartamentos READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Departamentos))
			begin
			 UPDATE Departamentos
			 SET 
			 IdDep = t2.IdDep,Departamento = t2.Departamento,Codigo = t2.Codigo,IdPais = t2.IdPais,Inactivo = t2.Inactivo
			 FROM Departamentos T1
			 JOIN @Departamentos T2 ON T1.IdDep = T2.IdDep
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Departamentos))
			BEGIN
			 INSERT INTO Departamentos(
			 IdDep,Departamento,Codigo,IdPais,Inactivo
			 )
			 SELECT 
			 IdDep,Departamento,Codigo,IdPais,Inactivo
			 FROM @Departamentos
			 WHERE IdDep NOT IN(SELECT IdDep FROM Departamentos)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(8)
			 SELECT @id = IdDep FROM @Departamentos
			 DELETE FROM Departamentos WHERE IdDep = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsDocConceptos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 12/07/2016
-- Description:	Insertar/Actualizar/Eliminar Conceptos y ConceptosCue.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsDocConceptos]
	@Conceptos dataTypeConceptos READONLY, 
	@ConceptosCue dataTypeConceptosCue READONLY,
	@ConceptosCia dataTypeConceptosCia READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Conceptos))
			begin
			 UPDATE Conceptos
			 SET
			  IdConcepto = t2.IdConcepto, Concepto = t2.Concepto, IdDoc = t2.IdDoc, IdCom = t2.IdCom,
			  Vcmto = t2.Vcmto, Imptos = t2.Imptos, Retfte = t2.Retfte, RetIca = t2.RetIca,
			  Observacion = t2.Observacion, Pdterminado = t2.Pdterminado, TrfaSanc = t2.TrfaSanc, RndTotal = t2.RndTotal,
			  DcmtoEquiv = t2.DcmtoEquiv, Inactivo = t2.Inactivo, FechaAdd = t2.FechaAdd, FechaUpdate = t2.FechaUpdate,
			  IdUsuario = t2.IdUsuario, TipoContab = t2.TipoContab, CdComNiif = t2.CdComNiif, CdComFiscal = t2.CdComFiscal,CodCiaTdo=t2.CodCiaTdo,
			  TipoConRev = t2.TipoConRev
			 FROM Conceptos t1
			 JOIN @Conceptos t2 ON t1.IdConcepto = t2.IdConcepto
			 WHERE t1.IdConcepto = t2.IdConcepto
			end

			IF(EXISTS(SELECT TOP 1 * FROM @ConceptosCia))
			begin
			  declare @id varchar(4) 
			  select top 1 @id = IdConcepto from @ConceptosCia
				delete from ConceptosCia where IdConcepto = @id
				
				insert into ConceptosCia(
				IdConcepto,IdCia )
				select 
				IdConcepto,IdCia
				from @ConceptosCia 
				where (IdConcepto+Idcia) NOT IN(SELECT (IdConcepto+Idcia) FROM ConceptosCia) 
			end

			IF(EXISTS(SELECT TOP 1 * FROM @ConceptosCue))
			begin
			 --Actualizar los que existen
			 UPDATE ConceptosCue
			 SET 
			  IdConcepto = t2.IdConcepto, IdClase = t2.IdClase,
			  Descripcion = t2.Descripcion, IdCuenta = t2.IdCuenta,
			  TipoMov = t2.TipoMov, DetalleMov = t2.DetalleMov,
			  CdCCosto = t2.CdCCosto, CdSubCos = t2.CdSubCos,
			  TipoTerc = t2.TipoTerc, FecAdd = t2.FecAdd, FecUpdate = t2.FecUpdate
			 FROM ConceptosCue t1
			 JOIN @ConceptosCue t2 ON t1.IdConcepto = t2.IdConcepto and t1.IdClase = t2.IdClase
			 WHERE t1.IdConcepto = t2.IdConcepto and t1.IdClase = t2.IdClase
			 --Inserta los que no existen
			 INSERT INTO ConceptosCue(
			  IdConcepto,IdClase,Descripcion,IdCuenta,TipoMov,DetalleMov,
			  CdCCosto,CdSubCos,TipoTerc,FecAdd,FecUpdate
			 )
			 SELECT 
			  IdConcepto,IdClase,Descripcion,IdCuenta,TipoMov,DetalleMov,
			  CdCCosto,CdSubCos,TipoTerc,FecAdd,FecUpdate
			 FROM @ConceptosCue
			 WHERE (IdConcepto+Convert(varchar,IdClase)) NOT IN(SELECT (IdConcepto+Convert(varchar,IdClase)) FROM ConceptosCue)
			end					
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Conceptos))
			BEGIN
			INSERT INTO Conceptos(
			IdConcepto,Concepto,IdDoc,IdCom,Vcmto,
			Imptos,Retfte,RetIca,Observacion,Pdterminado,
			TrfaSanc,RndTotal,DcmtoEquiv,Inactivo,FechaAdd,
			FechaUpdate,IdUsuario,TipoContab,CdComNiif,CdComFiscal,CodCiaTdo,TipoConRev
			)
			SELECT 
			IdConcepto,Concepto,IdDoc,IdCom,Vcmto,
			Imptos,Retfte,RetIca,Observacion,Pdterminado,
			TrfaSanc,RndTotal,DcmtoEquiv,Inactivo,FechaAdd,
			FechaUpdate,IdUsuario,TipoContab,CdComNiif,CdComFiscal,CodCiaTdo,TipoConRev
			FROM @Conceptos
			WHERE IdConcepto NOT IN(SELECT IdConcepto FROM Conceptos)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @ConceptosCia))
			BEGIN
			INSERT INTO ConceptosCia(
			IdConcepto,IdCia )
			SELECT 
			IdConcepto,IdCia
			FROM @ConceptosCia 
			WHERE (IdConcepto+Idcia) NOT IN(SELECT (IdConcepto+Idcia) FROM ConceptosCia)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @ConceptosCue))
			BEGIN
			INSERT INTO ConceptosCue(
			IdConcepto,IdClase,Descripcion,IdCuenta,TipoMov,DetalleMov,
			CdCCosto,CdSubCos,TipoTerc,FecAdd,FecUpdate)
			SELECT 
			IdConcepto,IdClase,Descripcion,IdCuenta,TipoMov,DetalleMov,
			CdCCosto,CdSubCos,TipoTerc,FecAdd,FecUpdate
			FROM @ConceptosCue
			WHERE (IdConcepto+Convert(varchar,IdClase)) NOT IN(SELECT (IdConcepto+Convert(varchar,IdClase)) FROM ConceptosCue)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @_id VARCHAR (4)
			 DECLARE @idcl int
			 
			 IF(EXISTS(SELECT TOP 1 * FROM @Conceptos))	
			 BEGIN
				SELECT @_id = IdConcepto FROM @Conceptos
				 DELETE FROM ConceptosCue WHERE IdConcepto = @_id
				DELETE FROM ConceptosCia WHERE IdConcepto = @_id
				DELETE FROM Conceptos WHERE IdConcepto = @_id	
			 END

			 IF(EXISTS(SELECT TOP 1 * FROM @ConceptosCue))
			 BEGIN
				if((SELECT count(IdClase) FROM @ConceptosCue) = 1)
				begin 
				 SELECT @_id = IdConcepto, @idcl = IdClase FROM @ConceptosCue
				 DELETE FROM ConceptosCue WHERE IdConcepto = @_id and IdClase = @idcl
				end
				else 
				begin
				 SELECT @_id = IdConcepto FROM @ConceptosCue
				 DELETE FROM ConceptosCue WHERE IdConcepto = @_id
				end
			 END
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEdsServicio]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 27/04/2016
-- Description:	Insertar/Actualizar/Eliminar EdsServicio.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsEdsServicio]
	@EdsServicio dataTypeEdsServicio READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE EdsServicio
			 SET 
			 IdEstacion = t2.IdEstacion,EstServicio = t2.EstServicio,Direccion = t2.Direccion,Inactivo = t2.Inactivo
		     FROM EdsServicio t1
			 JOIN @EdsServicio t2 ON t1.IdEstacion = t2.IdEstacion
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO EdsServicio(
			 IdEstacion,EstServicio,Direccion,Inactivo
			 )
			 SELECT 
			 IdEstacion,EstServicio,Direccion,Inactivo
			 FROM @EdsServicio
			 WHERE IdEstacion NOT IN(SELECT IdEstacion FROM EdsServicio)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdEstacion FROM @EdsServicio
			 DELETE FROM EdsServicio WHERE IdEstacion = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEstadoDoc]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar/Eliminar EstadoDoc.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsEstadoDoc]
	@EstadoDoc dataTypeEstadoDoc READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @EstadoDoc))
			begin
			 UPDATE EstadoDoc
			 SET 
			 IdEstado = t2.IdEstado,Estado = t2.Estado,NColor = t2.NColor,CodDcmto = t2.CodDcmto,Inactivo = t2.Inactivo
			 FROM EstadoDoc T1
			 JOIN @EstadoDoc T2 ON T1.IdEstado = T2.IdEstado
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @EstadoDoc))
			BEGIN
			 INSERT INTO EstadoDoc(
			 IdEstado,Estado,NColor,CodDcmto,Inactivo
			 )
			 SELECT 
			 IdEstado,Estado,NColor,CodDcmto,Inactivo
			 FROM @EstadoDoc
			 WHERE IdEstado NOT IN(SELECT IdEstado FROM EstadoDoc)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdEstado FROM @EstadoDoc		
			 DELETE FROM EstadoDoc WHERE IdEstado = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEstadoTer]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar/Eliminar EstadoTer.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsEstadoTer]
	@EstadoTer dataTypeEstadoTer READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @EstadoTer))
			begin
			 UPDATE EstadoTer
			 SET 
			 IdEstado = t2.IdEstado,Estado = t2.Estado,NColor = t2.NColor,Inactivo = t2.Inactivo
			 FROM EstadoTer T1
			 JOIN @EstadoTer T2 ON T1.IdEstado = T2.IdEstado
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @EstadoTer))
			BEGIN
			 INSERT INTO EstadoTer(
			 IdEstado,Estado,NColor,Inactivo
			 )
			 SELECT 
			 IdEstado,Estado,NColor,Inactivo
			 FROM @EstadoTer
			 WHERE IdEstado NOT IN(SELECT IdEstado FROM EstadoTer)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdEstado FROM @EstadoTer
			 DELETE FROM EstadoTer WHERE IdEstado = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsEstadoVeh]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar/Eliminar EstadoVeh.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsEstadoVeh]
	@EstadoVeh dataTypeEstadoVeh READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @EstadoVeh))
			begin
			 UPDATE EstadoVeh
			 SET 
			 IdEstado = t2.IdEstado, Estado = t2.Estado,
			 NColor = t2.NColor, OutDemand = t2.OutDemand,
			 Inactivo = t2.Inactivo
			 FROM EstadoVeh T1
			 JOIN @EstadoVeh T2 ON T1.IdEstado = T2.IdEstado
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @EstadoVeh))
			BEGIN
			 INSERT INTO EstadoVeh(
			 IdEstado,Estado,NColor,OutDemand,Inactivo
			 )
			 SELECT 
			 IdEstado,Estado,NColor,OutDemand,Inactivo
			 FROM @EstadoVeh
			 WHERE IdEstado NOT IN(SELECT IdEstado FROM EstadoVeh)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdEstado FROM @EstadoVeh
			 DELETE FROM EstadoVeh WHERE IdEstado = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsExpLicencias]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 27/04/2016
-- Description:	Insertar/Actualizar/Eliminar ExpLicencias.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsExpLicencias]
	@ExpLicencias dataTypeExpLicencias READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE ExpLicencias
			 SET 
			 IdLugar = t2.IdLugar,LugarLic = t2.LugarLic,CodDpto = t2.CodDpto,Dpto = t2.Dpto,Inactivo = t2.Inactivo
		     FROM ExpLicencias t1
			 JOIN @ExpLicencias t2 ON t1.IdLugar = t2.IdLugar
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO ExpLicencias(
			 IdLugar,LugarLic,CodDpto,Dpto,Inactivo
			 )
			 SELECT 
			 IdLugar,LugarLic,CodDpto,Dpto,Inactivo
			 FROM @ExpLicencias
			 WHERE IdLugar NOT IN(SELECT IdLugar FROM ExpLicencias)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(8)
			 SELECT @id = IdLugar FROM @ExpLicencias
			 DELETE FROM ExpLicencias WHERE IdLugar = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsGruposCli]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/08/2016
-- Description:	Insertar/Actualizar GruposCli.
-- =============================================
create PROCEDURE [dbo].[paWcfSeInsGruposCli]
	@GruposCli dataTypeGruposCli READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE GruposCli
			 SET 
			 IdGrupo = t2.IdGrupo,GrupoClie = t2.GrupoClie,ModApp = t2.ModApp,Inactivo = t2.Inactivo
		     FROM GruposCli t1
			 JOIN @GruposCli t2 ON t1.IdGrupo = t2.IdGrupo
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO GruposCli(
			 IdGrupo,GrupoClie,ModApp,Inactivo
			 )
			 SELECT 
			 IdGrupo,GrupoClie,ModApp,Inactivo
			 FROM @GruposCli
			 WHERE IdGrupo NOT IN(SELECT IdGrupo FROM GruposCli)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdGrupo FROM @GruposCli
			 DELETE FROM GruposCli WHERE IdGrupo = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsGruposPro]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar GruposPro.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsGruposPro]
	@GruposPro dataTypeGruposPro READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE GruposPro
			 SET
			 IdGrupo = t2.IdGrupo, GrupoProp = t2.GrupoProp, Inactivo = t2.Inactivo
		     FROM GruposPro t1
			 JOIN @GruposPro t2 ON t1.IdGrupo = t2.IdGrupo
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO GruposPro(
			 IdGrupo,GrupoProp,Inactivo
			 )
			 SELECT 
			 IdGrupo,GrupoProp,Inactivo
			 FROM @GruposPro
			 WHERE IdGrupo NOT IN(SELECT IdGrupo FROM GruposPro)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdGrupo FROM @GruposPro
			 DELETE FROM GruposPro WHERE IdGrupo = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsGruposRot]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar GruposRot.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsGruposRot]
	@GruposRot dataTypeGruposRot READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE GruposRot
			 SET
			 IdGrupo = t2.IdGrupo,GrupoRot = t2.GrupoRot,Inactivo = t2.Inactivo
		     FROM GruposRot t1
			 JOIN @GruposRot t2 ON t1.IdGrupo = t2.IdGrupo
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO GruposRot(
			 IdGrupo,GrupoRot,Inactivo
			 )
			 SELECT 
			 IdGrupo,GrupoRot,Inactivo
			 FROM @GruposRot
			 WHERE IdGrupo NOT IN(SELECT IdGrupo FROM GruposRot)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdGrupo FROM @GruposRot
			 DELETE FROM GruposRot WHERE IdGrupo = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsListaPasajeros]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 30/09/2016
-- Description:	Insertar Lista de pasajeros.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsListaPasajeros]
	@Trn_TraEspPasajeros dataTypeTrn_TraEspPasajeros READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPasajeros
	@Trn_TraEspListaPasajeros dataTypeTrn_TraEspListaPasajeros READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspListaPasajeros
	@Trn_TraEspContratoVehLista dataTypeTrn_TraEspContratoVehLista READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspContratoVehLista
	@operacion varchar(1)

AS
DECLARE @Numero INT --Esta variable guarda el número de consecutivo de la lista

	BEGIN TRAN
		BEGIN TRY

			IF(@operacion = 'i')
			BEGIN
				SELECT @Numero = ISNULL(MAX(IdLista),0) + 1  FROM Trn_TraEspLista
			END

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			   if(EXISTS(SELECT * FROM @Trn_TraEspPasajeros))
			   begin
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspPasajeros(
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				)
				SELECT 
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				FROM @Trn_TraEspPasajeros
				WHERE (TipId + Documento) NOT IN(SELECT (TipId + Documento) FROM Trn_TraEspPasajeros)

			   --UPDATE Trn_TraEspPasajeros
			   --SET 
			   --TipId = t2.TipId,Documento = t2.Documento,Apellidos = t2.Apellidos,
			   --Nombres = t2.Nombres,Cargo = t2.Cargo,EsMonitor = t2.EsMonitor,
			   --Telefono = t2.Telefono,Observacion = t2.Observacion
			   --FROM Trn_TraEspPasajeros t1
			   --JOIN @Trn_TraEspPasajeros t2 ON t1.TipId = t2.TipId and t1.Documento = t2.Documento			   
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspListaPasajeros))
			   begin
			   UPDATE Trn_TraEspListaPasajeros
			   SET 
			   IdLista = t2.IdLista,Documento = t2.Documento
		       FROM Trn_TraEspListaPasajeros t1
			   JOIN @Trn_TraEspListaPasajeros t2 ON t1.IdLista = t2.IdLista and t1.Documento = t2.Documento
			   --Insertar si no existe
			    INSERT INTO Trn_TraEspListaPasajeros(
				IdLista,Documento) 
				SELECT 
				IdLista,Documento
				FROM @Trn_TraEspListaPasajeros
				WHERE (CONVERT(VARCHAR(16),IdLista) + Documento) NOT IN(SELECT (CONVERT(VARCHAR(16),IdLista) + Documento) FROM Trn_TraEspListaPasajeros)
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspContratoVehLista))
			   begin
			   UPDATE Trn_TraEspContratoVehLista
			   SET 
			   IdLista = t2.IdLista,TipDoc = t2.TipDoc,Contrato = t2.Contrato,
			   IdCia = t2.IdCia,Item = t2.Item,IdVehiculo = t2.IdVehiculo,Fecha = t2.Fecha,IdEstado = t2.IdEstado,
			   FecUpdate = t2.FecUpdate,IdUsuario = t2.IdUsuario
		       FROM Trn_TraEspContratoVehLista t1
			   JOIN @Trn_TraEspContratoVehLista t2 ON t1.IdLista = t2.IdLista and t1.TipDoc = t2.TipDoc and t1.Contrato = t2.Contrato and t1.IdCia = t2.IdCia and t1.IdVehiculo = t2.IdVehiculo
			   end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN

				IF(EXISTS(SELECT * FROM @Trn_TraEspPasajeros))
				begin
				INSERT INTO Trn_TraEspPasajeros(
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				)
				SELECT 
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				FROM @Trn_TraEspPasajeros
				WHERE (TipId + Documento) NOT IN(SELECT (TipId + Documento) FROM Trn_TraEspPasajeros)
				end

				INSERT INTO Trn_TraEspLista(IdLista) values (@Numero)

				IF(EXISTS(SELECT * FROM @Trn_TraEspListaPasajeros))
				begin
				INSERT INTO Trn_TraEspListaPasajeros(
				IdLista,Documento
				) 
				SELECT 
				@Numero,Documento
				FROM @Trn_TraEspListaPasajeros
				WHERE (CONVERT(VARCHAR(16),IdLista) + Documento) NOT IN(SELECT (CONVERT(VARCHAR(16),IdLista) + Documento) FROM Trn_TraEspListaPasajeros)
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspContratoVehLista))
				begin
				INSERT INTO Trn_TraEspContratoVehLista(
				IdLista,TipDoc,Contrato,IdCia,Item,IdVehiculo,Fecha,IdEstado,FecUpdate,IdUsuario
				) 
				SELECT 
				@Numero,TipDoc,Contrato,IdCia,Item,IdVehiculo,Fecha,IdEstado,FecUpdate,IdUsuario
				FROM @Trn_TraEspContratoVehLista
				end						

			 END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 declare @Pedido int
			 select @Pedido = IdLista from @Trn_TraEspListaPasajeros
				 DELETE FROM Trn_TraEspListaPasajeros WHERE IdLista = @Pedido 

			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
			  UPDATE Trn_TraEspContratoVehLista 
			  SET IdEstado = '9999' 
			  WHERE 
			  IdLista = (select IdLista from @Trn_TraEspContratoVehLista) and TipDoc = (select TipDoc from @Trn_TraEspContratoVehLista) and IdCia = (select IdCIa from @Trn_TraEspContratoVehLista) and Contrato = (select Contrato from @Trn_TraEspContratoVehLista) and Item = (select Item from @Trn_TraEspContratoVehLista)
			END

			SELECT '1'

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsListaPasaRes]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyy): 28/01/2019
-- Description:	Insertar Lista de pasajeros de reservas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsListaPasaRes]
	@Trn_TraEspPasajeros dataTypeTrn_TraEspPasajeros READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPasajeros
	@Trn_TraEspListaPasajeros dataTypeTrn_TraEspListaPasajeros READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspListaPasajeros
	@Trn_TraEspReservaVehLista dataTypeTrn_TraEspReservaVehLista READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspContratoVehLista
	@operacion varchar(1)

AS
DECLARE @Numero INT --Esta variable guarda el número de consecutivo de la lista

	BEGIN TRAN
		BEGIN TRY

			IF(@operacion = 'i')
			BEGIN
				SELECT @Numero = ISNULL(MAX(IdLista),0) + 1  FROM Trn_TraEspListaRes
			END

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			   if(EXISTS(SELECT * FROM @Trn_TraEspPasajeros))
			   begin
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspPasajeros(
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				)
				SELECT 
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				FROM @Trn_TraEspPasajeros
				WHERE (TipId + Documento) NOT IN(SELECT (TipId + Documento) FROM Trn_TraEspPasajeros)

			   --UPDATE Trn_TraEspPasajeros
			   --SET 
			   --TipId = t2.TipId,Documento = t2.Documento,Apellidos = t2.Apellidos,
			   --Nombres = t2.Nombres,Cargo = t2.Cargo,EsMonitor = t2.EsMonitor,
			   --Telefono = t2.Telefono,Observacion = t2.Observacion
			   --FROM Trn_TraEspPasajeros t1
			   --JOIN @Trn_TraEspPasajeros t2 ON t1.TipId = t2.TipId and t1.Documento = t2.Documento			   
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspListaPasajeros))
			   begin
			   UPDATE Trn_TraEspListaPasaRes
			   SET 
			   IdLista = t2.IdLista,Documento = t2.Documento
		       FROM Trn_TraEspListaPasaRes t1
			   JOIN @Trn_TraEspListaPasajeros t2 ON t1.IdLista = t2.IdLista and t1.Documento = t2.Documento
			   --Insertar si no existe
			    INSERT INTO Trn_TraEspListaPasaRes(
				IdLista,Documento) 
				SELECT 
				IdLista,Documento
				FROM @Trn_TraEspListaPasajeros
				WHERE (CONVERT(VARCHAR(16),IdLista) + Documento) NOT IN(SELECT (CONVERT(VARCHAR(16),IdLista) + Documento) FROM Trn_TraEspListaPasaRes)
				--Eliminar los pasajeros que no existen en el tipo de dato
			   delete from Trn_TraEspListaPasaRes
			   WHERE Documento NOT IN(SELECT Documento FROM @Trn_TraEspListaPasajeros) and IdLista = (SELECT TOP 1 IdLista FROM @Trn_TraEspListaPasajeros)
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspReservaVehLista))
			   begin
			   UPDATE Trn_TraEspReservaVehLista
			   SET 
			   IdLista = t2.IdLista,TipDoc = t2.TipDoc,Reserva = t2.Reserva,
			   IdCia = t2.IdCia,Item = t2.Item,IdVehiculo = t2.IdVehiculo,Fecha = t2.Fecha,IdEstado = t2.IdEstado,
			   FecUpdate = t2.FecUpdate,IdUsuario = t2.IdUsuario, IdListaCOE = t2.IdListaCOE
		       FROM Trn_TraEspReservaVehLista t1
			   JOIN @Trn_TraEspReservaVehLista t2 ON t1.IdLista = t2.IdLista and t1.TipDoc = t2.TipDoc and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCia and t1.IdVehiculo = t2.IdVehiculo
			   end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN

				IF(EXISTS(SELECT * FROM @Trn_TraEspPasajeros))
				begin
				INSERT INTO Trn_TraEspPasajeros(
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				)
				SELECT 
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				FROM @Trn_TraEspPasajeros
				WHERE (TipId + Documento) NOT IN(SELECT (TipId + Documento) FROM Trn_TraEspPasajeros)
				end

				INSERT INTO Trn_TraEspListaRes(IdLista) values (@Numero)

				IF(EXISTS(SELECT * FROM @Trn_TraEspListaPasajeros))
				begin
				INSERT INTO Trn_TraEspListaPasaRes(
				IdLista,Documento
				) 
				SELECT 
				@Numero,Documento
				FROM @Trn_TraEspListaPasajeros
				WHERE (CONVERT(VARCHAR(16),IdLista) + Documento) NOT IN(SELECT (CONVERT(VARCHAR(16),IdLista) + Documento) FROM Trn_TraEspListaPasaRes)
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspReservaVehLista))
				begin
				INSERT INTO Trn_TraEspReservaVehLista(
				IdLista,TipDoc,Reserva,IdCia,Item,IdVehiculo,Fecha,IdEstado,FecUpdate,IdUsuario,IdListaCOE
				) 
				SELECT 
				@Numero,TipDoc,Reserva,IdCia,Item,IdVehiculo,Fecha,IdEstado,FecUpdate,IdUsuario,IdlistaCOE
				FROM @Trn_TraEspReservaVehLista
				end						

			 END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 declare @Pedido int
			 select @Pedido = IdLista from @Trn_TraEspListaPasajeros
				 DELETE FROM Trn_TraEspListaPasaRes WHERE IdLista = @Pedido 

			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
			  UPDATE Trn_TraEspReservaVehLista 
			  SET IdEstado = '9999' 
			  WHERE 
			  IdLista = (select IdLista from @Trn_TraEspReservaVehLista) and TipDoc = (select TipDoc from @Trn_TraEspReservaVehLista) and IdCia = (select IdCIa from @Trn_TraEspReservaVehLista) and Reserva = (select Reserva from @Trn_TraEspReservaVehLista) and Item = (select Item from @Trn_TraEspReservaVehLista)
			END

			SELECT '1'

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsListaPasaResProceso]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa Castañeda
-- Create date(dd/MM/yyyy): 06/01/2020
-- Description:	Insertar Lista de Reservas de una lista ya existente.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsListaPasaResProceso]
	@TrnListaPasaResProceso dataTypeListaPasaResProceso READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY
		--------------------------Varibales del procedimiento---------------------------------------------		 
		DECLARE @Numero INT --Esta variable guarda el número de consecutivo de la lista
		DECLARE @NumeroListaCopy INT  --Esta variable guarda el número de consecutivo de la lista a copiar
		--DECLARE @TipRes VARCHAR(3)  --Tipo de doc de la Reserva destino de réplica
		--DECLARE @Reserva INT --Número de la Reserva destino de réplica
		--DECLARE @ItemRes INT --Ítem de la Reserva destino de réplica
		--DECLARE @IdCiaRes CHAR(2)  --Cía de la Reserva destino de réplica
		---------------------------------------------------------------------------------------------------
		SELECT @Numero = ISNULL(MAX(IdLista),0) + 1  FROM Trn_TraEspListaRes
		SELECT @NumeroListaCopy = IdLista FROM @TrnListaPasaResProceso
		--Insertar el nuevo consecutivo para la lista
		INSERT INTO Trn_TraEspListaRes VALUES(@Numero)
		--Insertar los pasajeros para la nueva lista en base a una lista anterior
		INSERT INTO Trn_TraEspListaPasaRes(
			IdLista,Documento) 
			SELECT 
			@Numero,pa.Documento
			FROM Trn_TraEspListaPasaRes AS pa
			WHERE IdLista = @NumeroListaCopy
		INSERT INTO Trn_TraEspReservaVehLista(IdLista, TipDoc, Reserva, IdCia, Item, IdVehiculo, Fecha, IdEstado, FecUpdate, IdUsuario, IdListaCOE)
		SELECT @Numero, TipRes, Reserva, IdCiaRes, ItemRes, IdVehiculo, Fecha, '0001', NULL, IdUsuario, 0
		FROM @TrnListaPasaResProceso
		--Respuesta Devuelta
		SELECT @Numero

		COMMIT TRAN
	END TRY
BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsLocalidades]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar Localidades.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsLocalidades]
	@Localidades dataTypeLocalidades READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Localidades
			 SET 
			 IdLocal = t2.IdLocal,Localidad = t2.Localidad,IdDep = t2.IdDep,TipLocal = t2.TipLocal,Dist_Kmt = t2.Dist_Kmt,Time_hh = t2.Time_hh,
			 DistSede = t2.DistSede,TimeSede = t2.TimeSede,CelRow = t2.CelRow,CelCol = t2.CelCol,CodAlias = t2.CodAlias,Inactivo = t2.Inactivo
		     FROM Localidades t1
			 JOIN @Localidades t2 ON t1.IdLocal = t2.IdLocal
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Localidades(
			 IdLocal,Localidad,IdDep,TipLocal,Dist_Kmt,Time_hh,DistSede,TimeSede,CelRow,CelCol,CodAlias,Inactivo
			 )
			 SELECT 
			 IdLocal,Localidad,IdDep,TipLocal,Dist_Kmt,Time_hh,DistSede,TimeSede,CelRow,CelCol,CodAlias,Inactivo
			 FROM @Localidades
			 WHERE IdLocal NOT IN(SELECT IdLocal FROM Localidades)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id VARCHAR (8)
			 SELECT @id = IdLocal FROM @Localidades
			 DELETE FROM Localidades WHERE IdLocal = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMarcas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar Marcas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMarcas]
	@Marcas dataTypeMarcas READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Marcas
			 SET 
			 IdMarca = t2.IdMarca,Marca = t2.Marca,TipoMarca = t2.TipoMarca,CodigoMT = t2.CodigoMT,Inactivo = t2.Inactivo
		     FROM Marcas t1
			 JOIN @Marcas t2 ON t1.IdMarca = t2.IdMarca
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Marcas(
			 IdMarca,Marca,TipoMarca,CodigoMT,Inactivo
			 )
			 SELECT 
			 IdMarca,Marca,TipoMarca,CodigoMT,Inactivo
			 FROM @Marcas
			 WHERE IdMarca NOT IN(SELECT IdMarca FROM Marcas)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdMarca FROM @Marcas
			 DELETE FROM Marcas WHERE IdMarca = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMarcasLin]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar MarcasLin.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMarcasLin]
	@MarcasLin dataTypeMarcasLin READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE MarcasLin
			 SET 
			 IdLinea = t2.IdLinea,LineaVeh = t2.LineaVeh,IdMarca = t2.IdMarca,CodMT = t2.CodMT,Inactivo = t2.Inactivo
		     FROM MarcasLin t1
			 JOIN @MarcasLin t2 ON t1.IdLinea = t2.IdLinea 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO MarcasLin(
			 IdLinea,LineaVeh,IdMarca,CodMT,Inactivo
			 )
			 SELECT 
			 IdLinea,LineaVeh,IdMarca,CodMT,Inactivo
			 FROM @MarcasLin
			 WHERE (IdLinea NOT IN(SELECT IdLinea FROM MarcasLin)) 
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 DECLARE @idmarca varchar(4)
			 SELECT @id = IdLinea, @idmarca = IdMarca FROM @MarcasLin
			 DELETE FROM MarcasLin WHERE IdMarca = @idmarca and IdLinea = @id 
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvFuec]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Yaqueline Lizarazo Diaz, John Jairo Roa
-- Create date(dd/MM/yyy): 07/05/2019
-- Description:	Insertar CRUD de Masivo FUEC.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMsvFuec]
	@Trn_TraEspFuec dataTypeTrn_TraEspFuec READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuec
	@Trn_TraEspFuecDetalle dataTypeTrn_TraEspFuecDetalle READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuecDetalle
	@Trn_TraEspFuecAnexo dataTypeTrn_TraEspFuecAnexo READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuecAnexo
	@Trn_TraEspFuecCndtores dataTypeTrn_TraEspFuecCndtores READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuecCndtores
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Fuec
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Fuec
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Fuec
--declare @item int
	BEGIN TRAN
		BEGIN TRY
		
			CREATE TABLE #LogFuecDetalle(
			TipDocFuec varchar(3) NOT NULL,
			Fuec int NOT NULL,
			IdCiaFuec char(2) NOT NULL,
			IdVehiculo varchar(10) NOT NULL,
			TipDocRes varchar(3) NOT NULL,
			Reservas int NOT NULL,
			IdCiaRes char(2) NOT NULL,
			ItemRes int NOT NULL
			)

			--declare @NumProc int = 1
			declare @TipDocu varchar(3)
			declare @Fuec INT
			declare @CiaFuec varchar(2)
			declare @IdVehiculo varchar(10)
			declare @TipDocRes varchar(3)
			declare @Reservas int
			declare @IdCiaRes char(2)
			declare @ItemRes int
			--esta variable para ir asignando el consecutivo fuec
			declare @Resolucion varchar(30)
			declare @ConsecutivoFUEC int = 0
			declare @_TipDocCOE varchar(3) ='COE'
			declare @_COE INT = 0
			declare @_CiaCOE char(2) ='00'
			declare @TipDocCOE varchar(3)
			declare @COE INT
			declare @CiaCOE char(2)
			declare @TipDocPgr varchar(3)
			declare @NumPgr INT
			declare @IdCiaPgr char(2)
			declare @ItemPgr INT
			--

			DECLARE fueccursor CURSOR
			FOR SELECT TipDoc,Fuec,IdCia,IdVehiculo,TipDocCnt,Contrato,CiaCnt,TipDocPgr,NumPgr,IdCiaPgr,ItemPgr FROM @Trn_TraEspFuec order by TipDocCnt, Contrato, CiaCnt
			OPEN fueccursor
			FETCH NEXT FROM fueccursor INTO @TipDocu,@Fuec,@CiaFuec,@IdVehiculo,@TipDocCOE,@COE,@CiaCOE,@TipDocPgr,@NumPgr,@IdCiaPgr,@ItemPgr
			WHILE @@FETCH_STATUS = 0
			BEGIN

				--Seleccionar Variables
				IF(@operacion = 'i')
				BEGIN
					SELECT TOP 1 @TipDoc = @TipDocu, @IdCia = @CiaFuec
					SELECT @Documento = (Numero + 1 ), @Resolucion = Resolucion FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia

					IF(@Documento <> '')
						UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
					ELSE
					BEGIN
						SELECT @Documento = 1
						INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
					END
				END

				--INSERT NO-EXISTE RECORDS
				IF(@operacion = 'i')
				BEGIN
					--Para asignar el númro de consecutivo
					if((@_TipDocCOE =  @TipDocCOE) AND (@_COE = @COE) AND (@_CiaCOE = @CiaCOE))
					begin
						SET @ConsecutivoFUEC = @ConsecutivoFUEC + 1;
					end
					ELSE
					BEGIN
						set @ConsecutivoFUEC = 0
						SELECT Top 1  @ConsecutivoFUEC = (ISNULL(MAX(Consecutivo), 0) + 1), @_TipDocCOE = TipDocCnt, @_COE = Contrato,  @_CiaCOE = CiaCnt  FROM Trn_TraEspFuec where ((TipDocCnt + CONVERT(varchar, Contrato) + CiaCnt)IN(@TipDocCOE + CONVERT(varchar, @COE) + @CiaCOE)) group by Consecutivo, TipDocCnt, Contrato, CiaCnt order by Consecutivo desc
						IF(@ConsecutivoFUEC = 0)
						BEGIN
							SET @ConsecutivoFUEC = 1
						END
						IF(@ConsecutivoFUEC = 1)
						BEGIN
							SET  @_TipDocCOE = @TipDocCOE
							SET @_COE = @COE
							SET @_CiaCOE = @CiaCOE
						END
					END

					IF(EXISTS(SELECT * FROM @Trn_TraEspFuec))
					begin
					--this.txtvNumResolucion.Text + Convert.ToDateTime(this.msktxtFecFUECTES.Text).Year.ToString() + this.txtvNumCOE.Text.PadLeft(4, '0') + Fuec.Fuec.Consecutivo.ToString().PadLeft(4, '0');
					INSERT INTO Trn_TraEspFuec(
					TipDoc, Fuec, IdCia, Numero, Fecha, FechaInicio, FechaFin, CdCarga, IdVehiculo, IdConductor, IdConductor2, IdConductor3, IdPoseedor, 
					IdRuta, CdTipRuta, IdOrigen, IdDestino, Modalidad, CantPasajeros, CodTarRet,CodTarIca, VrPresupuesto, VrCobro, VrPagos, VrCargos, VrDctos,
					VrIva, VrRetencion, VrReteIca, Cantidad, Peso, TipDocPgr, NumPgr, IdCiaPgr, ItemPgr, TipDocCnt, Contrato, CiaCnt, OrigenAdd, Anulado, FecDev, 
					IdEstado,TimeSys, FecUpdate, IdCiaCrea, IdUsuario, Consecutivo, Itinerario, FuecParcial, ComenParcial
					)
					SELECT 
					@TipDoc,@Documento,@IdCia,SUBSTRING(convert(varchar, (@Resolucion + convert(varchar, DATEPART(YEAR, Fecha))  + (right(('0000' + convert(varchar, Contrato)), 4)) + (right(('0000' + convert(varchar, @ConsecutivoFUEC)), 4)))), 1, 21), Fecha, FechaInicio, FechaFin, CdCarga, IdVehiculo, IdConductor, IdConductor2, IdConductor3, IdPoseedor, 
					IdRuta, CdTipRuta, IdOrigen, IdDestino, Modalidad, CantPasajeros, CodTarRet,CodTarIca, VrPresupuesto, VrCobro, VrPagos, VrCargos, VrDctos,
					VrIva, VrRetencion, VrReteIca, Cantidad, Peso, TipDocPgr, NumPgr, IdCiaPgr, ItemPgr, TipDocCnt, Contrato, CiaCnt, OrigenAdd, Anulado, FecDev, 
					IdEstado,TimeSys, FecUpdate, IdCiaCrea, IdUsuario, @ConsecutivoFUEC, Itinerario, FuecParcial, ComenParcial
					FROM @Trn_TraEspFuec f WHERE f.TipDoc= @TipDocu and f.Fuec = @Fuec and f.IdCia = @CiaFuec
					end
			
					IF(EXISTS(SELECT * FROM @Trn_TraEspFuecDetalle))
					begin
					select @TipDocRes = TipRes, @Reservas = Reserva, @IdCiaRes = IdCiaRes, @ItemRes = ItemRes FROM @Trn_TraEspFuecDetalle df WHERE df.TipDoc = @TipDocu and df.Fuec = @Fuec and df.IdCia = @CiaFuec
					INSERT INTO Trn_TraEspFuecDetalle(
					TipDoc, Fuec, IdCia, Item, TipRes, Reserva, IdCiaRes, ItemRes, NumPasajeros, PesoNeto, VrCobro, VrPagos, Referencia1, Referencia2, Referencia3,
					CdTipServicio, EsRutaCliente, Kilometros, DirOrigen, FecOrigen, DirDestino, FecDestino
					) 
					SELECT 
					@TipDoc,@Documento,@IdCia,Item, TipRes, Reserva, IdCiaRes, ItemRes, NumPasajeros, PesoNeto, VrCobro, VrPagos, Referencia1, Referencia2, Referencia3,
					CdTipServicio, EsRutaCliente, Kilometros, DirOrigen, FecOrigen, DirDestino, FecDestino
					FROM @Trn_TraEspFuecDetalle df WHERE df.TipDoc = @TipDocu and df.Fuec = @Fuec and df.IdCia = @CiaFuec
					end
					
					IF(EXISTS(SELECT * FROM @Trn_TraEspFuecAnexo))
					begin
					INSERT INTO Trn_TraEspFuecAnexo(
					TipDoc, Fuec, IdCia, TipContrato, IdContrato, ObjContrato, DescripCarga, Observacion, RespViaje, VehConvenio, EmpresaVehCon
					) 
					SELECT 
					@TipDoc,@Documento,@IdCia,TipContrato, IdContrato, ObjContrato, DescripCarga, Observacion, RespViaje, VehConvenio, EmpresaVehCon
					FROM @Trn_TraEspFuecAnexo df WHERE df.TipDoc = @TipDocu and df.Fuec = @Fuec and df.IdCia = @CiaFuec
					end

					IF(EXISTS(SELECT * FROM @Trn_TraEspFuecCndtores))
					begin
					INSERT INTO Trn_TraEspFuecCndtores(
					TipDoc, Fuec, IdCia, Item, IdConductor) 
					SELECT 
					@TipDoc,@Documento,@IdCia,Item, IdConductor
					FROM @Trn_TraEspFuecCndtores df WHERE df.TipDoc = @TipDocu and df.Fuec = @Fuec and df.IdCia = @CiaFuec
					end

					--ACTUALIZAR PORGRAMACIONES 
					UPDATE Trn_TraEspProgramaDet
					SET TipDocFuec = @TipDoc,NumFuec = @Documento, IdCiaFuec = @CiaFuec
					FROM Trn_TraEspProgramaDet
					--@Trn_TraEspFuecDetalle t3
					WHERE TipDoc = 'PGR' and Programa = @NumPgr and IdCia = @IdCiaPgr and Item = @ItemPgr;

					INSERT INTO #LogFuecDetalle(TipDocFuec,Fuec,IdCiaFuec,IdVehiculo,TipDocRes,Reservas,IdCiaRes,ItemRes)
					select @TipDocu,@Fuec,@CiaFuec,@IdVehiculo,@TipDocRes,@Reservas,@IdCiaRes,@ItemRes
				END
			FETCH NEXT FROM fueccursor INTO @TipDocu,@Fuec,@CiaFuec,@IdVehiculo,@TipDocCOE,@COE,@CiaCOE,@TipDocPgr,@NumPgr,@IdCiaPgr,@ItemPgr
			END
			CLOSE fueccursor
			DEALLOCATE fueccursor

			SELECT * FROM #LogFuecDetalle
			--SELECT * FROM #LogProgDetalle
			--select @NumProc

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvLiquidacion]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 09/11/2017
-- Description:	Insertar Masivo de Liquidación de Ordenes de Pago
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMsvLiquidacion]
	@Trn_TraEspLiquida dataTypeTrn_TraEspLiquida READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquida
	@Trn_TraEspLiquidaDed dataTypeTrn_TraEspLiquidaDed READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquidaDed
	@Trn_TraEspLiquidaOdp dataTypeTrn_TraEspLiquidaOdp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquidaOdp
	@Trn_TraEspLiquidaOtr dataTypeTrn_TraEspLiquidaOtr READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquidaOtr
	@Trn_EgrFactura dataTypeTrn_EgrFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_EgrFactura

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeNiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY
		
			CREATE TABLE #LogLiquida(
			Numero int NOT NULL,
			Fecha smalldatetime NULL,
			EstadoProc int NULL,
			Observacion varchar(1000) NULL,
			TimeSys smalldatetime NULL,
			IdUsuario varchar(11) NULL,
			Nombre varchar(50) NULL
			)

			CREATE TABLE #LogLiquidaDet(
			Numero int NULL,
			Item int NULL,
			TipDoc varchar(3) NULL,
			Liquidacion int NULL,
			IdCia char(2) NULL,
			FechaLiq smalldatetime NULL,
			FechaDed smalldatetime NULL,
			FechaIniOdp smalldatetime NULL,
			FechaFinOdp smalldatetime NULL,
			IdConcepto varchar(4) NULL,
			CXP bit NULL, 
			TipoCom varchar(3) NULL,
			Comprobante int NULL,
			IdVehiculo varchar(10) NULL,
			IdConductor varchar(16) NULL,
			IdPoseedor varchar(16) NULL,
			Causaciones varchar(MAX) NULL,
			IdCiaCaus varchar(MAX) NULL,
			ItemCaus varchar(max) null,
			Odps varchar(MAX) NULL,
			IdCiaOdps  varchar(MAX) NULL,
			OtrPagos  varchar(MAX) NULL,
			IdCiaOtrpagos varchar(MAX) NULL,
			ItemOtros varchar(max) null,
			VrTotalLiq MONEY NULL,
			Comentarios varchar(1000) NULL
			)

			declare @Causaciones varchar(max) 
			declare @IdCiaCaus varchar(max)
			declare @ItemCaus varchar(max)
			declare @Odps varchar(max)  
			declare @IdCiaOdps varchar(max)
			declare @OtrPagos varchar(max) 
			declare @IdCiaOtrpagos varchar(max)
			declare @ItemOtros varchar(max) 
			declare @TipDocu varchar(3)
			declare @Liq int
			declare @IdCia CHAR(2)	
			declare @NumProc int = 1
			declare @ItemProc int = 1

			DECLARE liqcursor CURSOR
			FOR SELECT TipDoc,Liquidacion,IdCia FROM @Trn_TraEspLiquida
			OPEN liqcursor
			FETCH NEXT FROM liqcursor INTO @TipDocu,@Liq,@IdCia
			WHILE @@FETCH_STATUS = 0
			BEGIN
			
				IF(@operacion = 'i')
				begin
				SELECT TOP 1 @TipDoc = @TipDocu, @Cia = @IdCia, @IdCiaComp = @IdCia, @IdCiaCompNiif = @IdCia, @IdCiaCompFis = @IdCia
				SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

				IF(@Numero > 0)
					UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
				ELSE
				BEGIN
					SELECT @Numero = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes where TipDoc = @TipDocu and Documento = @Liq and  IdCiaDoc = @IdCia
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF' and TipDoc = @TipDocu and Documento = @Liq and  IdCiaDoc = @IdCia
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif

					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL' and TipDoc = @TipDocu and Documento = @Liq and  IdCiaDoc = @IdCia
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis

					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				--DIEGO ROMERO DICE QUE SI NO EXISTE EL COMPROBANTE CON ELMISMO NOMBRE DE DOC DEVOLUCIÓN INSERTA UN COMPROBANTE CON EL  TIPCOM SEA IIGUAL AL TIPDEV, en la tabla TiposCom(tipos de comprobantes)
				--es INACTIVO = 1, PARA PODER INSERTAR EN EGRFACTURA ESTE TIPCOM
				IF(NOT EXISTS(SELECT IdCom FROM TiposCom where IdCom = @TipDoc))
				BEGIN
				  INSERT INTO TiposCom VALUES (@TipDoc,'LIQUIDACION DE ORDENES ESPECIAL',0,0,0,1,CURRENT_TIMESTAMP,NULL,NULL,null)
				END
				--

				end

				IF(@operacion = 'i')
				begin
					IF(EXISTS(SELECT * FROM @Trn_TraEspLiquida))
					BEGIN
					INSERT INTO Trn_TraEspLiquida(
					TipDoc,Liquidacion,IdCia,Fecha,IdConcepto,IdVehiculo,IdPoseedor,IdConductor,VrTotal,CxPagar,TipCom,Comprobante,IdCiaCom,
					Anulado,NumDev,FecDev,Observacion,IdEstado,FecIniCau,FecFinCau,FecIniOdp,FecFinOdp,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,
					IdUsuario,ModLiquida
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Fecha,IdConcepto,IdVehiculo,IdPoseedor,IdConductor,VrTotal,CxPagar,@TipComp,@Comprobante,@IdCiaComp,
					Anulado,NumDev,FecDev,Observacion,IdEstado,FecIniCau,FecFinCau,FecIniOdp,FecFinOdp,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,
					IdUsuario,ModLiquida
					FROM @Trn_TraEspLiquida where TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_TraEspLiquidaDed))
					BEGIN
					INSERT INTO Trn_TraEspLiquidaDed(
					TipDoc,Liquidacion,IdCia,Item,TipCau,Causacion,IdCiaCau,ItemCau,FechaCau,IdConcepto,Descripcion,VrAbono,NitPoseedor,pVehiculo,
					EsVence,TipOdp,OrdenPago,IdCiaOdp,TipRes,Reserva,IdCiaRes,VrSaldoOrden,CdCuenta,CdCuePagar,NumFactura,CdCCosto,CdSubCos,TipoFac
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Item,TipCau,Causacion,IdCiaCau,ItemCau,FechaCau,IdConcepto,Descripcion,VrAbono,NitPoseedor,pVehiculo,
					EsVence,TipOdp,OrdenPago,IdCiaOdp,TipRes,Reserva,IdCiaRes,VrSaldoOrden,CdCuenta,CdCuePagar,NumFactura,CdCCosto,CdSubCos,TipoFac
					FROM @Trn_TraEspLiquidaDed where TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_TraEspLiquidaOdp))
					BEGIN
					INSERT INTO Trn_TraEspLiquidaOdp(
					TipDoc,Liquidacion,IdCia,Item,TipOdp,OrdPago,IdCiaOdp,VrAbonado
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Item,TipOdp,OrdPago,IdCiaOdp,VrAbonado
					FROM @Trn_TraEspLiquidaOdp where TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_TraEspLiquidaOtr))
					BEGIN
					INSERT INTO Trn_TraEspLiquidaOtr(
					TipDoc,Liquidacion,IdCia,Item,TipCau,Causacion,IdCiaCau,ItemCau,Factura,ItemFac,IdProveedor,pVehiculo,VrAbono,TipFac,VrFactura
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Item,TipCau,Causacion,IdCiaCau,ItemCau,Factura,ItemFac,IdProveedor,pVehiculo,VrAbono,TipFac,VrFactura
					FROM @Trn_TraEspLiquidaOtr where TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_EgrFactura))
					BEGIN
					INSERT INTO Trn_EgrFactura(
					TipCom,Comprobante,IdCia,Item,Fecha,TipFac,Factura,IdCiaFac,
					ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
					VehPropio,TipDev,NumDev,DetAbono
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Item,Fecha,TipFac,Factura,IdCiaFac,
					ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
					VehPropio,TipDev,NumDev,DetAbono
					FROM @Trn_EgrFactura where TipCom = @TipDocu and Comprobante = @Liq and  IdCia = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
					BEGIN
					INSERT INTO Trn_Comprobantes(
					TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
					NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
					TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
					VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
					Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
					PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
					CodRes, DescServicio
					)
					SELECT 
					@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
					NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
					TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
					VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
					Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
					PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
					CodRes, DescServicio
					FROM @Trn_Comprobantes where TipDoc = @TipDocu and Documento = @Liq and  IdCiaDoc = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
					BEGIN
					INSERT INTO Trn_ComDetalle(
					TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
					IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
					IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
					CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
					IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
					)
					SELECT 
					@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
					IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
					CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
					CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
					IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
					FROM @Trn_ComDetalle where TipDoc = @TipDocu and Documento = @Liq and  IdCiaDoc = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifComp))
					BEGIN
					INSERT INTO Trn_NiifComp(
					TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
					EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
					FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
					VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
					IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
					Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
					CtbTipo, CtbNumero,
					FisTipo, FisNumero 
					)
					SELECT 
					CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
					CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
					@Cia, 
					C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
					C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
					C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
					C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
					C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
					C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
					CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
					CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
					FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
					where C.TipDoc = @TipDocu and C.Documento = @Liq and C.IdCia = @IdCia and N.TipDoc = @TipDocu and N.Documento = @Liq and N.IdCiaDoc = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
					BEGIN
					INSERT INTO Trn_NiifDetalle(
					TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
					VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
					VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
					NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
					CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
					DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
					CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
					FechAutoriza, CodCuentaCG
					)
					SELECT 
					CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
					CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END,
					@Cia,
					N.Item, N.Fecha, N.IdCuenta, N.Detalle,
					N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
					N.VrBase, N.TarifaBase, @TipDoc,@Numero,@Cia, N.CodConce,
					N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
					N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
					N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
					N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
					N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
					N.FechAutoriza, N.CodCuentaCG
					FROM @Trn_NiifDetalle as N
					JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante and NC.TipDoc = @TipDocu and NC.Documento = @Liq and NC.IdCiaDoc = @IdCia
					where N.TipDoc = @TipDocu and N.Documento = @Liq and N.IdCia = @IdCia
					END
				end

				IF(@operacion = 'i')
				begin

				
				  declare @TipCau varchar(3)
				  declare @Causacion int
				  declare @IdCiaCau varchar(2)	
				  declare @ItemCau int		  
				  declare @VrAbonoCau decimal(14,4)
				  -- actualizar causaciones con deducciones
				  DECLARE ccausac CURSOR
	  			  FOR SELECT TipCau, Causacion, IdCiaCau, ItemCau, VrAbono from @Trn_TraEspLiquidaDed WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia
				  OPEN ccausac
				  FETCH NEXT FROM ccausac into @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
				  WHILE @@FETCH_STATUS = 0
				  BEGIN
			  
					  UPDATE Trn_TraEspCauDetalle
					  SET TipoLiq = @TipDoc, NumLiquida = @Numero, CiaLiquida = @Cia, VrAbonado = VrAbonado + @VrAbonoCau
					  FROM Trn_TraEspCauDetalle t1
					  WHERE t1.TipDoc = @TipCau and t1.Causacion = @Causacion and t1.IdCia = @IdCiaCau and t1.Item = @ItemCau

				  FETCH NEXT FROM ccausac INTO @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
				  END
				  CLOSE ccausac
				  DEALLOCATE ccausac

				  -- actualizar causaciones con otros pagos
				  DECLARE pcausac CURSOR
	  			  FOR SELECT TipCau,Causacion,IdCiaCau,ItemCau, VrAbono from @Trn_TraEspLiquidaOtr WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia
				  OPEN pcausac
				  FETCH NEXT FROM pcausac into @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
				  WHILE @@FETCH_STATUS = 0
				  BEGIN
			  
					  UPDATE Trn_TraEspCauDetalle
					  SET TipoLiq = @TipDoc, NumLiquida = @Numero, CiaLiquida = @Cia, VrAbonado = VrAbonado + @VrAbonoCau
					  FROM Trn_TraEspCauDetalle t1
					  WHERE t1.TipDoc = @TipCau and t1.Causacion = @Causacion and t1.IdCia = @IdCiaCau and t1.Item = @ItemCau

				  FETCH NEXT FROM pcausac INTO @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
				  END
				  CLOSE pcausac
				  DEALLOCATE pcausac

				  --actualizar Trn_ComFactura
				  declare @FactTipFac varchar(3)
				  declare @FactIdCiaFac varchar(2)
				  declare @FactFactura int
				  declare @FactIdProveedor varchar(16)
				  declare @VrAbono decimal(14,4)
				  declare @ItemFac int
				  DECLARE cprincipal CURSOR
	  			  FOR SELECT TipFac, Factura, IdCiaFac,ItemFac, IdProveedor, VrAbono FROM @Trn_EgrFactura WHERE TipCom = @TipDocu and Comprobante = @Liq and  IdCia = @IdCia
				  OPEN cprincipal
				  FETCH NEXT FROM cprincipal into @FactTipFac, @FactFactura, @FactIdCiaFac,@ItemFac, @FactIdProveedor, @VrAbono
				  WHILE @@FETCH_STATUS = 0
				  BEGIN
						  IF(@VrAbono > 0)
						  BEGIN
							  UPDATE Trn_ComFactura 
							  SET VrAbonado = VrAbonado + @VrAbono
							  FROM Trn_ComFactura t1 
							  WHERE t1.TipFac = @FactTipFac and t1.Factura = @FactFactura and t1.IdCia = @FactIdCiaFac and t1.Item = @ItemFac and t1.IdProveedor = @FactIdProveedor
						  END

				  FETCH NEXT FROM cprincipal INTO @FactTipFac, @FactFactura, @FactIdCiaFac,@ItemFac, @FactIdProveedor, @VrAbono
				  END
				  CLOSE cprincipal
				  DEALLOCATE cprincipal

				  --actualizar orden pago
				  update Trn_TraEspOrdenReservas
				  set EdoLiqCausac =  1
				  from Trn_TraEspOrdenReservas t1, @Trn_TraEspLiquidaDed t2
				  where t2.TipOdp = t1.TipDoc and t2.OrdenPago = t1.OrdPago and t2.IdCiaOdp = t1.IdCia

				end

				--Causaciones para la liquidación seleccionada
				select @Causaciones = SUBSTRING((SELECT ',' + cast(Causacion as VARCHAR(max)) FROM @Trn_TraEspLiquidaDed WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)
				select @IdCiaCaus = SUBSTRING((SELECT ',' + cast(IdCiaCau as VARCHAR(max)) FROM @Trn_TraEspLiquidaDed WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)
				select @ItemCaus = SUBSTRING((SELECT ',' + cast(ItemCau as VARCHAR(max)) FROM @Trn_TraEspLiquidaDed WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)

				--Ordenes de pago para la liquidación seleccionada
				select @Odps = SUBSTRING((SELECT ',' + cast(OrdPago as VARCHAR(max)) FROM @Trn_TraEspLiquidaOdp WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)
				select @IdCiaOdps = SUBSTRING((SELECT ',' + cast(IdCiaOdp as VARCHAR(max)) FROM @Trn_TraEspLiquidaOdp WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)

				--Otros pagos para la liquidación seleccionada
				select @OtrPagos = SUBSTRING((SELECT ',' + cast(Causacion as VARCHAR(max)) FROM @Trn_TraEspLiquidaOtr WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)
				select @IdCiaOtrpagos = SUBSTRING((SELECT ',' + cast(IdCiaCau as VARCHAR(max)) FROM @Trn_TraEspLiquidaOtr WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)
				select @ItemOtros = SUBSTRING((SELECT ',' + cast(ItemCau as VARCHAR(max)) FROM @Trn_TraEspLiquidaOtr WHERE TipDoc = @TipDocu and Liquidacion = @Liq and  IdCia = @IdCia FOR XML PATH('')), 2 , 9999)

				IF(@NumProc = @ItemProc)
				BEGIN
					INSERT INTO #LogLiquida(
					Numero,Fecha,EstadoProc,Observacion,TimeSys,IdUsuario,Nombre
					)
					SELECT 
					@NumProc,t1.Fecha,1,t1.Observacion,t1.TimeSys,t1.IdUsuario,u.Usuario
					FROM @Trn_TraEspLiquida as t1
					left join adm_Usuarios u on u.IdUsuario = t1.IdUsuario
					WHERE t1.TipDoc = @TipDocu and t1.Liquidacion = @Liq and t1.IdCia = @IdCia
				END 

				INSERT INTO #LogLiquidaDet(
				Numero,Item,TipDoc,Liquidacion,IdCia,FechaLiq,FechaDed,FechaIniOdp,FechaFinOdp,IdConcepto,
				CXP,TipoCom,Comprobante,IdVehiculo,IdConductor,IdPoseedor,
				Causaciones,IdCiaCaus,ItemCaus,Odps,IdCiaOdps,OtrPagos,IdCiaOtrpagos,ItemOtros,
				VrTotalLiq,Comentarios)
				SELECT 
				@NumProc,@ItemProc,@TipDoc,@Numero,@Cia,t1.Fecha,t1.FecFinCau,t1.FecIniOdp,t1.FecFinOdp,t1.IdConcepto,
				t1.CxPagar,@TipComp,@Comprobante,t1.IdVehiculo,t1.IdConductor,t1.IdPoseedor,
				@Causaciones,@IdCiaCaus,@ItemCaus,@Odps,@IdCiaOdps,@OtrPagos,@IdCiaOtrpagos,@ItemOtros,
				t1.VrTotal,'Se guarda correctamente'
				FROM (select * from @Trn_TraEspLiquida where TipDoc = @TipDocu and Liquidacion = @Liq and IdCia = @IdCia) as t1

				select @ItemProc = @ItemProc + 1

			FETCH NEXT FROM liqcursor INTO @TipDocu,@Liq,@IdCia
			END
			CLOSE liqcursor
			DEALLOCATE liqcursor

			SELECT * FROM #LogLiquida
			SELECT * FROM #LogLiquidaDet

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvOrdenPago]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 23/10/2017
-- Description:	Insertar Trn_TraEspOrdenPago Masivas
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMsvOrdenPago]
	@Trn_TraEspOrdenPago dataTypeTrn_TraEspOrdenPago READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenPago
	@Trn_TraEspOrdenReservas dataTypeTrn_TraEspOrdenReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenReservas
	@Trn_TraEspOrdenProg dataTypeTrn_TraEspOrdenProg READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenProg
	@Trn_TraEspConceptos dataTypeTrn_TraEspConceptos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspConceptos
	@Trn_TraEspAntAbonos dataTypeTrn_TraEspAntAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspAntAbonos
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas
	@Trn_ComFactura dataTypeTrn_ComFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComFactura
	@Trn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeNiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp	
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle
	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY
			
			 CREATE TABLE #LogOrden(
			 Numero int NOT NULL,
			 Fecha smalldatetime NOT NULL,
			 EstadoProc int NOT NULL,
			 Observacion varchar(1000) NULL,
			 TimeSys smalldatetime NOT NULL,
			 IdUsuario varchar(11) NOT NULL,
			 Nombre varchar(50) NOT NULL
			 )

			 CREATE TABLE #LogOrdenDet(
			 Numero int NOT NULL,
			 Item int NOT NULL,
			 TipDoc varchar(3) NOT NULL,
			 Orden int NOT NULL,
			 IdCia char(2) NOT NULL,
			 Fecha smalldatetime NOT NULL,
			 IdConcepto varchar(4) NOT NULL,
			 TipoCom varchar(3) NULL,
			 Comprobante int NOT NULL,
			 TipRes varchar(3) NOT NULL,
			 Reserva int NOT NULL,
			 IdCiaRes char(2) NOT NULL,
			 ItemRes int NOT NULL,
			 IdOrigen varchar(8) NOT NULL,
			 CiuOrigen varchar(50) NULL,
			 IdDestino varchar(8) NOT NULL,
			 CiuDestino varchar(50) NULL,
			 IdRuta varchar(4) NOT NULL,
			 Ruta varchar(100) NULL,
			 IdVehiculo varchar(10) NOT NULL,
			 IdConductor varchar(16) NOT NULL,
			 IdPropietario varchar(16) NOT NULL,
			 IdPoseedor varchar(16) NOT NULL,
			 Cumplido int NOT NULL,
			 IdCiaCum varchar(2) NOT NULL,
			 EstadoReg int NOT NULL,
			 VrServicio money NOT NULL,
			 VrDescuento money NOT NULL,
			 VrRetencion money NOT NULL,
			 VrReteIca money NOT NULL,
			 VrReteCREE money NOT NULL,
			 VrAnticipos money NOT NULL,
			 VrOtrosDctos money NOT NULL,
			 VrImpuestos money NOT NULL,
			 VrOtrosPagos money NOT NULL,
			 VrNeto money NOT NULL,
			 TarifaRet decimal(14, 4) NOT NULL,
			 TarifaIca decimal(14, 4) NOT NULL,
			 TarifaRtc decimal(14, 4) NOT NULL,
			 CodTarRet varchar(4) NULL,
			 CodTarIca varchar(4) NULL,
			 CodTarRtc varchar(4) NULL,
			 VrConcPagos money NOT NULL,
			 VrConcDctos money NOT NULL,
			 VrConcFondo money NOT NULL,
			 VrConcSeguro money NOT NULL,
			 VrConcAporte money NOT NULL,
			 VrConcImpuesto money NOT NULL,
			 VrRecCaja money NOT NULL,
			 CdForma varchar(4) NULL,
			 IdCCosto varchar(16) NULL,
			 IdSubCos varchar(16) NULL,
			 VrSeguros money NOT NULL,
			 VrFondos money NOT NULL,
			 VrAportes money NOT NULL,
			 Comentarios varchar(1000) NULL		 
			 )

			declare @TipDocu varchar(3)
			declare @Orden int
			declare @IdCia CHAR(2)		
			DECLARE @Reserva INT --Esta variable guarda el número de reserva
			DECLARE @IdCiaRes CHAR(2)  --Esta variable guarda la compañia de la reserva
			DECLARE @ItemRes INT --Esta variable guarda el número de ítem de reserva
			DECLARE @VrPagos MONEY = 0 --En esta variable va guarda el valor de pago real de la reserva
			DECLARE @VrTotalPagosaRES MONEY = 0 --En esta variable va guarda el valor de pagos hechas a la reserva por ordenes de pago
			DECLARE @TipoTarifa varchar(20)
			declare @NumProc int = 1
			declare @ItemProc int = 1

			DECLARE ordencursor CURSOR
			FOR SELECT TipDoc,OrdPago,IdCia FROM @Trn_TraEspOrdenPago
			OPEN ordencursor
			FETCH NEXT FROM ordencursor INTO @TipDocu,@Orden,@IdCia
			WHILE @@FETCH_STATUS = 0
			BEGIN
				
					IF(@operacion = 'i')
					begin					
						SELECT @TipDoc = @TipDocu, @Cia = @IdCia, @IdCiaComp = @IdCia, @IdCiaCompNiif = @IdCia, @IdCiaCompFis = @IdCia
						SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

						IF(@Numero > 0)
							UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
						ELSE
						BEGIN
							SELECT @Numero = 1
							INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
						END

						IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
						BEGIN
							SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes where TipDoc = @TipDocu and Documento = @Orden and  IdCiaDoc = @IdCia
							SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
							--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
							IF(@Comprobante <> '')
								UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
							ELSE
							BEGIN
								SELECT @Comprobante = 1
								INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
							END
						END

						IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
						BEGIN
							SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF' and TipDoc = @TipDocu and Documento = @Orden and  IdCiaDoc = @IdCia
							SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
							--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
							IF(@CompNiif <> '')
								UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
							ELSE
							BEGIN
								SELECT @CompNiif = 1
								INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
							END
						END

						IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
						BEGIN
							SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL' and TipDoc = @TipDocu and Documento = @Orden and  IdCiaDoc = @IdCia
							SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
							--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
							IF(@CompNiif <> '')
								UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
							ELSE
							BEGIN
								SELECT @CompFis = 1
								INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
							END
						END
					end

					IF(@operacion = 'i')
					begin					
						IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenPago))
						BEGIN
						INSERT INTO Trn_TraEspOrdenPago(
						TipDoc,OrdPago,IdCia,Fecha,TipRes,Reserva,IdCiaRes,IdConcepto,Cantidad,Modalidad,LiqReservas,CxPagar,MulPlazos,IdPlazo,FechaVence,
						TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Fecha,TipRes,Reserva,IdCiaRes,IdConcepto,Cantidad,Modalidad,LiqReservas,CxPagar,MulPlazos,IdPlazo,FechaVence,
						@TipComp,@Comprobante,@IdCiaComp,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
						FROM @Trn_TraEspOrdenPago where TipDoc = @TipDocu and OrdPago = @Orden and IdCia = @IdCia
						END 

						IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenReservas))
						BEGIN
						INSERT INTO Trn_TraEspOrdenReservas(
						TipDoc,OrdPago,IdCia,Item,Fecha,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdConductor,IdPropietario,IdPoseedor,VrServicio,VrDescuento,VrRetencion,
						VrReteIca,VrReteCREE,VrAnticipos,VrOtrosDctos,VrImpuestos,VrOtrosPagos,VrNeto,BaseRet,BaseIca,BaseCree,TarifaRet,TarifaIca,TarifaRtc,CodTarRet,
						CodTarIca,CodTarRtc,TipEgr,Egreso,IdCiaEgr,FechaEgr,NumCheque,Referencia,VrConcPagos,VrConcDctos,VrConcFondo,VrConcSeguro,VrConcAporte,VrConcImpuesto,
						VrRecCaja,CdForma,CdCenCosto,CdSubCenCos,VrSeguros,VrFondos,VrAportes,EdoLiqCausac,EstadoItem
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Item,Fecha,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdConductor,IdPropietario,IdPoseedor,VrServicio,VrDescuento,VrRetencion,
						VrReteIca,VrReteCREE,VrAnticipos,VrOtrosDctos,VrImpuestos,VrOtrosPagos,VrNeto,BaseRet,BaseIca,BaseCree,TarifaRet,TarifaIca,TarifaRtc,CodTarRet,
						CodTarIca,CodTarRtc,TipEgr,Egreso,IdCiaEgr,FechaEgr,NumCheque,Referencia,VrConcPagos,VrConcDctos,VrConcFondo,VrConcSeguro,VrConcAporte,VrConcImpuesto,
						VrRecCaja,CdForma,CdCenCosto,CdSubCenCos,VrSeguros,VrFondos,VrAportes,EdoLiqCausac,EstadoItem
						FROM @Trn_TraEspOrdenReservas where TipDoc = @TipDocu and OrdPago = @Orden and IdCia = @IdCia
						END 

						IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenProg))
						BEGIN
						INSERT INTO Trn_TraEspOrdenProg(
						TipDoc,OrdPago,IdCia,Item,TipRes,Reserva,IdCiaRes,ItemRes,TipPgr,Programa,IdCiaPgr,ItemPgr,VrRecorrido
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Item,TipRes,Reserva,IdCiaRes,ItemRes,TipPgr,Programa,IdCiaPgr,ItemPgr,VrRecorrido
						FROM @Trn_TraEspOrdenProg where TipDoc = @TipDocu and OrdPago = @Orden and IdCia = @IdCia
						END 

						IF(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
						BEGIN
						INSERT INTO Trn_TraEspConceptos(
						TipDoc,Documento,IdCia,Item,Descripcion,Tarifa,TipoConc,RubroConcep,Cantidad,VrUnitario,TarifIva,IdConcepto,CdCuenta,NitTercero,
						CdTipoEsc,FechaNov,VrBase,TipoTarif,RefConc,Fijos,IncBaseRet,Referencia2,Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Item,Descripcion,Tarifa,TipoConc,RubroConcep,Cantidad,VrUnitario,TarifIva,IdConcepto,CdCuenta,NitTercero,
						CdTipoEsc,FechaNov,VrBase,TipoTarif,RefConc,Fijos,IncBaseRet,Referencia2,Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
						FROM @Trn_TraEspConceptos where TipDoc = @TipDocu and Documento = @Orden and IdCia = @IdCia
						END

						IF(EXISTS(SELECT * FROM @Trn_TraEspAntAbonos))
						BEGIN
						INSERT INTO Trn_TraEspAntAbonos(
						TipDoc,Documento,IdCia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
						FROM @Trn_TraEspAntAbonos where TipDoc = @TipDocu and Documento = @Orden and IdCia = @IdCia
						END

						IF(EXISTS(SELECT * FROM @Trn_DetCuentas))
						BEGIN
						INSERT INTO Trn_DetCuentas(
						TipDoc,Documento,IdCia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
						VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
						VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
						FROM @Trn_DetCuentas where TipDoc = @TipDocu and Documento = @Orden and IdCia = @IdCia
						END

						IF(EXISTS(SELECT * FROM @Trn_ComFactura))
						BEGIN
						INSERT INTO Trn_ComFactura(
						TipFac,Factura,IdCia,Item,IdProveedor,IdCuenta,TipDoc,Documento,IdCiaDoc,FecEmision,FecVence,VrFactura,VrAbonado,TipCom,Comprobante,ItemCom,
						Referencia,Detalle,pVehiculo,VehPropio,TipRef,DocRef,IdCiaRef,EstadoApr,MontoAprob
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Item,IdProveedor,IdCuenta,@TipDoc,@Numero,@Cia,FecEmision,FecVence,VrFactura,VrAbonado,@TipComp,@Comprobante,ItemCom,
						Referencia,Detalle,pVehiculo,VehPropio,TipRef,DocRef,IdCiaRef,EstadoApr,MontoAprob
						FROM @Trn_ComFactura  where TipDoc = @TipDocu and Documento = @Orden and IdCiaDoc = @IdCia
						END 

						IF(EXISTS(SELECT * FROM @Trn_Pagos))
						BEGIN
						INSERT INTO Trn_Pagos(
						TipDoc, Documento, IdCia, Item, Fecha, IdForma, Detalle, VrPagado,
						VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
						CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
						VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
						CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
						)
						SELECT 
						@TipDoc, @Numero, @Cia, Item, Fecha, IdForma, Detalle, VrPagado,
						VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
						CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
						VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
						CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
						FROM @Trn_Pagos where TipDoc = @TipDocu and Documento = @Orden and IdCia = @IdCia
						END

						IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
						BEGIN
						INSERT INTO Trn_Comprobantes(
						TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
						NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
						TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
						VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
						Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
						PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
						CodRes, DescServicio
						)
						SELECT 
						@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
						NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
						TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
						VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
						Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
						PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
						CodRes, DescServicio
						FROM @Trn_Comprobantes where TipDoc = @TipDocu and Documento = @Orden and IdCia = @IdCia
						END

						IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
						BEGIN
						INSERT INTO Trn_ComDetalle(
						TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
						IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,IdCiaDoc,
						CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
						NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
						CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
						IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
						)
						SELECT 
						@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
						IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
						CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
						NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
						CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
						IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
						FROM @Trn_ComDetalle where TipDoc = @TipDocu and Documento = @Orden and IdCia = @IdCia
						END

						IF(EXISTS(SELECT * FROM @Trn_NiifComp))
						BEGIN
						INSERT INTO Trn_NiifComp(
						TipCom, 
						Comprobante, 
						IdCia,Fecha, IdTercero, VrTotal, IdCta,
						EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
						FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
						VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
						IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
						Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
						CtbTipo, CtbNumero,
						FisTipo, FisNumero 
						)
						SELECT 
						CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
						CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
						@Cia,C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
						C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
						C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
						C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
						C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
						C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
						CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
						CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
						FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont 
						where C.TipDoc = @TipDocu and C.Documento = @Orden and C.IdCia = @IdCia
							  and N.TipDoc = @TipDocu and N.Documento = @Orden and N.IdCiaDoc = @IdCia
						END

						IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
						BEGIN
						INSERT INTO Trn_NiifDetalle(
						TipCom, 
						Comprobante, 
						IdCia,Item, Fecha, IdCuenta, Detalle,
						VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
						VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
						NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
						NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
						CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
						DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
						CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
						FechAutoriza, CodCuentaCG
						)
						SELECT 
						CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
						CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
						@Cia,N.Item, N.Fecha, N.IdCuenta, N.Detalle,
						N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
						N.VrBase, N.TarifaBase, @TipDoc, @Numero, @Cia, N.CodConce,
						N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
						N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
						N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
						N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
						N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
						N.FechAutoriza, N.CodCuentaCG
						FROM @Trn_NiifDetalle as N 
						JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante and NC.TipDoc = @TipDocu and NC.Documento = @Orden and NC.IdCiaDoc = @IdCia
						where N.TipDoc = @TipDocu and N.Documento = @Orden and N.IdCia = @IdCia
						END
					end	

					IF(@operacion = 'i')
					begin					
						--actualiza los items de la programnación detalle de cada reserva agregada en la Orden de Pago
						UPDATE Trn_TraEspProgramaDet
						SET TipDocOdp = 'OPE',NumOdp = @Numero, IdCiaOdp = @Cia, FechaOdp = t3.Fecha
						FROM Trn_TraEspProgramaDet t1 
						,(Select TipRes,Reserva,IdCiaRes,ItemRes,TipPgr,Programa,IdCiaPgr,ItemPgr from Trn_TraEspOrdenProg where TipDoc = 'OPE' and OrdPago = @Numero and IdCia = @Cia) as t2
						,(Select Fecha from Trn_TraEspOrdenPago where TipDoc = 'OPE' and OrdPago = @Numero and IdCia = @Cia) as t3					 
						WHERE t1.TipDocRes = t2.TipRes and t1.Reserva = t2.Reserva and t1.IdCiaRes = t2.IdCiaRes and t1.ItemRes = t2.ItemRes and t1.TipDoc = t2.TipPgr and t1.Programa = t2.Programa and t1.IdCia = t2.IdCiaPgr and t1.Item = t2.ItemPgr 

						--actualización de la resdetalle
						Select @Reserva = Reserva, @IdCiaRes = IdCiaRes, @ItemRes = ItemRes from @Trn_TraEspOrdenReservas where TipDoc = @TipDocu and OrdPago = @Orden and IdCia = @IdCia
										
						SELECT @TipoTarifa = TipoTarifa FROM Trn_TraEspResDetalle WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes

						SELECT @VrTotalPagosaRES = ISNULL(SUM(R.VrServicio),0) 
						FROM Trn_TraEspOrdenReservas R
						LEFT JOIN Trn_TraEspOrdenPago AS OP ON R.TipDoc = OP.TipDoc AND  R.OrdPago = OP.OrdPago AND  R.IdCia = OP.IdCia
						WHERE R.Reserva = @Reserva AND R.IdCiaRes = @IdCiaRes AND R.ItemRes = @ItemRes AND OP.Anulado = 0
						
						IF(upper(@TipoTarifa) <> 'DIA')
						BEGIN
							SELECT @VrPagos = VrPagos FROM Trn_TraEspResDetalle WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes

							IF(@VrTotalPagosaRES >= @VrPagos)
							BEGIN
								UPDATE Trn_TraEspResDetalle
								SET EstadoItem ='LIQUIDADA'
								WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
							END
							ELSE -- revisar que la cant de veh se vayan a liquidar(programados no novedad) ya hayan sido liquidados(pasan de xliquidar a liquidado) y que la reserva no se haya vencido
							BEGIN
							  declare @cantveh int= 0, @cantord int = 0, @fechares date, @fechasys date,@idveh varchar(10)

							  select @cantveh = count(*) from trn_traespprogramadet where Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdNovedad = '0' and IdVehiculo <>'0'
							  select @fechares = fechafin from trn_traespreservas where Reserva = @Reserva AND IdCia = @IdCiaRes
							  select @fechasys = FechaActual from companias where IdCia = @IdCiaRes

							  --selecciono  los progdetalle de esos vehiculos
							  declare @Trn_TraEspProgramaDet dataTypeTrn_TraEspProgramaDet 
							  INSERT INTO @Trn_TraEspProgramaDet(
							  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
							  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
							  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
							  CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion
							  ) 
							  SELECT 
							  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
							  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
							  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
							  CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion
							  FROM Trn_TraEspProgramaDet  where Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdNovedad = '0' and IdVehiculo <>'0'
					  
							  --cursor para verififcar si los vehiculos fueron pagados en ordenes de pago					   
							  DECLARE verificar CURSOR
							  FOR SELECT IdVehiculo  FROM @Trn_TraEspProgramaDet
							  OPEN verificar
							  FETCH NEXT FROM verificar INTO @idveh
							  WHILE @@FETCH_STATUS = 0
							  BEGIN

							  --verifico la cantidad que ya fueron liquidados(tine encuenta la actual)
							   if (exists(select * from Trn_TraEspOrdenReservas where Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdVehiculo = @idveh))
								select @cantord = @cantord + 1

								FETCH NEXT FROM verificar INTO @idveh 
							  END
							  CLOSE verificar
							  DEALLOCATE verificar

							  --se verifica que cumpal para colocar la resrva a liquidada
							  IF((@cantord >= @cantveh) AND (@fechasys  >= @fechares))
							  BEGIN 
								UPDATE Trn_TraEspResDetalle
								SET EstadoItem ='LIQUIDADA'
								WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
							  END

							END

						END
						ELSE
						BEGIN 
							SELECT @VrPagos = ISNULL(SUM(VrPagos),0)  FROM Trn_TraEspProgramaDet WHERE Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdNovedad = '0' and IdVehiculo <>'0'

							IF(@VrTotalPagosaRES >= @VrPagos)
							BEGIN
								UPDATE Trn_TraEspResDetalle
								SET EstadoItem ='LIQUIDADA'
								WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
							END
						END

						--actualiza los anticipos
						UPDATE Trn_TraEspAnticipos
						SET VrAbonado = t2.VrAbono + VrAbonado
						FROM Trn_TraEspAnticipos t1
						,(Select TipAnt,Anticipo,IdCiaAnt,VrAbono from @Trn_TraEspAntAbonos where TipDoc = @TipDocu and Documento = @Orden and IdCia = @IdCia) as t2
						WHERE t1.TipDoc = t2.TipAnt and t1.Anticipo = t2.Anticipo and t1.IdCia = t2.IdCiaAnt 
						  
					end

					IF(@NumProc = @ItemProc)
					BEGIN
						INSERT INTO #LogOrden(
						Numero,Fecha,EstadoProc,Observacion,TimeSys,IdUsuario,Nombre
						)
						SELECT 
						@NumProc,t1.Fecha,1,t1.Observacion,t1.TimeSys,t1.IdUsuario,u.Usuario
						FROM @Trn_TraEspOrdenPago as t1
						left join adm_Usuarios u on u.IdUsuario = t1.IdUsuario
						WHERE t1.TipDoc = @TipDocu and t1.OrdPago = @Orden and t1.IdCia = @IdCia
					END

					INSERT INTO #LogOrdenDet(
					Numero,Item,TipDoc,Orden,IdCia,Fecha,IdConcepto,TipoCom,Comprobante,TipRes,Reserva,IdCiaRes,
					ItemRes,IdOrigen,CiuOrigen,IdDestino,CiuDestino,IdRuta,Ruta,IdVehiculo,IdConductor,IdPropietario,
					IdPoseedor,Cumplido,IdCiaCum,EstadoReg,VrServicio,VrDescuento,VrRetencion,VrReteIca,VrReteCREE,VrAnticipos,VrOtrosDctos,VrImpuestos,
					VrOtrosPagos,VrNeto,TarifaRet,TarifaIca,TarifaRtc,CodTarRet,CodTarIca,CodTarRtc,VrConcPagos,VrConcDctos,
					VrConcFondo,VrConcSeguro,VrConcAporte,VrConcImpuesto,VrRecCaja,CdForma,IdCCosto,IdSubCos,VrSeguros,VrFondos,
					VrAportes,Comentarios
					)
					SELECT 
					@NumProc,@ItemProc,@TipDoc,@Numero,@Cia,t1.Fecha,t1.IdConcepto,@TipComp,@Comprobante,t2.TipRes,t2.Reserva,t2.IdCiaRes,
					t2.ItemRes,t3.CdCiuOrigen,t3.CiuOrigen,t3.CdCiuDestino,t3.CiuDestino,t3.IdRuta,t3.Ruta,t2.IdVehiculo,t2.IdConductor,t2.IdPropietario,
					t2.IdPoseedor,t3.Cumplido,t3.IdCiaCum,1,t2.VrServicio,t2.VrDescuento,t2.VrRetencion,t2.VrReteIca,t2.VrReteCREE,t2.VrAnticipos,t2.VrOtrosDctos,t2.VrImpuestos,
					t2.VrOtrosPagos,t2.VrNeto,t2.TarifaRet,t2.TarifaIca,t2.TarifaRtc,t2.CodTarRet,t2.CodTarIca,t2.CodTarRtc,t2.VrConcPagos,t2.VrConcDctos,
					t2.VrConcFondo,t2.VrConcSeguro,t2.VrConcAporte,t2.VrConcImpuesto,t2.VrRecCaja,t2.CdForma,t2.CdCenCosto,t2.CdSubCenCos,t2.VrSeguros,t2.VrFondos,
					t2.VrAportes,'Se guarda correctamente'
					FROM (SELECT * FROM @Trn_TraEspOrdenPago WHERE TipDoc = @TipDocu and OrdPago = @Orden and IdCia = @IdCia) AS t1,
					(SELECT * FROM @Trn_TraEspOrdenReservas WHERE TipDoc = @TipDocu and OrdPago = @Orden and IdCia = @IdCia) AS t2,
					(SELECT r.IdRuta,rt.Ruta,r.CdCiuOrigen,lo.Localidad AS CiuOrigen,r.CdCiuDestino, ld.Localidad AS CiuDestino,r.Cumplido,r.IdCiaCum 
					 FROM @Trn_TraEspOrdenReservas AS ord 
					 join Trn_TraEspResDetalle r ON r.TipDoc = ord.TipRes and r.Reserva = ord.Reserva and r.IdCia = ord.IdCiaRes and r.Item = ord.ItemRes
					 left join Rutas rt ON rt.IdRuta = r.IdRuta 
					 left join Localidades lo ON lo.IdLocal = r.CdCiuOrigen 
					 left join Localidades ld ON ld.IdLocal = r.CdCiuDestino
					 WHERE ord.TipDoc = @TipDocu and ord.OrdPago = @Orden and ord.IdCia = @IdCia) AS t3

					SELECT @ItemProc = @ItemProc + 1
				
			FETCH NEXT FROM ordencursor INTO @TipDocu,@Orden,@IdCia
			END
			CLOSE ordencursor
			DEALLOCATE ordencursor

			SELECT * FROM #LogOrden
			SELECT * FROM #LogOrdenDet

		COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = Convert(varchar(10),ERROR_LINE()) +' '+ ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvPrograma]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 31/10/2016
-- Description:	Insertar CRUD de Masivo Programacion de vehiculos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMsvPrograma]
	@Trn_TraEspPrograma dataTypeTrn_TraEspPrograma READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPrograma
	@Trn_TraEspProgramaDet dataTypeTrn_TraEspProgramaDet READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspProgramaDet
	@Trn_TraEspProgramaPers dataTypeTrn_TraEspProgramaPers READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspProgramaPers
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Reserva/Cotización
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Reserva/Cotización
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Reserva/Cotización
declare @IdEstado varchar(4)
declare @item int
	BEGIN TRAN
		BEGIN TRY
		
			CREATE TABLE #LogPrograma(
			Numero int NOT NULL,
			Fecha smalldatetime NOT NULL,
			EstadoProc int NOT NULL,
			Observacion varchar(250) NULL,
			TimeSys smalldatetime NOT NULL,
			IdUsuario varchar(11) NOT NULL,
			Nombre varchar(50) NOT NULL
			)

			--CREATE TABLE #LogProgDetalle(
			--Numero int NOT NULL,
			--Item int NOT NULL,
			--TipDoc varchar(3) NOT NULL,
			--Programa int NOT NULL,
			--IdCia char(2) NOT NULL,
			--FechaIni smalldatetime NOT NULL,
			--FechaFin smalldatetime NOT NULL,
			--IdVehiculo varchar(10) NOT NULL,
			--Reservas int NOT NULL,
			--IdCiaRes char(2) NOT NULL,
			--ItemRes int NOT NULL,
			--Comentarios varchar(max) NULL
			--)
			
			--declare @IdVehiculo varchar(max)
			--declare @Reservas varchar(max)
			--declare @IdCiaRes varchar(max)
			--declare @ItemRes varchar(max)

			declare @NumProc int = 1
			declare @ItemProc int = 1
			declare @TipDocu varchar(3)
			declare @Programa INT
			declare @CiaProg varchar(2)
			declare @FechaInicio datetime
			declare @FechaFin datetime
			declare @observ varchar(250)

			--esta variable para cuando se haga actualización de programación masiva
			declare @itempgr int = 0
			--

			DECLARE progcursor CURSOR
			FOR SELECT TipDoc,Programa,IdCia FROM @Trn_TraEspPrograma
			OPEN progcursor
			FETCH NEXT FROM progcursor INTO @TipDocu,@Programa,@CiaProg
			WHILE @@FETCH_STATUS = 0
			BEGIN

				--Seleccionar Variables
				IF(@operacion = 'i')
				BEGIN
					SELECT TOP 1 @TipDoc = @TipDocu, @IdCia = @CiaProg
					SELECT @Documento = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia

					IF(@Documento <> '')
						UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
					ELSE
					BEGIN
						SELECT @Documento = 1
						INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
					END
				END
				ELSE IF(@operacion = 'u')
				BEGIN
					SELECT TOP 1 @TipDoc = @TipDocu, @IdCia = @CiaProg, @Documento = @Programa
				END

				--INSERT NO-EXISTE RECORDS
				IF(@operacion = 'i' or @operacion = 'u')
				BEGIN
					
					IF(@operacion = 'i')
					BEGIN
						IF(EXISTS(SELECT * FROM @Trn_TraEspPrograma))
						begin
						INSERT INTO Trn_TraEspPrograma(
						TipDoc,Programa,IdCia,Fecha,OrigenAdd,Anulado,FecDev,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
						)
						SELECT 
						@TipDoc,@Documento,@IdCia,Fecha,OrigenAdd,Anulado,FecDev,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
						FROM @Trn_TraEspPrograma p WHERE p.TipDoc = @TipDocu and p.Programa = @Programa and p.IdCia = @CiaProg
						end
					END

					IF(@operacion = 'i')
					BEGIN
						IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
						begin
						INSERT INTO Trn_TraEspProgramaDet(
						TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
						IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
						IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
						CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
						) 
						SELECT 
						@TipDoc,@Documento,@IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
						IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
						IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
						CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,'',VLargo
						FROM @Trn_TraEspProgramaDet dp WHERE dp.TipDoc = @TipDocu and dp.Programa = @Programa and dp.IdCia = @CiaProg
						end
					END
					ELSE IF(@operacion = 'u')
					BEGIN
						select @itempgr =  isnull(MAX(Item),0) from Trn_TraEspProgramaDet where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia

						IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
						begin
						INSERT INTO Trn_TraEspProgramaDet(
						TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
						IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
						IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
						CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
						) 
						SELECT 
						@TipDoc, @Documento, @IdCia,(@itempgr + ROW_NUMBER() OVER(ORDER BY Item ASC)),FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
						IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
						IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
						CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,'',VLargo
						FROM @Trn_TraEspProgramaDet dp WHERE dp.TipDoc = @TipDocu and dp.Programa = @Programa and dp.IdCia = @CiaProg
						end
					END

					IF(@operacion = 'i')
					BEGIN
						IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaPers))
						begin
						INSERT INTO Trn_TraEspProgramaPers(
						TipDoc,Programa,IdCia,Item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
						) 
						SELECT 
						@TipDoc,@Documento,@IdCia,Item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
						FROM @Trn_TraEspProgramaPers pp WHERE pp.TipDoc = @TipDocu and pp.Programa = @Programa and pp.IdCia = @CiaProg
						end
					END
					ELSE IF(@operacion = 'u')
					BEGIN						
						IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaPers))
						begin
						INSERT INTO Trn_TraEspProgramaPers(
						TipDoc,Programa,IdCia,Item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
						) 
						SELECT 
						@TipDoc,@Documento,@IdCia,(@itempgr + Item),IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
						FROM @Trn_TraEspProgramaPers pp WHERE pp.TipDoc = @TipDocu and pp.Programa = @Programa and pp.IdCia = @CiaProg
						end
					END

					--ACTUALIZAR RESERVAS 
					declare @actReserva int
					declare @actCiaRes varchar(2)
					declare @actItem int

					DECLARE actres CURSOR
					FOR SELECT Reserva,IdCiaRes,ItemRes FROM @Trn_TraEspProgramaDet WHERE TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg
					OPEN actres
					FETCH NEXT FROM actres INTO @actReserva,@actCiaRes,@actItem
					WHILE @@FETCH_STATUS = 0
					BEGIN
						UPDATE Trn_TraEspResDetalle
						SET EstadoItem = 'PROGRAMADA'
						FROM Trn_TraEspResDetalle r
						WHERE  r.TipDoc = 'RES' and r.Reserva = @actReserva and r.IdCia = @actCiaRes and r.Item = @actItem
					FETCH NEXT FROM actres INTO @actReserva,@actCiaRes,@actItem
					END
					CLOSE actres
					DEALLOCATE actres

					----ACTUALIZAR VEHICULOS 
					declare @actTipDoc varchar(3)
					declare @actPrograma int
					declare @actCiaProg varchar(2)
					declare @actIdVeh varchar(10)

					DECLARE actveh CURSOR
					FOR SELECT IdVehiculo FROM @Trn_TraEspProgramaDet WHERE TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg and IdVehiculo != '0' 
					OPEN actveh
					FETCH NEXT FROM actveh INTO @actIdVeh
					WHILE @@FETCH_STATUS = 0
					BEGIN
						UPDATE Vehiculos
						SET IdEstado = '0002'
						FROM Vehiculos v
						WHERE v.IdVehiculo = @actIdVeh
					FETCH NEXT FROM actveh INTO @actIdVeh
					END
					CLOSE actveh
					DEALLOCATE actveh

				 END
				
				IF(@NumProc = @ItemProc)
				BEGIN
					select top 1 @observ = Observacion FROM @Trn_TraEspProgramaDet  WHERE TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg 
					INSERT INTO #LogPrograma(
					Numero,Fecha,EstadoProc,Observacion,TimeSys,IdUsuario,Nombre
					)
					SELECT 
					@NumProc,t1.Fecha,1,@observ,t1.TimeSys,t1.IdUsuario,u.Usuario
					FROM @Trn_TraEspPrograma as t1
					left join adm_Usuarios u on u.IdUsuario = t1.IdUsuario
					WHERE t1.TipDoc = @TipDocu and t1.Programa = @Programa and t1.IdCia = @CiaProg
				END
				
				--Se cambia el 28/12/2017 por orden del dueño.
				--select @IdVehiculo = SUBSTRING((SELECT ',' + cast(IdVehiculo as VARCHAR(max)) FROM @Trn_TraEspProgramaDet where TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg FOR XML PATH('')), 2 , 9999)
				--select @Reservas = SUBSTRING((SELECT ',' + cast(Reserva as VARCHAR(max)) FROM @Trn_TraEspProgramaDet where TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg FOR XML PATH('')), 2 , 9999)
				--select @ItemRes = SUBSTRING((SELECT ',' + cast(ItemRes as VARCHAR(max)) FROM @Trn_TraEspProgramaDet where TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg FOR XML PATH('')), 2 , 9999)
				--select @IdCiaRes = SUBSTRING((SELECT ',' + cast(IdCiaRes as VARCHAR(max)) FROM @Trn_TraEspProgramaDet where TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg FOR XML PATH('')), 2 , 9999)
				--select @FechaInicio = min(FechaInicio), @FechaFin = max(FechaFin)  from @Trn_TraEspProgramaDet where TipDoc = @TipDocu and Programa = @Programa and IdCia = @CiaProg
				
				--select @cantidad = count(*) from #LogProgDetalle
				--INSERT INTO #LogProgDetalle(
				--Numero,Item,TipDoc,Programa,IdCia,FechaIni,FechaFin,IdVehiculo,Reservas,IdCiaRes,ItemRes,Comentarios
				--)
				--SELECT 
				--@NumProc,(@ItemProc + dp.Item),@TipDoc,@Documento,@IdCia,dp.FechaInicio,dp.FechaFin,dp.IdVehiculo,dp.Reserva,dp.IdCiaRes,dp.ItemRes,dp.Observacion
				--FROM @Trn_TraEspProgramaDet dp WHERE dp.TipDoc = @TipDocu and dp.Programa = @Programa and dp.IdCia = @CiaProg

				SELECT @ItemProc = @ItemProc + 1

			FETCH NEXT FROM progcursor INTO @TipDocu,@Programa,@CiaProg
			END
			CLOSE progcursor
			DEALLOCATE progcursor

			SELECT * FROM #LogPrograma
			--SELECT * FROM #LogProgDetalle

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvTrn_DevFcr]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 24/04/2018
-- Description:	Insertar Trn_DevFcr
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMsvTrn_DevFcr]
	@Trn_DevFcr dataTypeTrn_DevFcr READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DevFcr
	@Trn_TraEspFacReservas dataTypeTrn_TraEspFacReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFacReservas
	@Trn_RecAfavor dataTypeTrn_RecAfavor READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_RecAfavor
	@Trn_VencAbonos dataTypeTrn_VencAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_VencAbonos
	@Trn_DocMemo dataTypeTrn_DocMemo READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DocMemo
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeNiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			
			CREATE TABLE #LogTraEspFacturas(
			Numero int NOT NULL DEFAULT ((0)),
			Fecha smalldatetime NOT NULL,
			EstadoProc int NOT NULL DEFAULT ((0)),
			Observacion varchar(250) NULL,
			TimeSys smalldatetime NOT NULL,
			IdUsuario varchar(11) NOT NULL,
			Nombre varchar(50) NOT NULL,
			Tipo varchar(10) NOT NULL
			)	
			
			CREATE TABLE #LogTraEspFacReservas(
			Numero int NOT NULL,
			Item int NOT NULL,
			TipFac varchar(3) NOT NULL,
			Factura int NOT NULL,
			IdCia char(2) NOT NULL,
			TipoReg int NOT NULL DEFAULT ((0)),
			FechaFact smalldatetime NOT NULL,
			TipRes varchar(3) NOT NULL DEFAULT ('RES'),
			Reserva int NOT NULL DEFAULT ((0)),
			IdCiaRes char(2) NOT NULL DEFAULT ('01'),
			ItemRes int NOT NULL DEFAULT ((0)),
			FecReserva smalldatetime NOT NULL,
			Descripcion varchar(250) NOT NULL,
			Cantidad decimal(14, 4) NOT NULL DEFAULT ((0)),
			VrServicio money NOT NULL DEFAULT ((0)),
			VrUnitario money NOT NULL DEFAULT ((0)),
			VrCosto money NOT NULL DEFAULT ((0)),
			TarifaIva decimal(14, 4) NOT NULL DEFAULT ((0)),
			VrImpuesto money NOT NULL DEFAULT ((0)),
			TarifaDct decimal(14, 4) NOT NULL DEFAULT ((0)),
			VrDescuento money NOT NULL DEFAULT ((0)),
			DocCliente varchar(30) NOT NULL,
			Referencia1 varchar(50) NULL,
			Referencia2 varchar(50) NULL,
			Referencia3 varchar(50) NULL,
			CdConcepto varchar(4) NOT NULL,
			CdCCosto varchar(16) NULL,
			CdSubCos varchar(16) NULL,
			NitTercero varchar(16) NOT NULL DEFAULT ('0'),
			CdAgencia varchar(16) NOT NULL DEFAULT ('0'),
			pVehiculo varchar(10) NOT NULL DEFAULT ('0'),
			TipoAfiVehic varchar(10) NOT NULL DEFAULT ('TERCEROS'),
			IdOrigen varchar(8) NOT NULL,
			IdDestino varchar(8) NOT NULL,
			Anulado int NOT NULL DEFAULT ((0)),
			TipDocRef varchar(3) NULL,
			NumDocRef int NOT NULL DEFAULT ((0)),
			IdCiaRef char(2) NULL DEFAULT ('01'),
			FecDocRef smalldatetime NULL,
			CodTarDct varchar(4) NULL,
			CodTarRet varchar(4) NULL,
			CodTarIca varchar(4) NULL,
			TarifaRet decimal(14, 4) NOT NULL,
			VrRetencion money NOT NULL,
			TarifaIca decimal(14, 4) NOT NULL,
			VrReteIca money NOT NULL,
			Comentarios varchar(max) NULL
			) 

			declare @NumProc int = 1
			declare @ItemProc int = 1
			declare @TipDev varchar(3)
			declare @Devolucion INT
			declare @IdCia varchar(2)
			declare @TipFac varchar(3)
			declare @Factura INT
			declare @IdCiaDoc varchar(2)
			declare @Fecha datetime
			declare @observ varchar(250)
			declare @IdCliente varchar(16)
			declare @VrNeto money
			DECLARE @modalidad varchar(10)
			declare @fecdev smalldatetime

			DECLARE dvfactcursor CURSOR
			FOR SELECT TipDev,Devolucion,IdCia,TipDoc,Factura,IdCiaDoc,Fecha,IdCliente,VrNeto,Modalidad FROM @Trn_DevFcr
			OPEN dvfactcursor
			FETCH NEXT FROM dvfactcursor INTO @TipDev,@Devolucion,@IdCia, @TipFac,@Factura,@IdCiaDoc,@fecdev,@IdCliente,@VrNeto,@modalidad
			WHILE @@FETCH_STATUS = 0
			BEGIN

				IF(@operacion = 'i')
				begin
			
					SELECT TOP 1 @TipDoc = @TipDev, @Cia = @IdCia, @IdCiaComp = @IdCia, @IdCiaCompNiif = @IdCia, @IdCiaCompFis = @IdCia
					
					SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

					IF(@Numero > 0)
						UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
					ELSE
					BEGIN
						SELECT @Numero = 1
						INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
					END

					IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
					BEGIN
						SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
						SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
						--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
						IF(@Comprobante <> '')
							UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
						ELSE
						BEGIN
							SELECT @Comprobante = 1
							INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
						END
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
					BEGIN
						SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
						SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
						--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
						IF(@CompNiif <> '')
							UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
						ELSE
						BEGIN
							SELECT @CompNiif = 1
							INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
						END
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
					BEGIN
						SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
						SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
						--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
						IF(@CompNiif <> '')
							UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
						ELSE
						BEGIN
							SELECT @CompFis = 1
							INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
						END
					END
				end

				IF(@operacion = 'i')
				begin
					IF(EXISTS(SELECT * FROM @Trn_DevFcr))
					BEGIN
					INSERT INTO Trn_DevFcr(
					TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,Factura,IdCiaDoc,FecDoc,IdCliente,IdAgencia,VrSubTotal,VrDescuento,VrImpuesto,
					VrRetencion,VrReteICA,VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,
					VrNeto,Cantidad,CantPuntos,BaseImp,BaseRet,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,IdLocEnv,Pedido,IdCiaPed,Remision,
					IdCiaRem,Cotizacion,IdCiaCot,FecPedido,Modalidad,ModdDev,PlacaVehic,KmtVehic,ZonaFrontera,OrigenAdd,TipCom,Comprobante,IdCiaCom,
					Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio,
					VrImpCarbono,DevMasivo,NumRecibo,CdCiaRec,CdMotDev,BaseIvaIgp,VrIvaIngProd
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Fecha,IdConcepto,TipDoc,Factura,IdCiaDoc,FecDoc,IdCliente,IdAgencia,VrSubTotal,VrDescuento,VrImpuesto,
					VrRetencion,VrReteICA,VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,
					VrNeto,Cantidad,CantPuntos,BaseImp,BaseRet,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,IdLocEnv,Pedido,IdCiaPed,Remision,
					IdCiaRem,Cotizacion,IdCiaCot,FecPedido,Modalidad,ModdDev,PlacaVehic,KmtVehic,ZonaFrontera,OrigenAdd,@TipComp,@Comprobante,@IdCiaComp,
					Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio,
					VrImpCarbono,DevMasivo,NumRecibo,CdCiaRec,CdMotDev,BaseIvaIgp,VrIvaIngProd
					FROM @Trn_DevFcr df WHERE df.TipDev = @TipDev and df.Devolucion = @Devolucion and df.IdCia = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_TraEspFacReservas))
					BEGIN
					INSERT INTO Trn_TraEspFacReservas(
					TipDoc,Factura,IdCia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
					TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
					pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
					TarifaIca,VrReteIca,EstadoItem
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
					TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
					pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
					TarifaIca,VrReteIca,EstadoItem
					FROM @Trn_TraEspFacReservas dfr WHERE dfr.TipDoc = @TipDev and dfr.Factura = @Devolucion and dfr.IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_RecAFavor))
					BEGIN
					INSERT INTO Trn_RecAFavor(
					TipDoc,Recibo,IdCia,Fecha,VrAFavor,VrOtrosDb,VrAbono,IdCliente,IdAgencia,IdVend
					)
					SELECT
					@TipDev,@Devolucion,@IdCia,Fecha,VrAFavor,VrOtrosDb,VrAbono,IdCliente,IdAgencia,IdVend
					FROM @Trn_RecAFavor ra WHERE ra.TipDoc = @TipDev and ra.Recibo = @Devolucion and ra.IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_VencAbonos))
					BEGIN
						declare @tiprec varchar(3)
						declare @recibo int
						declare @idciarec varchar(2)
						declare @item int 
						SELECT TOP 1 @tiprec = TipRec, @idciarec = IdCia, @recibo = Recibo FROM @Trn_VencAbonos va where va.TipDoc = @TipFac and va.Factura = @Factura and va.IdCiaFac = @IdCiaDoc
						select @item =  isnull(MAX(Item),0) from Trn_VencAbonos where TipRec = @tiprec and Recibo = @recibo and IdCia = @idciarec

						INSERT INTO Trn_VencAbonos(
						TipRec,Recibo,IdCia,Item,Fecha,TipDoc,Factura,IdCiaFac,ItemFac,VrAbono,VrDescto,
						VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
						)
						SELECT 
						@TipDoc,@Numero,@Cia,(@item + ROW_NUMBER() OVER(ORDER BY Item ASC)),Fecha,TipDoc,Factura,IdCiaFac,ItemFac,VrAbono,VrDescto,
						VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
						FROM @Trn_VencAbonos
					END 

					IF(EXISTS(SELECT * FROM @Trn_DetCuentas))
					BEGIN
					INSERT INTO Trn_DetCuentas(
					TipDoc,Documento,IdCia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
					VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
					VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
					FROM @Trn_DetCuentas dc WHERE dc.TipDoc = @TipDev and dc.Documento = @Devolucion and dc.IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_DocMemo))
					BEGIN
					INSERT INTO Trn_DocMemo(
					TipDoc,Documento,IdCia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
					FROM @Trn_DocMemo dm WHERE dm.TipDoc = @TipDev and dm.Documento = @Devolucion and dm.IdCia = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
					BEGIN
					INSERT INTO Trn_Comprobantes(
					TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
					NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
					TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
					VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
					Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
					PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
					CodRes, DescServicio
					)
					SELECT 
					@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
					NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
					TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
					VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
					Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
					PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
					CodRes, DescServicio
					FROM @Trn_Comprobantes cp WHERE cp.TipDoc = @TipDev and cp.Documento = @Devolucion and cp.IdCiaDoc = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
					BEGIN
					INSERT INTO Trn_ComDetalle(
					TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
					IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
					IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
					CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
					IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
					)
					SELECT 
					@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
					IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
					CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
					CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
					IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
					FROM @Trn_ComDetalle cd WHERE cd.TipDoc = @TipDev and cd.Documento = @Devolucion and cd.IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifComp))
					BEGIN
					INSERT INTO Trn_NiifComp(
					TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
					EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
					FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
					VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
					IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
					Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
					CtbTipo, CtbNumero,
					FisTipo, FisNumero 
					)
					SELECT 
					CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
					CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
					@Cia, 
					C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
					C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
					C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
					C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
					C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
					C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
					CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
					CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
					FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
					where C.TipDoc = @TipDev and C.Documento = @Devolucion and C.IdCia = @IdCia
					      and N.TipDoc = @TipDev and N.Documento = @Devolucion and N.IdCiaDoc = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
					BEGIN
					INSERT INTO Trn_NiifDetalle(
					TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
					VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
					VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
					NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
					CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
					DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
					CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
					FechAutoriza, CodCuentaCG
					)
					SELECT 
					CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
					CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
					@Cia,
					N.Item, N.Fecha, N.IdCuenta, N.Detalle,
					N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
					N.VrBase, N.TarifaBase, @TipDoc,@Numero,@Cia, N.CodConce,
					N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
					N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
					N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
					N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
					N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
					N.FechAutoriza, N.CodCuentaCG
					FROM @Trn_NiifDetalle as N
					JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante and NC.TipDoc = @TipDev and NC.Documento = @Devolucion and NC.IdCiaDoc = @IdCia
					where N.TipDoc = @TipDev and N.Documento = @Devolucion and N.IdCiaDoc = @IdCia		
					END

				end	

				IF(@operacion = 'i')
				begin
				  --actualiza los items de las reservas con los que se relacionan en el tipo de datos nuevo de las facturasreservas
				  UPDATE Trn_TraEspResDetalle
				  SET  Factura = 0, IdCiaFac = '00', FechaFac = null, EstadoItem = r.EstadoItem
				  FROM Trn_TraEspResDetalle d, @Trn_TraEspFacReservas r 
				  WHERE d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCia and d.Item = r.ItemRes

				  --ACTUALIZAR FACTURA
				  IF(UPPER(@modalidad) = 'TOTAL')
				  BEGIN 
					  UPDATE Trn_Facturas
					  SET Anulado = 1,NumDev = @Numero,FecDev = @fecdev
					  FROM Trn_Facturas F, @Trn_DevFcr DF
					  WHERE F.TipDoc = DF.TipDoc AND F.Factura = DF.Factura AND F.IdCia = DF.IdCiaDoc
				  END

				  --actualiza el cliente
				  UPDATE TercCliente
				  SET  VrSaldo = c.VrSaldo - f.VrNeto
				  FROM TercCliente c, @Trn_DevFcr f
				  WHERE c.IdClie = f.IdCliente

				  --actualizar vencimientos,cuando es necesario
				  IF(EXISTS(SELECT * FROM @Trn_VencAbonos))
				  BEGIN 
					 UPDATE Trn_Vencimientos
					 SET  VrAbonado = v.VrAbonado + dv.VrAbono
					 FROM Trn_Vencimientos v, @Trn_VencAbonos dv
					 WHERE v.TipDoc = dv.TipDoc and v.Factura = dv.Factura and v.IdCia = dv.IdCiaFac
				  END

				end

				IF(@NumProc = @ItemProc)
				BEGIN
					select top 1 @observ = Observacion FROM @Trn_DevFcr  WHERE TipDoc = @TipDev and Devolucion = @Devolucion and IdCia = @IdCia
					INSERT INTO #LogTraEspFacturas(
					Numero,Fecha,EstadoProc,Observacion,TimeSys,IdUsuario,Nombre,Tipo
					)
					SELECT 
					@NumProc,t1.Fecha,1,@observ,t1.TimeSys,t1.IdUsuario,u.Usuario,'DEVOLUCION'
					FROM @Trn_DevFcr as t1
					left join adm_Usuarios u on u.IdUsuario = t1.IdUsuario
					WHERE t1.TipDev = @TipDev and t1.Devolucion = @Devolucion and t1.IdCia = @IdCia
				END

				SELECT @ItemProc = @ItemProc + 1
				
				INSERT INTO #LogTraEspFacReservas(
				Numero,Item,TipFac,Factura,IdCia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
				TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
				pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
				TarifaIca,VrReteIca,Comentarios
				)
				SELECT
				@NumProc,@item,TipDoc,Factura,IdCia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
				TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
				pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
				TarifaIca,VrReteIca,EstadoItem
				FROM Trn_TRaEspFAcReservas where TipDoc = @TipDoc and Factura = @Factura and IdCia = @IdCia

			FETCH NEXT FROM dvfactcursor INTO @TipDev,@Devolucion,@IdCia, @TipFac,@Factura,@IdCiaDoc,@fecdev,@IdCliente,@VrNeto,@modalidad
			END
			CLOSE dvfactcursor
			DEALLOCATE dvfactcursor
			
			SELECT * FROM #LogTraEspFacturas
			SELECT * FROM #LogTraEspFacReservas

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsMsvTrn_Facturas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 04/04/2018
-- Description:	Insertar Masivo de Facturas
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsMsvTrn_Facturas]
	@Trn_Facturas dataTypeTrn_Facturas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Facturas
	@Trn_TraEspFacReservas dataTypeTrn_TraEspFacReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFacReservas
	@Trn_TraEspFacResVehiculos dataTypeTrn_TraEspFacResVehiculos readonly,
	@Trn_DocMemo dataTypeTrn_DocMemo READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DocMemo
	@Trn_TraEspAuxFactura dataTypeTrn_TraEspAuxFactura READONLY,
	@Trn_RecAfavor dataTypeTrn_RecAfavor READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_RecAfavor
	@Trn_VencAbonos dataTypeTrn_VencAbonos READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_VencAbonos
	@Trn_Vencimientos dataTypeTrn_Vencimientos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Vencimientos
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas
	
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifCompFMsv READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif CHAR(2) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis CHAR(2) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CodigoPre VARCHAR(3)
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
declare @FechaFac smalldatetime
	BEGIN TRAN
		BEGIN TRY	
		
			--CREATE TABLE #LogTraEspFacturas(
			--Numero int NOT NULL DEFAULT ((0)),
			--Fecha smalldatetime NOT NULL,
			--EstadoProc int NOT NULL DEFAULT ((0)),
			--Observacion varchar(250) NULL,
			--TimeSys smalldatetime NOT NULL,
			--IdUsuario varchar(11) NOT NULL,
			--Nombre varchar(50) NOT NULL,
			--Tipo varchar(10) NOT NULL
			--)	
			
			CREATE TABLE #LogTraEspFacReservas(
			NewTipFac varchar(3) NOT NULL,
			NewFactura int NOT NULL,
			NewIdCiaFac char(2) NOT NULL,
			OldTipFac varchar(3) NOT NULL,
			OldFactura int NOT NULL,
			OldIdCiaFac char(2) NOT NULL,
			) 

			declare @NumProc int = 1
			declare @ItemProc int = 1
			declare @TipFac varchar(3)
			declare @Factura INT
			declare @IdCia varchar(2)
			declare @Fecha datetime
			declare @observ varchar(250)
			declare @IdCliente varchar(16)
			declare @VrNeto money

			DECLARE factcursor CURSOR
			FOR SELECT TipDoc,Factura,IdCia,Fecha,IdCliente,VrNeto FROM @Trn_Facturas
			OPEN factcursor
			FETCH NEXT FROM factcursor INTO @TipFac,@Factura,@IdCia,@Fecha,@IdCliente,@VrNeto
			WHILE @@FETCH_STATUS = 0
			BEGIN
				IF(@operacion = 'i')
				BEGIN
					SET @TipDoc = @TipFac
					SET @Cia = @IdCia
					SET @IdCiaComp = @IdCia
					SET @IdCiaCompNiif = @IdCia
					SET @IdCiaCompFis = @IdCia
					SET @FechaFac = @Fecha 
				
					SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

					IF(@Numero > 0)
						UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
					ELSE
					BEGIN
						SELECT @Numero = 1
						INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
					END

					IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
					BEGIN
						SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
						SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
						--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
						IF(@Comprobante <> '')
							UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
						ELSE
						BEGIN
							SELECT @Comprobante = 1
							INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
						END
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF' AND Documento = @Factura))
					BEGIN
						SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
						SELECT @CompNiif = (Numero + 1) FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
						
						--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
						IF(@CompNiif > 0)
						BEGIN
							--declare @bcpCommand varchar(255), @Result int
							--declare @FileName varchar(255)
							--set @FileName ='D:\hola.txt'
							--set @bcpCommand = 'bcp "Select 1 as a" queryout "' + @FileName + '" -c -t, -T -S '

							--exec @Result = master..xp_cmdshell @bcpCommand, no_output
							UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
						END
						ELSE
						BEGIN
							SELECT @CompNiif = 1
							INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
						END
					END
					IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL' AND Documento = @Factura))
					BEGIN
						SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
						SELECT @CompFis = (Numero + 1) FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
						--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
						IF(@CompFis > 0)
						BEGIN
							UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
						END
						ELSE
						BEGIN
							SELECT @CompFis = 1
							INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
						END
					END
	
					IF(EXISTS(SELECT * FROM @Trn_Facturas))
					BEGIN
						INSERT INTO Trn_Facturas(
						TipDoc, Factura, IdCia, Fecha, IdConcepto, IdCliente, IdAgencia, FechaVence, VrSubTotal, VrDescuento, VrImpuesto, VrRetencion, VrReteICA, VrReteIVA, VrFletes, VrOtros, 
						VrCargos, VrOtrDcto, VrCostos, VrSobretasa, VrImpGlobal, VrFaltantes, VrAnticipos, VrNeto, VrAplicado, Cantidad, CantPuntos, PuntosAcum, BaseImp, BaseRet, BaseIca, 
						BaseRiv, TarifaIva, TarifaRet, TarifaIca, TarifaRiv, CodTarIva, CodTarRet, CodTarIca, CodTarRiv, IdCCosto, IdSubCos, IdVend, TarifaCom, CodTarCom, DirEnvio, IdLocEnv, 
						DiasEntraga, NitContac, NomContac, TelContac, emlContac, CargoContac, IdForma, DetallePago, MulPlazos, IdPlazo, CdMney, NitEmpTrans, EmpTrans, pVehiculo, CdConductor, 
						CdRuta, TipPed, Pedido, IdCiaPed, TipRem, Remision, IdCiaRem, TipCot, Cotizacion, IdCiaCot, FecPedido, AutzaMora, AutzaCupo, Modalidad, KmtVehic, ZonaFrontera, PesoTotal, 
						UnidTotal, VolTotal, CantFalt, VrCostoRem, VrCostoAfi, CodAutoRet, OrigenAdd, TipCom, Comprobante, IdCiaCom, Anulado, NumDev, FecDev, Observacion, IdEstado, TimeSys, 
						FecUpdate, IdCiaCrea, IdUsuario, VrImpCons, VrReteCREE, TarifaRtc, CodTarRtc, Parqueadero, FecCuotaParq, BaseIvaObsq, VrIvaObsequio, VrImpCarbono, TipoFE, FechaFE, 
						BaseIvaIgp, VrIvaIngProd
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Fecha,IdConcepto,IdCliente,IdAgencia,FechaVence,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,VrReteICA,VrReteIVA,VrFletes,VrOtros,
						VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,VrNeto,VrAplicado,Cantidad,CantPuntos,PuntosAcum,BaseImp,BaseRet,BaseIca,
						BaseRiv,TarifaIva,TarifaRet,TarifaIca,TarifaRiv,CodTarIva,CodTarRet,CodTarIca,CodTarRiv,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,DirEnvio,IdLocEnv,
						DiasEntraga,NitContac,NomContac,TelContac,emlContac,CargoContac,IdForma,DetallePago,MulPlazos,IdPlazo,CdMney,NitEmpTrans,EmpTrans,pVehiculo,CdConductor,
						CdRuta,TipPed,Pedido,IdCiaPed,TipRem,Remision,IdCiaRem,TipCot,Cotizacion,IdCiaCot,FecPedido,AutzaMora,AutzaCupo,Modalidad,KmtVehic,ZonaFrontera,PesoTotal,
						UnidTotal,VolTotal,CantFalt,VrCostoRem,VrCostoAfi,CodAutoRet,OrigenAdd,@TipComp,@Comprobante,@IdCiaComp,Anulado,NumDev,FecDev,Observacion,IdEstado,TimeSys,
						FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,Parqueadero,FecCuotaParq,BaseIvaObsq,VrIvaObsequio,VrImpCarbono,TipoFE,FechaFE,
						BaseIvaIgp,VrIvaIngProd
						FROM @Trn_Facturas p WHERE p.TipDoc = @TipFac and p.Factura = @Factura and p.IdCia = @IdCia
					END
					 
					IF(EXISTS(SELECT * FROM @Trn_TraEspFacReservas))
					BEGIN
						INSERT INTO Trn_TraEspFacReservas(
						TipDoc,Factura,IdCia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
						TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
						pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
						TarifaIca,VrReteIca,EstadoItem
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
						TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
						pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
						TarifaIca,VrReteIca,EstadoItem
						FROM @Trn_TraEspFacReservas p WHERE p.TipDoc = @TipFac and p.Factura = @Factura and p.IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_TraEspFacResVehiculos))
					BEGIN
						INSERT INTO Trn_TraEspFacResVehiculos(
						TipDoc,Factura,IdCIa,Item,TipRes,Reserva,IdCIaRes,ItemRes,IdVehiculo,TipoAfil,VrRecorrido
						)
						SELECT
						@TipDoc,@Numero,@Cia,Item,TipRes,Reserva,IdCIaRes,ItemRes,IdVehiculo,TipoAfil,VrRecorrido
						FROM @Trn_TraEspFacResVehiculos p WHERE p.TipDoc = @TipFac and p.Factura = @Factura and p.IdCia = @IdCia 
					END

					IF(EXISTS(SELECT * FROM @Trn_Vencimientos))
					BEGIN
						INSERT INTO Trn_Vencimientos(
						TipDoc,Factura,IdCia,Item,Fecha,FechaVence,VrFactura,VrAbonado,IdCliente,IdAgencia,IdVend,Comision,TarifDcto,
						TipoDcto,TipoBase,FecLmtDcto,IdConcepto,Referencia,Detalle,TipRef,DocRef,IdCiaRef,FecUltPago,NumNota,IdCiaNot,
						TarifInt,FecLiqMora,FecPlazoCal
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Item,Fecha,FechaVence,VrFactura,VrAbonado,IdCliente,IdAgencia,IdVend,Comision,TarifDcto,
						TipoDcto,TipoBase,FecLmtDcto,IdConcepto,Referencia,Detalle,TipRef,DocRef,IdCiaRef,FecUltPago,NumNota,IdCiaNot,
						TarifInt,FecLiqMora,FecPlazoCal
						FROM @Trn_Vencimientos p WHERE p.TipDoc = @TipFac and p.Factura = @Factura and p.IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_DocMemo))
					BEGIN
					INSERT INTO Trn_DocMemo(
						TipDoc,Documento,IdCia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
						FROM @Trn_DocMemo p WHERE p.TipDoc = @TipFac and p.Documento = @Factura and p.IdCia = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_TraEspAuxFactura))
					BEGIN
						INSERT INTO Trn_TraEspAuxFactura(
						TipFac,Factura,IdCiaFac,Resolucion,Rango,FechaResl,Prefijo,TipDocPf,PreFactura,IdCiaPf,CodigoPreFact
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Resolucion,Rango,FechaResl,Prefijo,TipDocPf,PreFactura,IdCiaPf,CodigoPreFact
						FROM @Trn_TraEspAuxFactura p WHERE p.TipFac = @TipFac and p.Factura = @Factura and p.IdCiaFac = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_RecAfavor))
					BEGIN
						update Trn_RecAfavor
						set VrAbono = t1.VrAbono + t2.VrAbono
						from Trn_RecAfavor t1, @Trn_RecAfavor t2
						where t1.TipDoc = t2.TipDoc and t1.Recibo = t2.Recibo and t1.IdCia = t2.IdCia and t1.IdCliente = t2.IdCliente and t1.IdAgencia = t2.IdAgencia and t1.IdVend = t2.IdVend
							--and TipDoc = @TipDoc and t1.Factura = @Factura and t1.IdCia = @IdCia
					END 

					IF(EXISTS(SELECT * FROM @Trn_VencAbonos))
					BEGIN
						declare @tiprec varchar(3)
						declare @recibo int
						declare @idciarec varchar(2)
						declare @item int 
						SELECT TOP 1 @tiprec = TipRec, @idciarec = IdCia, @recibo = Recibo FROM @Trn_VencAbonos WHERE TipDoc = @TipFac and Factura = @Factura and IdCiaFac = @IdCia
						
						if((@tiprec <> null and @tiprec <> '') and @recibo > 0)
						BEGIN
							SELECT @item =  isnull(MAX(Item),0) FROM Trn_VencAbonos WHERE TipRec = @tiprec and Recibo = @recibo and IdCia = @idciarec

							INSERT INTO Trn_VencAbonos(
							TipRec,Recibo,IdCia,Item,Fecha,TipDoc,Factura,IdCiaFac,ItemFac,VrAbono,VrDescto,
							VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
							)
							SELECT 
							TipRec,Recibo,IdCia,(@item + ROW_NUMBER() OVER(ORDER BY Item ASC)),Fecha,@TipDoc,@Numero,@Cia,ItemFac,VrAbono,VrDescto,
							VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
							FROM @Trn_VencAbonos WHERE TipDoc = @TipFac and Factura = @Factura and IdCiaFac = @IdCia

							IF(EXISTS(SELECT * FROM @Trn_RecAfavor))
							BEGIN
								UPDATE Trn_RecAfavor
								SET VrAbono = t1.VrAbono + t2.VrAbono
								FROM Trn_RecAfavor t1
								JOIN(SELECT ra.TipDoc,ra.Recibo,ra.IdCia,ra.Fecha,ra.VrAFavor,ra.VrOtrosDb,ra.VrAbono,ra.IdCliente,ra.IdAgencia,ra.IdVend FROM @Trn_RecAfavor ra
										JOIN @Trn_VencAbonos va on ra.TipDoc = va.TipRec and ra. Recibo = va.Recibo and ra.IdCia = va.IdCia
										WHERE va.TipDoc = @TipFac and va.Factura = @Factura and va.IdCiaFac = @IdCia) AS t2
								ON t1.TipDoc = t2.TipDoc and t1.Recibo = t2.Recibo and t1.IdCia = t2.IdCia and t1.IdCliente = t2.IdCliente and t1.IdAgencia = t2.IdAgencia and t1.IdVend = t2.IdVend
							END
						END
					END 

					IF(EXISTS(SELECT * FROM @Trn_DetCuentas))
					BEGIN
						INSERT INTO Trn_DetCuentas(
						TipDoc,Documento,IdCia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
						VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
						)
						SELECT 
						@TipDoc,@Numero,@Cia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
						VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
						FROM @Trn_DetCuentas where TipDoc = @TipFac and Documento = @Factura and IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
					BEGIN
						INSERT INTO Trn_Comprobantes(
						TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
						NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
						TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
						VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
						Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
						PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
						CodRes, DescServicio
						)
						SELECT 
						@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
						NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
						TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
						VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
						Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
						PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
						CodRes, DescServicio
						FROM @Trn_Comprobantes where TipDoc = @TipFac and Documento = @Factura and IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
					BEGIN
						INSERT INTO Trn_ComDetalle(
						TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
						IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
						IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
						NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
						CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
						IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
						)
						SELECT 
						@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
						IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
						CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
						NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
						CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
						IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
						FROM @Trn_ComDetalle where TipDoc = @TipFac and Documento = @Factura and IdCia = @IdCia
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF' AND Documento = @Factura))
					BEGIN
						INSERT INTO Trn_NiifComp(
						TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
						EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
						FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
						VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
						IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
						Tipo_Pago, Establec, PEmision, Autorizac,FechaAut, CtbTipo, CtbNumero, FisTipo, FisNumero 
						)
						SELECT 
						@TipCompNiif, @CompNiif, @IdCia,C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
						C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @IdCia, C.Anulado, C.NumDev,
						C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
						C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
						C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
						C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut, @TipCompNiif, @CompNiif, NULL, 0
						FROM @Trn_NiifComp  AS N 
						JOIN  @Trn_Comprobantes AS C ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
						WHERE C.Documento = N.Documento AND N.Documento = @Factura AND N.TipoNiif = 'NIIF'

						IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
						BEGIN
							INSERT INTO Trn_NiifDetalle(
							TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
							VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
							VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
							NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
							NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
							CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
							DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
							CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
							FechAutoriza, CodCuentaCG
							)
							SELECT 
							@TipCompNiif, @CompNiif, @IdCia, N.Item, N.Fecha, N.IdCuenta, N.Detalle,
							N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
							N.VrBase, N.TarifaBase, @TipDoc,@Numero,@IdCia, N.CodConce,
							N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
							N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
							N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
							N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
							N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
							N.FechAutoriza, N.CodCuentaCG
							FROM @Trn_NiifComp  as NC
							JOIN @Trn_NiifDetalle AS N ON N.Comprobante = NC.ComprobanteCont  AND N.TipCom = @TipCompNiif
							--AND NC.TipoNiif = 'NIIF' 
							where N.Documento = @Factura  AND N.Documento = NC.Documento AND NC.TipoNiif = 'NIIF' 
						END
					END

					IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL' AND Documento = @Factura))
					BEGIN
						INSERT INTO Trn_NiifComp(
						TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
						EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
						FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
						VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
						IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
						Tipo_Pago, Establec, PEmision, Autorizac,FechaAut, CtbTipo, CtbNumero, FisTipo, FisNumero 
						)
						SELECT 
						@TipCompFis, @CompFis, @IdCia,C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
						C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @IdCia, C.Anulado, C.NumDev,
						C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
						C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
						C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
						C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut, @TipCompFis, @CompFis, NULL, 0
						FROM @Trn_NiifComp  AS N 
						JOIN  @Trn_Comprobantes AS C ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
						WHERE C.Documento = N.Documento AND N.Documento = @Factura AND N.TipoNiif = 'FISCAL'

						IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
						BEGIN
							INSERT INTO Trn_NiifDetalle(
							TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
							VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
							VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
							NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
							NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
							CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
							DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
							CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
							FechAutoriza, CodCuentaCG
							)
							SELECT 
							@TipCompFis, @CompFis, @IdCia, N.Item, N.Fecha, N.IdCuenta, N.Detalle,
							N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
							N.VrBase, N.TarifaBase, @TipDoc,@Numero,@IdCia, N.CodConce,
							N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
							N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
							N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
							N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
							N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
							N.FechAutoriza, N.CodCuentaCG
							FROM @Trn_NiifComp as NC
							JOIN @Trn_NiifDetalle AS N ON N.Comprobante = NC.ComprobanteCont  AND N.TipCom = @TipCompFis
							--AND NC.TipoNiif = 'FISCAL' 
							where N.Documento = @Factura AND N.Documento = NC.Documento AND NC.TipoNiif = 'FISCAL' 
						END
					END
					
					--actualiza los items de las reservas con los que se relacionan en el tipo de datos nuevo de las facturasreservas
					DECLARE @TipRes VARCHAR(3) 
					DECLARE @CiaRes VARCHAR(2) 
					DECLARE @NumRes INT 
					DECLARE @ItemRes INT
					DECLARE @Ref VARCHAR(50) 
					DECLARE @reserva Int = 0 
					DECLARE @cantres Int = 0 
					DECLARE @cantresfact Int = 0 

					DECLARE faccursor CURSOR
					FOR SELECT TipRes,Reserva,IdCiaRes,ItemRes, Referencia1 FROM @Trn_TraEspFacReservas where TipDoc = @TipFac and Factura = @Factura and IdCia = @IdCia
					OPEN faccursor
					FETCH NEXT FROM faccursor INTO @TipRes,@NumRes,@CiaRes,@ItemRes, @Ref
					WHILE @@FETCH_STATUS = 0
					BEGIN
						IF(@Ref = 'CLIENTE')
						BEGIN
							UPDATE Trn_TraEspResDetalle
							SET  TipFac = @TipDoc, Factura = @Numero, IdCiaFac = @IdCia, FechaFac = @FechaFac, EstadoItem = 'FACTURADA'
							FROM Trn_TraEspResDetalle d
							WHERE d.TipDoc = @TipRes  and d.Reserva = @NumRes and d.IdCia = @CiaRes and d.Item = @ItemRes
						END
						IF (@NumRes <> @reserva)
						BEGIN
						SET @reserva = @NumRes
						
						SELECT @cantres = count(*)
						FROM Trn_TraEspResDetalle AS rd
						WHERE rd.TipDoc = @TipRes  and rd.Reserva = @NumRes and rd.IdCia = @CiaRes

						SELECT @cantresfact = count(*)
						FROM Trn_TraEspResDetalle AS rd
						WHERE rd.TipDoc = @TipRes  and rd.Reserva = @NumRes and rd.IdCia = @CiaRes and rd.EstadoItem = 'FACTURADA'
						
						IF (@cantresfact = @cantres)
						BEGIN
							UPDATE Trn_TraEspReservas 
							SET EstadoRes = 'FACTURADA' 
							WHERE TipDoc = @TipRes  and Reserva = @NumRes and IdCia = @CiaRes                     
						END
						END
				  
					FETCH NEXT FROM faccursor INTO @TipRes,@NumRes,@CiaRes,@ItemRes,@Ref
					END
					CLOSE faccursor
					DEALLOCATE faccursor

					--actualizar el cliente de cada factura
					UPDATE TercCliente
					SET  VrSaldo = c.VrSaldo + @VrNeto
					FROM TercCliente c
					WHERE c.IdClie = @IdCliente

					--Tabla a Deovler para los nuevos numeros de factura
					INSERT INTO #LogTraEspFacReservas(NewTipFac,NewFactura,NewIdCiaFac,OldTipFac,OldFactura,OldIdCiaFac)
					SELECT @TipDoc,@Numero,@Cia,@TipFac, @Factura, @IdCia
				END
			FETCH NEXT FROM factcursor INTO @TipFac,@Factura,@IdCia,@Fecha,@IdCliente,@VrNeto
			END
			CLOSE factcursor
			DEALLOCATE factcursor

			--SELECT * FROM #LogTraEspFacturas
			SELECT * FROM #LogTraEspFacReservas
			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsOtroSiFromCOE]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa Castañeda
-- Create date(dd/MM/yyy): 23/07/2019
-- Description:	CRUD Adicionar OtroSi en Contrato Detalle.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsOtroSiFromCOE]
	@Trn_TraEspContratos dataTypeTrn_TraEspContratos READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOtroSiContratos
	@Trn_TraEspContratoDet dataTypeTrn_TraEspContratoDet READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspEspDetalle
	@operacion varchar(1)
AS
DECLARE @IdOtroSi INT --Esta variable guarda el número de consecutivo del otrosí
DECLARE @Contrato INT --Esta variable guarda el número de consecutivo del contrato a quien se le ha insertado un OtroSí
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de contrato a quien se le ha insertado un OtroSí
DECLARE @IdCia VARCHAR(2) --Esta variable guarda la cía de contrato a quien se le ha insertado un OtroSí
DECLARE @VrAdicion DECIMAL --Esta variable guarda el valor a adicionar al contrato a quien se le ha insertado un OtroSí
DECLARE @FechaFinNew SMALLDATETIME --Esta variable guarda el valor dela nueva fecha del contrato a quien se le ha insertado un OtroSí
DECLARE @Item INT --Esta variable guarda el número de consecutivo del Item contrato a quien se le ha insertado un OtroSí
DECLARE @VrCobro DECIMAL --Esta variable actualiza el valor a cobrar al contrato a quien se le ha insertado un OtroSí
--declare @item int
	BEGIN TRAN
		BEGIN TRY
		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			BEGIN
				SELECT @TipDoc= TipDoc, @Contrato = Contrato, @IdCia = IdCia From @Trn_TraEspContratos
				IF(EXISTS(SELECT * FROM @Trn_TraEspContratoDet))
				begin
					SET @VrCobro = (select (sum(VrDia * DiasDisp) + sum(VrMonitor * CantMonitor) + sum(VrUnitario)) FROM @Trn_TraEspContratoDet)
				end
				-- --Actualizar contrato
				UPDATE Trn_TraEspContratos SET VrCobro = VrCobro + ISNULL(@VrCobro, 0)
				WHERE TipDoc = @TipDoc AND Contrato = @Contrato and IdCia = @IdCia
				--AgrergarItems de Contrato Detalle
				IF(EXISTS(SELECT * FROM @Trn_TraEspContratoDet))
				begin
					SELECT TOP 1 @IdOtroSi = IdOtroSi FROM @Trn_TraEspContratoDet
					SET @Item = (select max(Item) from trn_traespcontratodet where TipDoc = @TipDoc AND contrato = @Contrato AND idcia = @IdCia)
					INSERT INTO Trn_TraEspContratoDet(
					TipDoc,Contrato,IdCia,Item,IdHorario,TipPed,Pedido,CiaPed,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
					Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
					DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,IdOtroSi,ItemAnuladoOS,
					EsItemPME
					) 
					SELECT --(Item + @Item)
					@TipDoc,@Contrato,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)),IdHorario,TipPed,Pedido,@IdCia,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
					Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
					DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,IdOtroSi,ItemAnuladoOS,
					EsItemPME
					FROM @Trn_TraEspContratoDet
				end
				--Cerrar el OtroSí
				UPDATE Trn_TraEspOtroSi SET Aplicado = 1 WHERE IdOtroSi = @IdOtroSi
			 END
			SELECT '1' 

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsPreFacturas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 26/01/2018
-- Description:	Insertar PreFacturas
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsPreFacturas]
	@Trn_Facturas dataTypeTrn_Facturas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Facturas
	@Trn_TraEspFacReservas dataTypeTrn_TraEspFacReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFacReservas
	@Trn_TraEspFacResVehiculos dataTypeTrn_TraEspFacResVehiculos readonly,
	@Trn_DocMemo dataTypeTrn_DocMemo READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DocMemo
	@Trn_TraEspAuxFactura dataTypeTrn_TraEspAuxFactura READONLY,
	@Trn_RecAfavor dataTypeTrn_RecAfavor READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_RecAfavor
	@Trn_VencAbonos dataTypeTrn_VencAbonos READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_VencAbonos
	@Trn_Vencimientos dataTypeTrn_Vencimientos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Vencimientos
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas
	
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @TipDocPre VARCHAR(3)
DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
declare @FechaFac smalldatetime
declare @OpcUco VARCHAR
	BEGIN TRAN
		BEGIN TRY		 
			
			IF(@operacion = 'i')
			BEGIN
				--OPCION DE UNIFICAR CONSECUTIVOS DE PREFACTURAS CON LAS FACTURAS
				SELECT @OpcUco  = Valor FROM adm_Opciones WHERE IdOpc = 'UCO' 
				IF(@OpcUco = '1')
					SELECT @TipDocPre = TipDoc, @TipDoc = CodigoPreFact FROM @Trn_Facturas
				ELSE 
					SELECT @TipDocPre = TipDoc, @TipDoc = TipDoc FROM @Trn_Facturas
				----

				SELECT TOP 1  @Cia = IdCia, @FechaFac = Fecha FROM @Trn_Facturas
				SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

				IF(@Numero > 0)
				BEGIN
					IF(@OpcUco = '1')
					begin
						UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
						UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDocPre AND IdCia = @Cia
					end
					else
						UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDocPre AND IdCia = @Cia
				END
				ELSE
				BEGIN
					SELECT @Numero = 1
					IF(@OpcUco = '1')
					begin
						INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
						INSERT INTO TiposDocCons VALUES (@TipDocPre,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
					end
					else
						INSERT INTO TiposDocCons VALUES (@TipDocPre,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			
				IF(EXISTS(SELECT * FROM @Trn_Facturas))
				BEGIN
				INSERT INTO Trn_Facturas(
				TipDoc,Factura,IdCia,Fecha,IdConcepto,IdCliente,IdAgencia,FechaVence,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,VrReteICA,
				VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,VrNeto,VrAplicado,Cantidad,
				CantPuntos,PuntosAcum,BaseImp,BaseRet,BaseIca,BaseRiv,TarifaIva,TarifaRet,TarifaIca,TarifaRiv,CodTarIva,CodTarRet,CodTarIca,
				CodTarRiv,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,DirEnvio,IdLocEnv,DiasEntraga,NitContac,NomContac,TelContac,emlContac,
				CargoContac,IdForma,DetallePago,MulPlazos,IdPlazo,CdMney,NitEmpTrans,EmpTrans,pVehiculo,CdConductor,CdRuta,TipPed,Pedido,IdCiaPed,
				TipRem,Remision,IdCiaRem,TipCot,Cotizacion,IdCiaCot,FecPedido,AutzaMora,AutzaCupo,Modalidad,KmtVehic,ZonaFrontera,PesoTotal,
				UnidTotal,VolTotal,CantFalt,VrCostoRem,VrCostoAfi,CodAutoRet,OrigenAdd,TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,
				IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,Parqueadero,FecCuotaParq,BaseIvaObsq,VrIvaObsequio,
				VrImpCarbono,TipoFE,FechaFE,BaseIvaIgp,VrIvaIngProd 
				)
				SELECT
				@TipDocPre,@Numero,@Cia,Fecha,IdConcepto,IdCliente,IdAgencia,FechaVence,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,VrReteICA,
				VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,VrNeto,VrAplicado,Cantidad,
				CantPuntos,PuntosAcum,BaseImp,BaseRet,BaseIca,BaseRiv,TarifaIva,TarifaRet,TarifaIca,TarifaRiv,CodTarIva,CodTarRet,CodTarIca,
				CodTarRiv,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,DirEnvio,IdLocEnv,DiasEntraga,NitContac,NomContac,TelContac,emlContac,
				CargoContac,IdForma,DetallePago,MulPlazos,IdPlazo,CdMney,NitEmpTrans,EmpTrans,pVehiculo,CdConductor,CdRuta,TipPed,Pedido,IdCiaPed,
				TipRem,Remision,IdCiaRem,TipCot,Cotizacion,IdCiaCot,FecPedido,AutzaMora,AutzaCupo,Modalidad,KmtVehic,ZonaFrontera,PesoTotal,
				UnidTotal,VolTotal,CantFalt,VrCostoRem,VrCostoAfi,CodAutoRet,OrigenAdd,TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,
				IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,Parqueadero,FecCuotaParq,BaseIvaObsq,VrIvaObsequio,
				VrImpCarbono,TipoFE,FechaFE,BaseIvaIgp,VrIvaIngProd 
				FROM @Trn_Facturas
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspFacReservas))
				BEGIN
				INSERT INTO Trn_TraEspFacReservas(
				TipDoc,Factura,IdCia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
				TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
				pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
				TarifaIca,VrReteIca,EstadoItem
				)
				SELECT 
				@TipDocPre,@Numero,@Cia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
				TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
				pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
				TarifaIca,VrReteIca,EstadoItem
				FROM @Trn_TraEspFacReservas
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspFacResVehiculos))
				BEGIN
				INSERT INTO Trn_TraEspFacResVehiculos(
				TipDoc,Factura,IdCIa,Item,TipRes,Reserva,IdCIaRes,ItemRes,IdVehiculo,TipoAfil,VrRecorrido
				)
				SELECT
				@TipDocPre,@Numero,@Cia,Item,TipRes,Reserva,IdCIaRes,ItemRes,IdVehiculo,TipoAfil,VrRecorrido
				FROM @Trn_TraEspFacResVehiculos
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspAuxFactura))
				BEGIN
				INSERT INTO Trn_TraEspAuxFactura(
				TipFac,Factura,IdCiaFac,Resolucion,Rango,FechaResl,Prefijo,TipDocPf,PreFactura,IdCiaPf,CodigoPreFact
				)
				SELECT 
				@TipDocPre,@Numero,@Cia,Resolucion,Rango,FechaResl,Prefijo,TipDocPf,PreFactura,IdCiaPf,CodigoPreFact
				FROM @Trn_TraEspAuxFactura
				END 
			END	

			SELECT @Numero

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsRutas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 12/05/2016
-- Description:	Insertar/Actualizar/Eliminar Rutas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsRutas]
	@Rutas dataTypeRutas READONLY, 
	--@RutasPlan dataTypeRutasPlan READONLY,
	--@RutasTramos dataTypeRutasTramos READONLY,
	@RutasRecorridos dataTypeRutasRecorridos READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 
		 CREATE TABLE #rutas(
		 IdRuta		VARCHAR (20)		NOT NULL,
		 Ruta		VARCHAR (100)	NOT NULL,
		 IdLocOri	VARCHAR (8)		NOT NULL,
		 IdLocDes	VARCHAR (8)		NOT NULL,
		 EsLocal	BIT				DEFAULT ((0)) NOT NULL,
		 Distkmt	DECIMAL (14, 4)	DEFAULT ((0)) NOT NULL,
		 TmHoras	VARCHAR (8)		NULL,
		 CodigoMt	VARCHAR (5)		NULL,
		 FleteTon	MONEY			DEFAULT ((0)) NULL,
		 Inactivo	BIT				DEFAULT ((0)) NOT NULL,
		 CdCiaTurno	CHAR (2)		NULL,
		 PuntosRut	DECIMAL (14, 4)	DEFAULT ((0)) NOT NULL,
		 Error      varchar(250)    NULL
		 )

		 CREATE TABLE #recorridos(
		 IdRuta		VARCHAR (4)		NOT NULL,
		 NumTramo	INT				DEFAULT ((0)) NOT NULL,
		 IdLocal	VARCHAR (8)		NOT NULL,
		 Detalle	VARCHAR (1000)	NULL,
		 kmstramo	DECIMAL (14, 4)	DEFAULT ((0)) NOT NULL,
		 kmstotal	DECIMAL (14, 4)	DEFAULT ((0)) NOT NULL,
		 Alterno	BIT				DEFAULT ((0)) NOT NULL,
		 Error      varchar(250)    null
		 )

		 --UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Rutas))
			begin
			 UPDATE Rutas
			 SET 
			 IdRuta = t2.IdRuta,Ruta = t2.Ruta,IdLocOri = t2.IdLocOri,IdLocDes = t2.IdLocDes,
			 EsLocal = t2.EsLocal,Distkmt = t2.Distkmt,TmHoras = t2.TmHoras,CodigoMt = t2.CodigoMt,
			 FleteTon = t2.FleteTon,Inactivo = t2.Inactivo,CdCiaTurno = t2.CdCiaTurno,PuntosRut = t2.PuntosRut
			 FROM Rutas t1
			 JOIN @Rutas t2 ON t1.IdRuta = t2.IdRuta
			end

			IF(EXISTS(SELECT TOP 1 * FROM @RutasRecorridos))
			BEGIN
			 UPDATE RutasRecorridos
			 SET 
			 IdRuta = t2.IdRuta,NumTramo = t2.NumTramo,IdLocal = t2.IdLocal,
			 Detalle = t2.Detalle,kmstramo = t2.kmstramo,kmstotal = t2.kmstotal,
			 Alterno = t2.Alterno
			 FROM RutasRecorridos t1
			 JOIN @RutasRecorridos t2 ON t1.IdRuta = t2.IdRuta and t1.NumTramo = t2.NumTramo
			 WHERE t1.IdRuta = t2.IdRuta and t1.NumTramo = t2.NumTramo
			 --Inserta los que no existen
			 INSERT INTO RutasRecorridos(
			 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno)
			 SELECT 
			 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno
			 FROM @RutasRecorridos
			 WHERE (IdRuta + Convert(varchar,NumTramo)) NOT IN(SELECT (IdRuta +Convert(varchar,NumTramo)) FROM RutasRecorridos)
			END

			--IF(EXISTS(SELECT TOP 1 * FROM @RutasPlan))
			--begin
			-- UPDATE RutasPlan
			-- SET 
			-- IdRuta = t2.IdRuta,IdPunto = t2.IdPunto,Descripcion = t2.Descripcion,Distancia = t2.Distancia,
			-- Tiempo = t2.Tiempo,ClasePto = t2.ClasePto,CdPto = t2.CdPto,IdLocal = t2.IdLocal,PosLat = t2.PosLat,
			-- PosLon = t2.PosLon,Inactivo = t2.Inactivo
			-- FROM RutasPlan t1
			-- JOIN @RutasPlan t2 ON t1.IdRuta = t2.IdRuta
			--end

			--IF(EXISTS(SELECT TOP 1 * FROM @RutasTramos))
			--begin
			-- UPDATE RutasTramos
			-- SET 
			-- IdRuta = t2.IdRuta,NumTramo = t2.NumTramo,IdLocal = t2.IdLocal,kmstramo = t2.kmstramo,kmstotal = t2.kmstotal
			-- FROM RutasTramos T1
			-- JOIN @RutasTramos T2 ON T1.IdRuta = T2.IdRuta
			--end
			
		 END

		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Rutas))
			BEGIN
			 INSERT INTO Rutas(
			 IdRuta,Ruta,IdLocOri,IdLocDes,EsLocal,Distkmt,TmHoras,CodigoMt,FleteTon,Inactivo,CdCiaTurno,PuntosRut
			 )
			 SELECT 
			 IdRuta,Ruta,IdLocOri,IdLocDes,EsLocal,Distkmt,TmHoras,CodigoMt,FleteTon,Inactivo,CdCiaTurno,PuntosRut
			 FROM @Rutas
			 WHERE IdRuta NOT IN(SELECT IdRuta FROM Rutas)
			END

			
			IF(EXISTS(SELECT TOP 1 * FROM @RutasRecorridos))
			BEGIN
			 INSERT INTO RutasRecorridos(
			 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno
			 )
			 SELECT 
			 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno
			 FROM @RutasRecorridos
			 WHERE (IdRuta + Convert(varchar,NumTramo)) NOT IN(SELECT (IdRuta +Convert(varchar,NumTramo)) FROM RutasRecorridos)
			END

			--IF(EXISTS(SELECT TOP 1 * FROM @RutasPlan))
			--BEGIN
			-- INSERT INTO RutasPlan(
			-- IdRuta,IdPunto,Descripcion,Distancia,Tiempo,ClasePto,CdPto,IdLocal,PosLat,PosLon,Inactivo
			-- )
			-- SELECT 
			-- IdRuta,IdPunto,Descripcion,Distancia,Tiempo,ClasePto,CdPto,IdLocal,PosLat,PosLon,Inactivo
			-- FROM @RutasPlan
			-- WHERE IdRuta NOT IN(SELECT IdRuta FROM RutasPlan)
			--END

			--IF(EXISTS(SELECT TOP 1 * FROM @RutasTramos))
			--BEGIN
			-- INSERT INTO RutasTramos(
			-- IdRuta,NumTramo,IdLocal,kmstramo,kmstotal
			-- )
			-- SELECT 
			-- IdRuta,NumTramo,IdLocal,kmstramo,kmstotal
			-- FROM @RutasTramos
			-- WHERE IdRuta NOT IN(SELECT IdRuta FROM @RutasTramos)
			--END
						
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id VARCHAR (4)
			 SELECT @id = IdRuta FROM @Rutas
			 --DELETE FROM RutasTramos WHERE IdRuta = @id
			 --DELETE FROM RutasPlan WHERE IdRuta = @id
			 DELETE FROM RutasRecorridos WHERE IdRuta = @id
			 DELETE FROM Rutas WHERE IdRuta = @id
		 END

		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'p')
		 BEGIN
		    IF(EXISTS(SELECT TOP 1 * FROM @Rutas))
			BEGIN
				DECLARE @IdRuta VARCHAR (20)
				DECLARE rutacursor CURSOR
				FOR SELECT IdRuta FROM @Rutas
				OPEN rutacursor
				FETCH NEXT FROM rutacursor into @IdRuta
				WHILE @@FETCH_STATUS = 0
				BEGIN
					BEGIN TRY
					 if(NOT EXISTS(SELECT IdRuta FROM Rutas WHERE IdRuta = @IdRuta))
					 BEGIN
						 INSERT INTO Rutas(
						 IdRuta,Ruta,IdLocOri,IdLocDes,EsLocal,Distkmt,TmHoras,CodigoMt,FleteTon,Inactivo,CdCiaTurno,PuntosRut)
						 SELECT 
						 IdRuta,Ruta,IdLocOri,IdLocDes,EsLocal,Distkmt,TmHoras,CodigoMt,FleteTon,0,CdCiaTurno,PuntosRut
						 FROM @Rutas WHERE IdRuta = @IdRuta
					 END
					 ELSE if(EXISTS(SELECT IdRuta FROM Rutas WHERE IdRuta = @IdRuta))
					 BEGIN
						--SE AGREGA LA LINEA NO INSERTADA PORQUE YA EXISTE
						 INSERT INTO #rutas
						 SELECT 
						 IdRuta,Ruta,IdLocOri,IdLocDes,EsLocal,Distkmt,TmHoras,CodigoMt,FleteTon,0,CdCiaTurno,PuntosRut, 'La Ruta ya existe.'
						 FROM @Rutas WHERE IdRuta = @IdRuta
					 END
					END TRY
					BEGIN CATCH
					 --SE AGREGA LA LINEA NO INSERTADA
					 INSERT INTO #rutas
					 SELECT 
					 IdRuta,Ruta,IdLocOri,IdLocDes,EsLocal,Distkmt,TmHoras,CodigoMt,FleteTon,0,CdCiaTurno,PuntosRut, ERROR_MESSAGE()
					 FROM @Rutas WHERE IdRuta = @IdRuta
					END CATCH
				   FETCH NEXT FROM rutacursor INTO @IdRuta
				END
				CLOSE rutacursor
				DEALLOCATE rutacursor
			END

			IF(EXISTS(SELECT TOP 1 * FROM @RutasRecorridos))
			BEGIN
				DECLARE @IdRutRec VARCHAR (4)
				Declare @Numero INT

				DECLARE recorridocursor CURSOR
					FOR SELECT IdRuta, NumTramo FROM @RutasRecorridos
				OPEN recorridocursor
				FETCH NEXT FROM recorridocursor into @IdRutRec,@Numero
				WHILE @@FETCH_STATUS = 0
				BEGIN
					BEGIN TRY				
						IF(NOT EXISTS(SELECT IdRuta FROM RutasRecorridos WHERE IdRuta = @IdRutRec and NumTramo = @Numero))
						BEGIN
						 INSERT INTO RutasRecorridos(
						 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno)
						 SELECT 
						 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno
						 FROM @RutasRecorridos WHERE IdRuta = @IdRutRec and NumTramo = @Numero
						END 
						ELSE IF(EXISTS(SELECT IdRuta FROM RutasRecorridos WHERE IdRuta = @IdRutRec and NumTramo = @Numero))
						BEGIN
						--SE AGREGA LA LINEA NO INSERTADA PORQUE YA EXISTE
						 INSERT INTO #recorridos
						 SELECT 
						 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno, 'El recorrido ya existe.'
						 FROM @RutasRecorridos WHERE IdRuta = @IdRutRec and NumTramo = @Numero
						END
					END TRY
					BEGIN CATCH
					 --SE AGREGA LA LINEA NO INSERTADA
					 INSERT INTO #recorridos
					 SELECT
					 IdRuta,NumTramo,IdLocal,Detalle,kmstramo,kmstotal,Alterno,ERROR_MESSAGE()
					 FROM @RutasRecorridos WHERE IdRuta = @IdRutRec and NumTramo = @Numero
					END CATCH
				   FETCH NEXT FROM recorridocursor INTO @IdRutRec, @Numero
				END
				CLOSE recorridocursor
				DEALLOCATE recorridocursor
			END

		 END

		IF(@operacion <> 'p')
			SELECT '1'
		ELSE
		BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Rutas))
				SELECT * FROM #rutas
			IF(EXISTS(SELECT TOP 1 * FROM @RutasRecorridos))
				SELECT * FROM #recorridos
		END

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Autoriza]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 26/04/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_Autoriza.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_Autoriza]
	@Sys_Autoriza dataTypeSys_Autoriza READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Sys_Autoriza
			 SET 
			 IdConcepto = t2.IdConcepto,ConceptoAut = t2.ConceptoAut,Inactivo = t2.Inactivo
		     FROM Sys_Autoriza t1
			 JOIN @Sys_Autoriza t2 ON t1.IdConcepto = t2.IdConcepto
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Sys_Autoriza(
			 IdConcepto,ConceptoAut,Inactivo
			 )
			 SELECT 
			 IdConcepto,ConceptoAut,Inactivo
			 FROM @Sys_Autoriza
			 WHERE IdConcepto NOT IN(SELECT IdConcepto FROM Sys_Autoriza)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdConcepto FROM @Sys_Autoriza
			 DELETE FROM Sys_Autoriza WHERE IdConcepto = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Cnxextna]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21¿6/04/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_Cnxextna.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_Cnxextna]
	@Sys_Cnxextna dataTypeSys_Cnxextna READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Sys_Cnxextna
			 SET 
			 IdReg = t2.IdReg, CnxTipo = t2.CnxTipo, CnxEngine = t2.CnxEngine, CnxDso = t2.CnxDso,
			 CnxDbname = t2.CnxDbname, CnxAutentic = t2.CnxAutentic, CnxUid = t2.CnxUid, CnxPwd = t2.CnxPwd,
			 CnxOwner = t2.CnxOwner, CnxPpties = t2.CnxPpties, CnxObserv = t2.CnxObserv, CnxDriver = t2.CnxDriver,
			 CnxPort = t2.CnxPort, CnxTerminal = t2.CnxTerminal
		     FROM Sys_Cnxextna t1
			 JOIN @Sys_Cnxextna t2 ON t1.IdReg = t2.IdReg
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Sys_Cnxextna(
			 IdReg, CnxTipo, CnxEngine, CnxDso, CnxDbname, CnxAutentic, CnxUid, CnxPwd, 
			 CnxOwner, CnxPpties,  CnxObserv, CnxDriver, CnxPort, CnxTerminal
			 )
			 SELECT 
			 IdReg, CnxTipo, CnxEngine, CnxDso, CnxDbname, CnxAutentic, CnxUid, CnxPwd, 
			 CnxOwner, CnxPpties,  CnxObserv, CnxDriver, CnxPort, CnxTerminal			 
			 FROM @Sys_Cnxextna
			 WHERE IdReg NOT IN(SELECT IdReg FROM Sys_Cnxextna)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @idreg int
			 SELECT @idreg = IdReg FROM @Sys_Cnxextna
			 DELETE FROM Sys_Cnxextna WHERE IdReg = @idreg
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Estaciones]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 11/05/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_Estaciones.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_Estaciones]
	@Sys_Estaciones dataTypeSys_Estaciones READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Sys_Estaciones
			 SET 
			 IdEstacion = t2.IdEstacion, Estacion = t2.Estacion
		     FROM Sys_Estaciones t1
			 JOIN @Sys_Estaciones t2 ON t1.IdEstacion = t2.IdEstacion
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Sys_Estaciones(
			 IdEstacion, Estacion
			 )
			 SELECT 
			 IdEstacion, Estacion
			 FROM @Sys_Estaciones
			 WHERE IdEstacion NOT IN(SELECT IdEstacion FROM Sys_Estaciones)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(2)
			 SELECT @id = IdEstacion FROM @Sys_Estaciones
			 DELETE FROM Sys_Estaciones WHERE IdEstacion = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_FmtDoc]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_FmtDoc.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_FmtDoc]
	@Sys_FmtDoc dataTypeSys_FmtDoc READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Sys_FmtDoc
			 SET 
			 IdDoc = t2.IdDoc,IdForma = t2.IdForma,Descripcion = t2.Descripcion,Formato = t2.Formato,
			 Predtmnado = t2.Predtmnado,TipoPapel = t2.TipoPapel,Orientacion = t2.Orientacion,
			 VistaPrevia = t2.VistaPrevia,VerSetup = t2.VerSetup,NumCopias = t2.NumCopias,sp_Nombre = t2.sp_Nombre,
			 Ind_Location = t2.Ind_Location
		     FROM Sys_FmtDoc t1
			 JOIN @Sys_FmtDoc t2 ON t1.IdDoc = t2.IdDoc and t1.IdForma = t2.IdForma 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Sys_FmtDoc(
			 IdDoc,IdForma,Descripcion,Formato,Predtmnado,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,sp_Nombre,Ind_Location
			 )
			 SELECT 
			 IdDoc,IdForma,Descripcion,Formato,Predtmnado,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,sp_Nombre,Ind_Location
			 FROM @Sys_FmtDoc
			 WHERE (IdDoc + IdForma NOT IN(SELECT IdDoc + IdForma FROM Sys_FmtDoc)) 
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @IdDoc varchar(3)
			 DECLARE @IdForma varchar(2)
			 SELECT @IdDoc = IdDoc, @IdForma = IdForma FROM @Sys_FmtDoc
			 DELETE FROM Sys_FmtDoc WHERE IdDoc = @IdDoc and IdForma = @IdForma
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_GruposUsu]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 12/05/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_GruposUsu.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_GruposUsu]
	@Sys_GruposUsu dataTypeSys_GruposUsu READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Sys_GruposUsu
			 SET 
			 IdGrupo = t2.IdGrupo, Grupo = t2.Grupo, Descripcion = t2.Descripcion
		     FROM Sys_GruposUsu t1
			 JOIN @Sys_GruposUsu t2 ON t1.IdGrupo = t2.IdGrupo
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Sys_GruposUsu(
			 IdGrupo,Grupo,Descripcion
			 )
			 SELECT 
			 IdGrupo,Grupo,Descripcion
			 FROM @Sys_GruposUsu
			 WHERE IdGrupo NOT IN(SELECT IdGrupo FROM Sys_GruposUsu)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id int
			 SELECT @id = IdGrupo FROM @Sys_GruposUsu
			 DELETE FROM Sys_GruposUsu WHERE IdGrupo = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Modulos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar Sys_Modulos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_Modulos]
	@Sys_Modulos dataTypeSys_Modulos READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
		 	 --Actualizar los que existen
			 UPDATE Sys_Modulos
			 SET 
			 IdMod = t2.IdMod, Consecutivo = t2.Consecutivo, Descripcion = t2.Descripcion,
			 Valor = t2.Valor, nModulo = t2.nModulo
		     FROM Sys_Modulos t1
			 JOIN @Sys_Modulos t2 ON t1.IdMod = t2.IdMod
			 --Inserta los que no existen
			 INSERT INTO Sys_Modulos(
			 IdMod,Consecutivo,Descripcion,Valor,nModulo
			 )
			 SELECT IdMod,Consecutivo,Descripcion,Valor,nModulo 
			 FROM @Sys_Modulos 
			 WHERE IdMod NOT IN(SELECT IdMod FROM Sys_Modulos)
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Sys_Modulos(
			 IdMod,Consecutivo,Descripcion,Valor,nModulo
			 )
			 SELECT 
			 IdMod,Consecutivo,Descripcion,Valor,nModulo
			 FROM @Sys_Modulos
			 WHERE IdMod NOT IN(SELECT IdMod FROM Sys_Modulos)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(3)
			 SELECT @id = IdMod FROM @Sys_Modulos
			 DELETE FROM Sys_Modulos WHERE IdMod = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Report]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21¿6/04/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_Report.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_Report]
	@Sys_Report dataTypeSys_Report READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Sys_Report
			 SET 
			 TipoRep = t2.TipoRep, IdRep = t2.IdRep, Descripcion = t2.Descripcion, Formato = t2.Formato,
			 TipoPapel = t2.TipoPapel, Orientacion = t2.Orientacion, VistaPrevia = t2.VistaPrevia,
			 VerSetup = t2.VerSetup, NumCopias = t2.NumCopias, sp_Nombre = t2.sp_Nombre,
			 Ind_Location = t2.Ind_Location, NomRep = t2.NomRep
		     FROM Sys_Report t1
			 JOIN @Sys_Report t2 ON t1.TipoRep = t2.TipoRep and t1.IdRep = t2.IdRep
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Sys_Report(
			 TipoRep,IdRep,Descripcion,Formato,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,sp_Nombre,Ind_Location,NomRep
			 )
			 SELECT 
			 TipoRep,IdRep,Descripcion,Formato,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,sp_Nombre,Ind_Location,NomRep
			 FROM @Sys_Report
			 WHERE (TipoRep + IdRep) NOT IN(SELECT (TipoRep + IdRep) FROM Sys_Report)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @tiporep varchar(3)
			 DECLARE @idrep char(2)

			 SELECT @tiporep = TipoRep ,@idrep = IdRep FROM @Sys_Report
			 if(@idrep <> null)
				DELETE FROM Sys_Report WHERE TipoRep = @tiporep and IdRep = @idrep
			 else
				DELETE FROM Sys_Report WHERE TipoRep = @tiporep
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsSys_Security]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 16/06/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_Security.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsSys_Security]
	@Sys_Security dataTypeSys_Security READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Sys_Security))
			begin
			 UPDATE Sys_Security
			 SET 
			 IdLla = t2.IdLla,Descripcion = t2.Descripcion,Pwd = t2.Pwd
			 FROM Sys_Security T1
			 JOIN @Sys_Security T2 ON T1.IdLla = T2.IdLla
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Sys_Security))
			BEGIN
			 INSERT INTO Sys_Security(
			 IdLla,Descripcion,Pwd
			 )
			 SELECT 
			 IdLla,Descripcion,Pwd
			 FROM @Sys_Security
			 WHERE IdLLa NOT IN(SELECT IdLla FROM Sys_Security)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdLla FROM @Sys_Security		
			 DELETE FROM Sys_Security WHERE IdLla = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTablaPor]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 19/04/2016
-- Description:	Insertar/Actualizar Tarifas(TablaPor) .
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTablaPor]
	@TablaPor dataTypeTablaPor READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Tablapor
			 SET 
			 IdTarifa = t2.IdTarifa, Descripcion = t2.Descripcion,  IdClase = t2.IdClase, Tarifa = t2.Tarifa, 
			 Simbolo = t2.Simbolo, CdLocdad = t2.CdLocdad, Minimo = t2.Minimo, Maximo = t2.Maximo,  Inactivo = t2.Inactivo
		     FROM Tablapor t1
			 JOIN @TablaPor t2 ON t1.IdTarifa = t2.IdTarifa
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Tablapor(
			 IdTarifa, Descripcion, IdClase, Tarifa, Simbolo, CdLocdad, Minimo, Maximo, Inactivo)
			 SELECT 
			 IdTarifa, Descripcion, IdClase, Tarifa, Simbolo, CdLocdad, Minimo, Maximo, Inactivo
			 FROM @TablaPor
			 WHERE IdTarifa NOT IN(SELECT IdTarifa FROM Tablapor)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = idtarifa FROM @TablaPor
			 DELETE FROM Tablapor WHERE IdTarifa = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTarifasEsp]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 05/10/2016
-- Description:	Insertar/Actualizar/Eliminar TarifasEsp.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTarifasEsp]
	@TarifasEsp dataTypeTarifasEsp READONLY, 
	@operacion varchar(1),
	@IdUsuario VARCHAR (11) = null,
    @FechaCrea datetime = null
AS
BEGIN TRAN
	BEGIN TRY		
	
		 CREATE TABLE #consolidado (
			 Numero		 INT					DEFAULT ((0))	NULL,
			 CdRuta		 VARCHAR (4)			DEFAULT ('0')   NULL,
			 IdOrigen	 VARCHAR (8)			NULL,
			 IdDestino	 VARCHAR (8)			NULL,
			 TipoTarifa	 VARCHAR (10)		DEFAULT ('RUTA')  NULL,
			 CdTipoVeh	 VARCHAR (4)			NULL,
			 TipAfilVeh	 VARCHAR (10)		NULL,
			 Kilometros	 DECIMAL (16, 4)		DEFAULT ((0))  NULL,
			 TarifClie	 MONEY				DEFAULT ((0))  NULL,
			 TarifPago	 MONEY				DEFAULT ((0))  NULL,
			 IdMneda	 VARCHAR (5)			DEFAULT ('COP')  NULL,
			 Inactivo	 BIT					DEFAULT ((0))	NULL,
			 FechaCrea	 SMALLDATETIME		NULL,
		 	 IdUsuario	 VARCHAR (11)		NULL,
			 VrDia		 MONEY				DEFAULT ((0))  NULL,
			 Horas		 INT					DEFAULT ((0))  NULL,
			 Nit         varchar(126)        DEFAULT ((0))  NULL,   
			 VrMonitor   decimal             DEFAULT ((0))  NULL,
			 TarifaXRuta BIT					DEFAULT ((1))	NULL,
			 Error      varchar(250)		null
			 )

		declare @CantRow int
		--declare @TAR varchar
		declare @item int 
		select @item =  isnull(MAX(Numero),0) from TarifasEsp

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TarifasEsp
			 SET 
			 Numero = t2.Numero,CdRuta = t2.CdRuta,IdOrigen = t2.IdOrigen,IdDestino = t2.IdDestino,
			 TipoTarifa = t2.TipoTarifa,CdTipoVeh = t2.CdTipoVeh,TipAfilVeh = t2.TipAfilVeh,
			 Kilometros = t2.Kilometros,TarifClie = t2.TarifClie,TarifPago = t2.TarifPago,
			 IdMneda = t2.IdMneda,Inactivo = t2.Inactivo,FechaCrea = t2.FechaCrea,
			 IdUsuario = t2.IdUsuario,VrDia = t2.VrDia, Horas = t2.Horas,Nit = t2.Nit,VrMonitor=t2.VrMonitor, TarifaXRuta=t2.TarifaXRuta
		     FROM TarifasEsp t1
			 JOIN @TarifasEsp t2 ON t1.Numero = t2.Numero
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 --select @CantRow = Count(t1.CdRuta) 
			 --from TarifasEsp t1 
			 --inner join @TarifasEsp t2 
			 --on t1.CdRuta= t2.CdRuta and t1.IdOrigen = t2.IdOrigen and t1.IdDestino = t2.IdDestino 
			 --and t1.TipoTarifa = t2.TipoTarifa  and t1.CdTipoVeh = t2.CdTipoVeh and t1.TipAfilVeh = t2.TipAfilVeh 
			 --and t1.IdMneda= t2.IdMneda
			 
			 --IF(@CantRow = 0)
			 --BEGIN
				 INSERT INTO TarifasEsp(
				 Numero,CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
				 TarifClie,TarifPago,IdMneda,Inactivo,FechaCrea,IdUsuario,VrDia,Horas,Nit,VrMonitor,TarifaXRuta)
				 SELECT 
				 (@Item + ROW_NUMBER() OVER(ORDER BY Numero ASC)),CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
				 TarifClie,TarifPago,IdMneda,Inactivo,FechaCrea,IdUsuario,VrDia,Horas,Nit,VrMonitor,TarifaXRuta
				 FROM @TarifasEsp
				 WHERE Numero NOT IN(SELECT Numero FROM TarifasEsp)
			 --END
		 END

		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'p')
		 BEGIN
			DECLARE @Numero INT
			--DECLARE @TarifClie money
			--DECLARE @TarifPago money
			DECLARE tarifacursor CURSOR
			FOR SELECT Numero FROM @TarifasEsp
			OPEN tarifacursor
			FETCH NEXT FROM tarifacursor into @Numero
			declare @contador int
			select @contador = @item+1
			WHILE @@FETCH_STATUS = 0
			BEGIN
				BEGIN TRY

					select @CantRow = Count(t1.CdRuta) 
					from TarifasEsp t1 
					inner join @TarifasEsp t2 
					on t1.CdRuta= t2.CdRuta and t1.IdOrigen = t2.IdOrigen and t1.IdDestino = t2.IdDestino and t1.TipoTarifa = t2.TipoTarifa and t1.TarifaXRuta = t2.TarifaXRuta 
					and (t1.CdTipoVeh = t2.CdTipoVeh or  t1.CdTipoVeh is null or t1.CdTipoVeh = '') and (t1.TipAfilVeh = t2.TipAfilVeh or  t1.TipAfilVeh is null or t1.TipAfilVeh = '') 
					and t1.IdMneda= t2.IdMneda and t1.Nit = t2.Nit  where t2.numero = @Numero 

					----

					IF(@CantRow = 0)
					BEGIN
						IF(NOT EXISTS(SELECT Numero FROM TarifasEsp WHERE Numero = @contador))
						BEGIN
							--IF((@TarifClie > @TarifPago) OR ((@TarifClie < @TarifPago) AND @TAR = '1'))
							--BEGIN
							 INSERT INTO TarifasEsp(
							 Numero,CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
							 TarifClie,TarifPago,IdMneda,Inactivo,FechaCrea,IdUsuario,VrDia,Horas,Nit,VrMonitor,TarifaXRuta)
							 SELECT 
							 @contador,CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
							 TarifClie,TarifPago,IdMneda,0,@FechaCrea,@IdUsuario,VrDia,Horas,Nit,VrMonitor,TarifaXRuta
							 FROM @TarifasEsp WHERE Numero = @Numero	
							--END
							--ELSE
							-- BEGIN 
							--  --SE AGREGA LA LINEA NO INSERTADA TARIFA DE COBRO MENOR A LA DE PAGO
							--  INSERT INTO #consolidado
							--  SELECT 
							--  Numero,CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
							--  TarifClie,TarifPago,IdMneda,0,@FechaCrea,@IdUsuario,VrDia,Horas,'LA TARIFA DE COBRO ES MENOR A LA TARIFA DE PAGO.'
							--  FROM @TarifasEsp WHERE Numero = @Numero
							--END
						 END
						 ELSE if(EXISTS(SELECT Numero FROM TarifasEsp WHERE Numero = @Numero))
						 BEGIN
							 --SE AGREGA LA LINEA NO INSERTADA PORQUE YA EXISTE
							 INSERT INTO #consolidado
							 SELECT 
							 Numero,CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
							 TarifClie,TarifPago,IdMneda,0,@FechaCrea,@IdUsuario,VrDia,Horas,Nit,VrMonitor,TarifaXRuta,'La Tarifa ya existe.'
							 FROM @TarifasEsp WHERE Numero = @Numero
						 END
					END
					ELSE IF(@CantRow >= 1)
					BEGIN
						--SE AGREGA LA LINEA NO INSERTADA PORQUE YA EXISTE UNA TARIFA IGUALES CONDICIONES
						INSERT INTO #consolidado
						SELECT 
						Numero,CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
						TarifClie,TarifPago,IdMneda,0,@FechaCrea,@IdUsuario,VrDia,Horas,Nit,VrMonitor,TarifaXRuta,'Existe una tarifa con las mismas condiciones.'
						FROM @TarifasEsp WHERE Numero = @Numero
					END
				END TRY
				BEGIN CATCH
				 --SE AGREGA LA LINEA NO INSERTADA
				 INSERT INTO #consolidado
				 SELECT 
				 Numero,CdRuta,IdOrigen,IdDestino,TipoTarifa,CdTipoVeh,TipAfilVeh,Kilometros,
				 TarifClie,TarifPago,IdMneda,0,@FechaCrea,@IdUsuario,VrDia,Horas,Nit,VrMonitor,TarifaXRuta,ERROR_MESSAGE()
				 FROM @TarifasEsp WHERE Numero = @Numero
				END CATCH
				select @contador = @contador +1
			   FETCH NEXT FROM tarifacursor INTO @Numero
			END
			CLOSE tarifacursor
			DEALLOCATE tarifacursor
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = Numero FROM @TarifasEsp
			 DELETE FROM TarifasEsp WHERE Numero = @id
		 END

		IF(@operacion <> 'p')
			SELECT '1'
		else
			select * from #consolidado

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndCapac]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 03/05/2016
-- Description:	Insertar/Actualizar/Eliminar TercCndCapac.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTercCndCapac]
	@TercCndCapac dataTypeTercCndCapac READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Item),0) FROM TercCndCapac WHERE IdConductor = (select IdConductor from @TercCndCapac)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TercCndCapac
			 SET 
			 IdConductor = t2.IdConductor,Item = t2.Item,IdClase = t2.IdClase,Fecha = t2.Fecha,FecVence = t2.FecVence,Habilitado = t2.Habilitado
		     FROM TercCndCapac t1
			 JOIN @TercCndCapac t2 ON t1.IdConductor = t2.IdConductor and t1.Item = t2.Item

		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TercCndCapac(
			 IdConductor,Item,IdClase,Fecha,FecVence,Habilitado
			 )
			 SELECT 
			 IdConductor,Item,IdClase,Fecha,FecVence,Habilitado
			 FROM @TercCndCapac
			 WHERE (IdConductor + Convert(varchar, (@Item+1))) NOT IN(SELECT IdConductor + Convert(varchar, Item) FROM TercCndCapac)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(16)
			 SELECT @id = IdConductor, @item = Item FROM @TercCndCapac
			 DELETE FROM TercCndCapac WHERE IdConductor = @id and Item = @item
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndContrato]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 03/05/2016
-- Description:	Insertar/Actualizar/Eliminar TercCndContrato.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTercCndContrato]
	@TercCndContrato dataTypeTercCndContrato READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		IF(@operacion = 'u')
		 BEGIN
			 UPDATE TercCndContrato
			 SET 
			 NumContrato = t2.NumContrato, IdConductor = t2.IdConductor,
			 IdTipCon = t2.IdTipCon, IdModd = t2.IdModd,
			 FecIngreso = t2.FecIngreso, FecRetiro = t2.FecRetiro,
			 FecVigencia = t2.FecVigencia, Observaciones = t2.Observaciones,
			 FecUpdate = t2.FecUpdate, IdUsuario = t2.IdUsuario
		     FROM TercCndContrato t1
			 JOIN @TercCndContrato t2 ON t1.IdConductor = t2.IdConductor and t1.NumContrato = t2.NumContrato

			 --Actualizar tabla TercCndtores
			 if((select FecRetiro from @TercCndContrato) <> null)
			 begin
				 update TercCndtores 
				 set				 
				 CdTipCon = t2.IdTipCon, Fec_Ingreso = t2.FecIngreso, Fec_Vigencia = t2.FecVigencia,
				 Contrato_Activo = '0', Fec_Retiro = t2.FecRetiro,
				 FechaUpdate = CURRENT_TIMESTAMP
				 from TercCndtores t1
				 JOIN @TercCndContrato t2 ON t1.IdConductor = t2.IdConductor and t1.Num_Contrato = t2.NumContrato
			 end
			 else 
			 begin
				 update TercCndtores 
				 set 
				 Num_Contrato = t2.NumContrato, Contrato_Activo = '1', CdTipCon = t2.IdTipCon
				 ,Fec_Ingreso = t2.FecIngreso, Fec_Vigencia = t2.FecVigencia
				 ,FechaUpdate = CURRENT_TIMESTAMP
				 from TercCndtores t1
				 JOIN @TercCndContrato t2 ON t1.IdConductor = t2.IdConductor and t1.Num_Contrato = t2.NumContrato
			 end
		 END
 
		--INSERT NO-EXISTE RECORDS
		IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TercCndContrato(
			 NumContrato,IdConductor,IdTipCon,IdModd,FecIngreso,FecRetiro,FecVigencia,Observaciones,FecUpdate,IdUsuario
			 )
			 SELECT 
			 NumContrato,IdConductor,IdTipCon,IdModd,FecIngreso,FecRetiro,FecVigencia,Observaciones,FecUpdate,IdUsuario
			 FROM @TercCndContrato
			 WHERE (Convert(varchar,NumContrato) + IdConductor) NOT IN(SELECT (Convert(varchar,NumContrato)+IdConductor) FROM TercCndContrato)

			 --Actualizar tabla TercCndtores
			 update TercCndtores 
			 set 
			 Num_Contrato = t2.NumContrato, Contrato_Activo = '1', CdTipCon = t2.IdTipCon
			 ,Fec_Ingreso = t2.FecIngreso, Fec_Retiro = t2.FecRetiro, Fec_Vigencia = t2.FecVigencia
			 ,FechaUpdate = CURRENT_TIMESTAMP
			 from TercCndtores t1
			 JOIN @TercCndContrato t2 ON t1.IdConductor = t2.IdConductor

		 END

		--DELETE RECORDS
		IF(@operacion = 'd')
		BEGIN
			DECLARE @id varchar(16)
			declare @num int
			SELECT @num = NumContrato FROM @TercCndContrato
			SELECT @id = IdConductor FROM @TercCndContrato
			DELETE FROM TercCndContrato WHERE IdConductor = @id and NumContrato = @num
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndDoc]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 03/05/2016
-- Description:	Insertar/Actualizar/Eliminar TercCndDoc.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTercCndDoc]
	@TercCndDoc dataTypeTercCndDoc READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Item),0) FROM TercCndDoc WHERE IdConductor = (select IdConductor from @TercCndDoc)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TercCndDoc
			 SET 
			 IdConductor = t2.IdConductor,Item = t2.Item,IdDoc = t2.IdDoc,Fecha = t2.Fecha,
			 FecVence = t2.FecVence,Radicado = t2.Radicado,Descripcion = t2.Descripcion
		     FROM TercCndDoc t1
			 JOIN @TercCndDoc t2 ON t1.IdConductor = t2.IdConductor and t1.Item = t2.Item
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TercCndDoc(
			 IdConductor,Item,IdDoc,Fecha,FecVence,Radicado,Descripcion
			 )
			 SELECT 
			 IdConductor,(@item + 1),IdDoc,Fecha,FecVence,Radicado,Descripcion
			 FROM @TercCndDoc
			 WHERE (IdConductor + Convert(varchar, (@item + 1))) NOT IN(SELECT (IdConductor + Convert(varchar, Item)) FROM TercCndDoc)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(16)
			 SELECT @id = IdConductor, @item = Item FROM @TercCndDoc
			 DELETE FROM TercCndDoc WHERE IdConductor = @id and Item = @item
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndReferencias]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 03/05/2016
-- Description:	Insertar/Actualizar/Eliminar TercCndReferencias.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTercCndReferencias]
	@TercCndReferencias dataTypeTercCndReferencias READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Item),0) FROM TercCndReferencias WHERE IdConductor = (select IdConductor from @TercCndReferencias)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TercCndReferencias
			 SET 
			 CargoRef = t2.CargoRef,ContactoRef = t2.ContactoRef,CuentaBanco = t2.CuentaBanco,
			 DireccionRef = t2.DireccionRef,EmailRef = t2.EmailRef,EmpresaRef = t2.EmpresaRef,
			 FechaFinal = t2.FechaFinal,FechaInicial = t2.FechaInicial,IdConductor = t2.IdConductor,
			 Item = t2.Item,NitRef = t2.NitRef,ObservRef = t2.ObservRef,TelefonoRef = t2.TelefonoRef,
			 TipoRef = t2.TipoRef,Verificado = t2.Verificado
		     FROM TercCndReferencias t1
			 JOIN @TercCndReferencias t2 ON t1.IdConductor = t2.IdConductor and t1.Item = t2.Item
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TercCndReferencias(
			 CargoRef,ContactoRef,CuentaBanco,DireccionRef,EmailRef,EmpresaRef,
			 FechaFinal,FechaInicial,IdConductor,Item,NitRef,ObservRef,TelefonoRef,
			 TipoRef,Verificado
			 )
			 SELECT 
			 CargoRef,ContactoRef,CuentaBanco,DireccionRef,EmailRef,EmpresaRef,
			 FechaFinal,FechaInicial,IdConductor,(@item+1),NitRef,ObservRef,TelefonoRef,
			 TipoRef,Verificado			 
			 FROM @TercCndReferencias
			 WHERE (IdConductor + Convert(varchar, (@item + 1))) NOT IN(SELECT (IdConductor +Convert(varchar, Item)) FROM TercCndReferencias)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(16)
			 SELECT @id = IdConductor, @item = Item FROM @TercCndReferencias
			 DELETE FROM TercCndReferencias WHERE IdConductor = @id and Item = @item
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndTarjetas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 03/05/2016
-- Description:	Insertar/Actualizar/Eliminar TercCndTarjetas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTercCndTarjetas]
	@TercCndTarjetas dataTypeTercCndTarjetas READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Item),0) FROM TercCndTarjetas WHERE IdConductor = (select IdConductor from @TercCndTarjetas)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TercCndTarjetas
			 SET 
			 IdConductor = t2.IdConductor,Item = t2.Item,NumeroTarj = t2.NumeroTarj,
			 Secuencia = t2.Secuencia,Fecha = t2.Fecha,FecVence = t2.FecVence
		     FROM TercCndTarjetas t1
			 JOIN @TercCndTarjetas t2 ON t1.IdConductor = t2.IdConductor and t1.Item = t2.Item
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TercCndTarjetas(
			 IdConductor,Item,NumeroTarj,Secuencia,Fecha,FecVence
			 )
			 SELECT 
			 IdConductor,Item,NumeroTarj,Secuencia,Fecha,FecVence
			 FROM @TercCndTarjetas
			 WHERE (IdConductor +'_'+ Convert(varchar,Item)) NOT IN(SELECT (IdConductor +'_'+ Convert(varchar,Item)) FROM TercCndTarjetas)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(16)
			 SELECT @id = IdConductor, @item = Item FROM @TercCndTarjetas
			 DELETE FROM TercCndTarjetas WHERE IdConductor = @id and Item = @item
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercCndtores]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 03/05/2016
-- Description:	Insertar/Actualizar/Eliminar TercCndtores.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTercCndtores]
	@TercCndtores dataTypeTercCndtores READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TercCndtores
			 SET 
			 IdConductor = t2.IdConductor, IdGrupo = t2.IdGrupo, IdModd = t2.IdModd, 
			 TipoSangre = t2.TipoSangre, FactorRh = t2.FactorRh, FecNacmto = t2.FecNacmto, 
			 LugarNacmto = t2.LugarNacmto, Sexo = t2.Sexo, IdEstCivil = t2.IdEstCivil, 
			 NHijos = t2.NHijos, LibMilitar = t2.LibMilitar, ClaseLib = t2.ClaseLib, 
			 FechaLib = t2.FechaLib, DistMil = t2.DistMil, CertJudicial = t2.CertJudicial, 
			 FecJudicial = t2.FecJudicial, VigJudicial = t2.VigJudicial, Pasporte = t2.Pasporte, 
			 VigPaspte = t2.VigPaspte, Licencia = t2.Licencia, IdLugar = t2.IdLugar, 
			 CatLicencia = t2.CatLicencia, FecLicencia = t2.FecLicencia, VigLicencia = t2.VigLicencia, 
			 IdClase = t2.IdClase, NumCuenta = t2.NumCuenta, IdBanco = t2.IdBanco, 
			 CdLocCue = t2.CdLocCue, CdFonPen = t2.CdFonPen, CdFonEps = t2.CdFonEps, 
			 CdFonArp = t2.CdFonArp, pVehiculo = t2.pVehiculo, PathFoto = t2.PathFoto, 
			 PathFirma = t2.PathFirma, PathLic = t2.PathLic, Cmntarios = t2.Cmntarios, 
			 IdEstado = t2.IdEstado, Inactivo = t2.Inactivo, NumTarjeta = t2.NumTarjeta, 
			 EdicTarjeta = t2.EdicTarjeta, FecTarjeta = t2.FecTarjeta, VigTarjeta = t2.VigTarjeta, 
			 PasSeguridad = t2.PasSeguridad, FecPasSeg = t2.FecPasSeg, VigPasSeg = t2.VigPasSeg, 
			 NitEmpTrans = t2.NitEmpTrans, FechaAdd = t2.FechaAdd, FechaUpdate = t2.FechaUpdate, 
			 IdUsuario = t2.IdUsuario, Num_Contrato = t2.Num_Contrato, Contrato_Activo = t2.Contrato_Activo, 
			 CdTipCon = t2.CdTipCon,  Fec_Ingreso = t2.Fec_Ingreso, Fec_Retiro = t2.Fec_Retiro, 
			 Fec_Vigencia = t2.Fec_Vigencia, Fec_IngresoAnt = t2.Fec_IngresoAnt, Fec_UltimoAcc = t2.Fec_UltimoAcc, 
			 PasadoJudicial = t2.PasadoJudicial, Restriccion = t2.Restriccion, FecPagoPen = t2.FecPagoPen, 
			 FecPagoEps = t2.FecPagoEps, FecPagoArp = t2.FecPagoArp, CdTipoOper = t2.CdTipoOper 
		     FROM TercCndtores t1
			 JOIN @TercCndtores t2 ON t1.IdConductor = t2.IdConductor 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TercCndtores(
			 IdConductor, IdGrupo, IdModd, TipoSangre, FactorRh, FecNacmto, 
			 LugarNacmto, Sexo, IdEstCivil, NHijos, LibMilitar, ClaseLib, 
			 FechaLib, DistMil, CertJudicial, FecJudicial, VigJudicial, Pasporte, 
			 VigPaspte, Licencia, IdLugar, CatLicencia, FecLicencia, VigLicencia, 
			 IdClase, NumCuenta, IdBanco, CdLocCue, CdFonPen, CdFonEps, 
			 CdFonArp,  pVehiculo, PathFoto, PathFirma, PathLic, Cmntarios, 
			 IdEstado, Inactivo, NumTarjeta, EdicTarjeta, FecTarjeta, VigTarjeta, 
			 PasSeguridad, FecPasSeg, VigPasSeg, NitEmpTrans, FechaAdd, FechaUpdate, 
			 IdUsuario, Num_Contrato, Contrato_Activo, CdTipCon, Fec_Ingreso, Fec_Retiro, 
			 Fec_Vigencia, Fec_IngresoAnt, Fec_UltimoAcc, PasadoJudicial, Restriccion, FecPagoPen, 
			 FecPagoEps, FecPagoArp, CdTipoOper 
			 )
			 SELECT 
			 IdConductor, IdGrupo, IdModd, TipoSangre, FactorRh, FecNacmto, 
			 LugarNacmto, Sexo, IdEstCivil, NHijos, LibMilitar, ClaseLib, 
			 FechaLib, DistMil, CertJudicial, FecJudicial, VigJudicial, Pasporte, 
			 VigPaspte, Licencia, IdLugar, CatLicencia, FecLicencia, VigLicencia, 
			 IdClase, NumCuenta, IdBanco, CdLocCue, CdFonPen, CdFonEps, 
			 CdFonArp,  pVehiculo, PathFoto, PathFirma, PathLic, Cmntarios, 
			 IdEstado, Inactivo, NumTarjeta, EdicTarjeta, FecTarjeta, VigTarjeta, 
			 PasSeguridad, FecPasSeg, VigPasSeg, NitEmpTrans, FechaAdd, FechaUpdate, 
			 IdUsuario, Num_Contrato, Contrato_Activo, CdTipCon, Fec_Ingreso, Fec_Retiro, 
			 Fec_Vigencia, Fec_IngresoAnt, Fec_UltimoAcc, PasadoJudicial, Restriccion, FecPagoPen, 
			 FecPagoEps, FecPagoArp, CdTipoOper 
			 FROM @TercCndtores
			 WHERE IdConductor NOT IN(SELECT IdConductor FROM TercCndtores)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(16)
			 SELECT @id = IdConductor FROM @TercCndtores
			 DELETE FROM TercCndtores WHERE IdConductor = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTerceros]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 02/05/2016
-- Description:	Insertar/Actualizar/Eliminar Terceros.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTerceros]
	@Terceros dataTypeTerceros READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Terceros
			 SET 
			 IdTercero = t2.IdTercero, RazonSocial = t2.RazonSocial, Codigo = t2.Codigo, TipoId = t2.TipoId,
			 Dv = t2.Dv, NomCial = t2.NomCial, SiglaRaz = t2.SiglaRaz, Direccion = t2.Direccion, IdLocal = t2.IdLocal,
			 Telefono = t2.Telefono, Fax = t2.Fax, TelMovil = t2.TelMovil, SitioWeb = t2.SitioWeb, e_mail = t2.e_mail,
			 EsCliente = t2.EsCliente, EsVendedor = t2.EsVendedor, EsConductor = t2.EsConductor, EsPropietario = t2.EsPropietario,
			 EsProveedor = t2.EsProveedor, EsEmpleado = t2.EsEmpleado, EsOperario = t2.EsOperario, EsAccnista = t2.EsAccnista,
			 EsCiaAseg = t2.EsCiaAseg, EsCliePres = t2.EsCliePres, IdSector = t2.IdSector, IdProf = t2.IdProf, IdRegimen = t2.IdRegimen,
			 TipEnte = t2.TipEnte, IdLugarCed = t2.IdLugarCed, FecExpCed = t2.FecExpCed, Observacion = t2.Observacion,
			 IniStgNom = t2.IniStgNom, IdEstado = t2.IdEstado, Inactivo = t2.Inactivo, FechaAdd = t2.FechaAdd, FechaUpdate = t2.FechaUpdate,
			 IdUsuario = t2.IdUsuario, ImgFoto = t2.ImgFoto, ImgFirma = t2.ImgFirma, ImagenDoc1 = t2.ImagenDoc1, ImagenDoc2 = t2.ImagenDoc2, 
			 ImagenDoc3 = t2.ImagenDoc3, FechaNac = t2.FechaNac,IdEstOper = t2.IdEstOper, IdLocUbic = t2.IdLocUbic, DescUbicac = t2.DescUbicac, 
			 CdGrupoTerc = t2.CdGrupoTerc, RegimenFE = t2.RegimenFE
		     FROM Terceros t1
			 JOIN @Terceros t2 ON t1.IdTercero = t2.IdTercero
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Terceros(
			 IdTercero,RazonSocial,Codigo,TipoId,Dv,NomCial,SiglaRaz,Direccion,IdLocal,Telefono,
			 Fax,TelMovil,SitioWeb,e_mail,EsCliente,EsVendedor,EsConductor,EsPropietario,EsProveedor,
			 EsEmpleado,EsOperario,EsAccnista,EsCiaAseg,EsCliePres,IdSector,IdProf,IdRegimen,TipEnte,
			 IdLugarCed,FecExpCed,Observacion,IniStgNom,IdEstado,Inactivo,FechaAdd,FechaUpdate,IdUsuario,
			 ImgFoto,ImgFirma,ImagenDoc1,ImagenDoc2,ImagenDoc3,FechaNac,IdEstOper,IdLocUbic,DescUbicac,
			 CdGrupoTerc, RegimenFE
			 )
			 SELECT 
			 IdTercero,RazonSocial,Codigo,TipoId,Dv,NomCial,SiglaRaz,Direccion,IdLocal,Telefono,
			 Fax,TelMovil,SitioWeb,e_mail,EsCliente,EsVendedor,EsConductor,EsPropietario,EsProveedor,
			 EsEmpleado,EsOperario,EsAccnista,EsCiaAseg,EsCliePres,IdSector,IdProf,IdRegimen,TipEnte,
			 IdLugarCed,FecExpCed,Observacion,IniStgNom,IdEstado,Inactivo,FechaAdd,FechaUpdate,IdUsuario,
			 ImgFoto,ImgFirma,ImagenDoc1,ImagenDoc2,ImagenDoc3,FechaNac,IdEstOper,IdLocUbic,DescUbicac,
			 CdGrupoTerc,RegimenFE
			 FROM @Terceros
			 WHERE IdTercero NOT IN(SELECT IdTercero FROM Terceros)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(16)
			 SELECT @id = IdTercero FROM @Terceros
			 DELETE FROM Terceros WHERE IdTercero = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTercPropietario]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 02/05/2016
-- Description:	Insertar/Actualizar/Eliminar TercPropietario.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTercPropietario]
	@TercPropietario dataTypeTercPropietario READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TercPropietario
			 SET 
			 IdPropietario = t2.IdPropietario, IdGrupo = t2.IdGrupo, CupoCredito = t2.CupoCredito, 
			 SaldoActual = t2.SaldoActual, Avala = t2.Avala, IdAdmon = t2.IdAdmon, IdTipCon = t2.IdTipCon,
			 ContratoActivo = t2.ContratoActivo, FecIngreso = t2.FecIngreso, FecRetiro = t2.FecRetiro,
			 FecVigencia = t2.FecVigencia, Observacion = t2.Observacion, IdEstado = t2.IdEstado,
			 FechaAdd = t2.FechaAdd, FechaUpdate = t2.FechaUpdate, IdUsuario = t2.IdUsuario
		     FROM TercPropietario t1
			 JOIN @TercPropietario t2 ON t1.IdPropietario = t2.IdPropietario
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TercPropietario(
			 IdPropietario,IdGrupo,CupoCredito,SaldoActual,Avala,IdAdmon,IdTipCon,
			 ContratoActivo,FecIngreso,FecRetiro,FecVigencia,Observacion,IdEstado,
			 FechaAdd,FechaUpdate,IdUsuario
			 )
			 SELECT 
			 IdPropietario,IdGrupo,CupoCredito,SaldoActual,Avala,IdAdmon,IdTipCon,
			 ContratoActivo,FecIngreso,FecRetiro,FecVigencia,Observacion,IdEstado,
			 FechaAdd,FechaUpdate,IdUsuario
			 FROM @TercPropietario
			 WHERE IdPropietario NOT IN(SELECT IdPropietario FROM TercPropietario)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(16)
			 SELECT @id = IdPropietario FROM @TercPropietario
			 DELETE FROM TercPropietario WHERE IdPropietario = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposAdm]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 13/03/2012017
-- Description:	Insertar/Actualizar TiposAdm.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposAdm]
	@TiposAdm dataTypeTiposAdm READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposAdm
			 SET 
			 IdAdmon = t2.IdAdmon, TipoAdmon = t2.TipoAdmon, Inactivo = t2.Inactivo
		     FROM TiposAdm t1
			 JOIN @TiposAdm t2 ON t1.IdAdmon = t2.IdAdmon
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposAdm(
			 IdAdmon,TipoAdmon,Inactivo
			 )
			 SELECT 
			 IdAdmon,TipoAdmon,Inactivo
			 FROM @TiposAdm
			 WHERE IdAdmon NOT IN(SELECT IdAdmon FROM TiposAdm)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdAdmon FROM @TiposAdm
			 DELETE FROM TiposAdm WHERE IdAdmon = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCalendarPgr]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 04/12/2017
-- Description:	Insertar/Actualizar TiposCalendarPgr.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposCalendarPgr]
	@TiposCalendarPgr dataTypeTiposCalendarPgr READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposCalendarPgr
			 SET 
			 Codigo = t2.Codigo, Dias = t2.Dias, Inactivo = t2.Inactivo,IncFestivo = t2.IncFestivo
		     FROM TiposCalendarPgr t1
			 JOIN @TiposCalendarPgr t2 ON t1.Codigo = t2.Codigo
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposCalendarPgr(
			 Codigo,Dias,Inactivo,IncFestivo
			 )
			 SELECT 
			 Codigo,Dias,Inactivo,IncFestivo
			 FROM @TiposCalendarPgr
			 WHERE (Codigo+''+ Dias) NOT IN(SELECT (Codigo+''+Dias) FROM TiposCalendarPgr)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(3)
			 SELECT @id = Codigo FROM @TiposCalendarPgr
			 DELETE FROM TiposCalendarPgr WHERE Codigo = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0


GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCatLic]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 13/02/2017
-- Description:	Insertar/Actualizar/eliminar TiposCatLic.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposCatLic]
	@TiposCatLic dataTypeTiposCatLic READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposCatLic
			 SET
			 IdCateg = t2.IdCateg,CategMT = t2.CategMT 
		     FROM TiposCatLic t1
			 JOIN @TiposCatLic t2 ON t1.IdCateg = t2.IdCateg
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposCatLic(
			 IdCateg, CategMT
			 )
			 SELECT 
			 IdCateg, CategMT
			 FROM @TiposCatLic
			 WHERE IdCateg NOT IN(SELECT IdCateg FROM TiposCatLic)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id int
			 SELECT @id = IdCateg FROM @TiposCatLic
			 DELETE FROM TiposCatLic WHERE IdCateg = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCol]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar TiposCol.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposCol]
	@TiposCol dataTypeTiposCol READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposCol
			 SET 
			 IdColor = t2.IdColor,NomColor = t2.NomColor,NColor = t2.NColor,Inactivo = t2.Inactivo,CodigoMT = t2.CodigoMT
		     FROM TiposCol t1
			 JOIN @TiposCol t2 ON t1.IdColor = t2.IdColor
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposCol(
			 IdColor,NomColor,NColor,Inactivo,CodigoMT
			 )
			 SELECT 
			 IdColor,NomColor,NColor,Inactivo,CodigoMT
			 FROM @TiposCol
			 WHERE IdColor NOT IN(SELECT IdColor FROM TiposCol)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdColor FROM @TiposCol
			 DELETE FROM TiposCol WHERE IdColor = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposComFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar/Eliminar TiposComFmt.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposComFmt]
	@TiposComFmt dataTypeTiposComFmt READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @TiposComFmt))
			begin
			 UPDATE TiposComFmt
			 SET 
			 IdCom = t2.IdCom, IdForma = t2.IdForma, Descripcion = t2.Descripcion,
			 Formato = t2.Formato, Predtmnado = t2.Predtmnado, TipoPapel = t2.TipoPapel,
			 Orientacion = t2.Orientacion, VistaPrevia = t2.VistaPrevia, VerSetup = t2.VerSetup,
			 NumCopias = t2.NumCopias, sp_Nombre = t2.sp_Nombre, Ind_Location = t2.Ind_Location
			 FROM TiposComFmt T1
			 JOIN @TiposComFmt T2 ON T1.IdCom = T2.IdCom and T1.IdForma = T2.IdForma
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @TiposComFmt))
			BEGIN
			 INSERT INTO TiposComFmt(
			 IdCom,IdForma,Descripcion,Formato,Predtmnado,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,sp_Nombre,Ind_Location
			 )
			 SELECT 
			 IdCom,IdForma,Descripcion,Formato,Predtmnado,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,sp_Nombre,Ind_Location
			 FROM @TiposComFmt
			 WHERE (IdCom + IdForma) NOT IN(SELECT (IdCom + IdForma) FROM TiposComFmt)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @idcom varchar(3)
			 DECLARE @idforma varchar(2)
			 SELECT @idcom = IdCom, @idforma = IdForma FROM @TiposComFmt		
			 DELETE FROM TiposComFmt WHERE IdCom = @idcom and IdForma = @idforma
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposCon]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar TiposCon.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposCon]
	@TiposCon dataTypeTiposCon READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposCon
			 SET
			 IdTipCon = t2.IdTipCon, TipoContrato = t2.TipoContrato, Duracion = t2.Duracion,
			 Inactivo = t2.Inactivo, VincLabUgpp = t2.VincLabUgpp
		     FROM TiposCon t1
			 JOIN @TiposCon t2 ON t1.IdTipCon = t2.IdTipCon
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposCon(
			 IdTipCon,TipoContrato,Duracion,Inactivo,VincLabUgpp
			 )
			 SELECT 
			 IdTipCon,TipoContrato,Duracion,Inactivo,VincLabUgpp
			 FROM @TiposCon
			 WHERE IdTipCon NOT IN(SELECT IdTipCon FROM TiposCon)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdTipCon FROM @TiposCon
			 DELETE FROM TiposCon WHERE IdTipCon = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposDocumentos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 05/07/2016
-- Description:	Insertar/Actualizar/Eliminar Sys_TiposDoc, Sys_TiposDocCue y TiposDocCons.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposDocumentos]
	@Sys_TiposDoc dataTypeSys_TiposDoc READONLY, 
	@Sys_TiposDocCue dataTypeSys_TiposDocCue READONLY,
	@TiposDocCons dataTypeTiposDocCons READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Sys_TiposDoc))
			begin
			 UPDATE Sys_TiposDoc
			 SET 
			 IdDoc = t2.IdDoc, TipoDoc = t2.TipoDoc,
			 ConsUnico = t2.ConsUnico, Leyenda = t2.Leyenda,
			 Inactivo = t2.Inactivo, IntegraCias = t2.IntegraCias
			 FROM Sys_TiposDoc t1
			 JOIN @Sys_TiposDoc t2 ON t1.IdDoc = t2.IdDoc
			 WHERE t1.IdDoc = t2.IdDoc
			end

			IF(EXISTS(SELECT TOP 1 * FROM @Sys_TiposDocCue))
			begin
			 --Actualizar los que existen
			 UPDATE Sys_TiposDocCue
			 SET 
			 IdDoc = t2.IdDoc, IdClase = t2.IdClase,
			 ClaseCuenta = t2.ClaseCuenta, TipoMov = t2.TipoMov
			 FROM Sys_TiposDocCue t1
			 JOIN @Sys_TiposDocCue t2 ON t1.IdDoc = t2.IdDoc and t1.IdClase = t2.IdClase
			 WHERE t1.IdDoc = t2.IdDoc and t1.IdClase = t2.IdClase
			 --Inserta los que no existen
			 INSERT INTO Sys_TiposDocCue(
			 IdDoc,IdClase,ClaseCuenta,TipoMov)
			 SELECT 
			 IdDoc,IdClase,ClaseCuenta,TipoMov
			 FROM @Sys_TiposDocCue
			 WHERE (IdDoc+Convert(varchar,IdClase)) NOT IN(SELECT (IdDoc+Convert(varchar,IdClase)) FROM Sys_TiposDocCue)
			end

			IF(EXISTS(SELECT TOP 1 * FROM @TiposDocCons))
			begin
			 --Actualizar los que existen
			 UPDATE TiposDocCons
			 SET 
			 IdDoc = t2.IdDoc, IdCia = t2.IdCia, LDesde = t2.LDesde,
			 LHasta = t2.LHasta, Resolucion = t2.Resolucion, RangoNum = t2.RangoNum, 
			 FechaRes = t2.FechaRes, Prefijo = t2.Prefijo, Numero = t2.Numero, 
			 NumManual = t2.NumManual, IntLotes = t2.IntLotes,ConfigFecha = t2.ConfigFecha, 
			 Formato = t2.Formato, TipoPapel = t2.TipoPapel, Orientacion = t2.Orientacion, 
			 VistaPrevia = t2.VistaPrevia, VerSetup = t2.VerSetup, NumCopias = t2.NumCopias, 
			 FechaAdd = t2.FechaAdd, FechaUpdate = t2.FechaUpdate, FechaVigRes=t2.FechaVigRes,
			 ClaveTecDian=t2.ClaveTecDian, CodResol = t2.CodResol
			 FROM TiposDocCons T1
			 JOIN @TiposDocCons T2 ON T1.IdDoc = T2.IdDoc and T1.IdCia = T2.IdCia
			 --Inserta los que no existen
			 INSERT INTO TiposDocCons(
			 IdDoc,IdCia,LDesde,LHasta,Resolucion,RangoNum,
			 FechaRes,Prefijo,Numero,NumManual,IntLotes,ConfigFecha,
			 Formato,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,
			 FechaAdd,FechaUpdate,FechaVigRes,ClaveTecDian,CodResol
			 )
			 SELECT 
			 IdDoc,IdCia,LDesde,LHasta,Resolucion,RangoNum,
			 FechaRes,Prefijo,Numero,NumManual,IntLotes,ConfigFecha,
			 Formato,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,
			 FechaAdd,FechaUpdate,FechaVigRes,ClaveTecDian,CodResol
			 FROM @TiposDocCons
			 WHERE (IdDoc+IdCia) NOT IN(SELECT (IdDoc+IdCia) FROM TiposDocCons)
			end			
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @Sys_TiposDoc))
			BEGIN
			 INSERT INTO Sys_TiposDoc(
			 IdDoc,TipoDoc,ConsUnico,Leyenda,Inactivo,IntegraCias
			 )
			 SELECT 
			 IdDoc,TipoDoc,ConsUnico,Leyenda,Inactivo,IntegraCias
			 FROM @Sys_TiposDoc
			 WHERE IdDoc NOT IN(SELECT IdDoc FROM Sys_TiposDoc)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @Sys_TiposDocCue))
			BEGIN
			 INSERT INTO Sys_TiposDocCue(
			 IdDoc,IdClase,ClaseCuenta,TipoMov
			 )
			 SELECT 
			 IdDoc,IdClase,ClaseCuenta,TipoMov
			 FROM @Sys_TiposDocCue
			 WHERE (IdDoc+Convert(varchar,IdClase)) NOT IN(SELECT (IdDoc+Convert(varchar,IdClase)) FROM Sys_TiposDocCue)
			END

			IF(EXISTS(SELECT TOP 1 * FROM @TiposDocCons))
			BEGIN
			 INSERT INTO TiposDocCons(
			 IdDoc,IdCia,LDesde,LHasta,Resolucion,RangoNum,
			 FechaRes,Prefijo,Numero,NumManual,IntLotes,ConfigFecha,
			 Formato,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,
			 FechaAdd,FechaUpdate,FechaVigRes,ClaveTecDian,CodResol
			 )
			 SELECT 
			 IdDoc,IdCia,LDesde,LHasta,Resolucion,RangoNum,
			 FechaRes,Prefijo,Numero,NumManual,IntLotes,ConfigFecha,
			 Formato,TipoPapel,Orientacion,VistaPrevia,VerSetup,NumCopias,
			 FechaAdd,FechaUpdate,FechaVigRes,ClaveTecDian,CodResol
			 FROM @TiposDocCons
			 WHERE (IdDoc+IdCia) NOT IN(SELECT (IdDoc+IdCia) FROM TiposDocCons)
			END

		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id VARCHAR (11)
			
			 IF(EXISTS(SELECT TOP 1 * FROM @Sys_TiposDocCue))
			 BEGIN 
				SELECT @id = IdDoc FROM @Sys_TiposDocCue
				DELETE FROM Sys_TiposDocCue WHERE IdDoc = @id
			 END

			 IF(EXISTS(SELECT TOP 1 * FROM @TiposDocCons))
			 BEGIN 
				SELECT @id = IdDoc FROM @TiposDocCons
				DELETE FROM TiposDocCons WHERE IdDoc = @id
			 END

			 IF(EXISTS(SELECT TOP 1 * FROM @Sys_TiposDoc))	
			 BEGIN
				SELECT @id = IdDoc FROM @Sys_TiposDoc
				DELETE FROM Sys_TiposDoc WHERE IdDoc = @id	
			 END
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposFuel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar TiposFuel.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposFuel]
	@TiposFuel dataTypeTiposFuel READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposFuel
			 SET 
			 IdCom = t2.IdCom, TipoComb = t2.TipoComb, Inactivo = t2.Inactivo
		     FROM TiposFuel t1
			 JOIN @TiposFuel t2 ON t1.IdCom = t2.IdCom
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposFuel(
			 IdCom,TipoComb,Inactivo
			 )
			 SELECT 
			 IdCom,TipoComb,Inactivo
			 FROM @TiposFuel
			 WHERE IdCom NOT IN(SELECT IdCom FROM TiposFuel)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdCom FROM @TiposFuel
			 DELETE FROM TiposFuel WHERE IdCom = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposLla]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar TiposLla.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposLla]
	@TiposLla dataTypeTiposLla READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposLla
			 SET 
			 IdTlla = t2.IdTlla,TipoLlanta = t2.TipoLlanta,Inactivo = t2.Inactivo
		     FROM TiposLla t1
			 JOIN @TiposLla t2 ON t1.IdTlla = t2.IdTlla
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposLla(
			 IdTlla,TipoLlanta,Inactivo
			 )
			 SELECT 
			 IdTlla,TipoLlanta,Inactivo
			 FROM @TiposLla
			 WHERE IdTlla NOT IN(SELECT IdTlla FROM TiposLla)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdTlla FROM @TiposLla
			 DELETE FROM TiposLla WHERE IdTlla = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposLub]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar TiposLub.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposLub]
	@TiposLub dataTypeTiposLub READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposLub
			 SET 
			 IdLub = t2.IdLub,TipoLub = t2.TipoLub,Inactivo = t2.Inactivo
		     FROM TiposLub t1
			 JOIN @TiposLub t2 ON t1.IdLub = t2.IdLub
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposLub(
			 IdLub,TipoLub,Inactivo
			 )
			 SELECT 
			 IdLub,TipoLub,Inactivo
			 FROM @TiposLub
			 WHERE IdLub NOT IN(SELECT IdLub FROM TiposLub)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdLub FROM @TiposLub
			 DELETE FROM TiposLub WHERE IdLub = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposMod]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar/Eliminar TiposMod.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposMod]
	@TiposMod dataTypeTiposMod READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposMod
			 SET 
			 IdModd = t2.IdModd,Modalidad = t2.Modalidad,Inactivo = t2.Inactivo
		     FROM TiposMod t1
			 JOIN @TiposMod t2 ON t1.IdModd = t2.IdModd
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposMod(
			 IdModd,Modalidad,Inactivo
			 )
			 SELECT 
			 IdModd,Modalidad,Inactivo
			 FROM @TiposMod
			 WHERE IdModd NOT IN(SELECT IdModd FROM TiposMod)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdModd FROM @TiposMod
			 DELETE FROM TiposMod WHERE IdModd = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposMot]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 22/04/2016
-- Description:	Insertar/Actualizar TiposMot.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposMot]
	@TiposMot dataTypeTiposMot READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposMot
			 SET 
			 IdTipoMot = t2.IdTipoMot,TipoMotor = t2.TipoMotor,Inactivo = t2.Inactivo
		     FROM TiposMot t1
			 JOIN @TiposMot t2 ON t1.IdTipoMot = t2.IdTipoMot
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposMot(
			 IdTipoMot,TipoMotor,Inactivo	
			 )
			 SELECT 
			 IdTipoMot,TipoMotor,Inactivo	
			 FROM @TiposMot
			 WHERE IdTipoMot NOT IN(SELECT IdTipoMot FROM TiposMot)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdTipoMot FROM @TiposMot
			 DELETE FROM TiposMot WHERE IdTipoMot = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposNivs]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar/Eliminar TiposNivs.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposNivs]
	@TiposNivs dataTypeTiposNivs READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposNivs
			 SET 
			 IdNiv = t2.IdNiv, NivelServicio = t2.NivelServicio, Inactivo = t2.Inactivo
		     FROM TiposNivs t1
			 JOIN @TiposNivs t2 ON t1.IdNiv = t2.IdNiv
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposNivs(
			 IdNiv, NivelServicio, Inactivo
			 )
			 SELECT 
			 IdNiv, NivelServicio, Inactivo
			 FROM @TiposNivs
			 WHERE IdNiv NOT IN(SELECT IdNiv FROM TiposNivs)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdNiv FROM @TiposNivs
			 DELETE FROM TiposNivs WHERE IdNiv = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposNovPgr]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 14/03/2017
-- Description:	Insertar/Actualizar/Eliminar TiposNovPgr.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposNovPgr]
	@TiposNovPgr dataTypeTiposNovPgr READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposNovPgr
			 SET 
			 IdNovedad = t2.IdNovedad,Novedad = t2.Novedad, Tipo = t2.Tipo,IdEstado = t2.IdEstado,Inactivo = t2.Inactivo
		     FROM TiposNovPgr t1
			 JOIN @TiposNovPgr t2 ON t1.IdNovedad = t2.IdNovedad
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposNovPgr(
			 IdNovedad,Novedad,Tipo,IdEstado,Inactivo
			 )
			 SELECT 
			 IdNovedad,Novedad,Tipo,IdEstado,Inactivo
			 FROM @TiposNovPgr
			 WHERE IdNovedad NOT IN(SELECT IdNovedad FROM TiposNovPgr)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdNovedad FROM @TiposNovPgr
			 DELETE FROM TiposNovPgr WHERE IdNovedad = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposOperac]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/08/2016
-- Description:	Insertar/Actualizar TiposOperac.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposOperac]
	@TiposOperac dataTypeTiposOperac READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposOperac
			 SET 
			 IdTipoOper = t2.IdTipoOper,TipoOperacion = t2.TipoOperacion,Inactivo = t2.Inactivo
		     FROM TiposOperac t1
			 JOIN @TiposOperac t2 ON t1.IdTipoOper = t2.IdTipoOper
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposOperac(
			 IdTipoOper,TipoOperacion,Inactivo
			 )
			 SELECT 
			 IdTipoOper,TipoOperacion,Inactivo
			 FROM @TiposOperac
			 WHERE IdTipoOper NOT IN(SELECT IdTipoOper FROM TiposOperac)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdTipoOper FROM @TiposOperac
			 DELETE FROM TiposOperac WHERE IdTipoOper = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposPpt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar/Eliminar TiposPpt.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposPpt]
	@TiposPpt dataTypeTiposPpt READONLY,
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @TiposPpt))
			begin
			 UPDATE TiposPpt
			 SET 
			 IdPpd = t2.IdPpd,TipoProp = t2.TipoProp,VehPropio = t2.VehPropio,Inactivo = t2.Inactivo
			 FROM TiposPpt T1
			 JOIN @TiposPpt T2 ON T1.IdPpd = T2.IdPpd
			end
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @TiposPpt))
			BEGIN
			 INSERT INTO TiposPpt(
			 IdPpd,TipoProp,VehPropio,Inactivo
			 )
			 SELECT 
			 IdPpd,TipoProp,VehPropio,Inactivo
			 FROM @TiposPpt
			 WHERE IdPpd NOT IN(SELECT IdPpd FROM TiposPpt)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdPpd FROM @TiposPpt		
			 DELETE FROM TiposPpt WHERE IdPpd = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposVeh]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar/eliminar TiposVeh.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposVeh]
	@TiposVeh dataTypeTiposVeh READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposVeh
			 SET
			 IdTipoVeh = t2.IdTipoVeh, TipoVehiculo = t2.TipoVehiculo, Configuracion = t2.Configuracion, Ejes = t2.Ejes, 
			 Llantas = t2.Llantas, CapacPeso = t2.CapacPeso, UndCapac = t2.UndCapac, CapacVol = t2.CapacVol, 
			 UndCapVol = t2.UndCapVol, CubAlto = t2.CubAlto, CubLargo = t2.CubLargo, CubAncho = t2.CubAncho, 
			 PesoBruto = t2.PesoBruto, Inactivo = t2.Inactivo 
		     FROM TiposVeh t1
			 JOIN @TiposVeh t2 ON t1.IdTipoVeh = t2.IdTipoVeh
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposVeh(
			 IdTipoVeh, TipoVehiculo, Configuracion, Ejes, Llantas, CapacPeso, UndCapac, CapacVol, 
			 UndCapVol, CubAlto, CubLargo, CubAncho, PesoBruto, Inactivo
			 )
			 SELECT 
			 IdTipoVeh, TipoVehiculo, Configuracion, Ejes, Llantas, CapacPeso, UndCapac, CapacVol, 
			 UndCapVol, CubAlto, CubLargo, CubAncho, PesoBruto, Inactivo
			 FROM @TiposVeh
			 WHERE IdTipoVeh NOT IN(SELECT IdTipoVeh FROM TiposVeh)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdTipoVeh FROM @TiposVeh
			 DELETE FROM TiposVeh WHERE IdTipoVeh = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTiposVehFactor]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 29/04/2016
-- Description:	Insertar/Actualizar/Eliminar TiposVehFactor.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTiposVehFactor]
	@TiposVehFactor dataTypeTiposVehFactor READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TiposVehFactor
			 SET 
			 IdTipoVeh = t2.IdTipoVeh,nSemana = t2.nSemana,TarifaFc = t2.TarifaFc
		     FROM TiposVehFactor t1
			 JOIN @TiposVehFactor t2 ON t1.IdTipoVeh = t2.IdTipoVeh and t1.nSemana = t2.nSemana
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TiposVehFactor(
			 IdTipoVeh,nSemana,TarifaFc
			 )
			 SELECT 
			 IdTipoVeh,nSemana,TarifaFc
			 FROM @TiposVehFactor
			 WHERE IdTipoVeh + '_' + Convert(varchar,nSemana) NOT IN(SELECT IdTipoVeh + '_' + Convert(varchar,nSemana) FROM TiposVehFactor)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 declare @nsem int
			 SELECT @id = IdTipoVeh, @nsem = nSemana FROM @TiposVehFactor
			 DELETE FROM TiposVehFactor WHERE IdTipoVeh = @id and nSemana = @nsem
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraConcCausac]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 13/02/2017
-- Description:	Insertar/Actualizar/Eliminar Conceptos Causacion(TraConcCausac).
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTraConcCausac]
	@TraConcCausac dataTypeTraConcCausac READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @TraConcCausac))
			begin
			 UPDATE TraConcCausac
			 SET
			  IdConcepto = t2.IdConcepto,
			  Concepto = t2.Concepto,
			  IdCuenta = t2.IdCuenta,
			  TipoConc = t2.TipoConc,
			  Inactivo = t2.Inactivo
			 FROM TraConcCausac t1
			 JOIN @TraConcCausac t2 ON t1.IdConcepto = t2.IdConcepto
			 WHERE t1.IdConcepto = t2.IdConcepto
			end
							
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(EXISTS(SELECT TOP 1 * FROM @TraConcCausac))
			BEGIN
			INSERT INTO TraConcCausac(
			IdConcepto,Concepto,IdCuenta,TipoConc,Inactivo
			)
			SELECT 
			IdConcepto,Concepto,IdCuenta,TipoConc,Inactivo
			FROM @TraConcCausac
			WHERE IdConcepto NOT IN(SELECT IdConcepto FROM TraConcCausac)
			END
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @_id VARCHAR(4)
			 
			 IF(EXISTS(SELECT TOP 1 * FROM @TraConcCausac))	
			 BEGIN
				SELECT @_id = IdConcepto FROM @TraConcCausac
				DELETE FROM TraConcCausac WHERE IdConcepto = @_id			 
			 END
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspColegios]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 01/08/2016
-- Description:	Insertar/Actualizar TraEspColegios.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTraEspColegios]
	@TraEspColegios dataTypeTraEspColegios READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TraEspColegios
			 SET 
			 IdColegio = t2.IdColegio,NomColegio = t2.NomColegio,IdGrupo = t2.IdGrupo,Inactivo = t2.Inactivo
		     FROM TraEspColegios t1
			 JOIN @TraEspColegios t2 ON t1.IdColegio = t2.IdColegio
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TraEspColegios(
			 IdColegio,NomColegio,IdGrupo,Inactivo
			 )
			 SELECT 
			 IdColegio,NomColegio,IdGrupo,Inactivo
			 FROM @TraEspColegios
			 WHERE IdColegio NOT IN(SELECT IdColegio FROM TraEspColegios)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdColegio FROM @TraEspColegios
			 DELETE FROM TraEspColegios WHERE IdColegio = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspGruposCol]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 01/08/2016
-- Description:	Insertar/Actualizar TraEspGruposCol.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTraEspGruposCol]
	@TraEspGruposCol dataTypeTraEspGruposCol READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TraEspGruposCol
			 SET 
			 IdGrupo = t2.IdGrupo,Grupo = t2.Grupo,Inactivo = t2.Inactivo
		     FROM TraEspGruposCol t1
			 JOIN @TraEspGruposCol t2 ON t1.IdGrupo = t2.IdGrupo
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TraEspGruposCol(
			 IdGrupo,Grupo,Inactivo
			 )
			 SELECT 
			 IdGrupo,Grupo,Inactivo
			 FROM @TraEspGruposCol
			 WHERE IdGrupo NOT IN(SELECT IdGrupo FROM TraEspGruposCol)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdGrupo FROM @TraEspGruposCol
			 DELETE FROM TraEspGruposCol WHERE IdGrupo = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspHorario]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 20/12/2016
-- Description:	Insertar/Actualizar TraEspHorario.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTraEspHorario]
	@TraEspHorario dataTypeTraEspHorario READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TraEspHorario
			 SET 
			 IdHorario = t2.IdHorario, Item = t2.Item, Inicio = t2.Inicio, Final = t2.Final, Inactivo = t2.Inactivo
		     FROM TraEspHorario t1
			 JOIN @TraEspHorario t2 ON t1.IdHorario = t2.IdHorario and t1.Item = t2.Item 
			 --Insertar lo que no existe
			 INSERT INTO TraEspHorario(
			 IdHorario,Item,Inicio,Final,Inactivo
			 )
			 SELECT 
			 IdHorario,Item,Inicio,Final,Inactivo
			 FROM @TraEspHorario
			 WHERE (IdHorario + Convert(varchar,Item)) NOT IN(SELECT (IdHorario + Convert(varchar,Item)) FROM TraEspHorario)
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TraEspHorario(
			 IdHorario,Item,Inicio,Final,Inactivo
			 )
			 SELECT 
			 IdHorario,Item,Inicio,Final,Inactivo
			 FROM @TraEspHorario
			 WHERE (IdHorario + Convert(varchar,Item)) NOT IN(SELECT (IdHorario + Convert(varchar,Item)) FROM TraEspHorario)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 DECLARE @item varchar(4)
			 SELECT @id = IdHorario, @item = Item FROM @TraEspHorario
			 DELETE FROM TraEspHorario WHERE IdHorario = @id and Item = @item
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspObjContratos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa Castañeda
-- Create date(dd/MM/yyyy): 04/01/2019
-- Description:	Insertar/Actualizar/Eliminar Objetos de Contratos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTraEspObjContratos]
	@TraEspObjContratos dataTypeTraEspObjContratos READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE  @Pdtminado bit	
		IF(@operacion = 'u' OR @operacion = 'i')
		BEGIN	 
			select TOP (1) @Pdtminado = Predtminado from @TraEspObjContratos
		END
		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			IF(@Pdtminado = 1)
			BEGIN
				UPDATE TraEspObjContratos SET Predtminado = 0
			END
			 UPDATE TraEspObjContratos
			 SET 
			 IdObj = t2.IdObj,Objeto = t2.Objeto, Predtminado = t2.Predtminado ,Inactivo = t2.Inactivo
		     FROM TraEspObjContratos t1
			 JOIN @TraEspObjContratos t2 ON t1.IdObj = t2.IdObj
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			IF(@Pdtminado = 1)
			BEGIN
				UPDATE TraEspObjContratos SET Predtminado = 0
			END
			 INSERT INTO TraEspObjContratos(
			 IdObj,Objeto,Predtminado,Inactivo
			 )
			 SELECT 
			 IdObj,Objeto,Predtminado,Inactivo
			 FROM @TraEspObjContratos
			 WHERE IdObj NOT IN(SELECT IdObj FROM TraEspObjContratos)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(4)
			 SELECT @id = IdObj FROM @TraEspObjContratos
			 DELETE FROM TraEspObjContratos WHERE IdObj = @id
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraEspPolizas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 16/11/2016
-- Description:	Insertar CRUD Masivo de polizas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTraEspPolizas]
	@TraEspPolizas dataTypeTraEspPolizas READONLY,--Tipo de dato definido por el usuario que representa la tabla TraEspPolizas
	@TraEspPolDetalle dataTypeTraEspPolDetalle READONLY,--Tipo de dato definido por el usuario que representa la tabla TraEspPolDetalle
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo de las Polizas
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento de las Polizas 
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia de las Polizas
declare @item int
	BEGIN TRAN
		BEGIN TRY

			--Seleccionar Variables
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia FROM @TraEspPolizas
				SELECT @Documento = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia

				IF(@Documento <> '')
					UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
				ELSE
				BEGIN
					SELECT @Documento = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			end

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			   if(EXISTS(SELECT * FROM @TraEspPolizas))
			   begin
			   UPDATE TraEspPolizas
			   SET 
			   TipDoc = t2.TipDoc,NumDoc = t2.NumDoc,IdCia = t2.IdCia,Fecha = t2.Fecha,FechaExp = t2.FechaExp,FechaVence = t2.FechaVence,
			   TipoPol = t2.TipoPol,IdProv = t2.IdProv,NumPoliza = t2.NumPoliza,VrPoliza = t2.VrPoliza,VrCobro = t2.VrCobro,
			   IdTipoVeh = t2.IdTipoVeh,TipoAfil = t2.TipoAfil,Todos = t2.Todos,OnlyActivos = t2.OnlyActivos,IdVehiculo = t2.IdVehiculo,
			   IdConcepto = t2.IdConcepto,TipCom = t2.TipCom,Comprobante = t2.Comprobante,IdCiaCom = t2.IdCiaCom,NCuotasOtros = t2.NCuotasOtros,NCuotasSocios = t2.NCuotasSocios,
			   IdMneda = t2.IdMneda,OrigenAdd = t2.OrigenAdd,IdEstado = t2.IdEstado,TimeSys = t2.TimeSys,FecUpdate = t2.FecUpdate,
			   IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario,Inactivo = t2.Inactivo
		       FROM TraEspPolizas t1
			   JOIN @TraEspPolizas t2 ON t1.TipDoc = t2.TipDoc and t1.NumDoc = t2.NumDoc and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @TraEspPolDetalle))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = NumDoc FROM @TraEspPolDetalle
			   select @item = isnull(MAX(Item),0) from TraEspPolDetalle where TipDoc = @TipDoc and NumDoc = @Documento and IdCia = @IdCia

			   --actualizar los que vienen en el tipo de dato y coincida con los que ya están en la tabla
			   UPDATE TraEspPolDetalle
			   SET 
			   TipDoc = t2.TipDoc,NumDoc = t2.NumDoc,IdCia = t2.IdCia,Item = t2.Item,IdVehiculo = t2.IdVehiculo
		       FROM TraEspPolDetalle t1
			   JOIN @TraEspPolDetalle t2 ON t1.TipDoc = t2.TipDoc and t1.NumDoc = t2.NumDoc and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.NumDoc = t2.NumDoc and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO TraEspPolDetalle(
			   TipDoc,NumDoc,IdCia,Item,IdVehiculo
			   ) 
			   SELECT 
			   @TipDoc,@Documento,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)),IdVehiculo
			   FROM @TraEspPolDetalle
			   WHERE (TipDoc + Convert(varchar,NumDoc)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,NumDoc)+IdCia+Convert(varchar,Item)) FROM TraEspPolDetalle)
			   --Eliminar los que no existen en lo que envian
			   delete from TraEspPolDetalle
			   WHERE TipDoc = @TipDoc and NumDoc = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @TraEspPolDetalle)

			   end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN
			  	select @item = isnull(MAX(Item),0) from TraEspPolDetalle where TipDoc = @TipDoc and NumDoc = @Documento and IdCia = @IdCia

				IF(EXISTS(SELECT * FROM @TraEspPolizas))
				begin
				INSERT INTO TraEspPolizas(
				TipDoc,NumDoc,IdCia,Fecha,FechaExp,FechaVence,TipoPol,IdProv,NumPoliza,VrPoliza,VrCobro,IdTipoVeh,TipoAfil,Todos,
				OnlyActivos,IdVehiculo,IdConcepto,TipCom,Comprobante,IdCiaCom,NCuotasOtros,NCuotasSocios,IdMneda,OrigenAdd,IdEstado,TimeSys,FecUpdate,
				IdCiaCrea,IdUsuario,Inactivo
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,Fecha,FechaExp,FechaVence,TipoPol,IdProv,NumPoliza,VrPoliza,VrCobro,IdTipoVeh,TipoAfil,Todos,
				OnlyActivos,IdVehiculo,IdConcepto,TipCom,Comprobante,IdCiaCom,NCuotasOtros,NCuotasSocios,IdMneda,OrigenAdd,IdEstado,TimeSys,FecUpdate,
				IdCiaCrea,IdUsuario,Inactivo
				FROM @TraEspPolizas
				end

				IF(EXISTS(SELECT * FROM @TraEspPolDetalle))
				begin
				INSERT INTO TraEspPolDetalle(
				TipDoc,NumDoc,IdCia,Item,IdVehiculo
				) 
				SELECT 
				@TipDoc,@Documento,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)),IdVehiculo
				FROM @TraEspPolDetalle
				end

			 END

			 IF(@operacion = 'i' or @operacion = 'u')
			 begin
			    UPDATE Vehiculos
				SET FecRCivil = t3.FechaExp , VigRCivil = t3.FechaVence, RespCivil = T3.NumPoliza
				FROM Vehiculos t1, @TraEspPolDetalle t2, @TraEspPolizas t3
				WHERE t1.IdVehiculo = t2.IdVehiculo and t3.TipoPol = 'RCC'

				UPDATE VehAnexo
				SET FecEmisionRCE = t3.FechaExp , FecVigenciaRCE = t3.FechaVence, PolizaRCE = T3.NumPoliza
				FROM VehAnexo t1, @TraEspPolDetalle t2, @TraEspPolizas t3
				WHERE t1.IdVehiculo = t2.IdVehiculo and t3.TipoPol <> 'RCC'
			end

			SELECT @Documento

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTraFijos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 30/11/2016
-- Description:	Insertar/Actualizar TraFijos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTraFijos]
	@TraFijos dataTypeTraFijos READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		if(@operacion = 'i')
		begin
			SELECT @item = isnull(MAX(Numero),0) + 1 FROM  TraFijos 
		end 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE TraFijos
			 SET 
			 Numero = t2.Numero,IdConcepto = t2.IdConcepto,DescConc = t2.DescConc,TipoConc = t2.TipoConc,Tarifa = t2.Tarifa,
			 TipoTarif = t2.TipoTarif,TipoAfilVeh = t2.TipoAfilVeh,CdTipoVeh = t2.CdTipoVeh,TipoTerc = t2.TipoTerc,Anulado = t2.Anulado,
			 CdCiuOrigen = t2.CdCiuOrigen,CdCiuDestino = t2.CdCiuDestino,pVehiculo = t2.pVehiculo,CedConductor = t2.CedConductor,CdRuta = t2.CdRuta,
			 TipoVigencia = t2.TipoVigencia, FechaInicial = t2.FechaInicial, FechaFinal = t2.FechaFinal, NitCliente = t2.NitCliente, CdMercancia = t2.CdMercancia
		     FROM TraFijos t1
			 JOIN @TraFijos t2 ON t1.Numero = t2.Numero and t1.IdConcepto = t2.IdConcepto
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO TraFijos(
			 Numero,IdConcepto,DescConc,TipoConc,Tarifa,TipoTarif,TipoAfilVeh,CdTipoVeh,TipoTerc,Anulado,CdCiuOrigen,CdCiuDestino,pVehiculo,
			 CedConductor,CdRuta,TipoVigencia,FechaInicial,FechaFinal,NitCliente,CdMercancia
			 )
			 SELECT 
			 @item,IdConcepto,DescConc,TipoConc,Tarifa,TipoTarif,TipoAfilVeh,CdTipoVeh,TipoTerc,Anulado,CdCiuOrigen,CdCiuDestino,pVehiculo,
			 CedConductor,CdRuta,TipoVigencia,FechaInicial,FechaFinal,NitCliente,CdMercancia
			 FROM @TraFijos
			 WHERE (Convert(varchar,Numero) + IdConcepto) NOT IN(SELECT (Convert(varchar,Numero) + IdConcepto) FROM TraFijos)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DELETE FROM TraFijos WHERE Numero = (Select Numero from @TraFijos)
			 -- and IdConcepto = (Select IdConcepto from @TraFijos)
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_Aprobacion]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 02/09/2016
-- Description:	Aprobacion de Cotización.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_Aprobacion]
	@Trn_Aprobacion dataTypeTrn_Aprobacion READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Aprobacion
	--@Trn_Autoriza dataTypeTrn_Autoriza READONLY --Tipo de dato definido por el usuario que representa la tabla Trn_Autoriza
	@operacion varchar(1)
AS
DECLARE @Documento INT --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el tipo de documento aprobación
DECLARE @IdCia VARCHAR(2) --En esta variable se guarda la compañia del documento aprobación
DECLARE @Tabla VARCHAR(250) --En esta variable se guarda el nombre de la tabla que se acutalizará 
DECLARE @ColTabla VARCHAR(250) --En esta variable se guarda la columna que se actualizará
DECLARE @Estado VARCHAR(4) --En esta variable se guarda el estado del documento que se aprobará
DECLARE @TipoPed VARCHAR(3) --En esta variable se guarda el tipo del documento que se actualizará
DECLARE @IdCiaPed VARCHAR(2) --En esta variable se guarda la compañia del documento que se actualizará
DECLARE @Pedido INT --En esta variable se guarda el numero del documento que se aprobará
DECLARE @Fecha SMALLDATETIME --En esta variable se guarda la fecha del documento
	BEGIN TRAN
		BEGIN TRY
		    
			--Consecutivos
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Tabla = Tabla, @ColTabla = ColTabla, @TipoPed = TipoPed, @IdCiaPed = IdCiaPed, @Pedido = Pedido, @Fecha = Fecha FROM @Trn_Aprobacion
				SELECT @Documento = Numero + 1  FROM TiposDocCons WHERE IdDoc = @TipDoc and IdCia = @IdCia
				--SELECT @Estado = IdEstado FROM EstadoDoc WHERE Estado = 'ACTIVO'

				IF(@Documento <> '')
					UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
				ELSE
				BEGIN
					SELECT @Documento = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			end
			
			--UPDATE SI-EXISTE RECORDS
			 IF(@operacion = 'u')
			 BEGIN
			 UPDATE Trn_Aprobacion
			 SET 
			 TipDoc = t2.TipDoc,Aprobacion = t2.Aprobacion,IdCia = t2.IdCia,Fecha = t2.Fecha,
			 TipoPed = t2.TipoPed,Pedido = t2.Pedido,IdCiaPed = t2.IdCiaPed,FecPedido = t2.FecPedido,
			 IdCliente = t2.IdCliente,IdAgencia = t2.IdAgencia,pVehiculo = t2.pVehiculo,VrCupoCred = t2.VrCupoCred,
			 VrSaldoAct = t2.VrSaldoAct,ChequesDev = t2.ChequesDev,ClienteMora = t2.ClienteMora,OrigenAdd = t2.OrigenAdd,
			 Anulado = t2.Anulado,FecDev = t2.FecDev,Observacion = t2.Observacion,IdEstado = t2.IdEstado,
			 TimeSys = t2.TimeSys,FecUpdate = t2.FecUpdate,IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario
			 FROM Trn_Aprobacion t1
			 JOIN @Trn_Aprobacion t2 ON t1.TipDoc = t2.TipDoc and t1.Aprobacion = t2.Aprobacion and t1.IdCia = t2.IdCia
			 END

			--INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			BEGIN
			INSERT INTO Trn_Aprobacion(
			TipDoc, Aprobacion, IdCia, Fecha, TipoPed, Pedido, IdCiaPed, FecPedido, IdCliente, IdAgencia,
			pVehiculo, VrCupoCred, VrSaldoAct, ChequesDev, ClienteMora, OrigenAdd, Anulado, FecDev, Observacion, 
			IdEstado, TimeSys, FecUpdate, IdCiaCrea, IdUsuario
			)
			SELECT			
			@TipDoc, @Documento, @IdCia, Fecha, TipoPed, Pedido, IdCiaPed, FecPedido, IdCliente, IdAgencia,
			pVehiculo, VrCupoCred, VrSaldoAct, ChequesDev, ClienteMora, OrigenAdd, Anulado, FecDev, Observacion, 
			'0001', TimeSys, FecUpdate, IdCiaCrea, IdUsuario			
			FROM @Trn_Aprobacion
			END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 DECLARE @Aprobacion int
			 SELECT @Aprobacion = Aprobacion FROM @Trn_Aprobacion
			 DELETE FROM Trn_Aprobacion WHERE TipDoc = @TipDoc and Aprobacion = @Aprobacion and IdCia = @IdCia
			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
			  declare @IdEstado varchar(4)
			  --select @IdEstado = IdEstado from EstadoDoc where Estado = 'ANULADO'
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Aprobacion from @Trn_Aprobacion
			  UPDATE Trn_Aprobacion SET IdEstado = '9999', Anulado = '1' WHERE TipDoc = @TipDoc and Aprobacion = @Documento and IdCia = @IdCia
			  --Actualizar Documento al cual se anula la aprobacion
			  SELECT TOP 1 @Tabla = Tabla, @ColTabla = ColTabla, @TipoPed = TipoPed, @IdCiaPed = IdCiaPed, @Pedido = Pedido FROM @Trn_Aprobacion
			  --SELECT @IdEstado = IdEstado from EstadoDoc where Estado = 'RADICADO'
			  EXEC('UPDATE '+@Tabla+' SET IdEstado = ''0002'', NumAprob = 0, IdCiaApr = ''00'' WHERE TipDoc = '''+@TipoPed+''' AND Idcia = '''+@IdciaPed+''' AND '+@ColTabla+' = '+@Pedido)
			END

			--IF(EXISTS(SELECT * FROM @Trn_Autoriza))
			--BEGIN
			--declare @numaut int
			--declare @idaut char(2) 
			--select @numaut = Autoriza, @idaut = IdCia from @dataTypeTrn_Autoriza

			--	UPDATE Trn_Autoriza SET IdEstado = '9998' WHERE Trn_Autoriza.NumAutoriza = @numaut AND Trn_Autoriza.IdCia = @idaut
			--END

			IF(@operacion = 'i')
			BEGIN
				SELECT @IdEstado = '0001'
				EXEC('UPDATE '+@Tabla+' SET IdEstado = '''+@IdEstado+''', NumAprob = '+@Documento+', IdCiaApr = '''+@IdCia+''', FecAprob = '''+@Fecha+'''  WHERE TipDoc = '''+@TipoPed+''' AND Idcia = '''+@IdciaPed+''' AND '+@ColTabla+' = '+@Pedido)
			END

			SELECT '1'

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
            DECLARE @ErrorSeverity INT;
            DECLARE @ErrorState INT;

		    SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR (
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_DevFco]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 24/01/2017
-- Description:	Insertar Trn_DevFco
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_DevFco]
	--@Trn_DevFco dataTypeTrn_DevFco READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DevFco
	--@Trn_FacReservas dataTypeTrn_TraEspFacReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFacReservas
	--@Trn_Kardex dataTypeTrn_Kardex READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Kardex
	--@Trn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos
	--@Trn_DocMemo dataTypeTrn_DocMemo READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DocMemo

	--@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	--@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	--@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	--@Trn_NiifDetalle dataTypeTrn_NiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	--@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			
			--SELECT TOP 1 @TipDoc = TipDoc, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_DevFco
			--SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

			--IF(@Numero > 0)
			--	UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
			--ELSE
			--BEGIN
			--	SELECT @Numero = 1
			--	INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--END

			--IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			--BEGIN
			--	SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
			--	SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
			--	--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
			--	IF(@Comprobante <> '')
			--		UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
			--	ELSE
			--	BEGIN
			--		SELECT @Comprobante = 1
			--		INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--	END
			--END

			--IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
			--BEGIN
			--	SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
			--	SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
			--	--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
			--	IF(@CompNiif <> '')
			--		UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
			--	ELSE
			--	BEGIN
			--		SELECT @CompNiif = 1
			--		INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--	END
			--END

			--IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
			--BEGIN
			--	SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
			--	SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
			--	--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
			--	IF(@CompNiif <> '')
			--		UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
			--	ELSE
			--	BEGIN
			--		SELECT @CompFis = 1
			--		INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--	END
			--END
			
			--IF(@operacion = 'i')
			--begin
			--	IF(EXISTS(SELECT * FROM @Trn_DevFco))
			--	BEGIN
			--	INSERT INTO Trn_DevFco(
			--	TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,Factura,IdCiaDoc,FecDoc,nClieCon,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,
			--	VrReteICA,VrReteIVA,VrFletes,VrCargos,VrOtrDcto,VrCostos,VrNeto,VrEfectivo,VrPagosOtr,Cantidad,CantPuntos,BaseImp,BaseRet,IdCajero,
			--	IdVend,TarifaCom,CodTarCom,NitCliente,CdAgencia,IdCCosto,IdSubCos,IdLocal,EnEfectivo,Pedido,IdCiaPed,Remision,IdCiaRem,FecPedido,
			--	Modalidad,ModdDev,NumAutoriza,PlacaVehic,KmtVehic,OrigenAdd,TipCom,Comprobante,IdCiaCom,Observacion,IdEstado,TimeSys,FecUpdate,
			--	IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Fecha,IdConcepto,TipDoc,Factura,IdCiaDoc,FecDoc,nClieCon,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,
			--	VrReteICA,VrReteIVA,VrFletes,VrCargos,VrOtrDcto,VrCostos,VrNeto,VrEfectivo,VrPagosOtr,Cantidad,CantPuntos,BaseImp,BaseRet,IdCajero,
			--	IdVend,TarifaCom,CodTarCom,NitCliente,CdAgencia,IdCCosto,IdSubCos,IdLocal,EnEfectivo,Pedido,IdCiaPed,Remision,IdCiaRem,FecPedido,
			--	Modalidad,ModdDev,NumAutoriza,PlacaVehic,KmtVehic,OrigenAdd,TipCom,Comprobante,IdCiaCom,Observacion,IdEstado,TimeSys,FecUpdate,
			--	IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio
			--	FROM @Trn_DevFco
			--	END 

			--	IF(EXISTS(SELECT * FROM @Trn_FacReservas))
			--	BEGIN
			--	INSERT INTO Trn_TraEspFacReservas(
			--	TipDoc,Factura,IdCia,Item,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,UndTarifa,
			--	TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
			--	pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Item,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,UndTarifa,
			--	TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
			--	pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct
			--	FROM @Trn_FacReservas
			--	END 

			--	IF(EXISTS(SELECT * FROM @Trn_Kardex))
			--	BEGIN
			--	INSERT INTO Trn_Kardex(
			--	TipDoc,Documento,IdCia,Item,Fecha,IdProducto,IdBodega,CdTanque,Entradas,Salidas,IdUnd,VrUnitario,VrPrecio,VrCostProm,
			--	TarifaIva,VrIvaEnt,VrIvaSal,TarifaDct,VrDctoEnt,VrDctoSal,VrCostoEnt,VrCostoSal,TarifaRet,VrReteEnt,VrReteSal,TarifaIca,
			--	VrIcaEnt,VrIcaSal,VrBruto,CdUbic,NumLote,FechLote,IdConcepto,IdTercero,CdAgencia,CdCCosto,CdSubCos,CdLocal,CdSzona,pVehiculo,
			--	IdVend,Comision,CdOperario,ComisnOper,Referencia,Descripcion,Comptmntos,CdProdEquiv,TipOrd,NumOrden,IdCiaOrd,Cotizacion,
			--	IdCiaCot,Remision,IdCiaRem,Factura,TipDocDev,NumDocDev,CdMngra,NumInicial,NumFinal,Sobretasa,TasaNac,TasaDep,TasaMun,Soldicom,
			--	ImpGlobal,OtroImpto,Unidades,ItemCombo,Servcios,NoVentas,EsCombo,EsProdBase,CodTarDct,CodTarIva,CodTarIca,CodTarRet,CodTarCom,
			--	CodTarCmc,ListaPrec,VrBase,CdMoneda,VrTasaCamb,VrDivisa1,VrDivisa2,VrDivisa3,Referencia2,FecOrden,galsbruto,galsneto,
			--	Temperatura,UmTemp,Densidad,TimeSys,IdUsuario,Rec_Costo,MgenCont,VrImvCosto,TarifaIco,VrImpCon,CantObseq,VrIvaObseq
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Item,Fecha,IdProducto,IdBodega,CdTanque,Entradas,Salidas,IdUnd,VrUnitario,VrPrecio,VrCostProm,
			--	TarifaIva,VrIvaEnt,VrIvaSal,TarifaDct,VrDctoEnt,VrDctoSal,VrCostoEnt,VrCostoSal,TarifaRet,VrReteEnt,VrReteSal,TarifaIca,
			--	VrIcaEnt,VrIcaSal,VrBruto,CdUbic,NumLote,FechLote,IdConcepto,IdTercero,CdAgencia,CdCCosto,CdSubCos,CdLocal,CdSzona,pVehiculo,
			--	IdVend,Comision,CdOperario,ComisnOper,Referencia,Descripcion,Comptmntos,CdProdEquiv,TipOrd,NumOrden,IdCiaOrd,Cotizacion,
			--	IdCiaCot,Remision,IdCiaRem,Factura,TipDocDev,NumDocDev,CdMngra,NumInicial,NumFinal,Sobretasa,TasaNac,TasaDep,TasaMun,Soldicom,
			--	ImpGlobal,OtroImpto,Unidades,ItemCombo,Servcios,NoVentas,EsCombo,EsProdBase,CodTarDct,CodTarIva,CodTarIca,CodTarRet,CodTarCom,
			--	CodTarCmc,ListaPrec,VrBase,CdMoneda,VrTasaCamb,VrDivisa1,VrDivisa2,VrDivisa3,Referencia2,FecOrden,galsbruto,galsneto,
			--	Temperatura,UmTemp,Densidad,TimeSys,IdUsuario,Rec_Costo,MgenCont,VrImvCosto,TarifaIco,VrImpCon,CantObseq,VrIvaObseq
			--	FROM @Trn_Kardex
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_Pagos))
			--	BEGIN
			--	INSERT INTO Trn_Pagos(
			--	TipDoc,Documento,IdCia,Item,Fecha,IdForma,Detalle,VrPagado,VrCambio,EsCaja,IdBanco,NitCliente,CdAgencia,NumForma,FecForma,
			--	CtaForma,Beneficiario,Referncia1,Referncia2,CdLocal,NumAutoriza,VrDenom,Cantidad,TipDenom,TipRef,DocRef,IdCiaRef,ItemDoc,
			--	CdCta,IdUsuario
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Item,Fecha,IdForma,Detalle,VrPagado,VrCambio,EsCaja,IdBanco,NitCliente,CdAgencia,NumForma,FecForma,
			--	CtaForma,Beneficiario,Referncia1,Referncia2,CdLocal,NumAutoriza,VrDenom,Cantidad,TipDenom,TipRef,DocRef,IdCiaRef,ItemDoc,
			--	CdCta,IdUsuario
			--	FROM @Trn_Pagos
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_DocMemo))
			--	BEGIN
			--	INSERT INTO Trn_DocMemo(
			--	TipDoc,Documento,IdCia,Comentarios,Nota1,Nota2,Nota3,CantImp
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Comentarios,Nota1,Nota2,Nota3,CantImp
			--	FROM @Trn_DocMemo
			--	END 

			--	IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			--	BEGIN
			--	INSERT INTO Trn_Comprobantes(
			--	TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			--	NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
			--	TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			--	VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			--	Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			--	PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero
			--	)
			--	SELECT 
			--	@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			--	NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
			--	TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			--	VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			--	Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			--	PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis
			--	FROM @Trn_Comprobantes
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
			--	BEGIN
			--	INSERT INTO Trn_ComDetalle(
			--	TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
			--	IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
			--	IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
			--	NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
			--	CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
			--	IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
			--	)
			--	SELECT 
			--	@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
			--	IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
			--	CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
			--	NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
			--	CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
			--	IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
			--	FROM @Trn_ComDetalle
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_NiifComp))
			--	BEGIN
			--	INSERT INTO Trn_NiifComp(
			--	TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
			--	EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
			--	FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
			--	VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
			--	IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
			--	Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
			--	CtbTipo, CtbNumero,
			--	FisTipo, FisNumero 
			--	)
			--	SELECT 
			--	CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, CASE N.TipoNiif WHEN 'NIIF' THEN @IdCiaCompNiif ELSE @IdCiaCompFis END, C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
			--	C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
			--	C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
			--	C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
			--	C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
			--	C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
			--	CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
			--	CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
			--	FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
			--	BEGIN
			--	INSERT INTO Trn_NiifDetalle(
			--	TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
			--	VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
			--	VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
			--	NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
			--	NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
			--	CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
			--	DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
			--	CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
			--	FechAutoriza, CodCuentaCG
			--	)
			--	SELECT 
			--	CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @IdCiaCompNiif ELSE @IdCiaCompFis END, N.Item, C.Fecha, N.IdCuenta, N.Detalle,
			--	N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo, N.IdCCosto, N.IdSubCos,
			--	C.VrBase, C.TarifaBase, @TipDoc, @Numero, @Cia, C.CodConce,
			--	C.NitDoc, C.TipFac, C.Factura, C.IdCiaFac, C.ItemFac, C.FecVence, C.CodCta, 
			--	C.NumCheque, C.Integrado, C.TipoAplica, C.Consolida, C.CodCargo, C.NitOtros,
			--	C.CodSubgpo, C.CiuOrigen, C.CodAgncia, C.VehPropio, N.Referncia, C.TipDocRef,
			--	C.DocRef, C.IdCiaRef, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario,
			--	C.CdConcTrib, C.CdTarifTrib, C.NumEstablec,C.PtoEmision, C.Num_Autoriza,
			--	C.FechAutoriza, C.IdCuenta
			--	FROM @Trn_ComDetalle AS C JOIN @Trn_NiifDetalle AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont AND C.Item = N.Item JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
			--	END
			--end

			----IF(@operacion = 'i')
			----begin
			----  --actualiza los items de un contrato con los que se relacionan en el tipo de datos nuevo
			----  UPDATE Trn_TraEspResDetalle
			----  SET  EstadoItem = 'FACTURADA'
			----  FROM Trn_TraEspResDetalle d, @Trn_FacReservas r 
			----  WHERE d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCia and d.Item = r.ItemRes
			----end
						
			--SELECT @Numero

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_DevFcr]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 24/01/2017
-- Description:	Insertar Trn_DevFcr
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_DevFcr]
	@Trn_DevFcr dataTypeTrn_DevFcr READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DevFcr
	@Trn_TraEspFacReservas dataTypeTrn_TraEspFacReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFacReservas
	@Trn_RecAfavor dataTypeTrn_RecAfavor READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_RecAfavor
	@Trn_VencAbonos dataTypeTrn_VencAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_VencAbonos
	@Trn_DocMemo dataTypeTrn_DocMemo READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DocMemo
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			
			declare @fecdev smalldatetime
			DECLARE @modalidad varchar(10)

			IF(@operacion = 'i')
			begin
			
				SELECT TOP 1 @TipDoc = TipDev, @Cia = IdCia,@fecdev = Fecha,@modalidad = ModdDev, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_DevFcr
				SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

				IF(@Numero > 0)
					UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
				ELSE
				BEGIN
					SELECT @Numero = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			end

			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_DevFcr))
				BEGIN
				INSERT INTO Trn_DevFcr(
				TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,Factura,IdCiaDoc,FecDoc,IdCliente,IdAgencia,VrSubTotal,VrDescuento,VrImpuesto,
				VrRetencion,VrReteICA,VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,
				VrNeto,Cantidad,CantPuntos,BaseImp,BaseRet,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,IdLocEnv,Pedido,IdCiaPed,Remision,
				IdCiaRem,Cotizacion,IdCiaCot,FecPedido,Modalidad,ModdDev,PlacaVehic,KmtVehic,ZonaFrontera,OrigenAdd,TipCom,Comprobante,IdCiaCom,
				Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio,
				VrImpCarbono,DevMasivo,NumRecibo,CdCiaRec,CdMotDev,BaseIvaIgp,VrIvaIngProd
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Fecha,IdConcepto,TipDoc,Factura,IdCiaDoc,FecDoc,IdCliente,IdAgencia,VrSubTotal,VrDescuento,VrImpuesto,
				VrRetencion,VrReteICA,VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,
				VrNeto,Cantidad,CantPuntos,BaseImp,BaseRet,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,IdLocEnv,Pedido,IdCiaPed,Remision,
				IdCiaRem,Cotizacion,IdCiaCot,FecPedido,Modalidad,ModdDev,PlacaVehic,KmtVehic,ZonaFrontera,OrigenAdd,@TipComp,@Comprobante,@IdCiaComp,
				Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio,
				VrImpCarbono,DevMasivo,NumRecibo,CdCiaRec,CdMotDev,BaseIvaIgp,VrIvaIngProd
				FROM @Trn_DevFcr
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspFacReservas))
				BEGIN
				INSERT INTO Trn_TraEspFacReservas(
				TipDoc,Factura,IdCia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
				TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
				pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
				TarifaIca,VrReteIca,EstadoItem
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
				TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
				pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
				TarifaIca,VrReteIca,EstadoItem
				FROM @Trn_TraEspFacReservas
				END

				IF(EXISTS(SELECT * FROM @Trn_RecAFavor))
				BEGIN
					INSERT INTO Trn_RecAFavor(
					TipDoc,	Recibo,	IdCia,	Fecha,	VrAFavor,	VrOtrosDb,	VrAbono,	IdCliente,	IdAgencia,	IdVend
					)
					SELECT
					@TipDoc, @Numero, @Cia,	Fecha,	VrAFavor,	VrOtrosDb,	VrAbono,	IdCliente,	IdAgencia,	IdVend
					FROM @Trn_RecAFavor
				END

				IF(EXISTS(SELECT * FROM @Trn_VencAbonos))
				BEGIN
					declare @tiprec varchar(3)
					declare @recibo int
					declare @idciarec varchar(2)
					declare @item int 
					SELECT TOP 1 @tiprec = TipRec, @idciarec = IdCia, @recibo = Recibo FROM @Trn_VencAbonos
					select @item =  isnull(MAX(Item),0) from Trn_VencAbonos where TipRec = @tiprec and Recibo = @recibo and IdCia = @idciarec

					INSERT INTO Trn_VencAbonos(
					TipRec,Recibo,IdCia,Item,Fecha,TipDoc,Factura,IdCiaFac,ItemFac,VrAbono,VrDescto,
					VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
					)
					SELECT 
					@TipDoc,@Numero,@Cia,(@item + ROW_NUMBER() OVER(ORDER BY Item ASC)),Fecha,TipDoc,Factura,IdCiaFac,ItemFac,VrAbono,VrDescto,
					VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
					FROM @Trn_VencAbonos
				END 

				IF(EXISTS(SELECT * FROM @Trn_DetCuentas))
				BEGIN
				INSERT INTO Trn_DetCuentas(
				TipDoc,Documento,IdCia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
				VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
				VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
				FROM @Trn_DetCuentas
				END

				IF(EXISTS(SELECT * FROM @Trn_DocMemo))
				BEGIN
				INSERT INTO Trn_DocMemo(
				TipDoc,Documento,IdCia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
				FROM @Trn_DocMemo
				END 

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDoc,@Numero,@Cia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante				
				END

			end	

			IF(@operacion = 'i')
			begin
				--esto antes de la versión 5048 estaba desués del cursor ahora no para poder buscar solo las factruas activas
				--ACTUALIZAR FACTURA
				IF(UPPER(@modalidad) = 'TOTAL')
				BEGIN 
					UPDATE Trn_Facturas
					SET Anulado = 1,NumDev = @Numero,FecDev = @fecdev
					FROM Trn_Facturas F, @Trn_DevFcr DF
					WHERE F.TipDoc = DF.TipDoc AND F.Factura = DF.Factura AND F.IdCia = DF.IdCiaDoc
				END
				--actualiza los items de las reservas con los que se relacionan en el tipo de datos nuevo de las facturasreservas
				--Antes de la versión 48 esto hacía Joe
				--UPDATE Trn_TraEspResDetalle
				--SET  Factura = 0, IdCiaFac = '00', FechaFac = null, EstadoItem = r.EstadoItem
				--FROM Trn_TraEspResDetalle d, @Trn_TraEspFacReservas r 
				--WHERE d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCiaRes and d.Item = r.ItemRes
				--Versión 48 se debe buscar si la opción FRM está activa y si está activa debe colocar la última factura que no esté anulada de la reserva (Con este parámetro se puede factrar muchas veces la reserva)
				--Si la factrua que se anula es menor a la última se debe seguir dejando la última factura, ejemplo: si la última factura de esa reserva es la 3 y se anula la factrua 2 correspondiente a esa reserva
				--Se sigue dejando la 3
				IF((SELECT ISNULL(Valor, '0') FROM adm_Opciones where IdOpc ='FRM') = '1')
				BEGIN
				DECLARE @TipRes VARCHAR(3)
				DECLARE @TipDocFacDev VARCHAR(3)
				DECLARE @TipDocFacActual VARCHAR(3)
				DECLARE @TipDocFac VARCHAR(3) 
				DECLARE @CiaRes VARCHAR(2) 
				DECLARE @CiaFac VARCHAR(2)
				DECLARE @CiaFacDev VARCHAR(2)
				DECLARE @CiaFacActual VARCHAR(2)
				DECLARE @NumRes INT
				DECLARE @NumFacDev INT 
				DECLARE @NumFacActual INT 
				DECLARE @NumFac INT 
				DECLARE @ItemRes INT 
				DECLARE @reserva Int = 0 
				DECLARE @cantres Int = 0 
				DECLARE @cantresfact Int = 0
				DECLARE @FechaFac datetime
				DECLARE @asingadofa BIT = 0
				SELECT TOP (1) @TipDocFacDev = TipDoc, @NumFacDev = Factura, @CiaFacDev = IdCiaDoc  FROM @Trn_DevFcr
				DECLARE faccursor CURSOR
				--Verificar todas las reservas que viene en la devolución, tenga facturas
				FOR SELECT TipRes,Reserva,IdCiaRes,ItemRes FROM @Trn_TraEspFacReservas 
				OPEN faccursor
				FETCH NEXT FROM faccursor INTO @TipRes,@NumRes,@CiaRes,@ItemRes
				WHILE @@FETCH_STATUS = 0
				BEGIN
					SELECT @TipDocFacActual = TipFac,  @NumFacActual = Factura, @CiaFacActual = IdCiaFac FROM Trn_TraEspResDetalle WHERE TipDoc = @TipRes and Reserva = @NumRes and IdCia = @CiaRes and Item = @ItemRes
					IF(@TipDocFacActual = @TipDocFacDev and  @NumFacActual = @NumFacDev and @CiaFacActual = @CiaFacDev)
					BEGIN
						IF(EXISTS(SELECT TOP(1) fd.Factura FROM Trn_TraEspFacReservas AS fd 
						JOIN Trn_Facturas AS f ON fd.TipDoc = f.TipDoc AND fd.Factura = f.Factura AND fd.IdCia = f.IdCia 
						WHERE fd.TipRes = @TipRes AND fd.Reserva = @NumRes AND fd.IdCia = @CiaRes AND fd.Item = @ItemRes AND f.Anulado = 0 and fd.TipDoc = @TipDocFacDev and fd.Factura  < @NumFacDev and fd.IdCia = @CiaFacDev and  fd.Factura <> @NumFacDev  order by fd.Factura desc))
						BEGIN
							SELECT TOP(1) @TipDocFac = fd.TipDoc, @NumFac = fd.Factura,  @CiaFac = fd.IdCia, @FechaFac = f.Fecha FROM Trn_TraEspFacReservas AS fd JOIN Trn_Facturas AS f ON fd.TipDoc = f.TipDoc AND fd.Factura = f.Factura AND fd.IdCia = f.IdCia WHERE fd.TipRes = @TipRes AND fd.Reserva = @NumRes AND fd.IdCia = @CiaRes AND fd.Item = @ItemRes AND f.Anulado = 0 and fd.TipDoc = @TipDocFacDev and fd.Factura < @NumFacDev and fd.IdCia = @CiaFacDev  and fd.Factura <> @NumFacDev  order by Fd.Factura desc
							UPDATE d
							SET  d.Factura = @NumFac, d.IdCiaFac = @CiaFac, d.FechaFac = @FechaFac, d.EstadoItem = r.EstadoItem
							FROM Trn_TraEspResDetalle AS d 
							JOIN @Trn_TraEspFacReservas AS r  ON d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCiaRes
							WHERE d.TipDoc = @TipRes and d.Reserva = @NumRes and d.IdCia = @CiaRes and d.Item = @ItemRes
							--DECLARE facupdatecursor CURSOR
							--FOR SELECT fd.TipDoc, fd.Factura, fd.IdCia, f.Fecha FROM Trn_TraEspFacReservas AS fd JOIN Trn_Facturas AS f ON fd.TipDoc = f.TipDoc AND fd.Factura = f.Factura AND fd.IdCia = f.IdCia  WHERE fd.TipRes = @TipRes AND fd.Reserva = @NumRes AND fd.IdCia = @CiaRes AND fd.Item = @ItemRes AND f.Anulado = 0
							--OPEN facupdatecursor
							--FETCH NEXT FROM facupdatecursor INTO @TipDocFac,@NumFac,@CiaFac,@FechaFac
							--WHILE @@FETCH_STATUS = 0 
							----OR @asingadofa = 0
							--BEGIN
							--	--La factura actual de la reserva debe ser menor
							--	IF((SELECT Factura FROM Trn_TraEspResDetalle WHERE TipDoc = @TipRes and Reserva = @NumRes and IdCia = @CiaRes and @ItemRes = Item) = @NumFac) -- AND @asingadofa = 0
							--	begin
							--		UPDATE d
							--		SET  d.Factura = @NumFac, d.IdCiaFac = @CiaFac, d.FechaFac = @FechaFac, d.EstadoItem = r.EstadoItem
							--		FROM Trn_TraEspResDetalle AS d 
							--		JOIN @Trn_TraEspFacReservas AS r  ON d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCiaRes
							--		WHERE d.TipDoc = @TipRes and d.Reserva = @NumRes and d.IdCia = @CiaRes and d.Item = @ItemRes
							--		--set @asingadofa = 1
							--		BREAK
							--	end
							--FETCH NEXT FROM facupdatecursor INTO @TipDocFac,@NumFac,@CiaFac,@FechaFac
							--END
							--CLOSE facupdatecursor
							--DEALLOCATE facupdatecursor
						END
						ELSE
						BEGIN
							UPDATE Trn_TraEspResDetalle
							SET  Factura = 0, IdCiaFac = '00', FechaFac = null, EstadoItem = r.EstadoItem
							FROM Trn_TraEspResDetalle d, @Trn_TraEspFacReservas r 
							WHERE d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCiaRes and d.Item = r.ItemRes
						END
					END
				FETCH NEXT FROM faccursor INTO @TipRes,@NumRes,@CiaRes,@ItemRes
				END
				CLOSE faccursor
				DEALLOCATE faccursor
				END
				ELSE
				BEGIN
				UPDATE Trn_TraEspResDetalle
					SET  Factura = 0, IdCiaFac = '00', FechaFac = null, EstadoItem = r.EstadoItem
					FROM Trn_TraEspResDetalle d, @Trn_TraEspFacReservas r 
					WHERE d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCiaRes and d.Item = r.ItemRes
				END

			  --actualiza el cliente
			  UPDATE TercCliente
			  SET  VrSaldo = c.VrSaldo - f.VrNeto
			  FROM TercCliente c, @Trn_DevFcr f
			  WHERE c.IdClie = f.IdCliente

			  --actualizar vencimientos,cuando es necesario
			  IF(EXISTS(SELECT * FROM @Trn_VencAbonos))
			  BEGIN 
				 UPDATE Trn_Vencimientos
				 SET  VrAbonado = v.VrAbonado + dv.VrAbono
				 FROM Trn_Vencimientos v, @Trn_VencAbonos dv
				 WHERE v.TipDoc = dv.TipDoc and v.Factura = dv.Factura and v.IdCia = dv.IdCiaFac
			  END

			end

			SELECT @Numero, @Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_Factcon]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 19/01/2017
-- Description:	Insertar Trn_Factcon
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_Factcon]
	--@Trn_Factcon dataTypeTrn_Factcon READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Factcon
	--@Trn_FacReservas dataTypeTrn_TraEspFacReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFacReservas
	--@Trn_Kardex dataTypeTrn_Kardex READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Kardex
	--@Trn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos
	--@Trn_DocMemo dataTypeTrn_DocMemo READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DocMemo

	--@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	--@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	--@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	--@Trn_NiifDetalle dataTypeTrn_NiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	--@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			
			--SELECT TOP 1 @TipDoc = TipDoc, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_Factcon
			--SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

			--IF(@Numero > 0)
			--	UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
			--ELSE
			--BEGIN
			--	SELECT @Numero = 1
			--	INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--END

			--IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			--BEGIN
			--	SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
			--	SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
			--	--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
			--	IF(@Comprobante <> '')
			--		UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
			--	ELSE
			--	BEGIN
			--		SELECT @Comprobante = 1
			--		INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--	END
			--END

			--IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
			--BEGIN
			--	SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
			--	SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
			--	--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
			--	IF(@CompNiif <> '')
			--		UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
			--	ELSE
			--	BEGIN
			--		SELECT @CompNiif = 1
			--		INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--	END
			--END

			--IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
			--BEGIN
			--	SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
			--	SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
			--	--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
			--	IF(@CompNiif <> '')
			--		UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
			--	ELSE
			--	BEGIN
			--		SELECT @CompFis = 1
			--		INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null)
			--	END
			--END
			
			--IF(@operacion = 'i')
			--begin
			--	IF(EXISTS(SELECT * FROM @Trn_Factcon))
			--	BEGIN
			--	INSERT INTO Trn_Factcon(
			--	TipDoc,Factura,IdCia,Fecha,IdConcepto,nClieCon,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,VrReteICA,VrReteIVA,VrFletes,VrCargos,
			--	VrOtrDcto,VrCostos,VrNeto,VrEfectivo,VrPagosOtr,Cantidad,CantPuntos,PuntosAcum,BaseImp,BaseRet,BaseIca,BaseRiv,TarifaIva,TarifaRet,
			--	TarifaIca,TarifaRiv,CodTarIva,CodTarRet,CodTarIca,CodTarRiv,IdCajero,IdVend,TarifaCom,CodTarCom,NitCliente,CdAgencia,IdCCosto,IdSubCos,
			--	IdLocal,EnEfectivo,CdForma,NumForma,DetallePago,Referncia1,Referncia2,CdBanco,TipPed,Pedido,IdCiaPed,TipRem,Remision,IdCiaRem,FecPedido,
			--	Modalidad,PlacaVehic,KmtVehic,OrigenAdd,TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,IdEstado,TimeSys,FecUpdate,
			--	IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Fecha,IdConcepto,nClieCon,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,VrReteICA,VrReteIVA,VrFletes,VrCargos,
			--	VrOtrDcto,VrCostos,VrNeto,VrEfectivo,VrPagosOtr,Cantidad,CantPuntos,PuntosAcum,BaseImp,BaseRet,BaseIca,BaseRiv,TarifaIva,TarifaRet,
			--	TarifaIca,TarifaRiv,CodTarIva,CodTarRet,CodTarIca,CodTarRiv,IdCajero,IdVend,TarifaCom,CodTarCom,NitCliente,CdAgencia,IdCCosto,IdSubCos,
			--	IdLocal,EnEfectivo,CdForma,NumForma,DetallePago,Referncia1,Referncia2,CdBanco,TipPed,Pedido,IdCiaPed,TipRem,Remision,IdCiaRem,FecPedido,
			--	Modalidad,PlacaVehic,KmtVehic,OrigenAdd,@TipComp,@Comprobante,@IdCiaComp,Anulado,NumDev,FecDev,Observacion,IdEstado,TimeSys,FecUpdate,
			--	IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,BaseIvaObsq,VrIvaObsequio
			--	FROM @Trn_Factcon
			--	END 

			--	IF(EXISTS(SELECT * FROM @Trn_FacReservas))
			--	BEGIN
			--	INSERT INTO Trn_TraEspFacReservas(
			--	TipDoc,Factura,IdCia,Item,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,UndTarifa,
			--	TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
			--	pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Item,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,UndTarifa,
			--	TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
			--	pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct
			--	FROM @Trn_FacReservas
			--	END 

			--	IF(EXISTS(SELECT * FROM @Trn_Kardex))
			--	BEGIN
			--	INSERT INTO Trn_Kardex(
			--	TipDoc,Documento,IdCia,Item,Fecha,IdProducto,IdBodega,CdTanque,Entradas,Salidas,IdUnd,VrUnitario,VrPrecio,VrCostProm,
			--	TarifaIva,VrIvaEnt,VrIvaSal,TarifaDct,VrDctoEnt,VrDctoSal,VrCostoEnt,VrCostoSal,TarifaRet,VrReteEnt,VrReteSal,TarifaIca,
			--	VrIcaEnt,VrIcaSal,VrBruto,CdUbic,NumLote,FechLote,IdConcepto,IdTercero,CdAgencia,CdCCosto,CdSubCos,CdLocal,CdSzona,pVehiculo,
			--	IdVend,Comision,CdOperario,ComisnOper,Referencia,Descripcion,Comptmntos,CdProdEquiv,TipOrd,NumOrden,IdCiaOrd,Cotizacion,
			--	IdCiaCot,Remision,IdCiaRem,Factura,TipDocDev,NumDocDev,CdMngra,NumInicial,NumFinal,Sobretasa,TasaNac,TasaDep,TasaMun,Soldicom,
			--	ImpGlobal,OtroImpto,Unidades,ItemCombo,Servcios,NoVentas,EsCombo,EsProdBase,CodTarDct,CodTarIva,CodTarIca,CodTarRet,CodTarCom,
			--	CodTarCmc,ListaPrec,VrBase,CdMoneda,VrTasaCamb,VrDivisa1,VrDivisa2,VrDivisa3,Referencia2,FecOrden,galsbruto,galsneto,
			--	Temperatura,UmTemp,Densidad,TimeSys,IdUsuario,Rec_Costo,MgenCont,VrImvCosto,TarifaIco,VrImpCon,CantObseq,VrIvaObseq
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Item,Fecha,IdProducto,IdBodega,CdTanque,Entradas,Salidas,IdUnd,VrUnitario,VrPrecio,VrCostProm,
			--	TarifaIva,VrIvaEnt,VrIvaSal,TarifaDct,VrDctoEnt,VrDctoSal,VrCostoEnt,VrCostoSal,TarifaRet,VrReteEnt,VrReteSal,TarifaIca,
			--	VrIcaEnt,VrIcaSal,VrBruto,CdUbic,NumLote,FechLote,IdConcepto,IdTercero,CdAgencia,CdCCosto,CdSubCos,CdLocal,CdSzona,pVehiculo,
			--	IdVend,Comision,CdOperario,ComisnOper,Referencia,Descripcion,Comptmntos,CdProdEquiv,TipOrd,NumOrden,IdCiaOrd,Cotizacion,
			--	IdCiaCot,Remision,IdCiaRem,Factura,TipDocDev,NumDocDev,CdMngra,NumInicial,NumFinal,Sobretasa,TasaNac,TasaDep,TasaMun,Soldicom,
			--	ImpGlobal,OtroImpto,Unidades,ItemCombo,Servcios,NoVentas,EsCombo,EsProdBase,CodTarDct,CodTarIva,CodTarIca,CodTarRet,CodTarCom,
			--	CodTarCmc,ListaPrec,VrBase,CdMoneda,VrTasaCamb,VrDivisa1,VrDivisa2,VrDivisa3,Referencia2,FecOrden,galsbruto,galsneto,
			--	Temperatura,UmTemp,Densidad,TimeSys,IdUsuario,Rec_Costo,MgenCont,VrImvCosto,TarifaIco,VrImpCon,CantObseq,VrIvaObseq
			--	FROM @Trn_Kardex
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_Pagos))
			--	BEGIN
			--	INSERT INTO Trn_Pagos(
			--	TipDoc,Documento,IdCia,Item,Fecha,IdForma,Detalle,VrPagado,VrCambio,EsCaja,IdBanco,NitCliente,CdAgencia,NumForma,FecForma,
			--	CtaForma,Beneficiario,Referncia1,Referncia2,CdLocal,NumAutoriza,VrDenom,Cantidad,TipDenom,TipRef,DocRef,IdCiaRef,ItemDoc,
			--	CdCta,IdUsuario
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Item,Fecha,IdForma,Detalle,VrPagado,VrCambio,EsCaja,IdBanco,NitCliente,CdAgencia,NumForma,FecForma,
			--	CtaForma,Beneficiario,Referncia1,Referncia2,CdLocal,NumAutoriza,VrDenom,Cantidad,TipDenom,TipRef,DocRef,IdCiaRef,ItemDoc,
			--	CdCta,IdUsuario
			--	FROM @Trn_Pagos
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_DocMemo))
			--	BEGIN
			--	INSERT INTO Trn_DocMemo(
			--	TipDoc,Documento,IdCia,Comentarios,Nota1,Nota2,Nota3,CantImp
			--	)
			--	SELECT 
			--	@TipDoc,@Numero,@Cia,Comentarios,Nota1,Nota2,Nota3,CantImp
			--	FROM @Trn_DocMemo
			--	END 

			--	IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			--	BEGIN
			--	INSERT INTO Trn_Comprobantes(
			--	TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			--	NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
			--	TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			--	VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			--	Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			--	PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero
			--	)
			--	SELECT 
			--	@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			--	NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
			--	TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			--	VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			--	Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			--	PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis
			--	FROM @Trn_Comprobantes
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
			--	BEGIN
			--	INSERT INTO Trn_ComDetalle(
			--	TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
			--	IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
			--	IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
			--	NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
			--	CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
			--	IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
			--	)
			--	SELECT 
			--	@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
			--	IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
			--	CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
			--	NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
			--	CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
			--	IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
			--	FROM @Trn_ComDetalle
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_NiifComp))
			--	BEGIN
			--	INSERT INTO Trn_NiifComp(
			--	TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
			--	EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
			--	FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
			--	VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
			--	IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
			--	Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
			--	CtbTipo, CtbNumero,
			--	FisTipo, FisNumero 
			--	)
			--	SELECT 
			--	CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, CASE N.TipoNiif WHEN 'NIIF' THEN @IdCiaCompNiif ELSE @IdCiaCompFis END, C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
			--	C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
			--	C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
			--	C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
			--	C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
			--	C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
			--	CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
			--	CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
			--	FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
			--	END

			--	IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
			--	BEGIN
			--	INSERT INTO Trn_NiifDetalle(
			--	TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
			--	VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
			--	VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
			--	NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
			--	NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
			--	CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
			--	DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
			--	CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
			--	FechAutoriza, CodCuentaCG
			--	)
			--	SELECT 
			--	CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @IdCiaCompNiif ELSE @IdCiaCompFis END, N.Item, C.Fecha, N.IdCuenta, N.Detalle,
			--	N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo, N.IdCCosto, N.IdSubCos,
			--	C.VrBase, C.TarifaBase, @TipDoc, @Numero, @Cia, C.CodConce,
			--	C.NitDoc, C.TipFac, C.Factura, C.IdCiaFac, C.ItemFac, C.FecVence, C.CodCta, 
			--	C.NumCheque, C.Integrado, C.TipoAplica, C.Consolida, C.CodCargo, C.NitOtros,
			--	C.CodSubgpo, C.CiuOrigen, C.CodAgncia, C.VehPropio, N.Referncia, C.TipDocRef,
			--	C.DocRef, C.IdCiaRef, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario,
			--	C.CdConcTrib, C.CdTarifTrib, C.NumEstablec,C.PtoEmision, C.Num_Autoriza,
			--	C.FechAutoriza, C.IdCuenta
			--	FROM @Trn_ComDetalle AS C JOIN @Trn_NiifDetalle AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont AND C.Item = N.Item JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
			--	END
			--end

			--IF(@operacion = 'i')
			--begin
			--  --actualiza los items de un contrato con los que se relacionan en el tipo de datos nuevo
			--  UPDATE Trn_TraEspResDetalle
			--  SET  EstadoItem = 'FACTURADA'
			--  FROM Trn_TraEspResDetalle d, @Trn_FacReservas r 
			--  WHERE d.TipDoc = r.TipRes  and d.Reserva = r.Reserva and d.IdCia = r.IdCia and d.Item = r.ItemRes
			--end
						
			--SELECT @Numero

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_Facturas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 19/01/2017
-- Description:	Insertar Trn_Facturas
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_Facturas]
	@Trn_Facturas dataTypeTrn_Facturas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Facturas
	@Trn_TraEspFacReservas dataTypeTrn_TraEspFacReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFacReservas
	@Trn_TraEspFacResVehiculos dataTypeTrn_TraEspFacResVehiculos readonly,
	@Trn_DocMemo dataTypeTrn_DocMemo READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DocMemo
	@Trn_TraEspAuxFactura dataTypeTrn_TraEspAuxFactura READONLY,
	@Trn_RecAfavor dataTypeTrn_RecAfavor READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_RecAfavor
	@Trn_VencAbonos dataTypeTrn_VencAbonos READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_VencAbonos
	@Trn_Vencimientos dataTypeTrn_Vencimientos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Vencimientos
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas
	
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CodigoPre VARCHAR(3)
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
declare @FechaFac smalldatetime
	BEGIN TRAN
		BEGIN TRY		 
			
			IF(@operacion = 'i')
			BEGIN
				SELECT TOP 1 @TipDoc = TipDoc,@CodigoPre = CodigoPreFact, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia, @FechaFac = Fecha FROM @Trn_Facturas
				
				IF(@CodigoPre is not null or @CodigoPre <> '')
				 select @Numero = (SELECT TOP 1 Factura FROM @Trn_Facturas)
				ELSE
				BEGIN
					SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

					IF(@Numero > 0)
						UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
					ELSE
					BEGIN
						SELECT @Numero = 1
						INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompFis <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			END

			IF(@operacion = 'i')
			BEGIN
				IF(EXISTS(SELECT * FROM @Trn_Facturas))
				BEGIN
					INSERT INTO Trn_Facturas(
					TipDoc,Factura,IdCia,Fecha,IdConcepto,IdCliente,IdAgencia,FechaVence,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,VrReteICA,
					VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,VrNeto,VrAplicado,Cantidad,
					CantPuntos,PuntosAcum,BaseImp,BaseRet,BaseIca,BaseRiv,TarifaIva,TarifaRet,TarifaIca,TarifaRiv,CodTarIva,CodTarRet,CodTarIca,
					CodTarRiv,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,DirEnvio,IdLocEnv,DiasEntraga,NitContac,NomContac,TelContac,emlContac,
					CargoContac,IdForma,DetallePago,MulPlazos,IdPlazo,CdMney,NitEmpTrans,EmpTrans,pVehiculo,CdConductor,CdRuta,TipPed,Pedido,IdCiaPed,
					TipRem,Remision,IdCiaRem,TipCot,Cotizacion,IdCiaCot,FecPedido,AutzaMora,AutzaCupo,Modalidad,KmtVehic,ZonaFrontera,PesoTotal,
					UnidTotal,VolTotal,CantFalt,VrCostoRem,VrCostoAfi,CodAutoRet,OrigenAdd,TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,
					IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,Parqueadero,FecCuotaParq,BaseIvaObsq,VrIvaObsequio,
					VrImpCarbono,TipoFE,FechaFE,BaseIvaIgp,VrIvaIngProd 
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Fecha,IdConcepto,IdCliente,IdAgencia,FechaVence,VrSubTotal,VrDescuento,VrImpuesto,VrRetencion,VrReteICA,
					VrReteIVA,VrFletes,VrOtros,VrCargos,VrOtrDcto,VrCostos,VrSobretasa,VrImpGlobal,VrFaltantes,VrAnticipos,VrNeto,VrAplicado,Cantidad,
					CantPuntos,PuntosAcum,BaseImp,BaseRet,BaseIca,BaseRiv,TarifaIva,TarifaRet,TarifaIca,TarifaRiv,CodTarIva,CodTarRet,CodTarIca,
					CodTarRiv,IdCCosto,IdSubCos,IdVend,TarifaCom,CodTarCom,DirEnvio,IdLocEnv,DiasEntraga,NitContac,NomContac,TelContac,emlContac,
					CargoContac,IdForma,DetallePago,MulPlazos,IdPlazo,CdMney,NitEmpTrans,EmpTrans,pVehiculo,CdConductor,CdRuta,TipPed,Pedido,IdCiaPed,
					TipRem,Remision,IdCiaRem,TipCot,Cotizacion,IdCiaCot,FecPedido,AutzaMora,AutzaCupo,Modalidad,KmtVehic,ZonaFrontera,PesoTotal,
					UnidTotal,VolTotal,CantFalt,VrCostoRem,VrCostoAfi,CodAutoRet,OrigenAdd,@TipComp,@Comprobante,@IdCiaComp,Anulado,NumDev,FecDev,Observacion,
					IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,VrImpCons,VrReteCREE,TarifaRtc,CodTarRtc,Parqueadero,FecCuotaParq,BaseIvaObsq,VrIvaObsequio,
					VrImpCarbono,TipoFE,FechaFE,BaseIvaIgp,VrIvaIngProd 
					FROM @Trn_Facturas
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspFacReservas))
				BEGIN
					INSERT INTO Trn_TraEspFacReservas(
					TipDoc,Factura,IdCia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
					TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
					pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
					TarifaIca,VrReteIca,EstadoItem
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Item,TipoReg,FechaFact,TipRes,Reserva,IdCiaRes,ItemRes,FecReserva,Descripcion,Cantidad,VrServicio,VrUnitario,VrCosto,
					TarifaIva,VrImpuesto,TarifaDct,VrDescuento,DocCliente,Referencia1,Referencia2,Referencia3,CdConcepto,CdCCosto,CdSubCos,NitTercero,CdAgencia,
					pVehiculo,TipoAfiVehic,IdOrigen,IdDestino,Anulado,TipDocRef,NumDocRef,IdCiaRef,FecDocRef,CodTarDct,CodTarRet,CodTarIca,TarifaRet,VrRetencion,
					TarifaIca,VrReteIca,EstadoItem
					FROM @Trn_TraEspFacReservas
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspFacResVehiculos))
				BEGIN
					INSERT INTO Trn_TraEspFacResVehiculos(
					TipDoc,Factura,IdCIa,Item,TipRes,Reserva,IdCIaRes,ItemRes,IdVehiculo,TipoAfil,VrRecorrido
					)
					SELECT
					@TipDoc,@Numero,@Cia,Item,TipRes,Reserva,IdCIaRes,ItemRes,IdVehiculo,TipoAfil,VrRecorrido
					FROM @Trn_TraEspFacResVehiculos
				END

				IF(EXISTS(SELECT * FROM @Trn_Vencimientos))
				BEGIN
					INSERT INTO Trn_Vencimientos(
					TipDoc,Factura,IdCia,Item,Fecha,FechaVence,VrFactura,VrAbonado,IdCliente,IdAgencia,IdVend,Comision,TarifDcto,
					TipoDcto,TipoBase,FecLmtDcto,IdConcepto,Referencia,Detalle,TipRef,DocRef,IdCiaRef,FecUltPago,NumNota,IdCiaNot,
					TarifInt,FecLiqMora,FecPlazoCal
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Item,Fecha,FechaVence,VrFactura,VrAbonado,IdCliente,IdAgencia,IdVend,Comision,TarifDcto,
					TipoDcto,TipoBase,FecLmtDcto,IdConcepto,Referencia,Detalle,TipRef,DocRef,IdCiaRef,FecUltPago,NumNota,IdCiaNot,
					TarifInt,FecLiqMora,FecPlazoCal
					FROM @Trn_Vencimientos
				END

				IF(EXISTS(SELECT * FROM @Trn_DocMemo))
					BEGIN
					INSERT INTO Trn_DocMemo(
					TipDoc,Documento,IdCia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Comentarios,Nota1,Nota2,Nota3,CantImp,ArchivoImg
					FROM @Trn_DocMemo
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspAuxFactura))
				BEGIN
					INSERT INTO Trn_TraEspAuxFactura(
					TipFac,Factura,IdCiaFac,Resolucion,Rango,FechaResl,Prefijo,TipDocPf,PreFactura,IdCiaPf,CodigoPreFact
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Resolucion,Rango,FechaResl,Prefijo,TipDocPf,PreFactura,IdCiaPf,CodigoPreFact
					FROM @Trn_TraEspAuxFactura
				END 

				IF(EXISTS(SELECT * FROM @Trn_RecAfavor))
				BEGIN
					update Trn_RecAfavor
					set VrAbono = t1.VrAbono + t2.VrAbono
					from Trn_RecAfavor t1, @Trn_RecAfavor t2
					where t1.TipDoc = t2.TipDoc and t1.Recibo = t2.Recibo and t1.IdCia = t2.IdCia and t1.IdCliente = t2.IdCliente and t1.IdAgencia = t2.IdAgencia and t1.IdVend = t2.IdVend
				END 

				IF(EXISTS(SELECT * FROM @Trn_VencAbonos))
				BEGIN
					declare @tiprec varchar(3)
					declare @recibo int
					declare @idciarec varchar(2)
					declare @item int 
					SELECT TOP 1 @tiprec = TipRec, @idciarec = IdCia, @recibo = Recibo FROM @Trn_VencAbonos
					select @item =  isnull(MAX(Item),0) from Trn_VencAbonos where TipRec = @tiprec and Recibo = @recibo and IdCia = @idciarec

					INSERT INTO Trn_VencAbonos(
					TipRec,Recibo,IdCia,Item,Fecha,TipDoc,Factura,IdCiaFac,ItemFac,VrAbono,VrDescto,
					VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
					)
					SELECT 
					TipRec,Recibo,IdCia,(@item + ROW_NUMBER() OVER(ORDER BY Item ASC)),Fecha,@TipDoc,@Numero,@Cia,ItemFac,VrAbono,VrDescto,
					VrBaseCms,IdCliente,IdAgencia,IdVend,Comision,Detalle,FecPago,TipoAplica,TimeSys
					FROM @Trn_VencAbonos
				END 

				IF(EXISTS(SELECT * FROM @Trn_DetCuentas))
				BEGIN
					INSERT INTO Trn_DetCuentas(
					TipDoc,Documento,IdCia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
					VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif 
					)
					SELECT 
					@TipDoc,@Numero,@Cia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
					VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
					FROM @Trn_DetCuentas
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					INSERT INTO Trn_Comprobantes(
					TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
					NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
					TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
					VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
					Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
					PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
					CodRes, DescServicio
					)
					SELECT 
					@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
					NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
					TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
					VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
					Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
					PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
					CodRes, DescServicio
					FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
					INSERT INTO Trn_ComDetalle(
					TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
					IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
					IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
					CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
					IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
					)
					SELECT 
					@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
					IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
					CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
					NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
					CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
					IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
					FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
					INSERT INTO Trn_NiifComp(
					TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
					EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
					FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
					VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
					IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
					Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
					CtbTipo, CtbNumero,
					FisTipo, FisNumero 
					)
					SELECT 
					CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
					CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
					@Cia, C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
					C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
					C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
					C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
					C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
					C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
					CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
					CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
					FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
					---------------factura una
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDoc,@Numero,@Cia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			END	

			IF(@operacion = 'i')
			BEGIN
			 IF(UPPER((SELECT TipDoc FROM @Trn_Facturas)) <> 'PFE')
			 BEGIN
				  --actualiza los items de las reservas con los que se relacionan en el tipo de datos nuevo de las facturasreservas
				  DECLARE @TipRes VARCHAR(3) 
				  DECLARE @CiaRes VARCHAR(2) 
				  DECLARE @NumRes INT 
				  DECLARE @ItemRes INT 
				  DECLARE @reserva Int = 0 
				  DECLARE @cantres Int = 0 
				  DECLARE @cantresfact Int = 0 

				  DECLARE faccursor CURSOR
				  FOR SELECT TipRes,Reserva,IdCiaRes,ItemRes FROM @Trn_TraEspFacReservas
				  OPEN faccursor
				  FETCH NEXT FROM faccursor INTO @TipRes,@NumRes,@CiaRes,@ItemRes
				  WHILE @@FETCH_STATUS = 0
				  BEGIN

					  UPDATE Trn_TraEspResDetalle
					  SET  TipFac = @TipDoc, Factura = @Numero, IdCiaFac = @Cia, FechaFac = @FechaFac, EstadoItem = 'FACTURADA'
					  FROM Trn_TraEspResDetalle d
					  WHERE d.TipDoc = @TipRes  and d.Reserva = @NumRes and d.IdCia = @CiaRes and d.Item = @ItemRes

					  --se agrega 11/04/2018 para sacar este codigo de la aplicación
					  IF (@NumRes <> @reserva)
					  BEGIN
						SET @reserva = @NumRes
						
						SELECT @cantres = count(*)
						FROM Trn_TraEspResDetalle AS rd
						WHERE rd.TipDoc = @TipRes  and rd.Reserva = @NumRes and rd.IdCia = @CiaRes

						SELECT @cantresfact = count(*)
						FROM Trn_TraEspResDetalle AS rd
						WHERE rd.TipDoc = @TipRes  and rd.Reserva = @NumRes and rd.IdCia = @CiaRes and rd.EstadoItem = 'FACTURADA'
						
						IF (@cantresfact = @cantres)
						BEGIN
							UPDATE Trn_TraEspReservas 
							SET EstadoRes = 'FACTURADA' 
							WHERE TipDoc = @TipRes  and Reserva = @NumRes and IdCia = @CiaRes                     
						END

					  END
					  -------------------------------------------------------------
				  
				  FETCH NEXT FROM faccursor INTO @TipRes,@NumRes,@CiaRes,@ItemRes
			      END
				  CLOSE faccursor
				  DEALLOCATE faccursor

				  --actualiza el cliente
				  UPDATE TercCliente
				  SET  VrSaldo = c.VrSaldo + f.VrNeto
				  FROM TercCliente c, @Trn_Facturas f
				  WHERE c.IdClie = f.IdCliente
			  END
			END

			SELECT @Numero, @Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_FcSemanas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 29/04/2016
-- Description:	Insertar/Actualizar Trn_FcSemanas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_FcSemanas]
	@Trn_FcSemanas dataTypeTrn_FcSemanas READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Trn_FcSemanas
			 SET 
			 IdVehiculo = t2.IdVehiculo,nSemana = t2.nSemana,NumCargue = t2.NumCargue,CiaCargue = t2.CiaCargue,
			 TipoSem = t2.TipoSem,Fecha = t2.Fecha,FecVence = t2.FecVence,VrCargo = t2.VrCargo,VrOtros = t2.VrOtros,
			 VrPagado = t2.VrPagado,TipRec = t2.TipRec,Recibo = t2.Recibo,IdCiaRec = t2.IdCiaRec,FechaPago = t2.FechaPago,
			 Observacion = t2.Observacion,FecSemIni = t2.FecSemIni,FecSemFin = t2.FecSemFin,TimeSys = t2.TimeSys,IdUsuario = t2.IdUsuario
		     FROM Trn_FcSemanas t1
			 JOIN @Trn_FcSemanas t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.nSemana = t2.nSemana
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Trn_FcSemanas(
			 IdVehiculo,nSemana,NumCargue,CiaCargue,TipoSem,Fecha,FecVence,VrCargo,VrOtros,
			 VrPagado,TipRec,Recibo,IdCiaRec,FechaPago,Observacion,FecSemIni,FecSemFin,TimeSys,IdUsuario
			 )
			 SELECT 
			 IdVehiculo,nSemana,NumCargue,CiaCargue,TipoSem,Fecha,FecVence,VrCargo,VrOtros,
			 VrPagado,TipRec,Recibo,IdCiaRec,FechaPago,Observacion,FecSemIni,FecSemFin,TimeSys,IdUsuario
			 FROM @Trn_FcSemanas
			 WHERE (IdVehiculo +'_'+ Convert(varchar,nSemana)) NOT IN(SELECT (IdVehiculo +'_'+ Convert(varchar,nSemana)) FROM Trn_FcSemanas)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @idvehiculo varchar(10)
			 DECLARE @nsemana int
			 SELECT @idvehiculo = IdVehiculo, @nsemana = nSemana FROM @Trn_FcSemanas
			 DELETE FROM Trn_FcSemanas WHERE IdVehiculo = @idvehiculo and nSemana = @nsemana
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspAnticipos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 15/12/2016
-- Description:	Insertar Trn_TraEspAnticipos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspAnticipos]
	@Trn_TraEspAnticipos dataTypeTrn_TraEspAnticipos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ATraESpAnticipos
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Aprobacion
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla NiifDetalle
	@Trn_ComFactura dataTypeTrn_ComFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComFactura
	@operacion varchar(1)
	--@dataTypeTrn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos
	--@dataTypeTrn_ComFactura dataTypeTrn_ComFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComFactura
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TDAnt VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CiaAnt VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Anticipo INT --En esta variable se guarda el consecutivo del documento aprobación
--DECLARE @Trn_TraComprobantes dataTypeTrn_Comprobantes --En esta variable se guarda el consecutivo del documento aprobación NO
--DECLARE @Trn_ComDetalle dataTypeTrn_ComDetalle --En esta variable se guarda el consecutivo del documento aprobación NO

	BEGIN TRAN
		BEGIN TRY		 
			declare @idcta varchar(4)
			declare @tpago varchar(10)
			declare @consecutivoCh int = 0
			declare @numcheque VARCHAR (20)
			declare @rango varchar(20)
			declare @rangof varchar(20)
			declare @TipFac varchar(3)
			declare @Factura varchar(15)
			declare @IdCiaFac varchar(2)

			if(@operacion = 'i')
			BEGIN

			SELECT TOP 1 @TDAnt = TipDoc, @CiaAnt = IdCia, @idcta = IdCta, @tpago = TipoPago, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia, @numcheque = NumCheque FROM @Trn_TraEspAnticipos
			SELECT @Anticipo = Numero + 1  FROM TiposDocCons where IdDoc = @TDAnt AND IdCia = @CiaAnt

			IF(@Anticipo > 0)
				UPDATE TiposDocCons SET Numero = @Anticipo WHERE IdDoc = @TDAnt AND IdCia = @CiaAnt
			ELSE
			BEGIN
				SELECT @Anticipo = 1
				INSERT INTO TiposDocCons VALUES (@TDAnt,@CiaAnt,0,0,0,0,NULL,'',@Anticipo,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
			END

			IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			BEGIN
				SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
				SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
				--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
				IF(@Comprobante <> '')
					UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
				ELSE
				BEGIN
					SELECT @Comprobante = 1
					INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
			BEGIN
				SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
				SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif

				IF(@CompNiif <> '')
					UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
				ELSE
				BEGIN
					SELECT @CompNiif = 1
					INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
			BEGIN
				SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
				SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis

				IF(@CompFis <> '')
					UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
				ELSE
				BEGIN
					SELECT @CompFis = 1
					INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF((select UPPER(TipoPago) from @Trn_TraEspAnticipos) = 'CHEQUE')
			BEGIN
				if((select ConsCheques from CtasCorrientes where IdCta = @idcta) = '1')
				begin
					begin try
						select 
						@consecutivoCh = (ConsActual + 1),
						@rango = (substring(RangoCons,1,(charindex('-',RangoCons)-1))), 
						@rangof = (substring(RangoCons,(charindex('-',RangoCons)+1),len(RangoCons))) 
						from CtasCorrientes where IdCta = @idcta
								
						if not(@consecutivoCh >= Convert(int,@rango) and @consecutivoCh <= Convert(int,@rangof))
						begin
							RAISERROR('Error, el consecutivo de cheque fuera del rango establecido', 16, 1);
						end
						else
						begin
							update CtasCorrientes set ConsActual = @consecutivoCh where IdCta = @idcta
						end
					end try
					begin catch
						RAISERROR('Error, el consecutivo de cheque fuera del rango establecido', 16, 1);
					end catch
				end
			END

			--4052
			IF (EXISTS(SELECT * FROM @Trn_ComFactura) AND (SELECT TOP 1 Modalidad FROM  @Trn_TraEspAnticipos) = 'COMBUSTBLE' AND (SELECT TOP 1 p.Vencimiento FROM Puc as p WHERE p.IdCuenta = (SELECT TOP 1 IdCuenta FROM @Trn_TraEspAnticipos)) = 1)
			BEGIN
				SELECT TOP 1 @TipFac =  TipFac, @Factura = Factura, @IdCiaFac = IdCia FROM @Trn_ComFactura
			END
			INSERT INTO Trn_TraEspAnticipos(
			TipDoc,Anticipo,IdCia,Fecha,IdConcepto,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdPoseedor,IdConductor,VrAnticipo,
			VrAbonado,Modalidad,TipoPago,NumCheque,FecCheque,IdCta,IdCuenta,Beneficiario,CedBenef,Cantidad,FechaVence,
			NumPresAnt,TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,
			IdCiaCrea,IdUsuario,PreAnticipo
			)
			SELECT 
			@TDAnt,@Anticipo,@CiaAnt,Fecha,IdConcepto,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdPoseedor,IdConductor,VrAnticipo,
			VrAbonado,Modalidad,TipoPago,
			(CASE WHEN Modalidad  = 'COMBUSTBLE' THEN 
				(CASE WHEN (SELECT TOP 1 p.Vencimiento FROM Puc as p WHERE p.IdCuenta = (SELECT TOP 1 IdCuenta FROM @Trn_TraEspAnticipos)) = 0  THEN 
					NumCheque 
				ELSE 
					ISNULL(NumCheque, @Anticipo) 
				END) 
			ELSE 
				(CASE WHEN @consecutivoCh > 0 THEN Convert(Varchar(20),@consecutivoCh) ELSE @numcheque END) 
			END),
			FecCheque,IdCta,IdCuenta,Beneficiario,CedBenef,Cantidad,FechaVence,
			NumPresAnt,@TipComp, @Comprobante, @IdCiaComp,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,
			IdCiaCrea,IdUsuario,PreAnticipo
			FROM @Trn_TraEspAnticipos

			--IF(EXISTS(SELECT * FROM @dataTypeTrn_ComFactura))
			--BEGIN
			--INSERT INTO Trn_ComFactura(
			--TipFac,Factura,IdCia,Item,IdProveedor,IdCuenta,TipDoc,Documento,IdCiaDoc,FecEmision,FecVence,
			--VrFactura,VrAbonado,TipCom,Comprobante,ItemCom,Referencia,Detalle,pVehiculo,VehPropio,TipRef,
			--DocRef,IdCiaRef,EstadoApr,MontoAprob
			--)
			--SELECT 
			--TipFac,CONVERT(VARCHAR(15), @Anticipo),IdCia,Item,IdProveedor,IdCuenta,@TDAnt,@Anticipo,@CiaAnt,FecEmision,FecVence,
			--VrFactura,VrAbonado,@TipComp,@Comprobante,ItemCom,Referencia,Detalle,pVehiculo,VehPropio,TipRef,
			--DocRef,IdCiaRef,EstadoApr
			--FROM @dataTypeTrn_ComFactura
			--END

			IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			BEGIN
			INSERT INTO Trn_Comprobantes(
			TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
			TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
			CodRes, DescServicio
			)
			SELECT 
			@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			NumCheque, FecCheque, @TDAnt, @Anticipo, @CiaAnt, Anulado, NumDev, FecDev,
			TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
			CodRes, DescServicio
			FROM @Trn_Comprobantes
			END

			IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
			BEGIN
			INSERT INTO Trn_ComDetalle(
			TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
			IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
			IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
			NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
			CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
			IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
			)
			SELECT 
			@TipComp, @Comprobante, @IdCiaComp, cd.Item, cd.Fecha, cd.IdCuenta, cd.Detalle, cd.VrDebito, cd.VrCredito,
			cd.IdTercero, cd.IdVehiculo, cd.IdCCosto, cd.IdSubCos, cd.VrBase, cd.TarifaBase, @TDAnt, @Anticipo, @CiaAnt,
			cd.CodConce, cd.NitDoc, 
			(CASE WHEN (SELECT TOP 1 p.Vencimiento FROM Puc as p WHERE p.IdCuenta = cd.IdCuenta) = 1  THEN ISNULL(@TipFac, (case WHEN cd.TipFac <> '' THEN @TDAnt ELSE '' END)) ELSE (case WHEN cd.TipFac <> '' THEN @TDAnt ELSE '' END) END), 
			(CASE WHEN (SELECT TOP 1 p.Vencimiento FROM Puc as p WHERE p.IdCuenta = cd.IdCuenta) = 1  THEN ISNULL(@Factura, (case WHEN cd.Factura <> '' THEN CONVERT(varchar(15), @Anticipo) ELSE '' END)) ELSE (case WHEN cd.Factura <> '' THEN CONVERT(varchar(15), @Anticipo) ELSE '' END) END), 
			(CASE WHEN (SELECT TOP 1 p.Vencimiento FROM Puc as p WHERE p.IdCuenta = cd.IdCuenta) = 1  THEN ISNULL(@IdCiaFac, (case WHEN cd.IdCiaFac <> '' THEN @CiaAnt ELSE '' END))ELSE (case WHEN cd.TipFac <> '' THEN @CiaAnt ELSE '' END) END),  
			cd.ItemFac, cd.FecVence, cd.CodCta,
			cd.NumCheque, cd.Integrado, cd.TipoAplica, cd.Consolida, cd.CodCargo, cd.NitOtros, cd.CodSubgpo, cd.CiuOrigen, 
			cd.CodAgncia,cd.VehPropio, cd.Referncia, cd.TipDocRef, cd.DocRef, cd.IdCiaRef, cd.TimeSys, cd.FecUpdate, cd.IdCiaCrea, 
			cd.IdUsuario, cd.CdConcTrib, cd.CdTarifTrib, cd.NumEstablec, cd.PtoEmision, cd.Num_Autoriza, cd.FechAutoriza,cd.CdCuentaNiif
			FROM @Trn_ComDetalle cd
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp))
			BEGIN
			INSERT INTO Trn_NiifComp(
			TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
			EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
			FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
			VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
			IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
			Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
			CtbTipo, CtbNumero,
			FisTipo, FisNumero 
			)
			SELECT 
			CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
			CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
			@CiaAnt,
			C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
			C.EnEfectivo, C.NumCheque, C.FecCheque, @TDAnt, @Anticipo, @CiaAnt, C.Anulado, C.NumDev,
			C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
			C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
			C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
			C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
			CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
		    CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
			FROM @Trn_Comprobantes AS C 
			JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
			BEGIN
			INSERT INTO Trn_NiifDetalle(
			TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
			VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
			VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
			NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
			NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
			CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
			DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
			CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
			FechAutoriza, CodCuentaCG
			)
			SELECT 
			CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
			CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
			@CiaAnt,
			N.Item, N.Fecha, N.IdCuenta, N.Detalle,
			N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
			N.VrBase, N.TarifaBase, @TDAnt, @Anticipo, @CiaAnt, N.CodConce,
			N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
			N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
			N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
			N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
			N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
			N.FechAutoriza, N.CodCuentaCG
			FROM @Trn_NiifDetalle as N
			JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante

			END
			IF(EXISTS(SELECT * FROM @Trn_ComFactura))--5042 SE AGREGA ANTICIPOS DE COMBUSTIBLES
			BEGIN
				INSERT INTO Trn_ComFactura(
				TipFac, Factura, IdCia, Item, IdProveedor, IdCuenta, TipDoc, Documento, IdCiaDoc, 
				FecEmision, FecVence, VrFactura, VrAbonado, TipCom, Comprobante, ItemCom, Referencia, 
				Detalle, pVehiculo, VehPropio, TipRef, DocRef, IdCiaRef, EstadoApr, MontoAprob
				)
				SELECT 
				ISNULL(TipFac, @TDAnt), ISNULL(Factura, @Anticipo),  ISNULL(IdCia, @CiaAnt), 1, IdProveedor, 
				IdCuenta, @TDAnt, @Anticipo, @CiaAnt, FecEmision, FecVence, VrFactura, VrAbonado, @TipComp, 
				@Comprobante, 0, Referencia, Detalle, pVehiculo, VehPropio, TipRef, DocRef, IdCiaRef, EstadoApr, 
				MontoAprob
				FROM @Trn_ComFactura 
			END

			END

			if(@operacion = 's')
			begin
				update Trn_TraEspAnticipos 
				set  VrAbonado = t1.VrAnticipo 
				from Trn_TraEspAnticipos t1, @Trn_TraEspAnticipos t2
				where t1.TipDoc = t2.TipDoc  and t1.Anticipo = t2.Anticipo and t1.IdCia = t2.IdCia
			end
						
			SELECT @Anticipo,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspCausacion]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 15/02/2017
-- Description:	Insertar Trn_TraEspCausacion
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspCausacion]
	@Trn_TraEspCausacion dataTypeTrn_TraEspCausacion READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspCausacion
	@Trn_TraEspCauDetalle dataTypeTrn_TraEspCauDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspCauDetalle
	@Trn_ComFactura dataTypeTrn_ComFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Vencimientos
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle
	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			
			IF(@operacion = 'i')
			BEGIN
			SELECT TOP 1 @TipDoc = TipDoc, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspCausacion
			SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

			IF(@Numero > 0)
				UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
			ELSE
			BEGIN
				SELECT @Numero = 1
				INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
			END

			IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			BEGIN
				SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
				SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
				--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
				IF(@Comprobante <> '')
					UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
				ELSE
				BEGIN
					SELECT @Comprobante = 1
					INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
			BEGIN
				SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
				SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
				--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
				IF(@CompNiif <> '')
					UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
				ELSE
				BEGIN
					SELECT @CompNiif = 1
					INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
			BEGIN
				SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
				SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
				--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
				IF(@CompNiif <> '')
					UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
				ELSE
				BEGIN
					SELECT @CompFis = 1
					INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END
			END

			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspCausacion))
				BEGIN
				INSERT INTO Trn_TraEspCausacion(
				TipDoc,Causacion,IdCia,Fecha,IdConcepto,IdProv,Factura,VrTotal,VrOtros,VrNeto,
				TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,
				TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Fecha,IdConcepto,IdProv,Factura,VrTotal,VrOtros,VrNeto,
				@TipComp, @Comprobante, @IdCiaComp,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,
				TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspCausacion
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspCauDetalle))
				BEGIN
				INSERT INTO Trn_TraEspCauDetalle(
				TipDoc,Causacion,IdCia,Item,IdConcepto,Descripcion,TipoConc,VrDebito,VrCredito,CdCuenta,
				NitTercero,CdCCosto,CdSubCos,pVehiculo,TipoAfiVehic,VrBase,TarifBase,Referencia,TipDocRef,DocRef,
				TipFac,Factura,IdCiaFac,ItemFac,FecVence,EstadoReg,TipoLiq,NumLiquida,CiaLiquida,VrAbonado
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,IdConcepto,Descripcion,TipoConc,VrDebito,VrCredito,CdCuenta,
				NitTercero,CdCCosto,CdSubCos,pVehiculo,TipoAfiVehic,VrBase,TarifBase,Referencia,TipDocRef,DocRef,
				TipFac,Factura,IdCiaFac,ItemFac,FecVence,EstadoReg,TipoLiq,NumLiquida,CiaLiquida,VrAbonado
				FROM @Trn_TraEspCauDetalle
				END 

				IF(EXISTS(SELECT * FROM @Trn_ComFactura))
				BEGIN
				INSERT INTO Trn_ComFactura(
				TipFac,Factura,IdCia,Item,IdProveedor,IdCuenta,TipDoc,Documento,IdCiaDoc,FecEmision,FecVence,
				VrFactura,VrAbonado,TipCom,Comprobante,ItemCom,Referencia,Detalle,pVehiculo,VehPropio,TipRef,
				DocRef,IdCiaRef,EstadoApr,MontoAProb
				)
				SELECT 
				TipFac,Factura,@Cia,Item,IdProveedor,IdCuenta,@TipDoc,@Numero,@Cia,FecEmision,FecVence,
				VrFactura,VrAbonado,@TipComp,@Comprobante,ItemCom,Referencia,Detalle,pVehiculo,VehPropio,TipRef,
				DocRef,IdCiaRef,EstadoApr,MontoAprob
				FROM @Trn_ComFactura
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,IdCiaDoc, 
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, cd.Item, cd.Fecha, cd.IdCuenta, cd.Detalle, cd.VrDebito, cd.VrCredito,
				cd.IdTercero, cd.IdVehiculo, cd.IdCCosto,cd.IdSubCos, cd.VrBase , cd.TarifaBase, @TipDoc, @Numero, @Cia,
				cd.CodConce, cd.NitDoc, cd.TipFac, cd.Factura, cd.IdCiaFac, cd.ItemFac, cd.FecVence, cd.CodCta,
				cd.NumCheque, cd.Integrado, cd.TipoAplica, cd.Consolida, cd.CodCargo, cd.NitOtros, cd.CodSubgpo, cd.CiuOrigen, 
				cd.CodAgncia, cd.VehPropio, cd.Referncia, cd.TipDocRef, cd.DocRef, cd.IdCiaRef, cd.TimeSys, cd.FecUpdate, cd.IdCiaCrea, 
				cd.IdUsuario, cd.CdConcTrib, cd.CdTarifTrib, cd.NumEstablec, cd.PtoEmision, cd.Num_Autoriza, cd.FechAutoriza,cd.CdCuentaNiif
				FROM @Trn_ComDetalle cd
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDoc, @Numero, @Cia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			end
						
			IF(@operacion = 'a')
			begin
				update Trn_TraEspCausacion 
				set  Anulado = '1', FecUpdate = GETDATE() 
				from  Trn_TraEspCausacion t1, @Trn_TraEspCausacion t2
				where t1.TipDoc = t2.TipDoc  and t1.Causacion = t2.Causacion and t1.IdCia = t2.IdCia
				select @Numero = (select Causacion from @Trn_TraEspCausacion)
			end

			if(@operacion = 's')
			begin
				update Trn_TraEspCauDetalle 
				set  
				VrAbonado = (t2.VrDebito + t2.VrCredito), EstadoReg = 1, 
				TipoLiq = t2.TipDoc, NumLiquida = t2.Causacion, CiaLiquida = t2.IdCia 
				from Trn_TraEspCauDetalle t1, @Trn_TraEspCauDetalle t2
				where t1.TipDoc = t2.TipDoc  and t1.Causacion = t2.Causacion and t1.IdCia = t2.IdCia  and t1.Item = t2.Item

				select @Numero = (select top 1 Causacion from @Trn_TraEspCauDetalle)
			end

			SELECT @Numero,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspConceptos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa Castañeda
-- Create date(dd/MM/yyy): 08/10/2018
-- Description:	Insertar Conceptos de Novedades de Reservas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspConceptos]
	@Trn_TraEspConceptos dataTypeTrn_TraEspConceptos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspConceptos
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Pedido/Cotización
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Pedido/Cotización
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Pedido/Cotización
DECLARE @ItemNov int
DECLARE @ItemDoc int
DECLARE @Cliente bit
DECLARE @Vehiculo bit
BEGIN TRAN
		BEGIN TRY
		--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
				BEGIN
					IF(EXISTS(SELECT COUNT(1) FROM @Trn_TraEspConceptos))
						BEGIN
							SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Documento FROM @Trn_TraEspConceptos
							SELECT @ItemNov =  isnull(MAX(Item),0) FROM Trn_TraEspConceptos WHERE TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia

							--actualizar los que vienen en el tipo de dato y coincidan con los que ya estan en la tabla
							UPDATE Trn_TraEspConceptos
							SET 
							TipDoc = t2.TipDoc,Documento = t2.Documento,IdCia = t2.IdCia,Item = t2.Item,
							Descripcion = t2.Descripcion,Tarifa = t2.Tarifa,TipoConc = t2.TipoConc,
							RubroConcep = t2.RubroConcep,Cantidad = t2.Cantidad,VrUnitario = t2.VrUnitario,
							TarifIva = t2.TarifIva,IdConcepto = t2.IdConcepto,CdCuenta = t2.CdCuenta,
							NitTercero = t2.NitTercero,CdTipoEsc = t2.CdTipoEsc,FechaNov = t2.FechaNov,
							VrBase = t2.VrBase,TipoTarif = t2.TipoTarif,RefConc = t2.RefConc,Fijos = t2.Fijos,
							IncBaseRet = t2.IncBaseRet,Referencia2 = t2.Referencia2,Referencia3 = t2.Referencia3,
							Cliente = t2.Cliente,Conductor = t2.Conductor,Vehiculo=t2.Vehiculo,ItemDoc=t2.ItemDoc,
							IdVehiculo = t2.IdVehiculo
							FROM Trn_TraEspConceptos t1
							JOIN @Trn_TraEspConceptos t2 ON t1.TipDoc = t2.TipDoc and t1.Documento = t2.Documento and t1.IdCia = t2.IdCia and t1.Item = t2.Item
							WHERE t1.TipDoc = t2.TipDoc and t1.Documento = t2.Documento and t1.IdCia = t2.IdCia and t1.Item = t2.Item
							--Inserta los que no existen
							INSERT INTO Trn_TraEspConceptos(
							TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
							TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
							CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
							IncBaseRet,Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo)
							SELECT 
							TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
							TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
							CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
							IncBaseRet,Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
							FROM @Trn_TraEspConceptos
							WHERE (TipDoc + Convert(varchar,Documento)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Documento)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspConceptos)
							--Eliminar los que no existen en el tipo de dato
							DELETE FROM Trn_TraEspConceptos
							WHERE TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspConceptos)
						END
					END

			--INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
				BEGIN
					IF(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
						BEGIN
							SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Documento, @ItemDoc = ItemDoc, @Cliente = Cliente, @Vehiculo = Vehiculo FROM @Trn_TraEspConceptos
							DELETE FROM Trn_TraEspConceptos WHERE TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia and ItemDoc = @ItemDoc  and Cliente = @Cliente and Vehiculo = @Vehiculo
							INSERT INTO Trn_TraEspConceptos(
							TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
							TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
							CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
							IncBaseRet,Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
							) 
							SELECT 
							TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
							TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
							CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
							IncBaseRet,Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
							FROM @Trn_TraEspConceptos
						END
				END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
				SELECT @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Documento, @ItemNov = Item, @ItemDoc = ItemDoc, @Cliente = Cliente, @Vehiculo = Vehiculo from @Trn_TraEspConceptos
				DELETE FROM Trn_TraEspConceptos WHERE TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia and Item = @ItemNov and ItemDoc = @ItemDoc and Cliente = @Cliente and Vehiculo = @Vehiculo
			END
				SELECT '1'
			COMMIT TRAN
		END TRY
BEGIN CATCH
	ROLLBACK TRAN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;

	SELECT 
	@ErrorMessage = ERROR_MESSAGE(),
	@ErrorSeverity = ERROR_SEVERITY(),
	@ErrorState = ERROR_STATE();
	RAISERROR(
	@ErrorMessage, -- Message text.
	@ErrorSeverity, -- Severity.
	@ErrorState -- State.
	);
END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspContratos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 19/10/2016
-- Description:	CRUD Contratos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspContratos]
	@Trn_TraEspContratos dataTypeTrn_TraEspContratos READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspContratos
	@Trn_TraEspContratoAnexo dataTypeTrn_TraEspContratoAnexo READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspContratoAnexo
	@Trn_TraEspContratoDet dataTypeTrn_TraEspContratoDet READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspEspDetalle
	@Trn_TraEspConceptos dataTypeTrn_TraEspConceptos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspConceptos
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Contrato/Cotización
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Contrato/Cotización
DECLARE @IdCia VARCHAR(2) --Esta variable guarda la compañia del Contrato/Cotización
declare @item int
	BEGIN TRAN
		BEGIN TRY

			--Seleccionar Variables
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia FROM @Trn_TraEspContratos
				SELECT @Documento = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia

				IF(@Documento <> '')
					UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
				ELSE
				BEGIN
					SELECT @Documento = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			end

			--Seleccionar Variables
			--IF(@operacion = 'u')
			--begin
			--	SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Contrato FROM @Trn_TraEspContratos
			--end

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN
			   if(EXISTS(SELECT * FROM @Trn_TraEspContratos))
			   begin
			   UPDATE Trn_TraEspContratos
			   SET 
			   TipDoc = t2.TipDoc,Contrato = t2.Contrato,IdCia = t2.IdCia,Fecha = t2.Fecha,FechaInicio = t2.FechaInicio,FechaFin = t2.FechaFin,
			   IdCliente = t2.IdCliente,IdVend = t2.IdVend,IdTarifCom = t2.IdTarifCom,IdForma = t2.IdForma,Plazos = t2.Plazos,TipoPago = t2.TipoPago,
			   Modalidad = t2.Modalidad,TipoLiquid = t2.TipoLiquid,CodTarRet = t2.CodTarRet,CodTarIca = t2.CodTarIca,VrPresupuesto = t2.VrPresupuesto,VrSaldoPresup = t2.VrSaldoPresup,
			   VrCobro = t2.VrCobro,VrCargos = t2.VrCargos,VrRetencion = t2.VrRetencion,VrReteIca = t2.VrReteIca,VrDctos = t2.VrDctos,Cantidad = t2.Cantidad,
			   Peso = t2.Peso,NumAprob = t2.NumAprob,IdCiaApr = t2.IdCiaApr,FecAprob = t2.FecAprob,TipOdp = t2.TipOdp,NumOdp = t2.NumOdp,IdCiaOdp = t2.IdCiaOdp,
			   FechaOdp = t2.FechaOdp,TipFac = t2.TipFac,Factura = t2.Factura,IdCiaFac = t2.IdCiaFac,FechaFac = t2.FechaFac,OrigenAdd = t2.OrigenAdd,
			   EsLicitacion = t2.EsLicitacion,Anulado = t2.Anulado,FecDev = t2.FecDev,Observacion = t2.Observacion,IdEstado = t2.IdEstado,TimeSys = t2.TimeSys,
			   FecUpdate = t2.FecUpdate,IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario,CdCarga = t2.CdCarga,IdAgencia = t2.IdAgencia,IdMneda = t2.IdMneda,
			   VrIva = t2.VrIva,CantPasajeros = t2.CantPasajeros, CdDescuento = t2.CdDescuento,UnionTemporal = t2.UnionTemporal,IdGrupo = t2.IdGrupo,IdRutaG = t2.IdRutaG
		       FROM Trn_TraEspContratos t1
			   JOIN @Trn_TraEspContratos t2 ON t1.TipDoc = t2.TipDoc and t1.Contrato = t2.Contrato and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspContratoAnexo))
			   begin
			   UPDATE Trn_TraEspContratoAnexo
			   SET 
			   TipDoc = t2.TipDoc,Contrato = t2.Contrato,IdCia = t2.IdCia,TipContrato = t2.TipContrato,IdContrato = t2.IdContrato,IdObjCOE = t2.IdObjCOE, ObjContrato = t2.ObjContrato,
			   NomCliente = t2.NomCliente,TelCliente = t2.TelCliente,emlCliente = t2.emlCliente,DireccionCli = t2.DireccionCli,Observacion = t2.Observacion,
			   NombArchivo = t2.NombArchivo,DescripCarga = t2.DescripCarga,Clausulas = t2.Clausulas,Responsable = t2.Responsable,NombreResp=t2.NombreResp
		       FROM Trn_TraEspContratoAnexo t1
			   JOIN @Trn_TraEspContratoAnexo t2 ON t1.TipDoc = t2.TipDoc and t1.Contrato = t2.Contrato and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspContratoDet))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Contrato FROM @Trn_TraEspContratoDet
			   select @item = isnull(MAX(Item),0) from Trn_TraEspContratoDet where TipDoc = @TipDoc and Contrato = @Documento and IdCia = @IdCia

			   --actualizar los que vienen en el tipo de dato y coincida con los que ya están en la tabla
			   UPDATE Trn_TraEspContratoDet
			   SET 
			   TipDoc = t2.TipDoc,Contrato = t2.Contrato,IdCia = t2.IdCia,Item = t2.Item,IdHorario = t2.IdHorario,TipPed = t2.TipPed,Pedido = t2.Pedido,CiaPed = t2.CiaPed,
			   ItemPed = t2.ItemPed,TipRes = t2.TipRes,NumRes = t2.NumRes,IdCiaRes = t2.IdCiaRes,ItemRes = t2.ItemRes,IdVehiculo = t2.IdVehiculo,
			   CdTipVeh = t2.CdTipVeh,NumPasajeros = t2.NumPasajeros,PesoNeto = t2.PesoNeto,VrUnitario = t2.VrUnitario,VrPago= t2.Vrpago,
			   IdRuta = t2.IdRuta,Referencia1 = t2.Referencia1,Referencia2 = t2.Referencia2,Referencia3 = t2.Referencia3,EsRutaCliente = t2.EsRutaCliente,
			   CdCiuOrigen = t2.CdCiuOrigen,DirOrigen = t2.DirOrigen,FecOrigen = t2.FecOrigen,CdCiuDestino = t2.CdCiuDestino,DirDestino = t2.DirDestino,
			   FecDestino = t2.FecDestino,DiasDisp = t2.DiasDisp,VrDia = t2.VrDia,Parada = t2.Parada,CdTipRuta = t2.CdTipRuta,CdTipServicio = t2.CdTipServicio,
			   CantVeh=t2.CantVeh,Retorno=t2.Retorno,VrMonitor=t2.VrMonitor,CantMonitor=t2.CantMonitor,VrMaxRec=t2.VrMaxRec,NumDias=t2.NumDias,TipoTarifa=t2.TipoTarifa,IdColegio = t2.IdColegio,Codigo = t2.Codigo,
			   Itinerario = t2.Itinerario, VLargo = t2.VLargo, IdOtroSi = t2.IdOtroSi, ItemAnuladoOS = t2.ItemAnuladoOS, EsItemPME = t2.EsItemPME
		       FROM Trn_TraEspContratoDet t1
			   JOIN @Trn_TraEspContratoDet t2 ON t1.TipDoc = t2.TipDoc and t1.Contrato = t2.Contrato and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Contrato = t2.Contrato and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspContratoDet(
			   TipDoc,Contrato,IdCia,Item,IdHorario,
			   TipPed,Pedido,CiaPed,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
				Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
				DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,
				IdOtroSi,ItemAnuladoOS,EsItemPME
				) 
				SELECT 
				@TipDoc,@Documento,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)),IdHorario,
				TipPed,Pedido,@IdCia,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
				Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
				DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,
				IdOtroSi,ItemAnuladoOS,EsItemPME
				FROM @Trn_TraEspContratoDet
				WHERE (TipDoc + Convert(varchar,Contrato)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Contrato)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspContratoDet)
			   --Eliminar los que no existen en lo que envian
			   delete from Trn_TraEspContratoDet
			   WHERE TipDoc = @TipDoc and Contrato = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspContratoDet)

			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Documento FROM @Trn_TraEspConceptos
			   select @item = isnull(MAX(Item),0) from Trn_TraEspConceptos where TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia
			   
			   --actualizar los que vienen en el tipo de dato y coincida con los que ya están en la tabla
			   UPDATE Trn_TraEspConceptos
			   SET 
			   TipDoc = t2.TipDoc,Documento = t2.Documento,IdCia = t2.IdCia,Item = t2.Item,
			   Descripcion = t2.Descripcion,Tarifa = t2.Tarifa,TipoConc = t2.TipoConc,
			   RubroConcep = t2.RubroConcep,Cantidad = t2.Cantidad,VrUnitario = t2.VrUnitario,
			   TarifIva = t2.TarifIva,IdConcepto = t2.IdConcepto,CdCuenta = t2.CdCuenta,
			   NitTercero = t2.NitTercero,CdTipoEsc = t2.CdTipoEsc,FechaNov = t2.FechaNov,
			   VrBase = t2.VrBase,TipoTarif = t2.TipoTarif,RefConc = t2.RefConc,Fijos = t2.Fijos,
			   IncBaseRet = t2.IncBaseRet,Referencia2 = t2.Referencia2,Referencia3 = t2.Referencia3,
			   Cliente = t2.Cliente,Conductor = t2.Conductor,Vehiculo = t2.Vehiculo,ItemDoc=t2.ItemDoc,
			   IdVehiculo = t2.IdVehiculo
		       FROM Trn_TraEspConceptos t1
			   JOIN @Trn_TraEspConceptos t2 ON t1.TipDoc = t2.TipDoc and t1.Documento = t2.Documento and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Documento = t2.Documento and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspConceptos(
			    TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo)
			   SELECT 
			    @TipDoc, @Documento, @IdCia, (@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)), Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
			   FROM @Trn_TraEspConceptos
			   WHERE (TipDoc + Convert(varchar,Documento)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Documento)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspConceptos)
			   --Eliminar los que no existen en lo que envian
			   delete from Trn_TraEspConceptos
			   WHERE TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspConceptos)
			   end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN
				IF(EXISTS(SELECT * FROM @Trn_TraEspContratos))
				begin
				INSERT INTO Trn_TraEspContratos(
				TipDoc,Contrato,IdCia,Fecha,FechaInicio,FechaFin,IdCliente,IdVend,IdTarifCom,IdForma,Plazos,TipoPago,Modalidad,TipoLiquid,CodTarRet,CodTarIca,
				VrPresupuesto,VrSaldoPresup,VrCobro,VrCargos,VrRetencion,VrReteIca,VrDctos,Cantidad,Peso,NumAprob,IdCiaApr,FecAprob,TipOdp,NumOdp,
				IdCiaOdp,FechaOdp,TipFac,Factura,IdCiaFac,FechaFac,OrigenAdd,EsLicitacion,Anulado,FecDev,Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,
				IdUsuario,CdCarga,IdAgencia,IdMneda,VrIva,CantPasajeros,CdDescuento,UnionTemporal,IdGrupo,IdRutaG
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,Fecha,FechaInicio,FechaFin,IdCliente,IdVend,IdTarifCom,IdForma,Plazos,TipoPago,Modalidad,TipoLiquid,CodTarRet,CodTarIca,
				VrPresupuesto,VrPresupuesto,VrCobro,VrCargos,VrRetencion,VrReteIca,VrDctos,Cantidad,Peso,NumAprob,IdCiaApr,FecAprob,TipOdp,NumOdp,
				IdCiaOdp,FechaOdp,TipFac,Factura,IdCiaFac,FechaFac,OrigenAdd,EsLicitacion,Anulado,FecDev,Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,
				IdUsuario,CdCarga,IdAgencia,IdMneda,VrIva,CantPasajeros,CdDescuento,UnionTemporal,IdGrupo,IdRutaG
				FROM @Trn_TraEspContratos
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspContratoAnexo))
				begin
				INSERT INTO Trn_TraEspContratoAnexo(
				TipDoc,Contrato,IdCia,TipContrato,IdContrato,IdObjCOE,ObjContrato,NomCliente,TelCliente,emlCliente,DireccionCli,
				Observacion,NombArchivo,DescripCarga,Clausulas,Responsable,NombreResp
				) 
				SELECT 
				@TipDoc, @Documento, @IdCia,TipContrato,IdContrato,IdObjCOE,ObjContrato,NomCliente,TelCliente,emlCliente,DireccionCli,
				Observacion,NombArchivo,DescripCarga,Clausulas,Responsable,NombreResp
				FROM @Trn_TraEspContratoAnexo
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspContratoDet))
				begin
				INSERT INTO Trn_TraEspContratoDet(
			    TipDoc,Contrato,IdCia,Item,IdHorario,TipPed,Pedido,CiaPed,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
				Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
				DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,IdOtroSi,ItemAnuladoOS,
				EsItemPME
				) 
				SELECT 
				@TipDoc,@Documento,@IdCia,Item,IdHorario,TipPed,Pedido,@IdCia,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
				Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
				DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,IdOtroSi,ItemAnuladoOS,
				EsItemPME
				FROM @Trn_TraEspContratoDet
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
				BEGIN
				INSERT INTO Trn_TraEspConceptos(
				TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				) 
				SELECT 
				@TipDoc, @Documento, @IdCia, Item, Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				FROM @Trn_TraEspConceptos
				END

			    --Actualizar cotización
			    UPDATE Trn_TraEspPedDetalle
			    SET TipCtn = @TipDoc, NumCnt = @Documento, IdCiaCnt = @IdCia,ItemCnt = d.Item
			    FROM Trn_TraEspPedDetalle p, @Trn_TraEspContratoDet d 
			    WHERE p.TipDoc = 'CTE'  and p.Pedido = d.Pedido and p.IdCia = d.CiaPed and p.Item = d.ItemPed and d.Pedido > 0 and d.CiaPed <> '00'

			    --Actualizar Contratos
			    IF(((SELECT upper(Modalidad) FROM @Trn_TraEspContratos) = 'OCASIONAL') AND ((SELECT Valor FROM adm_Opciones WHERE IdOpc = 'ACO') = '0'))
			    BEGIN
				  UPDATE Trn_TraEspContratos 
				  SET IdEstado = '9998'
				  WHERE TipDoc = @TipDoc and Contrato = @Documento and IdCia = @IdCia
			    END

			    --Actualizar Facturas de Contado
			    IF((SELECT TipoPago FROM @Trn_TraEspContratos) = '0001')
			    BEGIN
				  UPDATE Trn_Factcon
				  SET TipRem = 'COE', Remision = @Documento, IdCiaRem = @IdCia
				  FROM Trn_Factcon F, @Trn_TraEspContratos C
				  WHERE F.TipDoc = C.TipFac and F.Factura = C.Factura and F.IdCia = C.IdCiaFac
			    END

			 END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 declare @Contrato int
			 select @TipDoc = TipDoc, @IdCia = IdCia,  @Contrato = Contrato from @Trn_TraEspContratos
				 DELETE FROM Trn_TraEspContratoAnexo WHERE TipDoc = @TipDoc and Contrato = @Contrato and IdCia = @IdCia
				 DELETE FROM Trn_TraEspContratoDet WHERE TipDoc = @TipDoc and Contrato = @Contrato and IdCia = @IdCia
				 DELETE FROM Trn_TraEspConceptos WHERE TipDoc = @TipDoc and Documento = @Contrato and IdCia = @IdCia
				 DELETE FROM Trn_TraEspContratos WHERE TipDoc = @TipDoc and Contrato = @Contrato and IdCia = @IdCia
			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
			  --declare @IdEstado varchar(4)
			  --select @IdEstado = IdEstado from EstadoDoc where Estado = 'ANULADO'
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Contrato from @Trn_TraEspContratos
			  UPDATE Trn_TraEspContratos SET IdEstado = '9999', Anulado = '1' WHERE TipDoc = @TipDoc and Contrato = @Documento and IdCia = @IdCia

			  UPDATE Trn_TraEspPedDetalle
			  SET TipCtn = 'COE', NumCnt = 0, IdCiaCnt = '00',ItemCnt = 0
			  FROM Trn_TraEspPedDetalle p, @Trn_TraEspContratos d 
			  WHERE p.TipCtn = 'COE'  and p.NumCnt = d.Contrato and p.IdCiaCnt = d.IdCia --and p.Item = d.ItemPed

			  --Actualizar Facturas de Contado
			  IF((SELECT TipoPago FROM @Trn_TraEspContratos) = '0001')
			  BEGIN
				UPDATE Trn_Factcon
				SET TipRem = 'REM', Remision = 0, IdCiaRem = '00'
				FROM Trn_Factcon F, @Trn_TraEspContratos C
				WHERE F.TipDoc = C.TipFac and F.Factura = C.Factura and F.IdCia = C.IdCiaFac
			  END
			END

			SELECT @Documento

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspCumplido]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 15/09/2017
-- Description:	Insertar Trn_TraEspCumplido.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspCumplido]
	@Trn_TraEspCumplido dataTypeTrn_TraEspCumplido READONLY, --Tipo de dato definido por el usuario que representa la tabla cumplido
	@Trn_TraEspCumReservas dataTypeTrn_TraEspCumReservas READONLY,--Tipo de dato definido por el usuario que representa la tabla cumplido reservas
	@Trn_TraEspCumplidoProg dataTypeTrn_TraEspCumplidoProg READONLY,--Tipo de dato definido por el usuario que representa la tabla cumplido programacion
	@Trn_TraEspCumFacturas dataTypeTrn_TraEspCumFacturas READONLY, --Tipo de dato definido por el usuario que representa la tabla cumplido factura para reserva de estudiantes
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Aprobacion
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Aprobacion
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Aprobacion
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Aprobacion
	@operacion varchar(1)

AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CiaDoc VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cumplido INT --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @FechaCum smalldatetime
	BEGIN TRAN
		BEGIN TRY		 

			IF(@operacion = 'i')
			BEGIN

				SELECT TOP 1 @TDoc = TipDoc, @CiaDoc = IdCia,  @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia, @FechaCum = Fecha FROM @Trn_TraEspCumplido
				SELECT @Cumplido = Numero + 1  FROM TiposDocCons where IdDoc = @TDoc AND IdCia = @CiaDoc

				IF(@Cumplido > 0)
					UPDATE TiposDocCons SET Numero = @Cumplido WHERE IdDoc = @TDoc AND IdCia = @CiaDoc
				ELSE
				BEGIN
					SELECT @Cumplido = 1
					INSERT INTO TiposDocCons VALUES (@TDoc,@CiaDoc,0,0,0,0,NULL,'',@Cumplido,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif

					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis

					IF(@CompFis <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			END

			IF(@operacion = 'i')
			BEGIN

				IF(EXISTS(SELECT * FROM @Trn_TraEspCumplido))
				begin
				INSERT INTO Trn_TraEspCumplido(
				TipDoc, Cumplido, IdCia, Fecha, TipRes, Reserva, IdCiaRes,ItemRes,TipFac,Factura,IdCiaFac,IdClieFac, CdRuta, CdOrigen, CdDestino, Anulado,
				NumDev, FecDev, TipoComp, NumComp, CodConcepto, Observacion, IdEstado, OrigenAdd, TimeSys, FecUpdate,
				IdCiaCrea, IdUsuario, ObservAnulado, CdCenCosto, CdSubCenCos,VrPago,VrCobro, VrAfiliados, VrPropios, VrTotalServ, 
				VrTotalPagos, CodTarRtc, BaseRet, VrReteCree, VrNeto
				)
				SELECT 
				@TDoc,@Cumplido,@CiaDoc, Fecha, TipRes, Reserva, IdCiaRes,ItemRes,TipFac,Factura,IdCiaFac,IdClieFac, CdRuta, CdOrigen, CdDestino, Anulado,
				NumDev, FecDev, @TipComp, @Comprobante, CodConcepto, Observacion, IdEstado, OrigenAdd, TimeSys, FecUpdate,
				IdCiaCrea, IdUsuario, ObservAnulado, CdCenCosto, CdSubCenCos,VrPago,VrCobro, VrAfiliados, VrPropios, VrTotalServ, 
				VrTotalPagos, CodTarRtc, BaseRet, VrReteCree, VrNeto
				FROM @Trn_TraEspCumplido
				end 

				IF(EXISTS(SELECT * FROM @Trn_TraEspCumReservas))
				begin
				INSERT INTO Trn_TraEspCumReservas(
				TipDoc,Cumplido,IdCia,Item,TipRes,Reserva,IdCiaRes,ItemRes,EstadoItemRes,VrRecorridos,
				IdVehiculo,IdPoseedor,IdConductor,TipoAfil
				)
				SELECT 
				@TDoc,@Cumplido,@CiaDoc,Item,TipRes,Reserva,IdCiaRes,ItemRes,EstadoItemRes,VrRecorridos,
				IdVehiculo,IdPoseedor,IdConductor,TipoAfil
				FROM @Trn_TraEspCumReservas
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspCumplidoProg))
				begin
				INSERT INTO Trn_TraEspCumplidoProg(
				 TipDoc,Cumplido,IdCia,Item,TipRes,Reserva,IdCiaRes,ItemRes,TipPgr,Programa,IdCiaPgr,ItemPgr,VrRecorrido
				)
				SELECT 
				@TDoc,@Cumplido,@CiaDoc,Item,TipRes,Reserva,IdCiaRes,ItemRes,TipPgr,Programa,IdCiaPgr,ItemPgr,VrRecorrido
				FROM @Trn_TraEspCumplidoProg
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspCumFacturas))
				begin
				INSERT INTO Trn_TraEspCumFacturas(
				 TipDoc, Cumplido, IdCia, TipFac, Factura, IdCiaFac, IdCliente, VrIngreso
				)
				SELECT 
				@TDoc,@Cumplido,@CiaDoc, TipFac, Factura, IdCiaFac, IdCliente, VrIngreso
				FROM @Trn_TraEspCumFacturas
				end

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TDoc, @Cumplido, @CiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, cd.Item, cd.Fecha, cd.IdCuenta, cd.Detalle, cd.VrDebito, cd.VrCredito,
				cd.IdTercero, cd.IdVehiculo, cd.IdCCosto, cd.IdSubCos, cd.VrBase, cd.TarifaBase, @TDoc, @Cumplido, @CiaDoc,
				cd.CodConce, cd.NitDoc, case WHEN cd.TipFac <> '' THEN @TDoc ELSE '' END, case WHEN cd.TipFac <> '' THEN @Cumplido ELSE '' END, case WHEN cd.TipFac <> '' THEN @CiaDoc ELSE '' END, 
				cd.ItemFac, cd.FecVence, cd.CodCta,
				cd.NumCheque, cd.Integrado, cd.TipoAplica, cd.Consolida, cd.CodCargo, cd.NitOtros, cd.CodSubgpo, cd.CiuOrigen, 
				cd.CodAgncia,cd.VehPropio, cd.Referncia, cd.TipDocRef, cd.DocRef, cd.IdCiaRef, cd.TimeSys, cd.FecUpdate, cd.IdCiaCrea, 
				cd.IdUsuario, cd.CdConcTrib, cd.CdTarifTrib, cd.NumEstablec, cd.PtoEmision, cd.Num_Autoriza, cd.FechAutoriza,cd.CdCuentaNiif
				FROM @Trn_ComDetalle cd
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDoc,
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TDoc, @Cumplido, @CiaDoc, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C 
				JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDoc,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TDoc, @Cumplido, @CiaDoc, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante

				END

			END

			IF(@operacion = 'i')
			BEGIN
				--Actualizar ResDetalles
				UPDATE Trn_TraEspResDetalle
				SET TipCum = @TDoc, Cumplido = @Cumplido, IdCiaCum = @CiaDoc, FechaCum = @FechaCum
				FROM Trn_TraEspResDetalle t1, @Trn_TraEspCumReservas t2
				WHERE t1.TipDoc = t2.TipRes and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCiaRes and t1.Item = t2.ItemRes
			END

			SELECT @Cumplido,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevAnt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 16/12/2016
-- Description:	Insertar Trn_TraEspDevAnt.
-- ============================================= 
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevAnt]
	@Trn_TraEspDevAnt dataTypeTrn_TraEspDevAnt READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspDevAnt
	@Trn_TraEspAntAbonos dataTypeTrn_TraEspAntAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraAntAbonos
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle
	--@Trn_ComFactura dataTypeTrn_ComFactura READONLY --Tipo de dato definido por el usuario que representa la tabla Trn_Aprobacion
	@Trn_EgrFactura dataTypeTrn_EgrFactura  READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_EgrFactura, cuando el anticipo es de combustible
	@operacion varchar(1)

AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDev VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CiaDev VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Dev INT --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @DocAnt VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @IdCiaAnt VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Antic INT --En esta variable se guarda el consecutivo del documento aprobación
declare @VrDev money 

	BEGIN TRAN
		BEGIN TRY		 
			
			--Seleecionar variables de consecutivos
			if(@operacion = 'i')
			BEGIN

				SELECT TOP 1 @TipDev = TipDev, @CiaDev = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia, @DocAnt = TipDoc, @IdCiaAnt = IdCiaDoc, @Antic = Anticipo FROM @Trn_TraEspDevAnt
				SELECT @Dev = Numero + 1  FROM TiposDocCons where IdDoc = @TipDev AND IdCia = @CiaDev

				IF(@Dev > 0)
					UPDATE TiposDocCons SET Numero = @Dev WHERE IdDoc = @TipDev AND IdCia = @CiaDev
				ELSE
				BEGIN
					SELECT @Dev = 1
					INSERT INTO TiposDocCons VALUES (@TipDev,@CiaDev,0,0,0,0,NULL,'',@Dev,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			
				select @VrDev = isnull((sum(VrDevolucion)),0) from Trn_TraEspDevAnt where TipDoc = @DocAnt and Anticipo = @Antic and IdCiaDoc = @IdCiaAnt

				INSERT INTO Trn_TraEspDevAnt(
				TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,Anticipo,IdCiaDoc,FecDoc,IdVehiculo,IdPoseedor,IdConductor,
				VrDevolucion,CdCta,CdCuenta,ModdDev,OrigenAdd,TipCom,Comprobante,IdCiaCom,Observacion,IdEstado,TimeSys,
				FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDev,@Dev,@CiaDev,Fecha,IdConcepto,@DocAnt,@Antic,@IdCiaAnt,FecDoc,IdVehiculo,IdPoseedor,IdConductor,
				VrDevolucion,CdCta,CdCuenta,ModdDev,OrigenAdd,@TipComp,@Comprobante,@IdCiaComp,Observacion,IdEstado,TimeSys,
				FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspDevAnt

				INSERT INTO Trn_TraEspAntAbonos(
				TipDoc,Documento,IdCia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				)
				SELECT
				@TipDev,@Dev,@CiaDev,Item,Fecha,@DocAnt,@Antic,@IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				FROM @Trn_TraEspAntAbonos

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDev, @Dev, @CiaDev, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDev, @Dev, @CiaDev,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDev, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDev, @Dev, @CiaDev, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDev,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDev, @Dev, @CiaDev, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END

				IF(EXISTS(SELECT * FROM @Trn_EgrFactura))
				BEGIN
					DECLARE @TipFac varchar(3)
					DECLARE @Factura varchar(16)
					DECLARE @IdCiaFac varchar(2)
					DECLARE @VrAbonocf MONEY
					IF NOT EXISTS(SELECT IdCom FROM TiposCom WHERE IdCom = @TipDev) --Crea el tipo de comprobante por debajo para el tipo de devolución para poder gaurdar en la @Trn_EgrFactura
					begin
						INSERT INTO TiposCom VALUES(@TipDev,'DEVOLUCION DE ANTICIPOS TESPECIAL',0,0,0,1,getdate(),NULL,'CONTAB',0)
					end
					SELECT TOP 1 @TipFac = TipFac, @Factura = Factura, @IdCiaFac = IdCiaFac, @VrAbonocf = VrAbono FROM @Trn_EgrFactura
					INSERT INTO Trn_EgrFactura(
					TipCom, Comprobante, IdCia, Item, Fecha, TipFac, Factura, IdCiaFac, ItemFac, 
					IdProveedor, IdCuenta, VrAbono, EsEgreso, ItemCom, pVehiculo, VehPropio, TipDev, 
					NumDev, DetAbono
					)
					SELECT
					@TipDev,@Dev,@CiaDev, Item, Fecha, TipFac, Factura, IdCiaFac, ItemFac, 
					IdProveedor, IdCuenta, VrAbono, EsEgreso, ItemCom, pVehiculo, 
					(CASE WHEN UPPER((SELECT TipoAfil FROM Vehiculos WHERE IdVehiculo = pVehiculo)) = 'PROPIO' THEN 1 ELSE 0 END), 
					@TipDev, @Dev, DetAbono 
					FROM @Trn_EgrFactura

					UPDATE Trn_ComFactura SET VrAbonado = VrAbonado + @VrAbonocf WHERE TipFac = @TipFac AND Factura = @Factura AND IdCia = @IdCiaFac
				END
			END
			
			if(@operacion = 'i')
			begin 

				declare @VrAntic money
				declare @VrAbono money
				declare @VrDevN money
				declare @fecdev smalldatetime

				select @VrAntic = VrAnticipo, @VrAbono = VrAbonado from Trn_TraEspAnticipos where TipDoc = @DocAnt and Anticipo = @Antic and IdCia = @IdCiaAnt
				select @fecdev = Fecha,@VrDevN = VrDevolucion from @Trn_TraEspDevAnt

				update Trn_TraEspAnticipos 
				set NumDev = @Dev, FecDev = @fecdev, VrAbonado = (@VrAbono + @VrDevN)  
				where TipDoc = @DocAnt and Anticipo = @Antic and IdCia = @IdCiaAnt

				if(@VrAntic = (@VrAbono + @VrDevN))
				begin
					update Trn_TraEspAnticipos 
					set Anulado = 1  
					where TipDoc = @DocAnt and Anticipo = @Antic and IdCia = @IdCiaAnt
				end

			end 

			--if(@operacion = 'a')
			--begin
			--	update Trn_TraEspDevAnt set anu where TipDoc = (Select TipDoc from @Trn_TraEspAnticipos) and Anticipo = (Select Anticipo from @Trn_TraEspAnticipos) and IdCia = (Select IdCia from @Trn_TraEspAnticipos)
			--end

			SELECT @Dev,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevCau]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 15/02/2017
-- Description:	Insertar Trn_TraEspDevCau
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevCau]
	@Trn_TraEspDevCau dataTypeTrn_TraEspDevCau READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspDevCau
	@Trn_EgrFactura dataTypeTrn_EgrFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_EgrFactura

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDev VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @DevCia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Dev INT --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @TipFac VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CiaFac VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Fact VARCHAR(15) --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			

			declare @fecdev smalldatetime

			--Seleccionar Variables
			IF(@operacion = 'i')
			BEGIN
			SELECT TOP 1 @TipDev = TipDev, @DevCia = IdCia, @fecdev = Fecha, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspDevCau
			SELECT TOP 1 @TipFac = TipFac, @CiaFac = IdCiaFac, @Fact = Factura from @Trn_EgrFactura
			SELECT @Dev = Numero + 1  FROM TiposDocCons where IdDoc = @TipDev AND IdCia = @DevCia

			IF(@Dev > 0)
				UPDATE TiposDocCons SET Numero = @Dev WHERE IdDoc = @TipDev AND IdCia = @DevCia
			ELSE
			BEGIN
				SELECT @Dev = 1
				INSERT INTO TiposDocCons VALUES (@TipDev,@DevCia,0,0,0,0,NULL,'',@Dev,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
			END

			IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			BEGIN
				SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
				SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
				--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
				IF(@Comprobante <> '')
					UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
				ELSE
				BEGIN
					SELECT @Comprobante = 1
					INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
			BEGIN
				SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
				SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
				--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
				IF(@CompNiif <> '')
					UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
				ELSE
				BEGIN
					SELECT @CompNiif = 1
					INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
			BEGIN
				SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
				SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
				--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
				IF(@CompNiif <> '')
					UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
				ELSE
				BEGIN
					SELECT @CompFis = 1
					INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END
			END
			
			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspDevCau))
				BEGIN
				INSERT INTO Trn_TraEspDevCau(
				TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,Causacion,IdCiaDoc,FecDoc,IdProv,Factura,
				VrTotal,VrOtros,VrNeto,ModdDev,OrigenAdd,TipCom,Comprobante,IdCiaCom,Observacion,IdEstado,
				TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDev,@Dev,@DevCia,Fecha,IdConcepto,TipDoc,Causacion,IdCiaDoc,FecDoc,IdProv,Factura,
				VrTotal,VrOtros,VrNeto,ModdDev,OrigenAdd,@TipComp, @Comprobante, @IdCiaComp,Observacion,IdEstado,
				TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspDevCau
				END 

				IF(EXISTS(SELECT * FROM @Trn_EgrFactura))
				BEGIN
				INSERT INTO Trn_EgrFactura(
				TipCom,Comprobante,IdCia,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,TipDev,NumDev,DetAbono
				)
				SELECT 
				@TipComp,@Comprobante,@DevCia,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,TipDev,NumDev,DetAbono
				FROM @Trn_EgrFactura
				END 

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque,@TipDev,@Dev,@DevCia, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase,@TipDev,@Dev,@DevCia,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@DevCia, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque,@TipDev,@Dev,@DevCia, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				--INSERT INTO Trn_NiifDetalle(
				--TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				--VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				--VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				--NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				--NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				--CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				--DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				--CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				--FechAutoriza, CodCuentaCG
				--)
				--SELECT 
				--CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @IdCiaCompNiif ELSE @IdCiaCompFis END,
				--C.Item, C.Fecha, N.IdCuenta, C.Detalle,
				--C.VrDebito, C.VrCredito, C.IdTercero, C.IdVehiculo, C.IdCCosto, C.IdSubCos,
				--C.VrBase, C.TarifaBase,@TipDev,@Dev,@DevCia, C.CodConce,
				--C.NitDoc, C.TipFac, C.Factura, C.IdCiaFac, C.ItemFac, C.FecVence, C.CodCta, 
				--C.NumCheque, C.Integrado, C.TipoAplica, C.Consolida, C.CodCargo, C.NitOtros,
				--C.CodSubgpo, C.CiuOrigen, C.CodAgncia, C.VehPropio, C.Referncia, C.TipDocRef,
				--C.DocRef, C.IdCiaRef, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario,
				--C.CdConcTrib, C.CdTarifTrib, C.NumEstablec,C.PtoEmision, C.Num_Autoriza,
				--C.FechAutoriza, C.IdCuenta
				--FROM @Trn_ComDetalle AS C 
				--JOIN @Trn_NiifDetalle AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont AND C.Item = N.Item 
				--JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante

				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@DevCia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDev,@Dev,@DevCia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			end
						
			IF(@operacion = 'i')
			begin
				update Trn_TraEspCausacion 
				set NumDev = t2.Devolucion, FecDev = @fecdev, Anulado = 1 
				from Trn_TraEspCausacion t1, @Trn_TraEspDevCau t2
				where t1.TipDoc = t2.TipDoc  and t1.Causacion = t2.Causacion and t1.IdCia = t2.IdCiaDoc
				
				update Trn_ComFactura 
				set VrAbonado =  t2.VrAbono
				from Trn_ComFactura t1, @Trn_EgrFactura t2
				where t1.TipFac = t2.TipFac and t1.Factura = t2.Factura and t1.IdCia = t2.IdCiaFac and t1.Item = t2.Item and t1.IdProveedor = t2.IdProveedor
			end

			SELECT @Dev,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevCum]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 29/09/2017
-- Description:	Insertar Trn_TraEspDevCum.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevCum]
	@Trn_TraEspDevCum dataTypeTrn_TraEspDevCum READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspDevCum
	@Trn_TraEspCumReservas dataTypeTrn_TraEspCumReservas READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspCumReservas
	
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle
	
	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDev VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @DevCia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Dev INT --En esta variable se guarda el consecutivo del documento aprobación

	BEGIN TRAN
		BEGIN TRY

			IF(@operacion = 'i')
			BEGIN

				SELECT TOP 1 @TipDev = TipDev, @DevCia = IdCia,  @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspDevCum
				SELECT @Dev = Numero + 1  FROM TiposDocCons where IdDoc = @TipDev AND IdCia = @DevCia

				IF(@Dev > 0)
					UPDATE TiposDocCons SET Numero = @Dev WHERE IdDoc = @TipDev AND IdCia = @DevCia
				ELSE
				BEGIN
					SELECT @Dev = 1
					INSERT INTO TiposDocCons VALUES (@TipDev,@DevCia,0,0,0,0,NULL,'',@Dev,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif

					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis

					IF(@CompFis <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			END

			IF(@operacion = 'i')
			BEGIN

			IF(EXISTS(SELECT * FROM @Trn_TraEspDevCum))
			BEGIN
			INSERT INTO Trn_TraEspDevCum(
			TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,Cumplido,IdCiaDoc,FecDoc,ModdDev,OrigenAdd,
			TipCom,Comprobante,IdCiaCom,Observacion,TimeSys,IdCiaCrea,IdUsuario
			)
			SELECT 
			@TipDev,@Dev,@DevCia,Fecha,IdConcepto,TipDoc,Cumplido,IdCiaDoc,FecDoc,ModdDev,OrigenAdd,
			@TipComp,@Comprobante,@IdCiaComp,Observacion,TimeSys,IdCiaCrea,IdUsuario
			FROM @Trn_TraEspDevCum
			END

			IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			BEGIN
			INSERT INTO Trn_Comprobantes(
			TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
			TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
			CodRes, DescServicio
			)
			SELECT 
			@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
			NumCheque, FecCheque, @TipDev, @Dev, @DevCia, Anulado, NumDev, FecDev,
			TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
			VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
			Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
			PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
			CodRes, DescServicio
			FROM @Trn_Comprobantes
			END

			IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
			BEGIN
			INSERT INTO Trn_ComDetalle(
			TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
			IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
			IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
			NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
			CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
			IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
			)
			SELECT 
			@TipComp, @Comprobante, @IdCiaComp, cd.Item, cd.Fecha, cd.IdCuenta, cd.Detalle, cd.VrDebito, cd.VrCredito,
			cd.IdTercero, cd.IdVehiculo, cd.IdCCosto, cd.IdSubCos, cd.VrBase, cd.TarifaBase, @TipDev, @Dev, @DevCia,
			cd.CodConce, cd.NitDoc, case WHEN cd.TipFac <> '' THEN @TipDev ELSE '' END, case WHEN cd.TipFac <> '' THEN @Dev ELSE '' END, case WHEN cd.TipFac <> '' THEN @DevCia ELSE '' END, 
			cd.ItemFac, cd.FecVence, cd.CodCta,
			cd.NumCheque, cd.Integrado, cd.TipoAplica, cd.Consolida, cd.CodCargo, cd.NitOtros, cd.CodSubgpo, cd.CiuOrigen, 
			cd.CodAgncia,cd.VehPropio, cd.Referncia, cd.TipDocRef, cd.DocRef, cd.IdCiaRef, cd.TimeSys, cd.FecUpdate, cd.IdCiaCrea, 
			cd.IdUsuario, cd.CdConcTrib, cd.CdTarifTrib, cd.NumEstablec, cd.PtoEmision, cd.Num_Autoriza, cd.FechAutoriza,cd.CdCuentaNiif
			FROM @Trn_ComDetalle cd
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp))
			BEGIN
			INSERT INTO Trn_NiifComp(
			TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
			EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
			FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
			VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
			IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
			Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
			CtbTipo, CtbNumero,
			FisTipo, FisNumero 
			)
			SELECT 
			CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
			CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
			@DevCia,
			C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
			C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDev, @Dev, @DevCia, C.Anulado, C.NumDev,
			C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
			C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
			C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
			C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
			CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
		    CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
			FROM @Trn_Comprobantes AS C 
			JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
			BEGIN
			
			INSERT INTO Trn_NiifDetalle(
			TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
			VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
			VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
			NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
			NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
			CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
			DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
			CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
			FechAutoriza, CodCuentaCG
			)
			SELECT 
			CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
			CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
			@DevCia,
			N.Item, N.Fecha, N.IdCuenta, N.Detalle,
			N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
			N.VrBase, N.TarifaBase,  @TipDev, @Dev, @DevCia, N.CodConce,
			N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
			N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
			N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
			N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
			N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
			N.FechAutoriza, N.CodCuentaCG
			FROM @Trn_NiifDetalle as N
			JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante

			END

			UPDATE Trn_TraEspCumplido
			SET Anulado = '1', NumDev = @Dev, FecDev = D.Fecha
			FROM Trn_TraEspCumplido C, @Trn_TraEspDevCum D
			WHERE C.TipDoc = D.TipDoc AND C.Cumplido = D.Cumplido AND C.IdCia = D.IdCiaDoc

			END

			IF(@operacion = 'i')
			BEGIN
				--Actualizar ResDetalles
				UPDATE Trn_TraEspResDetalle
				--SET Cumplido = 0, IdCiaCum = '00', FechaCum = null, JOE NO ACTUALIZABA EL ITEM
				SET Cumplido = 0, IdCiaCum = '00', FechaCum = null, EstadoItem = t2.EstadoItemRes
				FROM Trn_TraEspResDetalle t1, @Trn_TraEspCumReservas t2
				WHERE t1.TipDoc = t2.TipRes and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCiaRes and t1.Item = t2.ItemRes
			END

			SELECT @Dev,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevLiq]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 10/02/2017
-- Description:	Insertar Trn_TraEspDevLiq
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevLiq]
	@Trn_TraEspDevLiq dataTypeTrn_TraEspDevLiq READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspDevLiq
	@Trn_TraEspLiquidaDed dataTypeTrn_TraEspLiquidaDed READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquidaDed
	@Trn_EgrFactura dataTypeTrn_EgrFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_EgrFactura

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 


		    if(@operacion = 'i')
			begin	
				SELECT TOP 1 @TipDoc = TipDev, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspDevLiq
				SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

				IF(@Numero > 0)
					UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
				ELSE
				BEGIN
					SELECT @Numero = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

			end

			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspDevLiq))
				BEGIN
				INSERT INTO Trn_TraEspDevLiq(
				TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,Liquidacion,IdCiaDoc,FecDoc,IdVehiculo,IdPoseedor,IdConductor,VrTotal,
				ModdDev,OrigenAdd,TipCom,Comprobante,IdCiaCom,Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Fecha,IdConcepto,TipDoc,Liquidacion,IdCiaDoc,FecDoc,IdVehiculo,IdPoseedor,IdConductor,VrTotal,
				ModdDev,OrigenAdd,TipCom,Comprobante,IdCiaCom,Observacion,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspDevLiq
				END 

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END,
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				--INSERT INTO Trn_NiifDetalle(
				--TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				--VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				--VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				--NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				--NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				--CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				--DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				--CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				--FechAutoriza, CodCuentaCG
				--)
				--SELECT 
				--CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, CASE NC.TipoNiif WHEN 'NIIF' THEN @IdCiaCompNiif ELSE @IdCiaCompFis END, 
				--C.Item, C.Fecha, N.IdCuenta, C.Detalle,
				--C.VrDebito, C.VrCredito, C.IdTercero, C.IdVehiculo, C.IdCCosto, C.IdSubCos,
				--C.VrBase, C.TarifaBase, @TipDoc, @Numero, @Cia, C.CodConce,
				--C.NitDoc, C.TipFac, C.Factura, C.IdCiaFac, C.ItemFac, C.FecVence, C.CodCta, 
				--C.NumCheque, C.Integrado, C.TipoAplica, C.Consolida, C.CodCargo, C.NitOtros,
				--C.CodSubgpo, C.CiuOrigen, C.CodAgncia, C.VehPropio, C.Referncia, C.TipDocRef,
				--C.DocRef, C.IdCiaRef, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario,
				--C.CdConcTrib, C.CdTarifTrib, C.NumEstablec,C.PtoEmision, C.Num_Autoriza,
				--C.FechAutoriza, C.IdCuenta
				--FROM @Trn_ComDetalle AS C JOIN @Trn_NiifDetalle AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont AND C.Item = N.Item JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante

				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDoc, @Numero, @Cia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			end	

			IF(@operacion = 'i')
			begin
			  -- actualizar causaciones 
			  declare @TipCau varchar(3)
			  declare @Causacion int
			  declare @IdCiaCau varchar(2)	
			  declare @ItemCau int		  
			  declare @VrAbonoCau decimal(14,4)
			  DECLARE ccausac CURSOR
	  		  FOR SELECT TipCau, Causacion, IdCiaCau, ItemCau, VrAbono from @Trn_TraEspLiquidaDed
	          OPEN ccausac
			  FETCH NEXT FROM ccausac into @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
			  WHILE @@FETCH_STATUS = 0
			  BEGIN
			  
				  UPDATE Trn_TraEspCauDetalle
					SET TipoLiq = '0', NumLiquida = 0, CiaLiquida = '00', VrAbonado = VrAbonado - @VrAbonoCau
				  FROM Trn_TraEspCauDetalle t1
				  WHERE t1.TipDoc = @TipCau and t1.Causacion = @Causacion and t1.IdCia = @IdCiaCau and t1.Item = @ItemCau

			  FETCH NEXT FROM ccausac INTO @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
			  END
			  CLOSE ccausac
			  DEALLOCATE ccausac

			  -- actualizar liquidaciones 
			  UPDATE Trn_TraEspLiquida
			  SET Anulado = '1',NumDev = @Numero, FecDev= t2.Fecha
			  FROM Trn_TraEspLiquida t1, @Trn_TraEspDevLiq t2
			  WHERE t1.TipDoc = t2.TipDoc and t1.Liquidacion = t2.Liquidacion and t1.IdCia = t2.IdCiaDoc

			  --actualizar Trn_ComFactura
			  declare @FactTipFac varchar(3)
			  declare @FactIdCiaFac varchar(2)
			  declare @FactFactura varchar(15)
			  declare @FactIdProveedor varchar(16)
			  declare @VrAbono decimal(14,4)
			  declare @ItemFac int
			  DECLARE cprincipal CURSOR
	  		  FOR select TipFac, Factura, IdCiaFac,ItemFac, IdProveedor, VrAbono from @Trn_EgrFactura
	          OPEN cprincipal
			  FETCH NEXT FROM cprincipal into @FactTipFac, @FactFactura, @FactIdCiaFac, @ItemFac, @FactIdProveedor, @VrAbono
			  WHILE @@FETCH_STATUS = 0
			  BEGIN

					  if(@VrAbono > 0)
					  begin
						  update Trn_ComFactura 
						  set VrAbonado = VrAbonado - @VrAbono
						  from Trn_ComFactura t1 
						  where t1.TipFac = @FactTipFac and t1.Factura = @FactFactura and t1.IdCia = @FactIdCiaFac and t1.Item = @ItemFac and t1.IdProveedor = @FactIdProveedor
					 end

				  --declare @acumulado decimal(14,4)
				  --declare @vrfactura decimal(14,4)
				  --declare @vrabonado decimal(14,4)
				  --declare @itemFact int
				  --declare @valor decimal(14,4)
				  --set @acumulado = @FactSaldo

				  --DECLARE csecundario CURSOR
	  			--  FOR SELECT Item, VrFactura, VrAbonado FROM Trn_ComFactura t1 WHERE t1.TipFac = @FactTipFac and t1.Factura = @FactFactura and t1.IdCia = @FactIdCiaFac and t1.IdProveedor = @FactIdProveedor order by FecVence asc
				  --OPEN csecundario
				  --FETCH NEXT FROM csecundario into @itemFact, @vrfactura, @vrabonado
				  --WHILE @@FETCH_STATUS = 0
				  --BEGIN
				  
					 -- if(@acumulado >= @vrfactura)
					 -- begin
						--  set @valor =  @vrfactura
						--  set @acumulado = @acumulado - @vrfactura
					 -- end
					 -- else
					 -- begin
						--  set @valor =  @acumulado
						--  set @acumulado = 0						
					 -- end

					 -- if(@valor > 0)
					 -- begin
						--  update Trn_ComFactura 
						--  set VrAbonado = VrAbonado - @valor
						--  from Trn_ComFactura t1 
						--  where t1.TipFac = @FactTipFac and t1.Factura = @FactFactura and t1.IdCia = @FactIdCiaFac and t1.Item = @itemFact and t1.IdProveedor = @FactIdProveedor
					 --end
	
   			--	  FETCH NEXT FROM csecundario INTO @itemFact, @vrfactura
				  --END
				  --CLOSE csecundario
				  --DEALLOCATE csecundario

			  FETCH NEXT FROM cprincipal INTO @FactTipFac, @FactFactura, @FactIdCiaFac, @ItemFac, @FactIdProveedor, @VrAbono
			  END
			  CLOSE cprincipal
			  DEALLOCATE cprincipal
			  
			  --actualizar orden pago
			  update Trn_TraEspOrdenReservas
			  set EdoLiqCausac =  0
			  from Trn_TraEspOrdenReservas t1, @Trn_TraEspLiquidaDed t2
			  where t2.TipOdp = t1.TipDoc and t2.OrdenPago = t1.OrdPago and t2.IdCiaOdp = t1.IdCia

			  --Eliminar los egreso factura
			  delete Trn_EgrFactura
			  from Trn_EgrFactura t1
			  inner join @Trn_EgrFactura t2 on t1.TipCom = t2.TipCom
			  where t1.Comprobante = t2.Comprobante and t1.IdCia = t2.IdCia
			end

			SELECT @Numero,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevOdp]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 30/01/2017
-- Description:	Insertar Trn_TraEspDevOdp
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevOdp]
	@Trn_TraEspDevOdp dataTypeTrn_TraEspDevOdp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspDevOdp
	@Trn_EgrFactura dataTypeTrn_EgrFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_EgrFactura
	@Trn_TraEspAntAbonos dataTypeTrn_TraEspAntAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspAntAbonos
	@Trn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos
	@Trn_TraEspOrdenReservas dataTypeTrn_TraEspOrdenReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenReservas

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDev VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CiaDev VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Dev INT --En esta variable se guarda el consecutivo del documento aprobación

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			declare @fecdev smalldatetime

			IF(@operacion = 'i')
			begin
				
				SELECT TOP 1 @TipDev = TipDev, @CiaDev = IdCia,@TipDoc = TipDoc, @Cia = IdCiaDoc,@fecdev = Fecha, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspDevOdp
				
				SELECT @Dev = Numero + 1  FROM TiposDocCons where IdDoc = @TipDev AND IdCia = @CiaDev
				IF(@Dev > 0)
					UPDATE TiposDocCons SET Numero = @Dev WHERE IdDoc = @TipDev AND IdCia = @CiaDev
				ELSE
				BEGIN
					SELECT @Dev = 1
					INSERT INTO TiposDocCons VALUES (@TipDev,@CiaDev,0,0,0,0,NULL,'',@Dev,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
				--John Roa--DIEGO ROMERO DICE QUE SI NO EXISTE EL COMPROBANTE CON ELMISMO NOMBRE DE DOC DEVOLUCIÓN INSERTA UN COMPROBANTE CON EL  TIPCOM SEA IIGUAL AL TIPDEV, en la tabla TiposCom(tipos de comprobantes)
				--es INACTIVO = 1, PARA PODER INSERTAR EN EGRFACTURA ESTE TIPCOM
				IF(NOT EXISTS(SELECT IdCom FROM TiposCom where IdCom = @TipDev))
				BEGIN
					INSERT INTO TiposCom VALUES (@TipDev,'DEVOLUCION DE ORDEN DE PAGO ESPECIAL',0,0,0,1,CURRENT_TIMESTAMP,NULL,NULL,null)
				END
				--
				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			end
			
			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspDevOdp))
				BEGIN
				INSERT INTO Trn_TraEspDevOdp(
				TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,OrdPago,IdCiaDoc,FecDoc,IdVehiculo,IdPoseedor,IdConductor,CxPagar,ModdDev,TipCom,Comprobante,
				IdCiaCom,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDev,@Dev,@CiaDev,Fecha,IdConcepto,TipDoc,OrdPago,IdCiaDoc,FecDoc,IdVehiculo,IdPoseedor,IdConductor,CxPagar,ModdDev,@TipComp, @Comprobante,
				@IdCiaComp,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspDevOdp
				END 

				IF(EXISTS(SELECT * FROM @Trn_EgrFactura))
				BEGIN
				INSERT INTO Trn_EgrFactura(
				TipCom,Comprobante,IdCia,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,TipDev,NumDev,DetAbono
				)
				SELECT 
				@TipDev,@Dev,@CiaDev,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,@TipDev,@Dev,DetAbono
				FROM @Trn_EgrFactura
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspAntAbonos))
				BEGIN
				INSERT INTO Trn_TraEspAntAbonos(
				TipDoc,Documento,IdCia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				)
				SELECT 
				@TipDev,@Dev,@CiaDev,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,(-VrAbono),TipoAplica,Detalle,CdCuentaAnt
				FROM @Trn_TraEspAntAbonos
				END

				IF(EXISTS(SELECT * FROM @Trn_Pagos))
				BEGIN
				INSERT INTO Trn_Pagos(
				TipDoc, Documento, IdCia, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto,FE_Ticket,Cant_Gals,PrecioBase,PrecioUnit
				)
				SELECT 
				@TipDev, @Dev, @CiaDev, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
				FROM @Trn_Pagos
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDev, @Dev, @CiaDev, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp,@Comprobante,@IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDev, @Dev, @CiaDev,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDev, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDev, @Dev, @CiaDev, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDev,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDev, @Dev, @CiaDev, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			end	

			IF(@operacion = 'i')
			begin
			  --Se actualiza la orden de pago con los datos de la devolución
			  update Trn_TraEspOrdenPago 
			  set NumDev = @Dev, FecDev = @fecdev,Anulado = 1  
			  from Trn_TraEspOrdenPago t1, @Trn_TraEspDevOdp t2
			  where t1.TipDoc = t2.TipDoc and t1.OrdPago = t2.OrdPago and t1.IdCia = t2.IdCiaDoc 
			  
			  --se actualiza la Trn_Comfactura
			  update Trn_ComFactura 
			  set VrAbonado =  t1.VrAbonado + t2.VrAbono 
			  from Trn_ComFactura t1, @Trn_EgrFactura t2
			  where t1.TipFac = t2.TipFac and t1.Factura = t2.Factura and t1.IdCia = t2.Idcia and t1.Item = t2.ItemFac and t1.IdProveedor = t2.IdProveedor

			  --Actualiza los items de la programación detalle de cada reserva agregada en la Orden de Pago y que se devuelve
			  UPDATE Trn_TraEspProgramaDet
			  SET TipDocOdp = 'OPE',NumOdp = 0, IdCiaOdp = '00'
			  FROM Trn_TraEspProgramaDet t1, @Trn_TraEspDevOdp t2
			  WHERE t1.TipDocOdp = 'OPE' and t1.NumOdp = t2.OrdPago and t1.IdCiaOdp = t2.IdCiaDoc 

			  --Actualizar item de Reservas al estado en el que se encontraba antes de cuando le realizaron la Orden de Pago
			  UPDATE Trn_TraEspResDetalle
			  SET EstadoItem = t.EstadoItem
			  FROM Trn_TraEspResDetalle r, @Trn_TraEspOrdenReservas t
			  WHERE r.TipDoc = t.TipRes and r.Reserva = t.Reserva and r.IdCia = t.IdCiaRes and r.Item = t.ItemRes

			  --actualiza los anticipos(restar) para que quede como estaba antes de hacer la Orden de Pago
			  UPDATE Trn_TraEspAnticipos
			  SET VrAbonado = t2.VrAbono - VrAbonado
			  FROM Trn_TraEspAnticipos t1, @Trn_TraEspAntAbonos t2
			  WHERE t1.TipDoc = t2.TipAnt and t1.Anticipo = t2.Anticipo and t1.IdCia = t2.IdCiaAnt

			end

			SELECT @Dev,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspDevOdpGIE]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Heiman Daza Tamayo
-- Create date(dd/MM/yyyy): 24/06/2021
-- Description:	Insertar Trn_TraEspDevOdp sin Generacion de ingresos
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspDevOdpGIE]
	@Trn_TraEspDevOdp dataTypeTrn_TraEspDevOdp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspDevOdp
	@Trn_EgrFactura dataTypeTrn_EgrFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_EgrFactura
	@Trn_TraEspAntAbonos dataTypeTrn_TraEspAntAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspAntAbonos
	@Trn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos
	@Trn_TraEspOrdenReservas dataTypeTrn_TraEspOrdenReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenReservas

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDev VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @CiaDev VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Dev INT --En esta variable se guarda el consecutivo del documento aprobación

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			declare @fecdev smalldatetime

			IF(@operacion = 'i')
			begin
				
				SELECT TOP 1 @TipDev = TipDev, @CiaDev = IdCia,@TipDoc = TipDoc, @Cia = IdCiaDoc,@fecdev = Fecha, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspDevOdp
				
				SELECT @Dev = Numero + 1  FROM TiposDocCons where IdDoc = @TipDev AND IdCia = @CiaDev
				IF(@Dev > 0)
					UPDATE TiposDocCons SET Numero = @Dev WHERE IdDoc = @TipDev AND IdCia = @CiaDev
				ELSE
				BEGIN
					SELECT @Dev = 1
					INSERT INTO TiposDocCons VALUES (@TipDev,@CiaDev,0,0,0,0,NULL,'',@Dev,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
				--John Roa--DIEGO ROMERO DICE QUE SI NO EXISTE EL COMPROBANTE CON ELMISMO NOMBRE DE DOC DEVOLUCIÓN INSERTA UN COMPROBANTE CON EL  TIPCOM SEA IIGUAL AL TIPDEV, en la tabla TiposCom(tipos de comprobantes)
				--es INACTIVO = 1, PARA PODER INSERTAR EN EGRFACTURA ESTE TIPCOM
				IF(NOT EXISTS(SELECT IdCom FROM TiposCom where IdCom = @TipDev))
				BEGIN
					INSERT INTO TiposCom VALUES (@TipDev,'DEVOLUCION DE ORDEN DE PAGO ESPECIAL',0,0,0,1,CURRENT_TIMESTAMP,NULL,NULL,null)
				END
				--
				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			end
			
			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspDevOdp))
				BEGIN
				INSERT INTO Trn_TraEspDevOdp(
				TipDev,Devolucion,IdCia,Fecha,IdConcepto,TipDoc,OrdPago,IdCiaDoc,FecDoc,IdVehiculo,IdPoseedor,IdConductor,CxPagar,ModdDev,TipCom,Comprobante,
				IdCiaCom,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDev,@Dev,@CiaDev,Fecha,IdConcepto,TipDoc,OrdPago,IdCiaDoc,FecDoc,IdVehiculo,IdPoseedor,IdConductor,CxPagar,ModdDev,@TipComp, @Comprobante,
				@IdCiaComp,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspDevOdp
				END 

				IF(EXISTS(SELECT * FROM @Trn_EgrFactura))
				BEGIN
				INSERT INTO Trn_EgrFactura(
				TipCom,Comprobante,IdCia,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,TipDev,NumDev,DetAbono
				)
				SELECT 
				@TipDev,@Dev,@CiaDev,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,@TipDev,@Dev,DetAbono
				FROM @Trn_EgrFactura
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspAntAbonos))
				BEGIN
				INSERT INTO Trn_TraEspAntAbonos(
				TipDoc,Documento,IdCia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				)
				SELECT 
				@TipDev,@Dev,@CiaDev,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,(-VrAbono),TipoAplica,Detalle,CdCuentaAnt
				FROM @Trn_TraEspAntAbonos
				END

				IF(EXISTS(SELECT * FROM @Trn_Pagos))
				BEGIN
				INSERT INTO Trn_Pagos(
				TipDoc, Documento, IdCia, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto,FE_Ticket,Cant_Gals,PrecioBase,PrecioUnit
				)
				SELECT 
				@TipDev, @Dev, @CiaDev, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
				FROM @Trn_Pagos
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDev, @Dev, @CiaDev, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp,@Comprobante,@IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDev, @Dev, @CiaDev,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDev, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDev, @Dev, @CiaDev, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@CiaDev,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDev, @Dev, @CiaDev, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			end	

			IF(@operacion = 'i')
			begin
			  --Se actualiza la orden de pago con los datos de la devolución
			  update Trn_TraEspOrdenPago 
			  set NumDev = @Dev, FecDev = @fecdev,Anulado = 1  
			  from Trn_TraEspOrdenPago t1, @Trn_TraEspDevOdp t2
			  where t1.TipDoc = t2.TipDoc and t1.OrdPago = t2.OrdPago and t1.IdCia = t2.IdCiaDoc 
			  
			  --se actualiza la Trn_Comfactura
			  update Trn_ComFactura 
			  set VrAbonado =  t1.VrAbonado + t2.VrAbono 
			  from Trn_ComFactura t1, @Trn_EgrFactura t2
			  where t1.TipFac = t2.TipFac and t1.Factura = t2.Factura and t1.IdCia = t2.Idcia and t1.Item = t2.ItemFac and t1.IdProveedor = t2.IdProveedor

			  --Actualizar item de Reservas al estado en el que se encontraba antes de cuando le realizaron la Orden de Pago
			  UPDATE Trn_TraEspResDetalle
			  SET EstadoItem = t.EstadoItem
			  FROM Trn_TraEspResDetalle r, @Trn_TraEspOrdenReservas t
			  WHERE r.TipDoc = t.TipRes and r.Reserva = t.Reserva and r.IdCia = t.IdCiaRes and r.Item = t.ItemRes

			  --actualiza los anticipos(restar) para que quede como estaba antes de hacer la Orden de Pago
			  UPDATE Trn_TraEspAnticipos
			  SET VrAbonado = t2.VrAbono - VrAbonado
			  FROM Trn_TraEspAnticipos t1, @Trn_TraEspAntAbonos t2
			  WHERE t1.TipDoc = t2.TipAnt and t1.Anticipo = t2.Anticipo and t1.IdCia = t2.IdCiaAnt

			end

			SELECT @Dev,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspFuec]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 16/11/2016
-- Description:	Insertar CRUD Fuec.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspFuec]
	@Trn_TraEspFuec dataTypeTrn_TraEspFuec READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuec
	@Trn_TraEspFuecAnexo dataTypeTrn_TraEspFuecAnexo READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuecAnexo
	@Trn_TraEspFuecDetalle dataTypeTrn_TraEspFuecDetalle READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuecDetalle
	@Trn_TraEspFuecCndtores dataTypeTrn_TraEspFuecCndtores READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspFuecDetalle
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Fuec
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Fuec
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Fuec
declare @item int
declare @consecutivo int = 0
declare @numcontrato int
declare @idciacnt varchar(4)
	BEGIN TRAN
		BEGIN TRY

			--Seleccionar Variables
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia,@idciacnt = CiaCnt, @numcontrato = Contrato FROM @Trn_TraEspFuec
				SELECT @Documento = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia
				select @consecutivo = (ISNULL(MAX(Consecutivo),0) + 1) from Trn_TraEspFuec where TipDocCnt = 'COE' and Contrato = @numcontrato AND CiaCnt = @idciacnt

				IF(@Documento <> '' OR @Documento is not null)
					UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
				ELSE
				BEGIN
					SELECT @Documento = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			end

			--Seleccionar Variables
			--IF(@operacion = 'u')
			--begin
			--	SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Fuec FROM @Trn_TraEspFuec
			--end

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			   if(EXISTS(SELECT * FROM @Trn_TraEspFuec))
			   begin
			   UPDATE Trn_TraEspFuec
			   SET 
			   TipDoc = t2.TipDoc,Fuec = t2.Fuec,IdCia = t2.IdCia,Numero = t2.Numero,Fecha = t2.Fecha,FechaInicio = t2.FechaInicio,
			   FechaFin = t2.FechaFin,CdCarga = t2.CdCarga,IdVehiculo = t2.IdVehiculo,IdConductor = t2.IdConductor,IdConductor2 = t2.IdConductor2,IdConductor3 = t2.IdConductor3
			   ,IdPoseedor = t2.IdPoseedor,
			   IdRuta = t2.IdRuta,CdTipRuta = t2.CdTipRuta,IdOrigen = t2.IdOrigen,IdDestino = t2.IdDestino,Modalidad = t2.Modalidad,
			   CantPasajeros = t2.CantPasajeros,CodTarRet = t2.CodTarRet,CodTarIca = t2.CodTarIca,VrPresupuesto = t2.VrPresupuesto,VrCobro = t2.VrCobro,
			   VrPagos = t2.VrPagos,VrCargos = t2.VrCargos,VrDctos = t2.VrDctos,VrIva = t2.VrIva,VrRetencion = t2.VrRetencion,VrReteIca = t2.VrReteIca,
			   Cantidad = t2.Cantidad,Peso = t2.Peso,TipDocPgr = t2.TipDocPgr,NumPgr = t2.NumPgr,IdCiaPgr = t2.IdCiaPgr,ItemPgr = t2.ItemPgr,TipDocCnt = t2.TipDocCnt,Contrato = t2.Contrato,CiaCnt = t2.CiaCnt,
			   OrigenAdd = t2.OrigenAdd,Anulado = t2.Anulado,FecDev = t2.FecDev,IdEstado = t2.IdEstado,TimeSys = t2.TimeSys,FecUpdate = t2.FecUpdate,
			   IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario,Consecutivo = t2.Consecutivo,Itinerario=t2.Itinerario, FuecParcial = t2.FuecParcial, ComenParcial = t2.ComenParcial 
		       FROM Trn_TraEspFuec t1
			   JOIN @Trn_TraEspFuec t2 ON t1.TipDoc = t2.TipDoc and t1.Fuec = t2.Fuec and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspFuecAnexo))
			   begin

			   UPDATE Trn_TraEspFuecAnexo
			   SET 
			   TipDoc = t2.TipDoc,Fuec = t2.Fuec,IdCia = t2.IdCia,TipContrato = t2.TipContrato,IdContrato = t2.IdContrato,ObjContrato = t2.ObjContrato,
			   DescripCarga = t2.DescripCarga,Observacion = t2.Observacion,RespViaje = t2.RespViaje,VehConvenio=t2.VehConvenio,EmpresaVehCon=t2.EmpresaVehCon
		       FROM Trn_TraEspFuecAnexo t1
			   JOIN @Trn_TraEspFuecAnexo t2 ON t1.TipDoc = t2.TipDoc and t1.Fuec = t2.Fuec and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspFuecDetalle))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Fuec FROM @Trn_TraEspFuecDetalle
			   select @item = isnull(MAX(Item),0) from Trn_TraEspFuecDetalle where TipDoc = @TipDoc and Fuec = @Documento and IdCia = @IdCia

			   --actualizar los que vienen en el tipo de dato y coincida con los que ya están en la tabla
			   UPDATE Trn_TraEspFuecDetalle
			   SET 
			   TipDoc = t2.TipDoc,Fuec = t2.Fuec,IdCia = t2.IdCia,Item = t2.Item,TipRes = t2.TipRes,Reserva = t2.Reserva,IdCiaRes = t2.IdCiaRes,ItemRes = t2.ItemRes,
			   NumPasajeros = t2.NumPasajeros,PesoNeto = t2.PesoNeto,VrCobro = t2.VrCobro,VrPagos = t2.VrPagos,Referencia1 = t2.Referencia1,Referencia2 = t2.Referencia2,
			   Referencia3 = t2.Referencia3,CdTipServicio = t2.CdTipServicio,EsRutaCliente = t2.EsRutaCliente,Kilometros = t2.Kilometros,DirOrigen = t2.DirOrigen,
			   FecOrigen = t2.FecOrigen,DirDestino = t2.DirDestino,FecDestino = t2.FecDestino
		       FROM Trn_TraEspFuecDetalle t1
			   JOIN @Trn_TraEspFuecDetalle t2 ON t1.TipDoc = t2.TipDoc and t1.Fuec = t2.Fuec and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Fuec = t2.Fuec and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspFuecDetalle(
			   TipDoc,Fuec,IdCia,Item,TipRes,Reserva,IdCiaRes,ItemRes,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,Referencia2,Referencia3,CdTipServicio,EsRutaCliente,
			   Kilometros,DirOrigen,FecOrigen,DirDestino,FecDestino
			   ) 
			   SELECT 
			   @TipDoc,@Documento,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC))
			   ,TipRes,Reserva,IdCiaRes,ItemRes,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,Referencia2,Referencia3,CdTipServicio,EsRutaCliente,
			   Kilometros,DirOrigen,FecOrigen,DirDestino,FecDestino
			   FROM @Trn_TraEspFuecDetalle
			   WHERE (TipDoc + Convert(varchar,Fuec)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Fuec)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspFuecDetalle)
			   --Eliminar los que no existen en lo que envian
			   delete from Trn_TraEspFuecDetalle
			   WHERE TipDoc = @TipDoc and Fuec = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspFuecDetalle)

			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspFuecAnexo))
			   begin

				   UPDATE Trn_TraEspFuecAnexo
				   SET 
				   TipDoc = t2.TipDoc,Fuec = t2.Fuec,IdCia = t2.IdCia,TipContrato = t2.TipContrato,IdContrato = t2.IdContrato,ObjContrato = t2.ObjContrato,
				   DescripCarga = t2.DescripCarga,Observacion = t2.Observacion,RespViaje = t2.RespViaje,VehConvenio=t2.VehConvenio,EmpresaVehCon=t2.EmpresaVehCon
				   FROM Trn_TraEspFuecAnexo t1
				   JOIN @Trn_TraEspFuecAnexo t2 ON t1.TipDoc = t2.TipDoc and t1.Fuec = t2.Fuec and t1.IdCia = t2.IdCia
				end

				if(EXISTS(SELECT top 1 Fuec FROM @Trn_TraEspFuecCndtores))
					begin
						SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Fuec FROM @Trn_TraEspFuecCndtores
						select @item = isnull(MAX(Item),0) from @Trn_TraEspFuecCndtores where TipDoc = @TipDoc and Fuec = @Documento and IdCia = @IdCia

						--actualizar los que vienen en el tipo de dato y coincida con los que ya están en la tabla
						UPDATE Trn_TraEspFuecCndtores
						SET 
						TipDoc = t2.TipDoc,Fuec = t2.Fuec,IdCia = t2.IdCia,Item = t2.Item, IdConductor = t2.IdConductor
						FROM Trn_TraEspFuecCndtores t1
						JOIN @Trn_TraEspFuecCndtores t2 ON t1.TipDoc = t2.TipDoc and t1.Fuec = t2.Fuec and t1.IdCia = t2.IdCia and t1.Item = t2.Item
						WHERE t1.TipDoc = t2.TipDoc and t1.Fuec = t2.Fuec and t1.IdCia = t2.IdCia and t1.Item = t2.Item
						--Eliminar los que no existen en lo que envian
						delete from Trn_TraEspFuecCndtores
						WHERE TipDoc = @TipDoc and Fuec = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspFuecCndtores)
						--Inserta los que no existen
						INSERT INTO Trn_TraEspFuecCndtores(
						TipDoc,Fuec,IdCia,Item,IdConductor
						) 
						SELECT 
						@TipDoc,@Documento,@IdCia,(@item + ROW_NUMBER() OVER(ORDER BY Item ASC)),IdConductor
						FROM @Trn_TraEspFuecCndtores
						WHERE (TipDoc + Convert(varchar,Fuec)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Fuec)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspFuecCndtores)
						
					end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN

				IF(EXISTS(SELECT * FROM @Trn_TraEspFuec))
				begin
				INSERT INTO Trn_TraEspFuec(
				TipDoc,Fuec,IdCia,Numero,Fecha,FechaInicio,FechaFin,CdCarga,IdVehiculo,IdConductor,IdConductor2,IdConductor3,IdPoseedor,
				IdRuta,CdTipRuta,IdOrigen,IdDestino,Modalidad,CantPasajeros,CodTarRet,CodTarIca,VrPresupuesto,VrCobro,VrPagos,VrCargos,VrDctos,VrIva,VrRetencion,VrReteIca,
				Cantidad,Peso,TipDocPgr,NumPgr,IdCiaPgr,ItemPgr,TipDocCnt,Contrato,CiaCnt,OrigenAdd,Anulado,FecDev,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,Consecutivo,
				Itinerario,FuecParcial,ComenParcial
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,Numero,Fecha,FechaInicio,FechaFin,CdCarga,IdVehiculo,IdConductor,IdConductor2,IdConductor3,IdPoseedor,
				IdRuta,CdTipRuta,IdOrigen,IdDestino,Modalidad,CantPasajeros,CodTarRet,CodTarIca,VrPresupuesto,VrCobro,VrPagos,VrCargos,VrDctos,VrIva,VrRetencion,VrReteIca,
				Cantidad,Peso,TipDocPgr,NumPgr,IdCiaPgr,ItemPgr,TipDocCnt,Contrato,CiaCnt,OrigenAdd,Anulado,FecDev,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,@consecutivo,
				Itinerario,FuecParcial,ComenParcial
				FROM @Trn_TraEspFuec
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspFuecAnexo))
				begin
				INSERT INTO Trn_TraEspFuecAnexo(
				TipDoc,Fuec,IdCia,TipContrato,IdContrato,ObjContrato,DescripCarga,Observacion,RespViaje,VehConvenio,EmpresaVehCon
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,TipContrato,IdContrato,ObjContrato,DescripCarga,Observacion,RespViaje,VehConvenio,EmpresaVehCon
				FROM @Trn_TraEspFuecAnexo
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspFuecDetalle))
				begin
				INSERT INTO Trn_TraEspFuecDetalle(
				TipDoc,Fuec,IdCia,Item,TipRes,Reserva,IdCiaRes,ItemRes,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,Referencia2,Referencia3,CdTipServicio,EsRutaCliente,
				Kilometros,DirOrigen,FecOrigen,DirDestino,FecDestino
				) 
				 SELECT 
				@TipDoc,@Documento,@IdCia,Item,TipRes,Reserva,IdCiaRes,ItemRes,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,Referencia2,Referencia3,CdTipServicio,EsRutaCliente,
				Kilometros,DirOrigen,FecOrigen,DirDestino,FecDestino
				FROM @Trn_TraEspFuecDetalle
				end

				IF(EXISTS(SELECT TOP 1 Fuec FROM @Trn_TraEspFuecCndtores))
				begin
					INSERT INTO Trn_TraEspFuecCndtores(
					TipDoc,Fuec,IdCia,Item,IdConductor) 
					SELECT 
					@TipDoc,@Documento,@IdCia,Item, IdConductor
					FROM @Trn_TraEspFuecCndtores
				end

				--Actualizar Programación-Detalles
				UPDATE Trn_TraEspProgramaDet
				SET TipDocFuec = @TipDoc,NumFuec = @Documento, IdCiaFuec = @IdCia
				FROM Trn_TraEspProgramaDet t1, @Trn_TraEspFuec t2, @Trn_TraEspFuecDetalle t3
				WHERE t1.TipDoc = 'PGR' and t1.Programa = t2.NumPgr and t1.IdCia = t2.IdCiaPgr and t1.TipDocRes = t3.TipRes and t1.Reserva = t3.Reserva and t1.IdCiaRes = t3.IdCiaRes and t1.ItemRes = t3.ItemRes

			 END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 declare @Fuec int
			 select @TipDoc = TipDoc, @IdCia = IdCia,  @Fuec = Fuec from @Trn_TraEspFuec
				 DELETE FROM Trn_TraEspFuecDetalle WHERE TipDoc = @TipDoc and Fuec = @Fuec and IdCia = @IdCia
				 DELETE FROM Trn_TraEspFuecAnexo WHERE TipDoc = @TipDoc and Fuec = @Fuec and IdCia = @IdCia
				 DELETE FROM Trn_TraEspFuec WHERE TipDoc = @TipDoc and Fuec = @Fuec and IdCia = @IdCia
				 DELETE FROM Trn_TraEspFuecCndtores WHERE TipDoc = @TipDoc and Fuec = @Fuec and IdCia = @IdCia
			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Fuec from @Trn_TraEspFuec
			  UPDATE Trn_TraEspFuec SET IdEstado = '9999', Anulado = 1 WHERE TipDoc = @TipDoc and Fuec = @Documento and IdCia = @IdCia

			  UPDATE Trn_TraEspProgramaDet
			  SET TipDocFuec = 'FUE',NumFuec = 0, IdCiaFuec = '00'
			  FROM Trn_TraEspProgramaDet t1, @Trn_TraEspFuec t2
			  WHERE t1.TipDocFuec = 'FUE' and t1.NumFuec = t2.Fuec and t1.IdCiaFuec = t2.IdCia
			END

			SELECT @Documento

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspLiquida]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 01/02/2017
-- Description:	Insertar Trn_TraEspLiquida
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspLiquida]
	@Trn_TraEspLiquida dataTypeTrn_TraEspLiquida READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquida
	@Trn_TraEspLiquidaDed dataTypeTrn_TraEspLiquidaDed READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquidaDed
	@Trn_TraEspLiquidaOdp dataTypeTrn_TraEspLiquidaOdp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquidaOdp
	@Trn_TraEspLiquidaOtr dataTypeTrn_TraEspLiquidaOtr READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspLiquidaOtr
	@Trn_EgrFactura dataTypeTrn_EgrFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_EgrFactura

	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
	BEGIN TRAN
		BEGIN TRY		 
			
			if(@operacion = 'i')
			begin
			SELECT TOP 1 @TipDoc = TipDoc, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspLiquida
			SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

			IF(@Numero > 0)
				UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
			ELSE
			BEGIN
				SELECT @Numero = 1
				INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
			END

			IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
			BEGIN
				SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
				SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
				--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
				IF(@Comprobante <> '')
					UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
				ELSE
				BEGIN
					SELECT @Comprobante = 1
					INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
			BEGIN
				SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
				SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
				--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
				IF(@CompNiif <> '')
					UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
				ELSE
				BEGIN
					SELECT @CompNiif = 1
					INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
			BEGIN
				SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
				SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
				--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
				IF(@CompNiif <> '')
					UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
				ELSE
				BEGIN
					SELECT @CompFis = 1
					INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
				END
			END

			--DIEGO ROMERO DICE QUE SI NO EXISTE EL COMPROBANTE CON ELMISMO NOMBRE DE DOC DEVOLUCIÓN INSERTA UN COMPROBANTE CON EL  TIPCOM SEA IIGUAL AL TIPDEV, en la tabla TiposCom(tipos de comprobantes)
			--es INACTIVO = 1, PARA PODER INSERTAR EN EGRFACTURA ESTE TIPCOM
			IF(NOT EXISTS(SELECT IdCom FROM TiposCom where IdCom = @TipDoc))
			BEGIN
			  INSERT INTO TiposCom VALUES (@TipDoc,'LIQUIDACION DE ORDENES ESPECIAL',0,0,0,1,CURRENT_TIMESTAMP,NULL,NULL,null)
			END
			--

			end

			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspLiquida))
				BEGIN
				INSERT INTO Trn_TraEspLiquida(
				TipDoc,Liquidacion,IdCia,Fecha,IdConcepto,IdVehiculo,IdPoseedor,IdConductor,VrTotal,CxPagar,TipCom,Comprobante,IdCiaCom,
				Anulado,NumDev,FecDev,Observacion,IdEstado,FecIniCau,FecFinCau,FecIniOdp,FecFinOdp,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,
				IdUsuario,ModLiquida
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Fecha,IdConcepto,IdVehiculo,IdPoseedor,IdConductor,VrTotal,CxPagar,TipCom,Comprobante,IdCiaCom,
				Anulado,NumDev,FecDev,Observacion,IdEstado,FecIniCau,FecFinCau,FecIniOdp,FecFinOdp,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,
				IdUsuario,ModLiquida
				FROM @Trn_TraEspLiquida
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspLiquidaDed))
				BEGIN
				INSERT INTO Trn_TraEspLiquidaDed(
				TipDoc,Liquidacion,IdCia,Item,TipCau,Causacion,IdCiaCau,ItemCau,FechaCau,IdConcepto,Descripcion,VrAbono,NitPoseedor,pVehiculo,
				EsVence,TipOdp,OrdenPago,IdCiaOdp,TipRes,Reserva,IdCiaRes,VrSaldoOrden,CdCuenta,CdCuePagar,NumFactura,CdCCosto,CdSubCos,TipoFac
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,TipCau,Causacion,IdCiaCau,ItemCau,FechaCau,IdConcepto,Descripcion,VrAbono,NitPoseedor,pVehiculo,
				EsVence,TipOdp,OrdenPago,IdCiaOdp,TipRes,Reserva,IdCiaRes,VrSaldoOrden,CdCuenta,CdCuePagar,NumFactura,CdCCosto,CdSubCos,TipoFac
				FROM @Trn_TraEspLiquidaDed
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspLiquidaOdp))
				BEGIN
				INSERT INTO Trn_TraEspLiquidaOdp(
				TipDoc,Liquidacion,IdCia,Item,TipOdp,OrdPago,IdCiaOdp,VrAbonado
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,TipOdp,OrdPago,IdCiaOdp,VrAbonado
				FROM @Trn_TraEspLiquidaOdp
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspLiquidaOtr))
				BEGIN
				INSERT INTO Trn_TraEspLiquidaOtr(
				TipDoc,Liquidacion,IdCia,Item,TipCau,Causacion,IdCiaCau,ItemCau,Factura,ItemFac,IdProveedor,pVehiculo,VrAbono,TipFac,VrFactura
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,TipCau,Causacion,IdCiaCau,ItemCau,Factura,ItemFac,IdProveedor,pVehiculo,VrAbono,TipFac,VrFactura
				FROM @Trn_TraEspLiquidaOtr
				END

				IF(EXISTS(SELECT * FROM @Trn_EgrFactura))
				BEGIN
				INSERT INTO Trn_EgrFactura(
				TipCom,Comprobante,IdCia,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,TipDev,NumDev,DetAbono
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,Fecha,TipFac,Factura,IdCiaFac,
				ItemFac,IdProveedor,IdCuenta,VrAbono,EsEgreso,ItemCom,pVehiculo,
				VehPropio,TipDev,NumDev,DetAbono
				FROM @Trn_EgrFactura
				END 

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END,
				@Cia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDoc,@Numero,@Cia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, N.Referncia, N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			end	

			IF(@operacion = 'i')
			begin

			  -- actualizar causaciones con deducciones
			  declare @TipCau varchar(3)
			  declare @Causacion int
			  declare @IdCiaCau varchar(2)	
			  declare @ItemCau int		  
			  declare @VrAbonoCau decimal(14,4)
			  
			  -- actualizar causaciones con deducciones
			  DECLARE ccausac CURSOR
	  		  FOR SELECT TipCau, Causacion, IdCiaCau, ItemCau, VrAbono from @Trn_TraEspLiquidaDed
	          OPEN ccausac
			  FETCH NEXT FROM ccausac into @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
			  WHILE @@FETCH_STATUS = 0
			  BEGIN
			  
				  UPDATE Trn_TraEspCauDetalle
				  SET TipoLiq = @TipDoc, NumLiquida = @Numero, CiaLiquida = @Cia, VrAbonado = VrAbonado + @VrAbonoCau
				  FROM Trn_TraEspCauDetalle t1
				  WHERE t1.TipDoc = @TipCau and t1.Causacion = @Causacion and t1.IdCia = @IdCiaCau and t1.Item = @ItemCau

			  FETCH NEXT FROM ccausac INTO @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
			  END
			  CLOSE ccausac
			  DEALLOCATE ccausac

			  -- actualizar causaciones con otros pagos
			  DECLARE pcausac CURSOR
	  		  FOR SELECT TipCau,Causacion,IdCiaCau,ItemCau, VrAbono from @Trn_TraEspLiquidaOtr
			  OPEN pcausac
			  FETCH NEXT FROM pcausac into @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
			  WHILE @@FETCH_STATUS = 0
			  BEGIN
			
				UPDATE Trn_TraEspCauDetalle
				SET TipoLiq = @TipDoc, NumLiquida = @Numero, CiaLiquida = @Cia, VrAbonado = VrAbonado + @VrAbonoCau
				FROM Trn_TraEspCauDetalle t1
				WHERE t1.TipDoc = @TipCau and t1.Causacion = @Causacion and t1.IdCia = @IdCiaCau and t1.Item = @ItemCau
			
			  FETCH NEXT FROM pcausac INTO @TipCau, @Causacion, @IdCiaCau, @ItemCau, @VrAbonoCau
			  END
			  CLOSE pcausac
			  DEALLOCATE pcausac

			  --actualizar Trn_ComFactura
			  declare @FactTipFac varchar(3)
			  declare @FactIdCiaFac varchar(2)
			  declare @FactFactura varchar(15)
			  declare @FactIdProveedor varchar(16)
			  declare @VrAbono decimal(14,4)
			  declare @ItemFac int
			  DECLARE cprincipal CURSOR
	  		  FOR select TipFac, Factura, IdCiaFac,ItemFac, IdProveedor, VrAbono from @Trn_EgrFactura
	          OPEN cprincipal
			  FETCH NEXT FROM cprincipal into @FactTipFac, @FactFactura, @FactIdCiaFac,@ItemFac, @FactIdProveedor, @VrAbono
			  WHILE @@FETCH_STATUS = 0
			  BEGIN

					  if(@VrAbono > 0)
					  begin
						  update Trn_ComFactura 
						  set VrAbonado = VrAbonado + @VrAbono
						  from Trn_ComFactura t1 
						  where t1.TipFac = @FactTipFac and t1.Factura = @FactFactura and t1.IdCia = @FactIdCiaFac and t1.Item = @ItemFac and t1.IdProveedor = @FactIdProveedor
					 end

			  FETCH NEXT FROM cprincipal INTO @FactTipFac, @FactFactura, @FactIdCiaFac,@ItemFac, @FactIdProveedor, @VrAbono
			  END
			  CLOSE cprincipal
			  DEALLOCATE cprincipal

			  --actualizar orden pago
			  update Trn_TraEspOrdenReservas
			  set EdoLiqCausac =  1
			  from Trn_TraEspOrdenReservas t1, @Trn_TraEspLiquidaDed t2
			  where t2.TipOdp = t1.TipDoc and t2.OrdenPago = t1.OrdPago and t2.IdCiaOdp = t1.IdCia

			end

			SELECT @Numero,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspOrdenPago]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 30/01/2017
-- Description:	Insertar Trn_TraEspOrdenPago
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspOrdenPago]
	@Trn_TraEspOrdenPago dataTypeTrn_TraEspOrdenPago READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenPago
	@Trn_TraEspOrdenReservas dataTypeTrn_TraEspOrdenReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenReservas
	@Trn_TraEspOrdenProg dataTypeTrn_TraEspOrdenProg READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenProg
	@Trn_TraEspConceptos dataTypeTrn_TraEspConceptos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspConceptos
	@Trn_TraEspAntAbonos dataTypeTrn_TraEspAntAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspAntAbonos
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas
	@Trn_ComFactura dataTypeTrn_ComFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComFactura
	@Trn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	--16-01-2020.Yaqueline Lizarazo Diaz.Se cambia por el tipo de dato que se utiliza en el masivo de ordenes de pago, modificación que se realizo despues de dejar la contabilización en la misma clase.
	--@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifComp dataTypeNiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
--Nuevas variables
DECLARE @Reserva INT = (SELECT  TOP 1 Reserva FROM @Trn_TraEspOrdenReservas) --Esta variable guarda el número de reserva
DECLARE @ItemRes INT = (SELECT  TOP 1 ItemRes FROM @Trn_TraEspOrdenReservas) --Esta variable guarda el número de ítem de reserva
DECLARE @IdCiaRes CHAR(2) = (SELECT  TOP 1 IdCiaRes FROM @Trn_TraEspOrdenReservas)  --Esta variable guarda la compañia de la reserva
DECLARE @VrPagos MONEY = 0 --En esta variable va guarda el valor de pago real de la reserva
DECLARE @VrTotalPagosaRES MONEY = 0 --En esta variable va guarda el valor de pagos hechas a la reserva por ordenes de pago
DECLARE @TipoTarifa varchar(20)
	BEGIN TRAN
		BEGIN TRY		 
			
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspOrdenPago
				SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

				IF(@Numero > 0)
					UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
				ELSE
				BEGIN
					SELECT @Numero = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			end

			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenPago))
				BEGIN
				INSERT INTO Trn_TraEspOrdenPago(
				TipDoc,OrdPago,IdCia,Fecha,TipRes,Reserva,IdCiaRes,IdConcepto,Cantidad,Modalidad,LiqReservas,CxPagar,MulPlazos,IdPlazo,FechaVence,
				TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Fecha,TipRes,Reserva,IdCiaRes,IdConcepto,Cantidad,Modalidad,LiqReservas,CxPagar,MulPlazos,IdPlazo,FechaVence,
				@TipComp,@Comprobante,@IdCiaComp,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspOrdenPago
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenReservas))
				BEGIN
				INSERT INTO Trn_TraEspOrdenReservas(
				TipDoc,OrdPago,IdCia,Item,Fecha,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdConductor,IdPropietario,IdPoseedor,VrServicio,VrDescuento,VrRetencion,
				VrReteIca,VrReteCREE,VrAnticipos,VrOtrosDctos,VrImpuestos,VrOtrosPagos,VrNeto,BaseRet,BaseIca,BaseCree,TarifaRet,TarifaIca,TarifaRtc,CodTarRet,
				CodTarIca,CodTarRtc,TipEgr,Egreso,IdCiaEgr,FechaEgr,NumCheque,Referencia,VrConcPagos,VrConcDctos,VrConcFondo,VrConcSeguro,VrConcAporte,VrConcImpuesto,
				VrRecCaja,CdForma,CdCenCosto,CdSubCenCos,VrSeguros,VrFondos,VrAportes,EdoLiqCausac,EstadoItem
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,Fecha,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdConductor,IdPropietario,IdPoseedor,VrServicio,VrDescuento,VrRetencion,
				VrReteIca,VrReteCREE,VrAnticipos,VrOtrosDctos,VrImpuestos,VrOtrosPagos,VrNeto,BaseRet,BaseIca,BaseCree,TarifaRet,TarifaIca,TarifaRtc,CodTarRet,
				CodTarIca,CodTarRtc,TipEgr,Egreso,IdCiaEgr,FechaEgr,NumCheque,Referencia,VrConcPagos,VrConcDctos,VrConcFondo,VrConcSeguro,VrConcAporte,VrConcImpuesto,
				VrRecCaja,CdForma,CdCenCosto,CdSubCenCos,VrSeguros,VrFondos,VrAportes,EdoLiqCausac,EstadoItem
				FROM @Trn_TraEspOrdenReservas
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenProg))
				BEGIN
				INSERT INTO Trn_TraEspOrdenProg(
				TipDoc,OrdPago,IdCia,Item,TipRes,Reserva,IdCiaRes,ItemRes,TipPgr,Programa,IdCiaPgr,ItemPgr,VrRecorrido
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,TipRes,Reserva,IdCiaRes,ItemRes,TipPgr,Programa,IdCiaPgr,ItemPgr,VrRecorrido
				FROM @Trn_TraEspOrdenProg
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
				BEGIN
				INSERT INTO Trn_TraEspConceptos(
				TipDoc,Documento,IdCia,Item,Descripcion,Tarifa,TipoConc,RubroConcep,Cantidad,VrUnitario,TarifIva,IdConcepto,CdCuenta,NitTercero,
				CdTipoEsc,FechaNov,VrBase,TipoTarif,RefConc,Fijos,IncBaseRet,Referencia2,Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,Descripcion,Tarifa,TipoConc,RubroConcep,Cantidad,VrUnitario,TarifIva,IdConcepto,CdCuenta,NitTercero,
				CdTipoEsc,FechaNov,VrBase,TipoTarif,RefConc,Fijos,IncBaseRet,Referencia2,Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				FROM @Trn_TraEspConceptos
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspAntAbonos))
				BEGIN
				INSERT INTO Trn_TraEspAntAbonos(
				TipDoc,Documento,IdCia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				FROM @Trn_TraEspAntAbonos
				END

				IF(EXISTS(SELECT * FROM @Trn_DetCuentas))
				BEGIN
				INSERT INTO Trn_DetCuentas(
				TipDoc,Documento,IdCia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
				VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
				VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
				FROM @Trn_DetCuentas
				END

				IF(EXISTS(SELECT * FROM @Trn_ComFactura))
				BEGIN
				INSERT INTO Trn_ComFactura(
				TipFac,Factura,IdCia,Item,IdProveedor,IdCuenta,TipDoc,Documento,IdCiaDoc,FecEmision,FecVence,VrFactura,VrAbonado,TipCom,Comprobante,ItemCom,
				Referencia,Detalle,pVehiculo,VehPropio,TipRef,DocRef,IdCiaRef,EstadoApr,MontoAprob
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,IdProveedor,IdCuenta,@TipDoc,@Numero,@Cia,FecEmision,FecVence,VrFactura,VrAbonado,@TipComp,@Comprobante,ItemCom,
				Referencia,Detalle,pVehiculo,VehPropio,TipRef,DocRef,IdCiaRef,EstadoApr,MontoAprob
				FROM @Trn_ComFactura
				END 

				IF(EXISTS(SELECT * FROM @Trn_Pagos))
				BEGIN
				INSERT INTO Trn_Pagos(
				TipDoc, Documento, IdCia, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
				)
				SELECT 
				@TipDoc, @Numero, @Cia, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
				FROM @Trn_Pagos
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, SUBSTRING(Referncia, 0, 50), TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDoc, @Numero, @Cia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, SUBSTRING(N.Referncia,0,50), N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END
			end	

			IF(@operacion = 'i')
			begin
				--actualiza los items de la programación detalle de cada reserva agregada en la Orden de Pago
				UPDATE Trn_TraEspProgramaDet
				SET TipDocOdp = 'OPE',NumOdp = @Numero, IdCiaOdp = t3.IdCia, FechaOdp = t3.Fecha
				FROM Trn_TraEspProgramaDet t1, @Trn_TraEspOrdenProg t2, @Trn_TraEspOrdenPago t3
				WHERE t1.TipDoc = t2.TipPgr and t1.Programa = t2.Programa and t1.IdCia = t2.IdCiaPgr and t1.Item = t2.ItemPgr and t1.TipDocRes = t2.TipRes and t1.Reserva = t2.Reserva and t1.IdCiaRes = t2.IdCiaRes and t1.ItemRes = t2.ItemRes

				--JHON ROA-->Nuevo línea de código actualizar el estado de la reserva cuando ya se cumpla el valor total de la reserva
				--11/12/2017 Se cambia para tener en cuenta cuando TipoTarifa de la reserva es diaria.
				SELECT @TipoTarifa = TipoTarifa FROM Trn_TraEspResDetalle WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
				
				--No se necesita traer la actual reserva, poque ya fue insertada arriba en este procedimiento
				SELECT @VrTotalPagosaRES = ROUND(ISNULL(SUM(R.VrServicio),0), 1) 
				FROM Trn_TraEspOrdenReservas R
				LEFT JOIN Trn_TraEspOrdenPago AS OP ON R.TipDoc = OP.TipDoc AND  R.OrdPago = OP.OrdPago AND  R.IdCia = OP.IdCia
				WHERE R.Reserva = @Reserva AND R.IdCiaRes = @IdCiaRes AND R.ItemRes = @ItemRes AND OP.Anulado = 0;

				IF(upper(@TipoTarifa) <> 'DIA')
				BEGIN
					SELECT @VrPagos = VrPagos FROM Trn_TraEspResDetalle WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes

					IF(@VrTotalPagosaRES >= @VrPagos)
					BEGIN
						UPDATE Trn_TraEspResDetalle
						SET EstadoItem ='LIQUIDADA'
						WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
					END
					ELSE -- revisar que la cant de veh que se vayan a liquidar(programados no novedad) ya hayan sido liquidados(pasan de xliquidar a liquidado) y que la reserva no se haya vencido
					BEGIN
					  declare @cantveh int= 0, @cantord int = 0, @fechares date, @fechasys date,@idveh varchar(10)

					  select @cantveh = count(*) from trn_traespprogramadet where Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdNovedad = '0' and IdVehiculo <>'0'
					  select @fechares = fechafin from trn_traespreservas where Reserva = @Reserva AND IdCia = @IdCiaRes
					  select @fechasys = FechaActual from companias where IdCia = @IdCiaRes

					  --selecciono  los progdetalle de esos vehiculos
					  declare @Trn_TraEspProgramaDet dataTypeTrn_TraEspProgramaDet 
					  INSERT INTO @Trn_TraEspProgramaDet(
					  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
					  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
					  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
					  CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion
					  ) 
					  SELECT 
					  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
					  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
					  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
					  CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion
					  FROM Trn_TraEspProgramaDet  where Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdNovedad = '0' and IdVehiculo <>'0'
					  
					  --cursor para verififcar si los vehiculos fueron pagados en ordenes de pago					   
					  DECLARE verificar CURSOR
					  FOR SELECT IdVehiculo  FROM @Trn_TraEspProgramaDet
					  OPEN verificar
					  FETCH NEXT FROM verificar INTO @idveh
					  WHILE @@FETCH_STATUS = 0
					  BEGIN

					  --verifico la cantidad que ya fueron liquidados(tiene en cuenta la actual)
					   if (exists(select * from Trn_TraEspOrdenReservas where Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdVehiculo = @idveh))
						select @cantord = @cantord + 1

						FETCH NEXT FROM verificar INTO @idveh 
					  END
					  CLOSE verificar
					  DEALLOCATE verificar

					  --se verifica que cumpal para colocar la resrva a liquidada
					  IF((@cantord >= @cantveh) AND (@fechasys  >= @fechares))
					  BEGIN 
						UPDATE Trn_TraEspResDetalle
						SET EstadoItem ='LIQUIDADA'
						WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
					  END

					END

				END
				ELSE
				BEGIN
					SELECT @VrPagos = ISNULL(SUM(VrPagos),0)  FROM Trn_TraEspProgramaDet AS PD JOIN Trn_TraEspPrograma  AS P ON P.TipDoc = PD.TipDoc AND P.Programa = PD.Programa AND P.IdCia = PD.IdCia WHERE Reserva = @Reserva AND IdCiaRes = @IdCiaRes AND ItemRes = @ItemRes and IdNovedad = '0' and IdVehiculo <>'0' and p.Anulado = 0

					IF(@VrTotalPagosaRES >= @VrPagos)
					BEGIN
						UPDATE Trn_TraEspResDetalle
						SET EstadoItem ='LIQUIDADA'
						WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
					END
				END

				--actualiza los anticipos
				UPDATE Trn_TraEspAnticipos
				SET VrAbonado = VrAbonado + t2.VrAbono
				FROM Trn_TraEspAnticipos t1, @Trn_TraEspAntAbonos t2
				WHERE t1.TipDoc = t2.TipAnt and t1.Anticipo = t2.Anticipo and t1.IdCia = t2.IdCiaAnt
			end

			SELECT @Numero,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspOrdenPagoGIE]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Heiman Daza Tamayo
-- Create date(dd/MM/yyyy): 24/06/2021
-- Description:	Insertar Trn_TraEspOrdenPago para fincas Santur
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspOrdenPagoGIE]
	@Trn_TraEspOrdenPago dataTypeTrn_TraEspOrdenPago READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenPago
	@Trn_TraEspOrdenReservas dataTypeTrn_TraEspOrdenReservas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenReservas
	@Trn_TraEspOrdenProg dataTypeTrn_TraEspOrdenProg READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOrdenProg
	@Trn_TraEspConceptos dataTypeTrn_TraEspConceptos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspConceptos
	@Trn_TraEspAntAbonos dataTypeTrn_TraEspAntAbonos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspAntAbonos
	@Trn_DetCuentas dataTypeTrn_DetCuentas READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_DetCuentas
	@Trn_ComFactura dataTypeTrn_ComFactura READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComFactura
	@Trn_Pagos dataTypeTrn_Pagos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Pagos
	@Trn_Comprobantes dataTypeTrn_Comprobantes READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_Comprobantes
	@Trn_ComDetalle dataTypeTrn_ComDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_ComDetalle
	--16-01-2020.Yaqueline Lizarazo Diaz.Se cambia por el tipo de dato que se utiliza en el masivo de ordenes de pago, modificación que se realizo despues de dejar la contabilización en la misma clase.
	--@Trn_NiifComp dataTypeTrn_NiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifComp dataTypeNiifComp READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifComp
	@Trn_NiifDetalle dataTypeNiifDetalle READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_NiifDetalle

	@operacion varchar(1)
AS
DECLARE @Comprobante INT = 0 --Esta variable guarda el número consecutivo del comprobante
DECLARE @TipComp VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante
DECLARE @IdCiaComp VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante

DECLARE @CompNiif INT = 0 --Esta variable guarda el número consecutivo del comprobante Niif
DECLARE @TipCompNiif VARCHAR(3) = '0' --Esta variable guarda el tipo de comprobante Niif
DECLARE @IdCiaCompNiif VARCHAR(4) = '00'--Esta variable guarda la compañia del comprobante Niif

DECLARE @CompFis INT = 0 --Esta variable guarda el número consecutivo de comprobante Fiscal
DECLARE @TipCompFis VARCHAR(3)  = '0' --Esta variable guarda el tipo de comprobante Fiscal
DECLARE @IdCiaCompFis VARCHAR(4) = '00' --Esta variable guarda la compañia del comprobante Fiscal

DECLARE @TipDoc VARCHAR(3) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Cia VARCHAR(2) --En esta variable se guarda el consecutivo del documento aprobación
DECLARE @Numero INT --En esta variable se guarda el consecutivo del documento aprobación
--Nuevas variables
DECLARE @Reserva INT = (SELECT  TOP 1 Reserva FROM @Trn_TraEspOrdenReservas) --Esta variable guarda el número de reserva
DECLARE @ItemRes INT = (SELECT  TOP 1 ItemRes FROM @Trn_TraEspOrdenReservas) --Esta variable guarda el número de ítem de reserva
DECLARE @IdCiaRes CHAR(2) = (SELECT  TOP 1 IdCiaRes FROM @Trn_TraEspOrdenReservas)  --Esta variable guarda la compañia de la reserva
DECLARE @VrPagos MONEY = 0 --En esta variable va guarda el valor de pago real de la reserva
DECLARE @VrTotalPagosaRES MONEY = 0 --En esta variable va guarda el valor de pagos hechas a la reserva por ordenes de pago
DECLARE @TipoTarifa varchar(20)
	BEGIN TRAN
		BEGIN TRY		 
			
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @Cia = IdCia, @IdCiaComp = IdCia, @IdCiaCompNiif = IdCia, @IdCiaCompFis = IdCia FROM @Trn_TraEspOrdenPago
				SELECT @Numero = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @Cia

				IF(@Numero > 0)
					UPDATE TiposDocCons SET Numero = @Numero WHERE IdDoc = @TipDoc AND IdCia = @Cia
				ELSE
				BEGIN
					SELECT @Numero = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@Cia,0,0,0,0,NULL,'',@Numero,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
					SELECT TOP 1 @TipComp = TipCom FROM @Trn_Comprobantes
					SELECT @Comprobante = Numero + 1  FROM TiposComCons where IdCom  = @TipComp AND IdCia = @IdCiaComp
					--UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp AND IdCia = @IdCiaComp
					IF(@Comprobante <> '')
						UPDATE TiposComCons SET Numero = @Comprobante WHERE IdCom = @TipComp and IdCia = @IdCiaComp
					ELSE
					BEGIN
						SELECT @Comprobante = 1
						INSERT INTO TiposComCons VALUES (@TipComp,@IdCiaComp,0,0,@Comprobante,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'))
				BEGIN
					SELECT TOP 1 @TipCompNiif = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'NIIF'
					SELECT @CompNiif = Numero + 1  FROM TiposComCons where IdCom  = @TipCompNiif AND IdCia = @IdCiaCompNiif
					--UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif AND IdCia = @IdCiaCompNiif
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompNiif WHERE IdCom = @TipCompNiif and IdCia = @IdCiaCompNiif
					ELSE
					BEGIN
						SELECT @CompNiif = 1
						INSERT INTO TiposComCons VALUES (@TipCompNiif,@IdCiaCompNiif,0,0,@CompNiif,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'))
				BEGIN
					SELECT TOP 1 @TipCompFis = TipCom FROM @Trn_NiifComp WHERE TipoNiif = 'FISCAL'
					SELECT @CompFis = Numero + 1  FROM TiposComCons where IdCom  = @TipCompFis AND IdCia = @IdCiaCompFis
					--UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis AND IdCia = @IdCiaCompFis
					IF(@CompNiif <> '')
						UPDATE TiposComCons SET Numero = @CompFis WHERE IdCom = @TipCompFis and IdCia = @IdCiaCompFis
					ELSE
					BEGIN
						SELECT @CompFis = 1
						INSERT INTO TiposComCons VALUES (@TipCompFis,@IdCiaCompFis,0,0,@CompFis,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null)
					END
				END
			end

			IF(@operacion = 'i')
			begin
				IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenPago))
				BEGIN
				INSERT INTO Trn_TraEspOrdenPago(
				TipDoc,OrdPago,IdCia,Fecha,TipRes,Reserva,IdCiaRes,IdConcepto,Cantidad,Modalidad,LiqReservas,CxPagar,MulPlazos,IdPlazo,FechaVence,
				TipCom,Comprobante,IdCiaCom,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Fecha,TipRes,Reserva,IdCiaRes,IdConcepto,Cantidad,Modalidad,LiqReservas,CxPagar,MulPlazos,IdPlazo,FechaVence,
				@TipComp,@Comprobante,@IdCiaComp,Anulado,NumDev,FecDev,Observacion,IdEstado,OrigenAdd,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspOrdenPago
				END 

				IF(EXISTS(SELECT * FROM @Trn_TraEspOrdenReservas))
				BEGIN
				INSERT INTO Trn_TraEspOrdenReservas(
				TipDoc,OrdPago,IdCia,Item,Fecha,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdConductor,IdPropietario,IdPoseedor,VrServicio,VrDescuento,VrRetencion,
				VrReteIca,VrReteCREE,VrAnticipos,VrOtrosDctos,VrImpuestos,VrOtrosPagos,VrNeto,BaseRet,BaseIca,BaseCree,TarifaRet,TarifaIca,TarifaRtc,CodTarRet,
				CodTarIca,CodTarRtc,TipEgr,Egreso,IdCiaEgr,FechaEgr,NumCheque,Referencia,VrConcPagos,VrConcDctos,VrConcFondo,VrConcSeguro,VrConcAporte,VrConcImpuesto,
				VrRecCaja,CdForma,CdCenCosto,CdSubCenCos,VrSeguros,VrFondos,VrAportes,EdoLiqCausac,EstadoItem
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,Fecha,TipRes,Reserva,IdCiaRes,ItemRes,IdVehiculo,IdConductor,IdPropietario,IdPoseedor,VrServicio,VrDescuento,VrRetencion,
				VrReteIca,VrReteCREE,VrAnticipos,VrOtrosDctos,VrImpuestos,VrOtrosPagos,VrNeto,BaseRet,BaseIca,BaseCree,TarifaRet,TarifaIca,TarifaRtc,CodTarRet,
				CodTarIca,CodTarRtc,TipEgr,Egreso,IdCiaEgr,FechaEgr,NumCheque,Referencia,VrConcPagos,VrConcDctos,VrConcFondo,VrConcSeguro,VrConcAporte,VrConcImpuesto,
				VrRecCaja,CdForma,CdCenCosto,CdSubCenCos,VrSeguros,VrFondos,VrAportes,EdoLiqCausac,EstadoItem
				FROM @Trn_TraEspOrdenReservas
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
				BEGIN
				INSERT INTO Trn_TraEspConceptos(
				TipDoc,Documento,IdCia,Item,Descripcion,Tarifa,TipoConc,RubroConcep,Cantidad,VrUnitario,TarifIva,IdConcepto,CdCuenta,NitTercero,
				CdTipoEsc,FechaNov,VrBase,TipoTarif,RefConc,Fijos,IncBaseRet,Referencia2,Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,Descripcion,Tarifa,TipoConc,RubroConcep,Cantidad,VrUnitario,TarifIva,IdConcepto,CdCuenta,NitTercero,
				CdTipoEsc,FechaNov,VrBase,TipoTarif,RefConc,Fijos,IncBaseRet,Referencia2,Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				FROM @Trn_TraEspConceptos
				END

				IF(EXISTS(SELECT * FROM @Trn_TraEspAntAbonos))
				BEGIN
				INSERT INTO Trn_TraEspAntAbonos(
				TipDoc,Documento,IdCia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,Fecha,TipAnt,Anticipo,IdCiaAnt,VrAbono,TipoAplica,Detalle,CdCuentaAnt
				FROM @Trn_TraEspAntAbonos
				END

				IF(EXISTS(SELECT * FROM @Trn_DetCuentas))
				BEGIN
				INSERT INTO Trn_DetCuentas(
				TipDoc,Documento,IdCia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
				VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Concepto,Item,IdCuenta,Valor,Detalle,IdTercero,CodAgncia,CdCCosto,CdSubCos,pVehiculo,
				VrBase,TipFac,Factura,IdCiaFac,ItemFac,FecVence,Cheque,CiuOrigen,Referencia,VrTarifa,TipoTarif,CodConc,CodTarif
				FROM @Trn_DetCuentas
				END

				IF(EXISTS(SELECT * FROM @Trn_ComFactura))
				BEGIN
				INSERT INTO Trn_ComFactura(
				TipFac,Factura,IdCia,Item,IdProveedor,IdCuenta,TipDoc,Documento,IdCiaDoc,FecEmision,FecVence,VrFactura,VrAbonado,TipCom,Comprobante,ItemCom,
				Referencia,Detalle,pVehiculo,VehPropio,TipRef,DocRef,IdCiaRef,EstadoApr,MontoAprob
				)
				SELECT 
				@TipDoc,@Numero,@Cia,Item,IdProveedor,IdCuenta,@TipDoc,@Numero,@Cia,FecEmision,FecVence,VrFactura,VrAbonado,@TipComp,@Comprobante,ItemCom,
				Referencia,Detalle,pVehiculo,VehPropio,TipRef,DocRef,IdCiaRef,EstadoApr,MontoAprob
				FROM @Trn_ComFactura
				END 

				IF(EXISTS(SELECT * FROM @Trn_Pagos))
				BEGIN
				INSERT INTO Trn_Pagos(
				TipDoc, Documento, IdCia, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
				)
				SELECT 
				@TipDoc, @Numero, @Cia, Item, Fecha, IdForma, Detalle, VrPagado,
				VrCambio, EsCaja, IdBanco, NitCliente, CdAgencia, NumForma, FecForma, 
				CtaForma, Beneficiario, Referncia1, Referncia2, CdLocal, NumAutoriza, 
				VrDenom, Cantidad, TipDenom, TipRef, DocRef, IdCiaRef, ItemDoc, CdCta, IdUsuario,
				CdProducto, FE_Ticket, Cant_Gals, PrecioBase, PrecioUnit
				FROM @Trn_Pagos
				END

				IF(EXISTS(SELECT * FROM @Trn_Comprobantes))
				BEGIN
				INSERT INTO Trn_Comprobantes(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, NiifTipo, NiifNumero, FisTipo, FisNumero, DocSoporte,
				CodRes, DescServicio
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Fecha, IdTercero, VrTotal, IdCta, EnEfectivo,
				NumCheque, FecCheque, @TipDoc, @Numero, @Cia, Anulado, NumDev, FecDev,
				TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario, VrDivisa1,
				VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion, IdEstado,
				Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, CdSustento, Tipo_Pago, Establec,
				PEmision, Autorizac, FechaAut, @TipCompNiif, @CompNiif, @TipCompFis, @CompFis, DocSoporte,
				CodRes, DescServicio
				FROM @Trn_Comprobantes
				END

				IF(EXISTS(SELECT * FROM @Trn_ComDetalle))
				BEGIN
				INSERT INTO Trn_ComDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, TipDoc, Documento,
				IdCiaDoc, CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, Referncia, TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				)
				SELECT 
				@TipComp, @Comprobante, @IdCiaComp, Item, Fecha, IdCuenta, Detalle, VrDebito, VrCredito,
				IdTercero, IdVehiculo, IdCCosto, IdSubCos, VrBase, TarifaBase, @TipDoc, @Numero, @Cia,
				CodConce, NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta,
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros, CodSubgpo, CiuOrigen, 
				CodAgncia, VehPropio, SUBSTRING(Referncia, 0, 50), TipDocRef, DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, 
				IdUsuario, CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza, FechAutoriza,CdCuentaNiif
				FROM @Trn_ComDetalle
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifComp))
				BEGIN
				INSERT INTO Trn_NiifComp(
				TipCom, Comprobante, IdCia, Fecha, IdTercero, VrTotal, IdCta,
				EnEfectivo, NumCheque, FecCheque, TipDoc, Documento, IdCiaDoc, Anulado, NumDev,
				FecDev, TipEgr, NEgreso, pVehiculo, VehPropio, CedCondtor, CodConce, Beneficiario,
				VrDivisa1, VrDivisa2, VrDivisa3, PermEditar, Integrado, EsEgreso, Anticipo, Observacion,
				IdEstado, Propddes, TimeSys, FecUpdate, IdCiaCrea, IdUsuario, TipoNiif, CdSustento,
				Tipo_Pago, Establec, PEmision, Autorizac,FechaAut,
				CtbTipo, CtbNumero,
				FisTipo, FisNumero 
				)
				SELECT 
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia, 
				C.Fecha, C.IdTercero, C.VrTotal, C.IdCta,
				C.EnEfectivo, C.NumCheque, C.FecCheque, @TipDoc, @Numero, @Cia, C.Anulado, C.NumDev,
				C.FecDev, C.TipEgr, C.NEgreso, C.pVehiculo, C.VehPropio, C.CedCondtor, C.CodConce, C.Beneficiario,
				C.VrDivisa1, C.VrDivisa2, C.VrDivisa3, C.PermEditar, C.Integrado, C.EsEgreso, C.Anticipo, C.Observacion,
				C.IdEstado, C.Propddes, C.TimeSys, C.FecUpdate, C.IdCiaCrea, C.IdUsuario, N.TipoNiif, C.CdSustento,
				C.Tipo_Pago, C.Establec, C.PEmision, C.Autorizac, C.FechaAut,
				CASE N.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE NULL END, CASE N.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE 0 END,
				CASE N.TipoNiif WHEN 'FISCAL' THEN @TipCompFis ELSE NULL END, CASE N.TipoNiif WHEN 'FISCAL' THEN @CompFis ELSE 0 END
				FROM @Trn_Comprobantes AS C JOIN @Trn_NiifComp AS N ON C.TipCom = N.TipComCont AND C.Comprobante = N.ComprobanteCont
				END

				IF(EXISTS(SELECT * FROM @Trn_NiifDetalle))
				BEGIN
				INSERT INTO Trn_NiifDetalle(
				TipCom, Comprobante, IdCia, Item, Fecha, IdCuenta, Detalle,
				VrDebito, VrCredito, IdTercero, IdVehiculo,IdCCosto, IdSubCos,
				VrBase, TarifaBase, TipDoc, Documento, IdCiaDoc, CodConce,
				NitDoc, TipFac, Factura, IdCiaFac, ItemFac, FecVence, CodCta, 
				NumCheque, Integrado, TipoAplica, Consolida, CodCargo, NitOtros,
				CodSubgpo, CiuOrigen, CodAgncia, VehPropio, Referncia, TipDocRef,
				DocRef, IdCiaRef, TimeSys, FecUpdate, IdCiaCrea, IdUsuario,
				CdConcTrib, CdTarifTrib, NumEstablec, PtoEmision, Num_Autoriza,
				FechAutoriza, CodCuentaCG
				)
				SELECT 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @TipCompNiif ELSE @TipCompFis END, 
				CASE NC.TipoNiif WHEN 'NIIF' THEN @CompNiif ELSE @CompFis END, 
				@Cia,
				N.Item, N.Fecha, N.IdCuenta, N.Detalle,
				N.VrDebito, N.VrCredito, N.IdTercero, N.IdVehiculo,N.IdCCosto, N.IdSubCos,
				N.VrBase, N.TarifaBase, @TipDoc, @Numero, @Cia, N.CodConce,
				N.NitDoc, N.TipFac, N.Factura, N.IdCiaFac, N.ItemFac, N.FecVence, N.CodCta, 
				N.NumCheque, N.Integrado, N.TipoAplica, N.Consolida, N.CodCargo, N.NitOtros,
				N.CodSubgpo, N.CiuOrigen, N.CodAgncia, N.VehPropio, SUBSTRING(N.Referncia,0,50), N.TipDocRef,
				N.DocRef, N.IdCiaRef, N.TimeSys, N.FecUpdate, N.IdCiaCrea, N.IdUsuario,
				N.CdConcTrib, N.CdTarifTrib, N.NumEstablec, N.PtoEmision ,N.Num_Autoriza,
				N.FechAutoriza, N.CodCuentaCG
				FROM @Trn_NiifDetalle as N
				JOIN @Trn_NiifComp AS NC ON N.TipCom = NC.TipCom AND N.Comprobante = NC.Comprobante
				END

				BEGIN 
					UPDATE Trn_TraEspResDetalle
					SET EstadoItem ='LIQUIDADA'
					WHERE Reserva = @Reserva AND IdCia = @IdCiaRes AND Item = @ItemRes
				END
			end	

			SELECT @Numero,@Comprobante

			COMMIT TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspOtroSi]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa Castañeda
-- Create date(dd/MM/yyy): 15/07/2019
-- Description:	CRUD OtroSi.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspOtroSi]
	@Trn_TraEspOtroSi dataTypeTrn_TraEspOtroSi READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOtroSi
	@Trn_TraEspOtroSiContratos dataTypeTrn_TraEspOtroSiContratos READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspOtroSiContratos
	@Trn_TraEspContratoDet dataTypeTrn_TraEspContratoDet READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspEspDetalle
	@operacion varchar(1)
AS
DECLARE @IdOtroSi INT --Esta variable guarda el número de consecutivo del OtroSí insertado actualmente
DECLARE @Contrato INT --Esta variable guarda el número de consecutivo del contrato a quien se le ha insertado un OtroSí
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de contrato a quien se le ha insertado un OtroSí
DECLARE @IdCia VARCHAR(2) --Esta variable guarda la cía de contrato a quien se le ha insertado un OtroSí
DECLARE @VrAdicion DECIMAL --Esta variable guarda el valor a adicionar al contrato a quien se le ha insertado un OtroSí
DECLARE @FechaFinNew SMALLDATETIME --Esta variable guarda el valor dela nueva fecha del contrato a quien se le ha insertado un OtroSí
DECLARE @Item INT --Esta variable guarda el número de consecutivo del Item contrato a quien se le ha insertado un OtroSí
DECLARE @VrCobro DECIMAL --Esta variable actualiza el valor a cobrar al contrato a quien se le ha insertado un OtroSí
--declare @item int
	BEGIN TRAN
		BEGIN TRY

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN
				IF(EXISTS(SELECT * FROM @Trn_TraEspOtroSi))
				begin
					INSERT INTO Trn_TraEspOtroSi(
					Fecha, Adicion, CFecha, Items, Aplicado, TimeSys, Observacion, IdUsuario, Anulado, FecDev
					)
					SELECT 
					Fecha, Adicion, CFecha, Items, Aplicado, TimeSys, Observacion, IdUsuario, Anulado, FecDev
					FROM @Trn_TraEspOtroSi
				end
				SET @IdOtroSi = SCOPE_IDENTITY()
				IF(EXISTS(SELECT * FROM @Trn_TraEspOtroSiContratos))
				begin
					EXEC('DISABLE TRIGGER [dbo].[Tr_OtroSiCOE] on Trn_TraEspOtroSiContratos');
					INSERT INTO Trn_TraEspOtroSiContratos(
					IdOtroSi, TipDocCnt, Contrato, IdCiaCnt, FechaFinAnt, FechaFinNew, VrPpto, VrSaldoPpo, VrAdicionPpto
					)
					SELECT 
					@IdOtroSi, TipDocCnt, Contrato, IdCiaCnt, FechaFinAnt, FechaFinNew, VrPpto, VrSaldoPpo, VrAdicionPpto
					FROM @Trn_TraEspOtroSiContratos
					SELECT @TipDoc = TipDocCnt,  @Contrato = Contrato, @IdCia = IdCiaCnt, @VrAdicion = VrAdicionPpto, @FechaFinNew = FechaFinNew  FROM @Trn_TraEspOtroSiContratos
					EXEC('ENABLE TRIGGER [dbo].[Tr_OtroSiCOE] on Trn_TraEspOtroSiContratos');
				end
				--row["VrTotal"] = (((Convert.ToDecimal(this.txtvVrDiaAdi.Value) * Convert.ToInt32(this.txtvDiasAdi.Value)) + (Convert.ToDecimal(this.txtvVrMonitor.Value) * Convert.ToInt32(this.txtvCantMo.Value)) + Convert.ToDecimal(row["VrUnitario"])) * Convert.ToInt32(row["Cantveh"]));
			   IF(EXISTS(SELECT * FROM @Trn_TraEspContratoDet))
				begin
					SET @VrCobro = (select (sum(VrDia * DiasDisp) + sum(VrMonitor * CantMonitor) + sum(VrUnitario)) FROM @Trn_TraEspContratoDet)
				end
			   -- --Actualizar contrato
				UPDATE Trn_TraEspContratos SET VrPresupuesto = (VrPresupuesto + @VrAdicion), VrSaldoPresup = (VrSaldoPresup + @VrAdicion), FechaFin = @FechaFinNew, VrCobro = VrCobro + ISNULL(@VrCobro, 0)
				WHERE TipDoc = @TipDoc AND Contrato = @Contrato and IdCia = @IdCia
				--AgrergarItems de Contrato Detalle
				IF(EXISTS(SELECT * FROM @Trn_TraEspContratoDet))
				begin
					SET @Item = (select max(Item) from trn_traespcontratodet where TipDoc = @TipDoc AND contrato = @Contrato AND idcia = @IdCia)
					INSERT INTO Trn_TraEspContratoDet(
					TipDoc,Contrato,IdCia,Item,IdHorario,TipPed,Pedido,CiaPed,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
					Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
					DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,IdOtroSi,ItemAnuladoOS,
					EsItemPME
					) 
					SELECT --(Item + @Item)
					@TipDoc,@Contrato,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)),IdHorario,TipPed,Pedido,@IdCia,ItemPed,TipRes,NumRes,IdCiaRes,ItemRes,IdVehiculo,CdTipVeh,NumPasajeros,PesoNeto,VrUnitario,VrPago,IdRuta,
					Referencia1,Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,
					DiasDisp,VrDia,Parada,CdTipRuta,CdTipServicio,CantVeh,Retorno,VrMonitor,CantMonitor,VrMaxRec,NumDias,TipoTarifa,IdColegio,Codigo,Itinerario,VLargo,@IdOtroSi,ItemAnuladoOS,EsItemPME
					FROM @Trn_TraEspContratoDet
				end
			 END

			 --ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
				declare @FecDev smalldatetime 
				select @IdOtroSi = IdOtroSi, @FecDev = FecDev from @Trn_TraEspOtroSi
				SET @VrCobro = (select (sum(VrDia * DiasDisp) + sum(VrMonitor * CantMonitor) + sum(VrUnitario)) FROM Trn_TraEspContratoDet where IdOtroSi = @IdOtroSi)
				UPDATE Trn_TraEspOtroSi SET Anulado = 1, FecDev = @FecDev  WHERE IdOtroSi = @IdOtroSi
				--Devolver el contrato a los datos anteiores al OtroSí
				UPDATE  C SET  C.FechaFin = OSC.FechaFinAnt, C.VrPresupuesto = OSC.VrPpto, C.VrSaldoPresup = (OSC.VrSaldoPpo  - OSC.VrAdicionPpto) , C.VrCobro  = (C.VrCobro -ISNULL(@VrCobro, 0))
				FROM Trn_TraEspContratos as C
				JOIN Trn_TraEspContratoDet AS D ON C.TipDoc = D.TipDoc AND C.Contrato = D.Contrato AND C.IdCia = D.IdCia
				LEFT JOIN  Trn_TraEspOtroSiContratos OSC ON OSC.IdOtroSi = @IdOtroSi AND D.TipDoc = OSC.TipDocCnt AND OSC.Contrato = D.Contrato AND OSC.IdCiaCnt = D.IdCia
				Where D.IdOtroSi = @IdOtroSi 
				--Anula los ítems de OtroSí
				UPDATE Trn_TraEspContratoDet
				SET ItemAnuladoOS = 1, VrUnitario = 0, VrDia = 0, DiasDisp = 0,  VrMonitor = 0, CantMonitor = 0 WHERE IdOtroSi = @IdOtroSi
				  ------------------------------------
			END

			SELECT @IdOtroSi

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPasajeros]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 30/09/2016
-- Description:	Crud de pasajeros.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPasajeros]
	@Trn_TraEspPasajeros dataTypeTrn_TraEspPasajeros READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPasajeros
	@operacion varchar(1)

AS
DECLARE @Numero INT --Esta variable guarda el número de consecutivo de la lista

	BEGIN TRAN
		BEGIN TRY

			--IF(@operacion = 'i')
			--BEGIN
			--	SELECT @Numero = ISNULL(MAX(IdLista),0) + 1  FROM Trn_TraEspListaPasajeros
			--END

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			   IF(EXISTS(SELECT * FROM @Trn_TraEspPasajeros))
			   begin
			   UPDATE Trn_TraEspPasajeros
			   SET 
			   TipId = t2.TipId,Documento = t2.Documento,Apellidos = t2.Apellidos,
			   Nombres = t2.Nombres,Cargo = t2.Cargo,EsMonitor = t2.EsMonitor,
			   Telefono = t2.Telefono,Observacion = t2.Observacion,
			   EsEstudiante = t2.EsEstudiante,IdResponsable = t2.IdResponsable,
			   Porcentaje = t2.Porcentaje,VrPago = t2.VrPago,IdColegio = t2.IdColegio,
			   CdEstudiante = t2.CdEstudiante,Jornada = t2.Jornada,Sede = t2.Sede,Inactivo = t2.Inactivo,
			   FechaNac = t2.FechaNac, IncluirPeriodo = t2.IncluirPeriodo
			   FROM Trn_TraEspPasajeros t1
			   JOIN @Trn_TraEspPasajeros t2 ON t1.TipId = t2.TipId and t1.Documento = t2.Documento
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspPasajeros(
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				)
				SELECT 
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				FROM @Trn_TraEspPasajeros
				WHERE (Documento) NOT IN(SELECT (Documento) FROM Trn_TraEspPasajeros)
			   end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			BEGIN
				IF(EXISTS(SELECT * FROM @Trn_TraEspPasajeros))
				begin
				INSERT INTO Trn_TraEspPasajeros(
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				)
				SELECT 
				TipId,Documento,Apellidos,Nombres,Cargo,EsMonitor,Telefono,Observacion,
				EsEstudiante,IdResponsable,Porcentaje,VrPago,IdColegio,CdEstudiante,
				Jornada,Sede,Inactivo,FechaNac,IncluirPeriodo
				FROM @Trn_TraEspPasajeros
				WHERE (Documento) NOT IN(SELECT (Documento) FROM Trn_TraEspPasajeros)
				end					
			END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			  DELETE FROM Trn_TraEspPasajeros WHERE Documento = (select Documento from @Trn_TraEspPasajeros)
			END

			SELECT '1'

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPedido]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 31/08/2016
-- Description:	Insertar Cotización Transporte Especial.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPedido]
	@Trn_TraEspPedido dataTypeTrn_TraEspPedido READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPedido
	@Trn_TraEspPedAnexo dataTypeTrn_TraEspPedAnexo READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPedAnexo
	@Trn_TraEspPedDetalle dataTypeTrn_TraEspPedDetalle READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspEspDetalle
	@Trn_TraEspConceptos dataTypeTrn_TraEspConceptos READONLY, --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspConceptos
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Pedido/Cotización
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Pedido/Cotización
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Pedido/Cotización
declare @item int
	BEGIN TRAN
		BEGIN TRY

			--Seleccionar Variables
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia FROM @Trn_TraEspPedido
				SELECT @Documento = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia

				IF(@Documento <> '')
					UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
				ELSE
				BEGIN
					SELECT @Documento = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			end

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			   if(EXISTS(SELECT * FROM @Trn_TraEspPedido))
			   begin
			   UPDATE Trn_TraEspPedido
			   SET 
			   TipDoc = t2.TipDoc,Pedido = t2.Pedido,IdCia = t2.IdCia,Fecha = t2.Fecha,FechaVence = t2.FechaVence,
			   FecInicio = t2.FecInicio,FecFinal = t2.FecFinal,IdCliente = t2.IdCliente,IdAgencia = t2.IdAgencia,
			   IdVend = t2.IdVend,IdTarifCom = t2.IdTarifCom,TipoContrato = t2.TipoContrato,TipoPago = t2.TipoPago,
			   Modalidad = t2.Modalidad,Vigencia = t2.Vigencia,VrCobro = t2.VrCobro,VrPagos = t2.VrPagos,VrCargos = t2.VrCargos,
			   VrDctos = t2.VrDctos,VrIva = t2.VrIva,CdDescuento = t2.CdDescuento,Presupuesto = t2.Presupuesto,
			   CantPasajeros = t2.CantPasajeros,Cantidad = t2.Cantidad,Peso = t2.Peso,IdMneda = t2.IdMneda,
			   NumAprob = t2.NumAprob,IdCiaApr = t2.IdCiaApr,
			   FecAprob = t2.FecAprob,EsLicitacion = t2.EsLicitacion,OrigenAdd = t2.OrigenAdd,Anulado = t2.Anulado,
			   FecDev = t2.FecDev,Observacion = t2.Observacion,IdEstado = t2.IdEstado,TimeSys = t2.TimeSys,FecUpdate = t2.FecUpdate,
			   IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario,CdCarga = t2.CdCarga,VrEditado = t2.VrEditado,CantDias = t2.CantDias
		       FROM Trn_TraEspPedido t1
			   JOIN @Trn_TraEspPedido t2 ON t1.TipDoc = t2.TipDoc and t1.Pedido = t2.Pedido and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspPedAnexo))
			   begin
			   UPDATE Trn_TraEspPedAnexo
			   SET 
			   TipDoc = t2.TipDoc,Pedido = t2.Pedido,IdCia = t2.IdCia,NomCliente = t2.NomCliente,DirCliente = t2.DirCliente,
			   NomContacto = t2.NomContacto,TelContacto = t2.TelContacto,emlContacto = t2.emlContacto,emlCliente = t2.emlCliente,
			   DescripCarga = t2.DescripCarga,Clausulas = t2.Clausulas
		       FROM Trn_TraEspPedAnexo t1
			   JOIN @Trn_TraEspPedAnexo t2 ON t1.TipDoc = t2.TipDoc and t1.Pedido = t2.Pedido and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspPedDetalle))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Pedido FROM @Trn_TraEspPedDetalle
			   select @item =  isnull(MAX(Item),0) from Trn_TraEspPedDetalle where TipDoc = @TipDoc and Pedido = @Documento and IdCia = @IdCia

			   --actualizar los que vienen en el tipo de dato y coincidan con los que ya estan en la tabla
			   UPDATE Trn_TraEspPedDetalle
			   SET 
			   TipDoc = t2.TipDoc,Pedido = t2.Pedido,IdCia = t2.IdCia,Item = t2.Item,CdTipVeh = t2.CdTipVeh,NumPasajeros = t2.NumPasajeros,
			   Parada = t2.Parada,PesoNeto = t2.PesoNeto,VrUnitario = t2.VrUnitario,IdRuta = t2.IdRuta,Referencia1 = t2.Referencia1,
			   Referencia2 = t2.Referencia2,Referencia3 = t2.Referencia3,EsRutaCliente = t2.EsRutaCliente,CdCiuOrigen = t2.CdCiuOrigen,
			   DirOrigen = t2.DirOrigen,FecOrigen = t2.FecOrigen,CdCiuDestino = t2.CdCiuDestino,DirDestino = t2.DirDestino,FecDestino = t2.FecDestino,
			   CdTipRuta = t2.CdTipRuta,CdTipServicio = t2.CdTipServicio,DiasDisp = t2.DiasDisp,VrDia = t2.VrDia,
			   TipCtn=t2.TipCtn,NumCnt=t2.NumCnt,IdCiaCnt=t2.IdCiaCnt,ItemCnt=t2.ItemCnt, CantVeh=t2.CantVeh,Retorno=t2.Retorno
			   ,VrMonitor = t2.VrMonitor,CantMonitor=t2.CantMonitor,TipoTarifa=t2.TipoTarifa,Dias = t2.Dias,Itinerario = t2.Itinerario,VLargo = t2.VLargo
			   ,ItemPpalRet = t2.ItemPpalRet,CiaPpalRet = t2.CiaPpalRet,VrPago = t2.VrPago
		       FROM Trn_TraEspPedDetalle t1
			   JOIN @Trn_TraEspPedDetalle t2 ON t1.TipDoc = t2.TipDoc and t1.Pedido = t2.Pedido and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Pedido = t2.Pedido and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspPedDetalle(
				TipDoc,Pedido,IdCia,Item,CdTipVeh,NumPasajeros,Parada,PesoNeto,VrUnitario,IdRuta,Referencia1,Referencia2,
				Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,CdTipRuta,
				CdTipServicio,DiasDisp,VrDia,TipCtn,NumCnt,IdCiaCnt,ItemCnt,CantVeh,Retorno,VrMonitor,CantMonitor,TipoTarifa,Dias,Itinerario,
				VLargo,ItemPpalRet,CiaPpalRet,VrPago) 
				SELECT 
				@TipDoc,@Documento,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)),CdTipVeh,NumPasajeros,Parada,PesoNeto,VrUnitario,IdRuta,Referencia1,Referencia2,
				Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,CdTipRuta,
				CdTipServicio,DiasDisp,VrDia,TipCtn,NumCnt,IdCiaCnt,ItemCnt,CantVeh,Retorno,VrMonitor,CantMonitor,TipoTarifa,Dias,Itinerario,
				VLargo,ItemPpalRet,CiaPpalRet,VrPago
				FROM @Trn_TraEspPedDetalle
				WHERE (TipDoc + Convert(varchar,Pedido)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Pedido)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspPedDetalle)
			   --Eliminar los que no existen en lo que envian
			   delete from Trn_TraEspPedDetalle
			   WHERE TipDoc = @TipDoc and Pedido = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspPedDetalle)

			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Documento FROM @Trn_TraEspConceptos
			   select @item =  isnull(MAX(Item),0) from Trn_TraEspConceptos where TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia

			   --actualizar los que vienen en el tipo de dato y coincidan con los que ya estan en la tabla
			   UPDATE Trn_TraEspConceptos
			   SET 
			   TipDoc = t2.TipDoc,Documento = t2.Documento,IdCia = t2.IdCia,Item = t2.Item,
			   Descripcion = t2.Descripcion,Tarifa = t2.Tarifa,TipoConc = t2.TipoConc,
			   RubroConcep = t2.RubroConcep,Cantidad = t2.Cantidad,VrUnitario = t2.VrUnitario,
			   TarifIva = t2.TarifIva,IdConcepto = t2.IdConcepto,CdCuenta = t2.CdCuenta,
			   NitTercero = t2.NitTercero,CdTipoEsc = t2.CdTipoEsc,FechaNov = t2.FechaNov,
			   VrBase = t2.VrBase,TipoTarif = t2.TipoTarif,RefConc = t2.RefConc,Fijos = t2.Fijos,
			   IncBaseRet = t2.IncBaseRet,Referencia2 = t2.Referencia2,Referencia3 = t2.Referencia3,
			   Cliente = t2.Cliente,Conductor = t2.Conductor,Vehiculo=t2.Vehiculo,ItemDoc=t2.ItemDoc,
			   IdVehiculo = t2.IdVehiculo
		       FROM Trn_TraEspConceptos t1
			   JOIN @Trn_TraEspConceptos t2 ON t1.TipDoc = t2.TipDoc and t1.Documento = t2.Documento and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Documento = t2.Documento and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspConceptos(
			    TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo)
			   SELECT 
			    @TipDoc, @Documento, @IdCia, (@Item + ROW_NUMBER() OVER(ORDER BY Item ASC)), Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
			   FROM @Trn_TraEspConceptos
			   WHERE (TipDoc + Convert(varchar,Documento)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Documento)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspConceptos)
			   --Eliminar los que no existen en el tipo de dato
			   delete from Trn_TraEspConceptos
			   WHERE TipDoc = @TipDoc and Documento = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspConceptos)

			   end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN

				IF(EXISTS(SELECT * FROM @Trn_TraEspPedido))
				begin
				INSERT INTO Trn_TraEspPedido(
				TipDoc,Pedido,IdCia,Fecha,FechaVence,FecInicio,FecFinal,IdCliente,IdAgencia,IdVend,
				IdTarifCom,TipoContrato,TipoPago,Modalidad,Vigencia,VrCobro,VrPagos,VrCargos,VrDctos,
				VrIva,CdDescuento,Presupuesto,CantPasajeros,Cantidad,Peso,IdMneda,
				NumAprob,IdCiaApr,FecAprob,EsLicitacion,OrigenAdd,Anulado,FecDev,Observacion,
				IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,CdCarga,VrEditado,CantDias
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,Fecha,FechaVence,FecInicio,FecFinal,IdCliente,IdAgencia,IdVend,
				IdTarifCom,TipoContrato,TipoPago,Modalidad,Vigencia,VrCobro,VrPagos,VrCargos,VrDctos,
				VrIva,CdDescuento,Presupuesto,CantPasajeros,Cantidad,Peso,IdMneda,
				NumAprob,IdCiaApr,FecAprob,EsLicitacion,OrigenAdd,Anulado,FecDev,Observacion,
				IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario,CdCarga,VrEditado,CantDias
				FROM @Trn_TraEspPedido
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspPedAnexo))
				begin
				INSERT INTO Trn_TraEspPedAnexo(
				TipDoc,Pedido,IdCia,NomCliente,DirCliente,NomContacto,TelContacto,emlContacto,emlCliente,DescripCarga,Clausulas
				) 
				SELECT 
				@TipDoc, @Documento, @IdCia,NomCliente,DirCliente,NomContacto,TelContacto,emlContacto,emlCliente,DescripCarga,Clausulas
				FROM @Trn_TraEspPedAnexo
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspPedDetalle))
				begin
				INSERT INTO Trn_TraEspPedDetalle(
				TipDoc,Pedido,IdCia,Item,CdTipVeh,NumPasajeros,Parada,PesoNeto,VrUnitario,IdRuta,Referencia1,Referencia2,
				Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,CdTipRuta,
				CdTipServicio,DiasDisp,VrDia,TipCtn,NumCnt,IdCiaCnt,ItemCnt,CantVeh,Retorno,VrMonitor,CantMonitor,TipoTarifa,Dias,Itinerario,VLargo
				,ItemPpalRet,CiaPpalRet,VrPago
				) 
				SELECT 
				@TipDoc,@Documento,@IdCia,Item,CdTipVeh,NumPasajeros,Parada,PesoNeto,VrUnitario,IdRuta,Referencia1,Referencia2,
				Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,CdTipRuta,
				CdTipServicio,DiasDisp,VrDia,TipCtn,NumCnt,IdCiaCnt,ItemCnt,CantVeh,Retorno,VrMonitor,CantMonitor,TipoTarifa,Dias,Itinerario,VLargo
				,ItemPpalRet,CiaPpalRet,VrPago
				FROM @Trn_TraEspPedDetalle
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspConceptos))
				BEGIN
				INSERT INTO Trn_TraEspConceptos(
				TipDoc, Documento, IdCia, Item, Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				) 
				SELECT 
				@TipDoc, @Documento, @IdCia, Item, Descripcion, Tarifa, 
				TipoConc, RubroConcep, Cantidad, VrUnitario, TarifIva, IdConcepto, 
				CdCuenta, NitTercero, CdTipoEsc, FechaNov, VrBase,TipoTarif,RefConc,Fijos,
				Referencia2, Referencia3,Cliente,Conductor,Vehiculo,ItemDoc,IdVehiculo
				FROM @Trn_TraEspConceptos
				END

			 END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 declare @Pedido int
			 select @TipDoc = TipDoc, @IdCia = IdCia,  @Pedido = Pedido from @Trn_TraEspPedido
				 DELETE FROM Trn_TraEspPedAnexo WHERE TipDoc = @TipDoc and Pedido = @Pedido and IdCia = @IdCia
				 DELETE FROM Trn_TraEspPedDetalle WHERE TipDoc = @TipDoc and Pedido = @Pedido and IdCia = @IdCia
				 DELETE FROM Trn_TraEspConceptos WHERE TipDoc = @TipDoc and Documento = @Pedido and IdCia = @IdCia
				 DELETE FROM Trn_TraEspPedido WHERE TipDoc = @TipDoc and Pedido = @Pedido and IdCia = @IdCia
			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
			  declare @IdEstado varchar(4)
			  --select @IdEstado = IdEstado from EstadoDoc where Estado = 'ANULADO'
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Pedido from @Trn_TraEspPedido
			  UPDATE Trn_TraEspPedido SET IdEstado = '9999', Anulado = '1' WHERE TipDoc = @TipDoc and Pedido = @Documento and IdCia = @IdCia
			END

			SELECT @Documento

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPicoPlaca]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 29/04/2016
-- Description:	Insertar/Actualizar PicoPlaca.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPicoPlaca]
	@Trn_TraEspPicoPlaca dataTypeTrn_TraEspPicoPlaca READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Trn_TraEspPicoPlaca
			 SET 
			 IdLocal = t2.IdLocal,Fecha = t2.Fecha, UltimoDig = t2.UltimoDig,Observacion = t2.Observacion,
			 ClaseMat = t2.ClaseMat,IdTipoVeh = t2.IdTipoVeh,Horas = t2.Horas
		     FROM Trn_TraEspPicoPlaca t1
			 JOIN @Trn_TraEspPicoPlaca t2 ON t1.Idlocal = t2.IdLocal and t1.Fecha = t2.Fecha and t1.ClaseMat = t2.ClaseMat and t1.IdTipoVeh = t2.IdTipoVeh and t1.Horas = t2.Horas
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Trn_TraEspPicoPlaca(
			 IdLocal,Fecha,UltimoDig,Observacion,ClaseMat,IdTipoVeh,Horas
			 )
			 SELECT 
			 IdLocal,Fecha,UltimoDig,Observacion,ClaseMat,IdTipoVeh,Horas
			 FROM @Trn_TraEspPicoPlaca
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DELETE FROM Trn_TraEspPicoPlaca 
			 WHERE IdLocal = (select IdLocal from @Trn_TraEspPicoPlaca) 
			 and Fecha = (select Fecha from @Trn_TraEspPicoPlaca) 
			 and ClaseMat = (select ClaseMat from @Trn_TraEspPicoPlaca) 
			 and IdTipoVeh = (select IdTipoVeh from @Trn_TraEspPicoPlaca) 
			 and Horas = (select Horas from @Trn_TraEspPicoPlaca) 
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspPrograma]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 21/10/2016
-- Description:	Insertar CRUD Programacion de vehiculos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspPrograma]
	@Trn_TraEspPrograma dataTypeTrn_TraEspPrograma READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPrograma
	@Trn_TraEspProgramaDet dataTypeTrn_TraEspProgramaDet READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspProgramaDet
	@Trn_TraEspProgramaPers dataTypeTrn_TraEspProgramaPers READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspProgramaPers
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Reserva/Cotización
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Reserva/Cotización
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Reserva/Cotización
declare @IdEstado varchar(4)
declare @item int 
declare @kmp varchar 
	BEGIN TRAN
		BEGIN TRY

			--Seleccionar Variables
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia FROM @Trn_TraEspPrograma
				SELECT @Documento = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia

				IF(@Documento <> '')
					UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
				ELSE
				BEGIN
					SELECT @Documento = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			end

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			   IF(EXISTS(SELECT * FROM @Trn_TraEspPrograma))
			   begin
			   UPDATE Trn_TraEspPrograma
			   SET 
			   TipDoc = t2.TipDoc,Programa = t2.Programa,IdCia = t2.IdCia,
			   Fecha = t2.Fecha,OrigenAdd = t2.OrigenAdd,Anulado = t2.Anulado,
			   FecDev = t2.FecDev,IdEstado = t2.IdEstado,TimeSys = t2.TimeSys,
			   FecUpdate = t2.FecUpdate,IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario
		       FROM Trn_TraEspPrograma t1
			   JOIN @Trn_TraEspPrograma t2 ON t1.TipDoc = t2.TipDoc and t1.Programa = t2.Programa and t1.IdCia = t2.IdCia
			   end

			   IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Programa FROM @Trn_TraEspProgramaDet
			   select @item =  isnull(MAX(Item),0) from Trn_TraEspProgramaDet where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia

			   --se actuallizan los que vienen en el tipo de dato y coincidan con los que estan el la tabla
			   UPDATE Trn_TraEspProgramaDet
			   SET 
			   TipDoc = t2.TipDoc,Programa = t2.Programa,IdCia = t2.IdCia,Item = t2.Item,
			   FechaInicio = t2.FechaInicio,FechaFin = t2.FechaFin,TipDocRes = t2.TipDocRes,
			   Reserva = t2.Reserva,IdCiaRes = t2.IdCiaRes,ItemRes = t2.ItemRes,IdOrigen = t2.IdOrigen,
			   IdDestino = t2.IdDestino,IdVehiculo = t2.IdVehiculo,
			   CdTipVeh = t2.CdTipVeh,IdConductor = t2.IdConductor,NumPasajeros = t2.NumPasajeros,TipDocFuec = t2.TipDocFuec,
			   NumFuec = t2.NumFuec,IdCiaFuec = t2.IdCiaFuec,TipDocOdp = t2.TipDocOdp,NumOdp = t2.NumOdp,
			   IdCiaOdp = t2.IdCiaOdp,FechaOdp=t2.FechaOdp,IdNovedad = t2.IdNovedad,Novedad = t2.Novedad,Cumplido = t2.Cumplido,FecIniCump = t2.FecIniCump, FecFinCump = t2.FecFinCump,
			   VrCobro = t2.VrCobro, VrPagos = t2.VrPagos,DiasDisp= t2.DiasDisp,Parada= t2.Parada,CdTipServicio= t2.CdTipServicio,
			   DirOrigen= t2.DirOrigen,DirDestino= t2.DirDestino,IdRuta= t2.IdRuta,CdTipRuta= t2.CdTipRuta,PesoNeto= t2.PesoNeto,EstadoItem=t2.EstadoItem,
			   VrMonitor=t2.VrMonitor,CantMonitor=t2.CantMonitor,VrRecorrido= t2.VrRecorrido, Observacion= t2.Observacion,VLargo = t2.VLargo
		       FROM Trn_TraEspProgramaDet t1
			   JOIN @Trn_TraEspProgramaDet t2 ON t1.TipDoc = t2.TipDoc and t1.Programa = t2.Programa and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Programa = t2.Programa and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspProgramaDet(
			   TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			   IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			   IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
			   CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
	           ) 
			   SELECT 
			   @TipDoc,@Documento,@IdCia,(@item + ROW_NUMBER() OVER(ORDER BY Item ASC)),FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			   IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			   IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
			   CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
			   FROM @Trn_TraEspProgramaDet
			   WHERE (TipDoc + Convert(varchar,Programa)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Programa)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspProgramaDet)
			    
			   --Actualizar estado de vehiculo CUANDO NO TIENE NOVEDAD
			   UPDATE Vehiculos
			   SET IdEstado = '0002'
			   FROM Vehiculos v
			   JOIN (SELECT DISTINCT IdVehiculo FROM @Trn_TraEspProgramaDet where IdNovedad = '0' and Cumplido = 0) AS pd ON v.IdVehiculo = pd.IdVehiculo 
			   WHERE v.IdVehiculo = pd.IdVehiculo 


			   --Actualizar estado de vehiculo CUANDO TENGA NOVEDAD DE TIPO VEHICULO
			   ----DECLARE @IDNOV VARCHAR(4)
			   ----SELECT @IDNOV = IdNovedad FROM @Trn_TraEspProgramaDet
			   ----IF(UPPER((select Tipo from TiposNovPgr where IdNovedad = @IDNOV)) = 'VEHICULO')
			   ----BEGIN
				  ---- UPDATE Vehiculos
				  ---- SET IdEstado = (select IdEstado from TiposNovPgr where IdNovedad = pd.IdNovedad and Tipo = 'VEHICULO')
				  ---- FROM Vehiculos v
				  ---- JOIN @Trn_TraEspProgramaDet pd ON v.IdVehiculo = pd.IdVehiculo and pd.IdNovedad != '0' and pd.Cumplido = 0
				  ---- WHERE v.IdVehiculo = pd.IdVehiculo 
			   ----END

			   --se cambia el cursor de Joe el día 25 de octubre porque demoraba la actualización, cuando la prograamciónn tiene muchos ítems, cambio opr JohnRoa-------
				--   declare @acveh varchar(11)
				--   declare @acidnov varchar(4)
				----declare @acItem int
				
				--DECLARE acvehic CURSOR
				--FOR SELECT IdVehiculo,IdNovedad FROM @Trn_TraEspProgramaDet where IdNovedad != '0' and Cumplido = 0
				--OPEN acvehic
				--FETCH NEXT FROM acvehic INTO @acveh,@acidnov
				--WHILE @@FETCH_STATUS = 0
				--BEGIN
				--   UPDATE Vehiculos
				--   SET IdEstado = tn.IdEstado
				--   FROM Vehiculos v, TiposNovPgr tn
				--   WHERE v.IdVehiculo = @acveh and tn.IdNovedad = @acidnov and tn.Tipo = 'VEHICULO'
				--FETCH NEXT FROM acvehic INTO @acveh,@acidnov
				--END
				--CLOSE acvehic
				--DEALLOCATE acvehic
				-------------------------------------------------------------John Roa --------------------------------------------------------------------------
				-----------------------------------Esto reemplaza al cursor anterior----------------------------------------------------------------------------
				--UPDATE Vehiculos
				--SET IdEstado = tn.IdEstado
				--FROM Vehiculos v
				--JOIN @Trn_TraEspProgramaDet pd ON v.IdVehiculo = pd.IdVehiculo and pd.IdNovedad != '0' and pd.Cumplido = 0
				--JOIN TiposNovPgr AS tn ON tn.IdNovedad = pd.IdNovedad and tn.Tipo = 'VEHICULO'
				--WHERE v.IdVehiculo = pd.IdVehiculo

				UPDATE Vehiculos
				SET IdEstado = tn.IdEstado
				FROM Vehiculos v
				JOIN (SELECT DISTINCT IdVehiculo, IdNovedad FROM @Trn_TraEspProgramaDet WHERE  IdNovedad != '0' and Cumplido = 0) AS pd ON v.IdVehiculo = pd.IdVehiculo 
				JOIN TiposNovPgr AS tn ON tn.IdNovedad = pd.IdNovedad and tn.Tipo = 'VEHICULO'
				WHERE v.IdVehiculo = pd.IdVehiculo
				-------------------------------------------------------------------------------------------------------------------------------------------------
			   --ACTUALIZAR RESERVAS 
			   ----UPDATE Trn_TraEspResDetalle
			   ----SET EstadoItem = 'PROGRAMADA'
			   ----FROM Trn_TraEspResDetalle p
			   ----JOIN @Trn_TraEspProgramaDet d ON p.TipDoc = d.TipDocRes  and p.Reserva = d.Reserva and p.IdCia = d.IdCiaRes and p.Item = d.ItemRes
			   ----WHERE d.TipDoc = @TipDoc and d.Programa = @Documento and d.IdCia = @IdCia and d.IdNovedad = '0' and d.Cumplido = 0

			   	--se cambia el cursor de Joe el día 25 de octubre porque demoraba la actualización, cuando la prograamciónn tiene muchos ítems, cambio opr JohnRoa-------
			 --  	declare @acReserva int
				--declare @acCiaRes varchar(2)
				--declare @acItem int
				
				--DECLARE acres CURSOR
				--FOR SELECT Reserva,IdCiaRes,ItemRes FROM @Trn_TraEspProgramaDet where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia and IdNovedad = '0' and Cumplido = 0
				--OPEN acres
				--FETCH NEXT FROM acres INTO @acReserva,@acCiaRes,@acItem
				--WHILE @@FETCH_STATUS = 0
				--BEGIN
				--	UPDATE Trn_TraEspResDetalle
				--	SET EstadoItem = 'PROGRAMADA'
				--	FROM Trn_TraEspResDetalle p
				--	WHERE  p.TipDoc = 'RES' and p.Reserva = @acReserva and p.IdCia = @acCiaRes and p.Item = @acItem
				--	-- Fecha:20/11/2017 Se desactiva esta condición porque al entrar 2 usuarios a hacer la misma operación queda desactualizado 
				--	-- el número de consecutivo que se obtiene en el software y se actualizaría reservas del primera operación, en este caso, quedaría mal para la segunada transacción.
				--	--WHERE d.TipDoc = @TipDoc and d.Programa = @Documento and d.IdCia = @IdCia
				--FETCH NEXT FROM acres INTO @acReserva,@acCiaRes,@acItem
				--END
				--CLOSE acres
				--DEALLOCATE acres
				-------------------------------------------------------------John Roa --------------------------------------------------------------------------
				-----------------------------------Esto reemplaza al cursor anterior----------------------------------------------------------------------------
				--UPDATE p
				--SET p.EstadoItem = 'PROGRAMADA'
				--FROM Trn_TraEspResDetalle p
				--JOIN @Trn_TraEspProgramaDet pd ON p.TipDoc = pd.TipDocRes and p.IdCia = pd.IdCiaRes and p.Item = pd.ItemRes
				--WHERE  p.TipDoc = 'RES' and p.Reserva = pd.Reserva and p.IdCia = pd.IdCiaRes and p.Item = pd.ItemRes

				UPDATE p
				SET p.EstadoItem = 'PROGRAMADA'
				FROM (SELECT DISTINCT TipDocRes, Reserva, IdCiaRes, ItemRes FROM @Trn_TraEspProgramaDet where IdNovedad = '0' and Cumplido = 0) AS pd 
				JOIN  Trn_TraEspResDetalle p ON p.TipDoc = pd.TipDocRes and p.Reserva = pd.Reserva and p.IdCia = pd.IdCiaRes and p.Item = pd.ItemRes
				WHERE  p.TipDoc = 'RES' and p.Reserva = pd.Reserva and p.IdCia = pd.IdCiaRes and p.Item = pd.ItemRes 
				------------------------------------------------------------------------------------------------------------------------------------------------

			   --ACTUALIZAR Vehiculos en ProgramaPers 
			   UPDATE Trn_TraEspProgramaPers
			   SET IdVehiculo = d.IdVehiculo
			   FROM Trn_TraEspProgramaPers p
			   JOIN @Trn_TraEspProgramaDet d ON p.TipDoc = d.TipDoc  and p.Programa = d.Programa and p.IdCia = d.IdCia and p.Item = d.Item
			   WHERE p.TipDoc = d.TipDoc and p.Programa = d.Programa and p.IdCia = d.IdCia and p.Item= d.Item and d.IdNovedad = '0' and d.Cumplido = 0

			   end

			   IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaPers))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Programa, @item = Item FROM @Trn_TraEspProgramaPers
			
			  --Eliminar los registros
			   delete from Trn_TraEspProgramaPers where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia and Item = @item 
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspProgramaPers(
			   TipDoc,Programa,IdCia,Item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
	           ) 
			   SELECT 
			   @TipDoc,@Documento,@IdCia,@item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
			   FROM @Trn_TraEspProgramaPers
			   			   
			   end

			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN

				IF(EXISTS(SELECT * FROM @Trn_TraEspPrograma))
				begin
				INSERT INTO Trn_TraEspPrograma(
				TipDoc,Programa,IdCia,Fecha,OrigenAdd,Anulado,FecDev,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,Fecha,OrigenAdd,Anulado,FecDev,IdEstado,TimeSys,FecUpdate,IdCiaCrea,IdUsuario
				FROM @Trn_TraEspPrograma
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
				begin
				INSERT INTO Trn_TraEspProgramaDet(
			    TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			    IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			    IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
				CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
				) 
			    SELECT 
			    @TipDoc,@Documento,@IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			    IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			    IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
				CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
			    FROM @Trn_TraEspProgramaDet
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaPers))
				begin
				INSERT INTO Trn_TraEspProgramaPers(
			    TipDoc,Programa,IdCia,Item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
				) 
			    SELECT 
			    @TipDoc,@Documento,@IdCia,Item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
			    FROM @Trn_TraEspProgramaPers
				end

				--ACTUALIZAR VEHICULOS 
				UPDATE Vehiculos
				SET IdEstado = '0002'
				FROM Vehiculos v
				JOIN @Trn_TraEspProgramaDet pd ON v.IdVehiculo = pd.IdVehiculo 
				WHERE v.IdVehiculo = pd.IdVehiculo --AND pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia

				--ACTUALIZAR RESERVAS 
				declare @actReserva int
				declare @actCiaRes varchar(2)
				declare @actItem int
				
				DECLARE actres CURSOR
				FOR SELECT Reserva,IdCiaRes,ItemRes FROM @Trn_TraEspProgramaDet
				OPEN actres
				FETCH NEXT FROM actres INTO @actReserva,@actCiaRes,@actItem
				WHILE @@FETCH_STATUS = 0
				BEGIN
					UPDATE Trn_TraEspResDetalle
					SET EstadoItem = 'PROGRAMADA'
					FROM Trn_TraEspResDetalle p
					WHERE  p.TipDoc = 'RES' and p.Reserva = @actReserva and p.IdCia = @actCiaRes and p.Item = @actItem
					-- Fecha:20/11/2017 Se desactiva esta condición porque al entrar 2 usuarios a hacer la misma operación queda desactualizado 
					-- el número de consecutivo que se obtiene en el software y se actualizaría reservas del primera operación, en este caso, quedaría mal para la segunada transacción.
					--WHERE d.TipDoc = @TipDoc and d.Programa = @Documento and d.IdCia = @IdCia
				FETCH NEXT FROM actres INTO @actReserva,@actCiaRes,@actItem
				END
				CLOSE actres
				DEALLOCATE actres

			 END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 declare @Programa int
			 select @TipDoc = TipDoc, @IdCia = IdCia,  @Programa = Programa from @Trn_TraEspPrograma
			 DELETE FROM Trn_TraEspProgramaPers WHERE TipDoc = @TipDoc and Programa = @Programa and IdCia = @IdCia
			 DELETE FROM Trn_TraEspProgramaDet WHERE TipDoc = @TipDoc and Programa = @Programa and IdCia = @IdCia
			 DELETE FROM Trn_TraEspPrograma WHERE TipDoc = @TipDoc and Programa = @Programa and IdCia = @IdCia
			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
			  --select @IdEstado = IdEstado from EstadoDoc where Estado = 'ANULADO'
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Programa from @Trn_TraEspPrograma
			  UPDATE Trn_TraEspPrograma SET IdEstado = '9999',Anulado = '1' WHERE TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia

			  --ACTUALIZAR VEHICULOS 
			  UPDATE Vehiculos
			  SET IdEstado = '0001'
			  FROM Vehiculos v
			  JOIN Trn_TraEspProgramaDet pd ON v.IdVehiculo = pd.IdVehiculo and pd.IdNovedad = '0'
			  WHERE v.IdVehiculo = pd.IdVehiculo AND pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia

			  -- --ACTUALIZAR Reservas 
			  --UPDATE Trn_TraEspResDetalle
			  --SET 
			  --FROM Trn_TraEspResDetalle rd
			  --JOIN Trn_TraEspProgramaDet pd ON pd.TipDocRes = rd.TipDoc and rd.Reserva = pd.Reserva and pd.IdCiaRes = rd.IdCia
			  ----WHERE v.IdVehiculo = pd.IdVehiculo AND pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia
			END

			--CERRAR PROGRAMACIÓN
			IF(@operacion = 'c')
			BEGIN
			  DECLARE @cFechaProg date
			  DECLARE @cthirtydaysago DATE
			  declare @date date
			  select @date = Convert(date, getdate())
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Programa, @cFechaProg= FECHA from @Trn_TraEspPrograma
			  SET @cthirtydaysago = DATEADD(DAY,-30,@cFechaProg)

			  ------------------------------------------------------- Inicio Sección para VIAJES NO LARGOS / VIAJES LARGOS-------------------------------------------
			  ------------------------------------------------------- Inicio Sección para verificacion de TiposCalendarPgr y lo de Incluir Festivos -------------------------------------------
			  --Actualizar las reservasdet al estado XLIQUIDAR, cuando tienen tiposcalendarpgr
			  --verficar que el dia se encuentre en tiposcalendarpgr a través de una funcion sql
			  --VERIFICAR SI LA SIGUIENTE PROGRAMACION ES IGUAL A LA FECHA FINAL Y SI ESTA ES FESTIVA(VERIFICAR SI ESTA INCLUIDO EL FESTIVO EN TIPOSCALENDARPGR)
			  
			  DECLARE @Trn_TraEspProgramaDet2 dataTypeTrn_TraEspProgramaDet	  
			  INSERT INTO @Trn_TraEspProgramaDet2(
			  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
			  CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
			  ) 
			  select 
			  V.TipDoc,V.Programa,V.IdCia,V.Item,FechaInicio,FechaFin,TipDocRes,V.Reserva,IdCiaRes,ItemRes,
			  IdOrigen,IdDestino,V.IdVehiculo,V.CdTipVeh,V.IdConductor,V.NumPasajeros,TipDocFuec,NumFuec,
			  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,V.Cumplido,FecIniCump,FecFinCump,
			  V.VrCobro,V.VrPagos,V.DiasDisp,V.Parada,V.CdTipServicio,V.DirOrigen,V.DirDestino,V.IdRuta,V.CdTipRuta,
			  V.PesoNeto,V.EstadoItem,V.VrMonitor,V.CantMonitor,V.VrRecorrido,Observacion,V.VLargo		
			  FROM Trn_TraEspProgramaDet  v 
			  --from 
			  --(
				 -- SELECT 
				 -- TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
				 -- IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
				 -- IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
				 -- CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
				 -- FROM Trn_TraEspProgramaDet  where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia and VLargo = 0 and IdNovedad = 0
				  --UNION
				  --SELECT 
				  --TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
				  --IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
				  --IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
				  --CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
				  --FROM Trn_TraEspProgramaDet d where  d.VLargo = 1 and D.IdNovedad = '0' and (Convert(DATE,d.FechaFin) BETWEEN @cthirtydaysago and @cFechaProg)
			  --) as v 
			  JOIN Trn_TraEspResDetalle t2 ON t2.TipDoc = V.TipDocRes and t2.Reserva = V.Reserva and t2.IdCia = V.IdCiaRes and t2.Item = V.ItemRes and (t2.EstadoItem ='PROGRAMADA' or (t2.EstadoItem = 'FACTURADA' and t2.Factura > 0))
			  --04/07/2018 - 05/07/2018 Se cambia el Join(Abajo por el de Arriba) para tener en cuenta aquellas reservas que se facturan antes de Cerrar las Programaciones
			  --JOIN Trn_TraEspResDetalle t2 ON t2.TipDoc = V.TipDocRes and t2.Reserva = V.Reserva and t2.IdCia = V.IdCiaRes and t2.Item = V.ItemRes and t2.EstadoItem = 'PROGRAMADA'
			  WHERE v.TipDoc = @TipDoc and v.Programa = @Documento and v.IdCia = @IdCia and v.VLargo = 0 and v.IdNovedad = 0 and (Convert(DATE,@date) >= Convert(DATE,t2.FecDestino))

			  declare @xlqTipDoc varchar(3),@xlqTipDocRes varchar(3), @xlqPrograma int, @xlqCiaPgr varchar(2), @xlqItemPgr int,@fechaitem date
			  declare @xlqReserva int,@xlqCiares varchar(2),@xlqItemRes int
			  DECLARE cerrarlq CURSOR
			  FOR SELECT p.TipDoc,p.Programa,p.IdCia,p.Item,Convert(date,p.FechaFin),p.Reserva,p.IdCiaRes,p.ItemRes 
			  FROM @Trn_TraEspProgramaDet2 p JOIN trn_traespresdetalle r on r.TipDoc = p.TipDocRes and r.Reserva = p.Reserva and r.IdCia = p.IdCiaRes and r.Item = p.ItemRes and (r.EstadoItem ='PROGRAMADA' or (r.EstadoItem = 'FACTURADA' and r.Factura > 0))
			  --04/07/2018 - 05/07/2018 Se cambia el Join(Abajo por el de Arriba) para tener en cuenta aquellas reservas que se facturan antes de Cerrar las Programaciones
			  --FROM @Trn_TraEspProgramaDet2 p JOIN trn_traespresdetalle r on r.TipDoc = p.TipDocRes and r.Reserva = p.Reserva and r.IdCia = p.IdCiaRes and r.Item = p.ItemRes and r.EstadoItem = 'PROGRAMADA'
			  OPEN cerrarlq
			  FETCH NEXT FROM cerrarlq INTO @xlqTipDoc,@xlqPrograma,@xlqCiaPgr,@xlqItemPgr,@fechaitem,@xlqReserva,@xlqCiaRes,@xlqItemRes
			  WHILE @@FETCH_STATUS = 0
			  BEGIN

			  declare @EsFest bit = '0'
			  declare @DI varchar(max)
			  declare @DI2 varchar(max)
			  declare @fechafin date
			  declare @DIAS varchar(max)
			  declare @IncFest bit
			  declare @valor DATE = Convert(date, dateadd(day,1,@fechaitem))
			  declare @resultado INT = 0
			  declare @prox INT = 0

			  select @fechafin = Convert(date,r.FechaFin), @DIAS = tc.Dias, @IncFest = ISNULL(tc.IncFestivo,0)
			  from Trn_TraEspResDetalle rd 
			  inner join Trn_TraEspReservas r on r.Reserva=rd.Reserva and r.IdCia=rd.IdCia
			  left join TiposCalendarPgr tc on tc.Codigo = rd.Codigo
			  where rd.Reserva = @xlqReserva and rd.IdCia = @xlqCiaRes and rd.Item = @xlqItemRes and rd.Codigo <> ''
		  			 			  			 
			  IF(datediff(day,@fechaitem, @fechafin) <= 7)
			  BEGIN
			
				WHILE ((@valor <= @fechafin) and (@resultado = 0))
				BEGIN
				   SET @DI = Datename(DW,(@valor))
				  
				   IF (@DI = 'Miércoles')
					Set @DI = 'Miercoles'
				   ELSE IF (@DI = 'Sábado')
					Set @DI = 'Sabado'
				   
				   --verficar que el dia se encuentre en tiposcalendarpgr a través de una funcion sql 		  	
				   SELECT @resultado = 1 WHERE @DI in (SELECT splitdata FROM FuncEspSplit(@DIAS,'-'))
				   SET @valor = dateadd(day,1,@valor)
				END	
										    
			  END

			  IF (@resultado = 0) 
				UPDATE Trn_TraEspResDetalle SET EstadoItem = 'XLIQUIDAR' WHERE Reserva = @xlqReserva and IdCia = @xlqCiaRes and Item = @xlqItemRes
			  
			  --VERIFICAR SI LA SIGUIENTE PROGRAMACION ES IGUAL A LA FECHA FINAL Y SI ESTA ES FESTIVA(VERIFICAR SI ESTA INCLUIDO EL FESTIVO EN TIPOSCALENDARPGR)
			  IF(@IncFest = '0')
			  BEGIN
				SET @fechaitem = dateadd(day,1,@fechaitem)
				declare @siguiente int = 1
				WHILE ((@fechaitem <= @fechafin) and @siguiente = 1)
				BEGIN
					SET @DI = Datename(DW,(@fechaitem))
					IF (@DI = 'Miércoles')
					Set @DI = 'Miercoles'
				    ELSE IF (@DI = 'Sábado')
					Set @DI = 'Sabado'

					SELECT @prox = 1 WHERE @DI in (SELECT splitdata FROM FuncEspSplit(@DIAS,'-'))

					IF(@prox = 1)
					BEGIN 
						select @EsFest = '1' from Calndario where FechaDia in (@fechaitem) and TipoFtvo = 'FES'

						IF((@fechaitem = @fechafin) and @EsFest = '1')
						BEGIN
						 UPDATE Trn_TraEspResDetalle SET EstadoItem = 'XLIQUIDAR' WHERE Reserva = @xlqReserva and IdCia = @xlqCiaRes and Item = @xlqItemRes
						 SET @siguiente = 0	
						END
						ELSE 
						 SET @siguiente = 0						 
					END

					--Aumentar @fechaitem
					SET @fechaitem = dateadd(day,1,@fechaitem)
				END
			  END

			  FETCH NEXT FROM cerrarlq INTO @xlqTipDoc,@xlqPrograma,@xlqCiaPgr,@xlqItemPgr,@fechaitem,@xlqReserva,@xlqCiaRes,@xlqItemRes
			  END
			  CLOSE cerrarlq
			  DEALLOCATE cerrarlq

			  --cerrar las programaciones y programacion detalle
			  UPDATE Trn_TraEspPrograma SET IdEstado = '9998' WHERE TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia
			  
			  UPDATE Trn_TraEspProgramaDet 
			  SET EstadoItem = '0' 
			  from Trn_TraEspProgramaDet pd
			  JOIN @Trn_TraEspProgramaDet2 pdv on pd.TipDoc = pdv.TipDoc and pd.Programa = pdv.Programa and pd.IdCia = pdv.IdCia --WHERE TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia AND VLargo = 0

			  --Actualizar las reservasdet al estado XLIQUIDAR, las que cumplan con la condición de que la fecha sea igual al dia actual
			  DECLARE @auxTrn_TraEspProgramaDet2 dataTypeTrn_TraEspProgramaDet 
			  INSERT INTO @auxTrn_TraEspProgramaDet2(
			  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,
			  FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,CdTipServicio,DirOrigen,DirDestino,IdRuta,
			  CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
			  ) 
			  select 
			  V.TipDoc,V.Programa,V.IdCia,V.Item,FechaInicio,FechaFin,TipDocRes,V.Reserva,IdCiaRes,ItemRes,
			  IdOrigen,IdDestino,V.IdVehiculo,V.CdTipVeh,V.IdConductor,V.NumPasajeros,TipDocFuec,NumFuec,
			  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,V.Cumplido,FecIniCump,FecFinCump,
			  V.VrCobro,V.VrPagos,V.DiasDisp,V.Parada,V.CdTipServicio,V.DirOrigen,V.DirDestino,V.IdRuta,V.CdTipRuta,
			  V.PesoNeto,V.EstadoItem,V.VrMonitor,V.CantMonitor,V.VrRecorrido,Observacion,V.VLargo				
			  from 
			  (
				  SELECT 
				  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
				  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
				  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,
				  FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,CdTipServicio,DirOrigen,DirDestino,IdRuta,
				  CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
				  FROM Trn_TraEspProgramaDet  where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia and VLargo = 0 and IdNovedad = '0'
				  UNION
				  SELECT 
				  TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
				  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
				  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,
				  FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,CdTipServicio,DirOrigen,DirDestino,IdRuta,
				  CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
				  FROM Trn_TraEspProgramaDet d where d.VLargo = 1 and IdNovedad = '0'  and (Convert(DATE,d.FechaFin) BETWEEN @cthirtydaysago and @cFechaProg)
			  ) as v
			  JOIN Trn_TraEspResDetalle t2 on t2.TipDoc = V.TipDocRes and t2.Reserva = V.Reserva and t2.IdCia = V.IdCiaRes and t2.Item = V.ItemRes and (t2.EstadoItem ='PROGRAMADA' or (t2.EstadoItem = 'FACTURADA' and t2.Factura > 0))
			  --04/07/2018 - 05/07/2018 Se cambia el Join(Abajo por el de Arriba) para tener en cuenta aquellas reservas que se facturan antes de Cerrar las Programaciones
			  --JOIN Trn_TraEspResDetalle t2 on t2.TipDoc = V.TipDocRes and t2.Reserva = V.Reserva and t2.IdCia = V.IdCiaRes and t2.Item = V.ItemRes and t2.EstadoItem = 'PROGRAMADA'
			  where (Convert(date,@date) >= Convert(date,t2.FecDestino))

			  declare @lqTipDocRes varchar(3), @lqReserva int,@lqCiares varchar(2),@lqItemRes int 
			  DECLARE cerrarOtr CURSOR
			  FOR SELECT Reserva, IdCiaRes, ItemRes FROM @auxTrn_TraEspProgramaDet2
			  OPEN cerrarOtr
			  FETCH NEXT FROM cerrarOtr INTO @lqReserva,@lqCiaRes,@lqItemRes
			  WHILE @@FETCH_STATUS = 0
			  BEGIN
				
				UPDATE Trn_TraEspResDetalle
				SET EstadoItem = 'XLIQUIDAR'
				from Trn_TraEspResDetalle rd
				where rd.Reserva = @lqReserva and rd.IdCia = @lqCiaRes and rd.Item = @lqItemRes and (Convert(date,@date) >= Convert(date,rd.FecDestino))

				FETCH NEXT FROM cerrarOtr INTO @lqReserva,@lqCiaRes,@lqItemRes
			  END
			  CLOSE cerrarOtr
			  DEALLOCATE cerrarOtr
			  -------------------------------------------------------------------------------------------------------------------------------------------

			  --actualizar vehiculos
			  select @kmp = Valor from adm_opciones where IdOpc = 'kmp'
			  IF(@kmp = '2')
			  BEGIN
				UPDATE Vehiculos 
				SET Km2Actual = (Km2Actual + (SELECT Distkmt FROM Rutas WHERE IdRuta = pd.IdRuta))
				FROM Vehiculos v
				JOIN @Trn_TraEspProgramaDet2 pd ON pd.IdVehiculo = v.IdVehiculo --and pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia
			  END

			  --Actualizar fechas de servicio
			  UPDATE Vehiculos 
			  SET FecPriServ = CASE WHEN FecPriServ <> NULL THEN v.FecPriServ ELSE pd.FecIniCump END, FecUltServ = pd.FecFinCump
			  FROM Vehiculos v
			  JOIN @Trn_TraEspProgramaDet2 pd on v.IdVehiculo = pd.IdVehiculo --and pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia

			  --Actualizar estado de vehiculo
			  UPDATE Vehiculos 
			  SET IdEstado = '0001'
			  FROM Vehiculos v
			  JOIN @Trn_TraEspProgramaDet2 pd on v.IdVehiculo = pd.IdVehiculo and pd.IdNovedad = '0' --and pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia
			  where v.IdEstado = '0002' 

			  ------------------------------------------------------- Fin Sección para verificacion de TiposCalendarPgr y lo de Incluir Festivos ----------------------------------------------
			  ------------------------------------------------------- Fin Sección para VIAJES NO LARGOS / VIAJES LARGOS----------------------------------------------


			 -- ------------------------------------------------------- Inicio Sección para VIAJES LARGOS -------------------------------------------
			 -- ------------------------------------------------------- Inicio Sección para verificacion de TiposCalendarPgr y lo de Incluir Festivos -------------------------------------------
			 -- --Actualizar las reservasdet al estado XLIQUIDAR, cuando tienen tiposcalendarpgr
			 -- --verficar que el dia se encuentre en tiposcalendarpgr a través de una funcion sql
			 -- --VERIFICAR SI LA SIGUIENTE PROGRAMACION ES IGUAL A LA FECHA FINAL Y SI ESTA ES FESTIVA(VERIFICAR SI ESTA INCLUIDO EL FESTIVO EN TIPOSCALENDARPGR)
			 -- DECLARE @cFechaProg datetime
			 -- SELECT @cFechaProg = Fecha FROM Trn_TraEspPrograma p
			 -- JOIN (SELECT TOP 1 TipDoc,Programa,IdCia  FROM @Trn_TraEspProgramaDet) AS pd ON p.TipDoc = pd.TipDoc and p.Programa = pd.Programa and p.IdCia = pd.IdCia

			 -- DECLARE @cthirtydaysago DATETIME
			 -- SET @cthirtydaysago = DATEADD(DAY,-30,@cFechaProg)

			 -- declare @Trn_TraEspProgramaDetC dataTypeTrn_TraEspProgramaDet 
			 -- INSERT INTO @Trn_TraEspProgramaDetC(
			 -- TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			 -- IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			 -- IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
			 -- CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
			 -- ) 
			 -- SELECT 
			 -- TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
			 -- IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
			 -- IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
			 -- CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
			 -- FROM Trn_TraEspProgramaDet  where VLargo = 1  and Convert(DATE,d.FechaFin) between Convert(DATE,@cthirtydaysago) and Convert(DATE,@cFechaProg)

			 -- declare @xlqTipDoc varchar(3), @xlqPrograma int, @xlqCiaPgr varchar(2), @xlqItemPgr int,@fechaitem date
			 -- declare @xlqReserva int,@xlqCiares varchar(2),@xlqItemRes int
			 -- DECLARE cerrarlq CURSOR
			 -- FOR SELECT p.TipDoc,p.Programa,p.IdCia,p.Item,Convert(date,p.FechaFin), p.Reserva,p.IdCiaRes,p.ItemRes 
			 -- FROM @Trn_TraEspProgramaDetC p JOIN trn_traespresdetalle r on r.EstadoItem = 'PROGRAMADA' and r.TipDoc = p.TipDocRes and r.Reserva = p.Reserva and r.IdCia = p.IdCiaRes and r.Item = p.ItemRes
			 -- OPEN cerrarlq
			 -- FETCH NEXT FROM cerrarlq INTO @xlqTipDoc,@xlqPrograma,@xlqCiaPgr,@xlqItemPgr,@fechaitem,@xlqReserva,@xlqCiaRes,@xlqItemRes
			 -- WHILE @@FETCH_STATUS = 0
			 -- BEGIN

			 -- declare @EsFest bit = '0'
			 -- declare @DI varchar(max)
			 -- declare @DI2 varchar(max)
			 -- declare @fechafin date
			 -- declare @DIAS varchar(max)
			 -- declare @IncFest bit
			 -- declare @valor DATE = Convert(date, dateadd(day,1,@fechaitem))
			 -- declare @resultado INT = 0
			 -- declare @prox INT = 0

			 -- select @fechafin = Convert(date,r.FechaFin), @DIAS = tc.Dias, @IncFest = ISNULL(tc.IncFestivo,0)
			 -- from Trn_TraEspResDetalle rd 
			 -- inner join Trn_TraEspReservas r on r.Reserva=rd.Reserva and r.IdCia=rd.IdCia
			 -- left join TiposCalendarPgr tc on tc.Codigo = rd.Codigo
			 -- where rd.Reserva = @xlqReserva and rd.IdCia = @xlqCiaRes and rd.Item = @xlqItemRes and rd.Codigo <> ''
		  			 			  			 
			 -- IF(datediff(day,@fechaitem, @fechafin) <= 7)
			 -- BEGIN
			
				--WHILE ((@valor <= @fechafin) and (@resultado = 0))
				--BEGIN
				--   SET @DI = Datename(DW,(@valor))
				  
				--   IF (@DI = 'Miércoles')
				--	Set @DI = 'Miercoles'
				--   ELSE IF (@DI = 'Sábado')
				--	Set @DI = 'Sabado'
				   
				--   --verficar que el dia se encuentre en tiposcalendarpgr a través de una funcion sql 		  	
				--   SELECT @resultado = 1 WHERE @DI in (SELECT splitdata FROM FuncEspSplit(@DIAS,'-'))
				--   SET @valor = dateadd(day,1,@valor)
				--END	
										    
			 -- END

			 -- IF (@resultado = 0) 
				--UPDATE Trn_TraEspResDetalle SET EstadoItem = 'XLIQUIDAR' WHERE Reserva = @xlqReserva and IdCia = @xlqCiaRes and Item = @xlqItemRes
			  
			 -- --VERIFICAR SI LA SIGUIENTE PROGRAMACION ES IGUAL A LA FECHA FINAL Y SI ESTA ES FESTIVA(VERIFICAR SI ESTA INCLUIDO EL FESTIVO EN TIPOSCALENDARPGR)
			 -- IF(@IncFest = '0')
			 -- BEGIN
				--SET @fechaitem = dateadd(day,1,@fechaitem)
				--declare @siguiente int = 1
				--WHILE ((@fechaitem <= @fechafin) and @siguiente = 1)
				--BEGIN
				--	SET @DI = Datename(DW,(@fechaitem))
				--	IF (@DI = 'Miércoles')
				--	Set @DI = 'Miercoles'
				--    ELSE IF (@DI = 'Sábado')
				--	Set @DI = 'Sabado'

				--	SELECT @prox = 1 WHERE @DI in (SELECT splitdata FROM FuncEspSplit(@DIAS,'-'))

				--	IF(@prox = 1)
				--	BEGIN 
				--		select @EsFest = '1' from Calndario where FechaDia in (@fechaitem) and TipoFtvo = 'FES'

				--		IF((@fechaitem = @fechafin) and @EsFest = '1')
				--		BEGIN
				--		 UPDATE Trn_TraEspResDetalle SET EstadoItem = 'XLIQUIDAR' WHERE Reserva = @xlqReserva and IdCia = @xlqCiaRes and Item = @xlqItemRes
				--		 SET @siguiente = 0	
				--		END
				--		ELSE 
				--		 SET @siguiente = 0						 
				--	END

				--	--Aumentar @fechaitem
				--	SET @fechaitem = dateadd(day,1,@fechaitem)
				--END
			 -- END

			 -- FETCH NEXT FROM cerrarlq INTO @xlqTipDoc,@xlqPrograma,@xlqCiaPgr,@xlqItemPgr,@fechaitem,@xlqReserva,@xlqCiaRes,@xlqItemRes
			 -- END
			 -- CLOSE cerrarlq
			 -- DEALLOCATE cerrarlq

			 -- --cerrar las programaciones 
			 -- UPDATE Trn_TraEspPrograma SET IdEstado = '9998' WHERE TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia
			 -- UPDATE Trn_TraEspProgramaDet SET EstadoItem = '0' WHERE TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia AND VLargo = 0

			 -- --Actualizar las reservasdet al estado XLIQUIDAR, las que cumplan con la condición de que la fecha sea igual al dia actual
			 -- UPDATE Trn_TraEspResDetalle
			 -- SET EstadoItem = 'XLIQUIDAR'
		  --    FROM Trn_TraEspResDetalle t1
			 -- JOIN Trn_TraEspProgramaDet t2 ON t1.TipDoc = t2.TipDocRes and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCiaRes and t1.Item = t2.ItemRes
			 -- where (@date >= Convert(date,t1.FecDestino)) AND t2.TipDoc = @TipDoc and t2.Programa = @Documento and t2.IdCia = @IdCia and t2.VLargo = 0

			 -- --actualizar vehiculos
			  
			 -- select @kmp = Valor from adm_opciones where IdOpc = 'kmp'
			 -- IF(@kmp = '2')
			 -- BEGIN
				--UPDATE Vehiculos 
				--SET 
				--Km2Actual = (Km2Actual + (SELECT Distkmt FROM Rutas WHERE IdRuta = pd.IdRuta))
				--FROM Vehiculos v
				--JOIN Trn_TraEspProgramaDet pd ON pd.IdVehiculo = v.IdVehiculo and pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia and VLargo = 0
			 -- END

			 -- --Actualizar fechas de servicio
			 -- UPDATE Vehiculos 
			 -- SET 
			 -- FecPriServ = CASE WHEN FecPriServ <> NULL THEN v.FecPriServ ELSE pd.FecIniCump END, 
			 -- FecUltServ = pd.FecFinCump
			 -- FROM Vehiculos v
			 -- JOIN Trn_TraEspProgramaDet pd on v.IdVehiculo = pd.IdVehiculo and pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia and pd.VLargo = 0

			 -- --Actualizar estado de vehiculo
			 -- UPDATE Vehiculos 
			 -- SET 
			 -- IdEstado = '0001'
			 -- FROM Vehiculos v
			 -- JOIN Trn_TraEspProgramaDet pd on v.IdVehiculo = pd.IdVehiculo and pd.IdNovedad = '0' and pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia and pd.VLargo = 0
			 -- where v.IdEstado = '0002' 


			 -- ------------------------------------------------------- Fin Sección para verificacion de TiposCalendarPgr y lo de Incluir Festivos ----------------------------------------------
			 -- ------------------------------------------------------- Fin Sección para VIAJES LARGOS ----------------------------------------------

			END

			--ABRIR PROGRAMACIÓN
			IF(@operacion = 'o')
			BEGIN
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Programa from @Trn_TraEspPrograma

			  --abrir las programaciones 
			  UPDATE Trn_TraEspPrograma SET IdEstado = '0001' WHERE TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia

			  --Actualizar las reservasdet al estado programada porque se abre la programacion
			  UPDATE Trn_TraEspResDetalle
			  SET EstadoItem = 'PROGRAMADA'
		      FROM Trn_TraEspResDetalle t1
			  --JOIN Trn_TraEspProgramaDet t2 ON t1.TipDoc = t2.TipDocRes and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCiaRes and t1.Item = t2.ItemRes
			  --SOLO SE ABREN LAS Q ESTÉN DIFERENTE DE POR LIQUIDAR
			  JOIN Trn_TraEspProgramaDet t2 ON t1.TipDoc = t2.TipDocRes and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCiaRes and t1.Item = t2.ItemRes and t1.EstadoItem <>'XLIQUIDAR'
			  			  
			  --actualizar vehiculos
			  declare @kmpa varchar 
			  select @kmpa = Valor from adm_opciones where IdOpc = 'kmp'
			  IF(@kmpa = '2')
			  BEGIN
				UPDATE Vehiculos 
				SET 
				Km2Actual = (Km2Actual - (SELECT Distkmt FROM Rutas WHERE IdRuta = pd.IdRuta))
				FROM Vehiculos v
				JOIN Trn_TraEspProgramaDet pd ON pd.IdVehiculo = v.IdVehiculo and pd.TipDoc = @TipDoc and pd.Programa = @Documento and pd.IdCia = @IdCia
			  END

			END

			--Cumplido de Detalles y Personas
			IF(@operacion = 'f')
			BEGIN
			   IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
			   BEGIN
					-------------------------------Inicio Sección para cumplir cuando NO ES VIAJES LARGOS / VIAJES LARGOS----------------------------------------------------------------
					 --declare @date date
					 --select @date = Convert(date, getdate())
					 select top 1 @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Programa from @Trn_TraEspProgramaDet

					declare @fTipDoc varchar(MAX)
					declare @fPrograma int
					declare @fCiaPgr varchar(2)
					declare @fItemPgr int
					declare @fCumplido bit
					declare @fFecIniCump datetime
					declare @fFecFinCump datetime
					declare @fvehiculo varchar(10)
					declare @fObser varchar(MAX)
					declare @fVLargo bit 
					DECLARE @fFechaProg datetime
					declare @auxTrn_TraEspProgramaDet dataTypeTrn_TraEspProgramaDet 
					DECLARE @thirtydaysago DATETIME

					SELECT @fFechaProg = Fecha FROM Trn_TraEspPrograma p where p.TipDoc = @TipDoc and p.Programa = @Documento and p.IdCia = @IdCia										
					SET @thirtydaysago = DATEADD(DAY,-30,@fFechaProg)

					INSERT INTO @auxTrn_TraEspProgramaDet(
					TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
					IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
					IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
					CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
					) 
					select 
					TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
					IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
					IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
					CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo				
					from 
					(						
						SELECT 
						TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
						IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
						IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,VrCobro,VrPagos,DiasDisp,Parada,
						CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
						FROM @Trn_TraEspProgramaDet  where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia and VLargo = 0
						UNION
						(
						  SELECT 
						  D.TipDoc,D.Programa,D.IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
						  IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
						  IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FechaInicio,FechaFin,VrCobro,VrPagos,DiasDisp,Parada,
						  CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,('Cumplido por el sistema automáticamente por viaje largo, el día: '+ convert(varchar(30),getdate(),100) + isnull(Observacion,'')),VLargo
						  FROM Trn_TraEspProgramaDet d JOIN Trn_TraEspPrograma p ON p.TipDoc = d.TipDoc and p.Programa = d.Programa and p.IdCia = d.IdCia
						  WHERE D.VLargo = 1 and d.IdNovedad = 0 and p.Anulado = 0 and d.Cumplido = 0 and Convert(DATE,d.FechaFin) between Convert(DATE,@thirtydaysago) and Convert(DATE,@fFechaProg)
						)
					)as auxv

					DECLARE cumpserv CURSOR
					FOR SELECT TipDoc,Programa,IdCia,Item,Cumplido,FecIniCump,FecFinCump,IdVehiculo,Observacion,VLargo FROM @auxTrn_TraEspProgramaDet
					OPEN cumpserv
					FETCH NEXT FROM cumpserv INTO @fTipDoc,@fPrograma,@fCiaPgr,@fItemPgr,@fCumplido,@fFecIniCump,@fFecFinCump,@fvehiculo,@fObser,@fVLargo
					WHILE @@FETCH_STATUS = 0
					BEGIN
				   
					   --IF(@fVLargo = 0)
					   --BEGIN
						   UPDATE Trn_TraEspProgramaDet
						   SET Cumplido = '1',FecIniCump = @fFecIniCump, FecFinCump = @fFecFinCump, Observacion = @fObser			   
						   FROM Trn_TraEspProgramaDet 
						   WHERE TipDoc = @fTipDoc and Programa = @fPrograma and IdCia = @fCiaPgr  and Item = @fItemPgr

						   UPDATE Trn_TraEspProgramaPers
						   SET Cumplido = '1'
						   from Trn_TraEspProgramaPers
						   WHERE TipDoc = @fTipDoc and Programa = @fPrograma and IdCia = @fCiaPgr  and Item = @fItemPgr

						   --Actualizar estado de vehiculo
						   UPDATE Vehiculos SET IdEstado = '0001' FROM Vehiculos v WHERE v.IdEstado = '0002' and v.IdVehiculo = @fvehiculo
					   --END
				
					FETCH NEXT FROM cumpserv INTO @fTipDoc,@fPrograma,@fCiaPgr,@fItemPgr,@fCumplido,@fFecIniCump,@fFecFinCump,@fvehiculo,@fObser,@fVLargo
					END
					CLOSE cumpserv
					DEALLOCATE cumpserv

					---------------------------------------------------------------------Código Anterior-----------------------------------------------------------
					-------------------------------Fin Sección para el requerimiento cuando NO ES VIAJES LARGOS / VIAJES LARGOS----------------------------------------------------------------
					------------------------------Inicio Sección para cumplir cuando ES VIAJES LARGOS---------------------------------------------------------------------

					--SELECT @fFechaProg = Fecha FROM Trn_TraEspPrograma p
					--JOIN (SELECT TOP 1 TipDoc,Programa,IdCia  FROM @Trn_TraEspProgramaDet) AS pd ON p.TipDoc = pd.TipDoc and p.Programa = pd.Programa and p.IdCia = pd.IdCia

					--DECLARE @thirtydaysago DATETIME
					--SET @thirtydaysago = DATEADD(DAY,-30,@fFechaProg)

					--DECLARE @Trn_TraEspProgramaDet3 dataTypeTrn_TraEspProgramaDet 

					--INSERT INTO @Trn_TraEspProgramaDet3(
					--TipDoc,Programa,IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
					--IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
					--IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,
					--VrCobro,VrPagos,DiasDisp,Parada,CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,
					--EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
					--) 
					--SELECT 
					--D.TipDoc,D.Programa,D.IdCia,Item,FechaInicio,FechaFin,TipDocRes,Reserva,IdCiaRes,ItemRes,
					--IdOrigen,IdDestino,IdVehiculo,CdTipVeh,IdConductor,NumPasajeros,TipDocFuec,NumFuec,
					--IdCiaFuec,TipDocOdp,NumOdp,IdCiaOdp,FechaOdp,IdNovedad,Novedad,Cumplido,FecIniCump,FecFinCump,
					--VrCobro,VrPagos,DiasDisp,Parada,CdTipServicio,DirOrigen,DirDestino,IdRuta,CdTipRuta,PesoNeto,
					--EstadoItem,VrMonitor,CantMonitor,VrRecorrido,Observacion,VLargo
					--FROM Trn_TraEspProgramaDet d 					 
					--JOIN Trn_TraEspPrograma p ON p.TipDoc = d.TipDoc and p.Programa = d.Programa and p.IdCia = d.IdCia
					--WHERE D.VLargo = 1 and d.IdNovedad = 0 and p.Anulado = 0 and d.Cumplido = 0 and Convert(DATE,d.FechaFin) between Convert(DATE,@thirtydaysago) and Convert(DATE,@fFechaProg)

					--IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet3))
					--BEGIN
					--	DECLARE @fvlTipDoc varchar(MAX)
					--	DECLARE @fvlPrograma int
					--	DECLARE @fvlCiaPgr varchar(2)
					--	DECLARE @fvlItemPgr int
					--	DECLARE @fvlCumplido bit
					--	DECLARE @fvlFecIniCump datetime
					--	DECLARE @fvlFecFinCump datetime
					--	DECLARE @fvlvehiculo varchar(10)
					--	DECLARE @fvlVLargo bit 
					--	DECLARE @fvlFechaProg datetime

					--	set @fvlFecFinCump = GETDATE()

					--	DECLARE vlcumpserv CURSOR
					--	FOR SELECT TipDoc,Programa,IdCia,Item,FechaInicio,IdVehiculo,VLargo FROM @Trn_TraEspProgramaDet3
					--	OPEN vlcumpserv
					--	FETCH NEXT FROM vlcumpserv INTO @fvlTipDoc,@fvlPrograma,@fvlCiaPgr,@fvlItemPgr,@fvlFecIniCump,@fvlvehiculo,@fvlVLargo
					--	WHILE @@FETCH_STATUS = 0
					--	BEGIN
				   
					--	   IF(@fvlVLargo = 1)
					--	   BEGIN
					--		   UPDATE Trn_TraEspProgramaDet
					--		   SET Cumplido = 1,FecIniCump = @fvlFecIniCump, FecFinCump = @fvlFecFinCump			   
					--		   FROM Trn_TraEspProgramaDet 
					--		   WHERE TipDoc = @fvlTipDoc and Programa = @fvlPrograma and IdCia = @fvlCiaPgr  and Item = @fvlItemPgr

					--		   UPDATE Trn_TraEspProgramaPers
					--		   SET Cumplido = 1
					--		   from Trn_TraEspProgramaPers
					--		   WHERE TipDoc = @fvlTipDoc and Programa = @fvlPrograma and IdCia = @fvlCiaPgr  and Item = @fvlItemPgr

					--		   --Actualizar estado de vehiculo
					--		   UPDATE Vehiculos SET IdEstado = '0001' FROM Vehiculos v WHERE v.IdEstado = '0002' and v.IdVehiculo = @fvlvehiculo
					--	   END
				
					--	FETCH NEXT FROM vlcumpserv INTO @fvlTipDoc,@fvlPrograma,@fvlCiaPgr,@fvlItemPgr,@fvlFecIniCump,@fvlvehiculo,@fvlVLargo
					--	END
					--	CLOSE vlcumpserv
					--	DEALLOCATE vlcumpserv
					--END

					------------------------------Fin Sección para cumplir cuando ES VIAJES LARGOS------------------------------------------------------------------------

			   END
			END

			--Cancelar servicio
			IF(@operacion = 's')
			BEGIN
			   IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
			   BEGIN

			    declare @cveh varchar(11)
			    declare @cidnov varchar(4)
				declare @cnov varchar(MAX)
				declare @cObserv varchar(MAX)
				declare @cPrograma int
				declare @cCiaPgr varchar(2)
				declare @cItemPgr int
				declare @cEstadoItem int

				DECLARE cancelserv CURSOR
				FOR SELECT IdVehiculo,IdNovedad,Novedad,Programa,IdCia,Item,Observacion,EstadoItem FROM @Trn_TraEspProgramaDet where IdNovedad != '0'
				OPEN cancelserv
				FETCH NEXT FROM cancelserv INTO @cveh,@cidnov,@cnov,@cPrograma,@cCiaPgr,@cItemPgr,@cObserv,@cEstadoItem
				WHILE @@FETCH_STATUS = 0
				BEGIN
				   --Actualizar programa detalles las columnas de la novedad
				   UPDATE Trn_TraEspProgramaDet
				   SET IdNovedad = @cidnov, Novedad = @cnov, Observacion = @cObserv,EstadoItem = @cEstadoItem
				   FROM Trn_TraEspProgramaDet
				   WHERE TipDoc = 'PGR' and Programa = @cPrograma and IdCia = @cCiaPgr  and Item=  @cItemPgr

				   --Verificar vehiculos
				   declare @count int
				   select @count = count(*) from Trn_TraEspProgramaDet 
				   WHERE IdVehiculo = @cveh and  TipDoc = 'PGR' and Programa = @cPrograma and IdCia = @cCiaPgr

				   IF(@count = 1)
				   BEGIN
					   UPDATE Vehiculos
					   SET IdEstado = '0001'
					   FROM Vehiculos
					   WHERE IdVehiculo = @cveh 
				   END

				   --Eliminar personas de la programacion detalle cancelada
				   DELETE FROM Trn_TraEspProgramaPers WHERE TipDoc = 'PGR' and Programa = @cPrograma and IdCia = @cCiaPgr  and Item =  @cItemPgr

				FETCH NEXT FROM cancelserv INTO @cveh,@cidnov,@cnov,@cPrograma,@cCiaPgr,@cItemPgr,@cObserv,@cEstadoItem
				END
				CLOSE cancelserv
				DEALLOCATE cancelserv

			   END
			END

			--Not Cumplido de Detalles y Personas
			IF(@operacion = 'n')
			BEGIN
			   IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
			   BEGIN
			    declare @nfTipDoc varchar(MAX)
				declare @nfPrograma int
				declare @nfCiaPgr varchar(2)
				declare @nfItemPgr int
				declare @nfCumplido bit
				--declare @nfFecIniCump datetime
				--declare @nfFecFinCump datetime
				declare @nfvehiculo varchar(10)

			    DECLARE ncumpserv CURSOR
				FOR SELECT TipDoc,Programa,IdCia,Item,Cumplido,IdVehiculo FROM @Trn_TraEspProgramaDet
				OPEN ncumpserv
				FETCH NEXT FROM ncumpserv INTO @nfTipDoc,@nfPrograma,@nfCiaPgr,@nfItemPgr,@nfCumplido,@nfvehiculo
				WHILE @@FETCH_STATUS = 0
				BEGIN

				   UPDATE Trn_TraEspProgramaDet
				   SET Cumplido = '0',FecIniCump = null, FecFinCump = null			   
				   FROM Trn_TraEspProgramaDet 
				   WHERE TipDoc = @nfTipDoc and Programa = @nfPrograma and IdCia = @nfCiaPgr  and Item = @nfItemPgr

				   UPDATE Trn_TraEspProgramaPers
				   SET Cumplido = '0'
				   from Trn_TraEspProgramaPers
				   WHERE TipDoc = @nfTipDoc and Programa = @nfPrograma and IdCia = @nfCiaPgr  and Item = @nfItemPgr

				   --Actualizar estado de vehiculo Es mejor no actulizar el vehículo por temas de otras programciones y si está en mantenimiento o otro estado
				   --UPDATE Vehiculos SET IdEstado = '0002' FROM Vehiculos v WHERE v.IdEstado = '0001' and v.IdVehiculo = @nfvehiculo
				
				FETCH NEXT FROM ncumpserv INTO @nfTipDoc,@nfPrograma,@nfCiaPgr,@nfItemPgr,@nfCumplido,@nfvehiculo
				END
				CLOSE ncumpserv
				DEALLOCATE ncumpserv

			   END
			END

			SELECT @Documento

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspReservas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 21/10/2016
-- Description:	Insertar CRUD Rerservas.
				--Se actualiza procedimiento para agregar campo de reservas NoRequiereGIE 24/06/2021
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspReservas]
	@Trn_TraEspReservas dataTypeTrn_TraEspReservas READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspReservas
	@Trn_TraEspResAnexo dataTypeTrn_TraEspResAnexo READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspEspAnexo
	@Trn_TraEspResDetalle dataTypeTrn_TraEspResDetalle READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspEspDetalle
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Reserva/Cotización
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Reserva/Cotización
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Reserva/Cotización
declare @item int
declare @vranterior money
DECLARE @Detalle dataTypeTrn_TraEspResDetalle --Tipo de dato definido por el usuario que representa la tabla Trn_TraEspEspDetalle

	BEGIN TRAN
		BEGIN TRY

			--Seleccionar Variables
			IF(@operacion = 'i')
			begin
				SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia FROM @Trn_TraEspReservas
				SELECT @Documento = Numero + 1  FROM TiposDocCons where IdDoc = @TipDoc AND IdCia = @IdCia

				IF(@Documento <> '')
					UPDATE TiposDocCons SET Numero = @Documento WHERE IdDoc = @TipDoc and IdCia = @IdCia
				ELSE
				BEGIN
					SELECT @Documento = 1
					INSERT INTO TiposDocCons VALUES (@TipDoc,@IdCia,0,0,0,0,NULL,'',@Documento,0,0,'','',1,1,1,0,1,CURRENT_TIMESTAMP,null,null,null,null)
				END
			end

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Reserva FROM @Trn_TraEspResDetalle

			    --captura el valor de cobro para ver si cambia o no cambia para actualizarlo en el contrato
			   select @vranterior = VrCobro from Trn_TraEspReservas where TipDoc = (select TipDoc from @Trn_TraEspReservas) and IdCia = (select IdCia from @Trn_TraEspReservas) and Reserva = (select Reserva from @Trn_TraEspReservas)
			   
			   INSERT INTO @Detalle(
			   TipDoc,Reserva,IdCia,Item,ItemCnt,IdVehiculo,CdTipVeh,IdConductor,IdRuta,CdTipRuta,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,
			   Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,DiasDisp,VrDia,
			   Parada,CdTipServicio,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,NumDias,TipoTarifa,IdColegio,TipFac,Factura,IdCiaFac,FechaFac,
			   TipCum,Cumplido,IdCiaCum,FechaCum,Codigo,Itinerario,VLargo,IdOtroSi,EsItemPME)
			   SELECT 
			   TipDoc,Reserva,IdCia,Item,ItemCnt,IdVehiculo,CdTipVeh,IdConductor,IdRuta,CdTipRuta,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,
			   Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,DiasDisp,VrDia,
			   Parada,CdTipServicio,EstadoItem,VrMonitor,CantMonitor,VrRecorrido,NumDias,TipoTarifa,IdColegio,TipFac,Factura,IdCiaFac,FechaFac,
			   TipCum,Cumplido,IdCiaCum,FechaCum,Codigo,Itinerario,VLargo,IdOtroSi,EsItemPME
			   FROM Trn_TraEspResDetalle WHERE TipDoc = @TipDoc and Reserva = @Documento and IdCia = @IdCia

			   if(EXISTS(SELECT * FROM @Trn_TraEspReservas))
			   begin
			   UPDATE Trn_TraEspReservas
			   SET 
			   TipDoc = t2.TipDoc,Reserva = t2.Reserva,IdCia = t2.IdCia,Fecha = t2.Fecha,FechaInicio = t2.FechaInicio,FechaFin = t2.FechaFin,
			   TipDocCnt = t2.TipDocCnt,Contrato = t2.Contrato,IdCiaCnt = t2.IdCiaCnt,EstadoRes = t2.EstadoRes,IdCliente = t2.IdCliente,
			   IdAgencia = t2.IdAgencia,IdMneda = t2.IdMneda,CdCarga = t2.CdCarga,Modalidad = t2.Modalidad,TipoLiquid = t2.TipoLiquid,
			   TipFac = t2.TipFac,Factura = t2.Factura,IdCiaFac = t2.IdCiaFac,FechaFac = t2.FechaFac,
			   TipFuec = t2.TipFuec,NumFuec = t2.NumFuec,IdCiaFuec = t2.IdCiaFuec,
			   VrCobro = t2.VrCobro,VrPagos = t2.VrPagos,OrigenAdd = t2.OrigenAdd,Anulado = t2.Anulado,FecDev = t2.FecDev,
			   IdEstado = t2.IdEstado,TimeSys = t2.TimeSys,FecUpdate = t2.FecUpdate,IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario,
			   IdGrupo = t2.IdGrupo, IdRutaG = t2.IdRutaG, NoRequiereGIE = t2.NoRequiereGIE
		       FROM Trn_TraEspReservas t1
			   JOIN @Trn_TraEspReservas t2 ON t1.TipDoc = t2.TipDoc and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspResAnexo))
			   begin
			   UPDATE Trn_TraEspResAnexo
			   SET 
			   TipDoc = t2.TipDoc,Reserva = t2.Reserva,IdCia = t2.IdCia,NomCliente = t2.NomCliente,TelCliente = t2.TelCliente,
			   emlCliente = t2.emlCliente,DireccionCli = t2.DireccionCli,Observacion = t2.Observacion,NombArchivo = t2.NombArchivo,
			   DescripCarga = t2.DescripCarga,Clausulas = t2.Clausulas,Responsable = t2.Responsable
		       FROM Trn_TraEspResAnexo t1
			   JOIN @Trn_TraEspResAnexo t2 ON t1.TipDoc = t2.TipDoc and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCia
			   end

			   if(EXISTS(SELECT * FROM @Trn_TraEspResDetalle))
			   begin
			   select @item =  isnull(MAX(Item),0) from Trn_TraEspResDetalle where TipDoc = @TipDoc and Reserva = @Documento and IdCia = @IdCia

			   --actualizar los que vienen en el tipo de datos y coincida con los que estan en la tabla
			   UPDATE Trn_TraEspResDetalle
			   SET 
			   TipDoc = t2.TipDoc,Reserva = t2.Reserva,IdCia = t2.IdCia,Item = t2.Item,ItemCnt = t2.ItemCnt,IdVehiculo = t2.IdVehiculo,
			   CdTipVeh = t2.CdTipVeh,IdConductor = t2.IdConductor,IdRuta = t2.IdRuta,CdTipRuta = t2.CdTipRuta,NumPasajeros = t2.NumPasajeros,
			   PesoNeto = t2.PesoNeto,VrCobro = t2.VrCobro,VrPagos = t2.VrPagos,Referencia1 = t2.Referencia1,Referencia2 = t2.Referencia2,
			   Referencia3 = t2.Referencia3,EsRutaCliente = t2.EsRutaCliente,CdCiuOrigen = t2.CdCiuOrigen,DirOrigen = t2.DirOrigen,
			   FecOrigen = t2.FecOrigen,CdCiuDestino = t2.CdCiuDestino,DirDestino = t2.DirDestino,FecDestino = t2.FecDestino,DiasDisp = t2.DiasDisp,
			   VrDia = t2.VrDia,Parada = t2.Parada,CdTipServicio = t2.CdTipServicio,EstadoItem = t2.EstadoItem,VrMonitor = t2.VrMonitor,CantMonitor = t2.CantMonitor,
			   VrRecorrido = t2.VrRecorrido,NumDias=t2.NumDias,TipoTarifa=t2.TipoTarifa,IdColegio = t2.IdColegio,
			   TipFac = t2.TipFac,Factura = t2.Factura,IdCiaFac = t2.IdCiaFac,FechaFac = t2.FechaFac,
			   TipCum = t2.TipCum,Cumplido = t2.Cumplido,IdCiaCum = t2.IdCiaCum,FechaCum = t2.FechaCum,Codigo=t2.Codigo, Itinerario=t2.Itinerario,VLargo = t2.VLargo,
			   IdOtroSi = t2.IdOtroSi, EsItemPME = t2.EsItemPME
		       FROM Trn_TraEspResDetalle t1
			   JOIN @Trn_TraEspResDetalle t2 ON t1.TipDoc = t2.TipDoc and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspResDetalle(
			   TipDoc,Reserva,IdCia,Item,ItemCnt,IdVehiculo,CdTipVeh,IdConductor,IdRuta,CdTipRuta,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,
			   Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,DiasDisp,VrDia,Parada,CdTipServicio,EstadoItem,
			   VrMonitor,CantMonitor,VrRecorrido,NumDias,TipoTarifa,IdColegio,TipFac,Factura,IdCiaFac,FechaFac,TipCum,Cumplido,IdCiaCum,FechaCum,Codigo,Itinerario,VLargo,
			   IdOtroSi,EsItemPME
	           ) 
			   SELECT 
			   @TipDoc,@Documento,@IdCia,(@Item + ROW_NUMBER() OVER(ORDER BY Item ASC))
			   ,ItemCnt,IdVehiculo,CdTipVeh,IdConductor,IdRuta,CdTipRuta,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,
			   Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,DiasDisp,VrDia,Parada,CdTipServicio,EstadoItem
			   ,VrMonitor,CantMonitor,VrRecorrido,NumDias,TipoTarifa,IdColegio,TipFac,Factura,IdCiaFac,FechaFac,TipCum,Cumplido,IdCiaCum,FechaCum,isnull(Codigo,null),
			   Itinerario,VLargo,IdOtroSi,EsItemPME
			   FROM @Trn_TraEspResDetalle
			   WHERE (TipDoc + Convert(varchar,Reserva)+IdCia+Convert(varchar,Item)) NOT IN(SELECT(TipDoc + Convert(varchar,Reserva)+IdCia+Convert(varchar,Item)) FROM Trn_TraEspResDetalle)
			   --Eliminar los que no existen en el tipo de dato
			   delete from Trn_TraEspResDetalle
			   WHERE TipDoc = @TipDoc and Reserva = @Documento and IdCia = @IdCia and Item NOT IN(SELECT Item FROM @Trn_TraEspResDetalle)
			   end
			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN

				IF(EXISTS(SELECT * FROM @Trn_TraEspReservas))
				begin
				INSERT INTO Trn_TraEspReservas(
				TipDoc,Reserva,IdCia,Fecha,FechaInicio,FechaFin,TipDocCnt,Contrato,IdCiaCnt,EstadoRes,IdCliente,IdAgencia,IdMneda,CdCarga,Modalidad,TipoLiquid,
				TipFac,Factura,IdCiaFac,FechaFac,TipFuec,NumFuec,IdCiaFuec,VrCobro,VrPagos,OrigenAdd,Anulado,FecDev,IdEstado,
				TimeSys,FecUpdate,IdCiaCrea,IdUsuario,IdGrupo,IdRutaG,NoRequiereGIE
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,Fecha,FechaInicio,FechaFin,TipDocCnt,Contrato,IdCiaCnt,EstadoRes,IdCliente,IdAgencia,IdMneda,CdCarga,Modalidad,TipoLiquid,
				TipFac,Factura,IdCiaFac,FechaFac,TipFuec,NumFuec,IdCiaFuec,VrCobro,VrPagos,OrigenAdd,Anulado,FecDev,IdEstado,
				TimeSys,FecUpdate,IdCiaCrea,IdUsuario,IdGrupo,IdRutaG,NoRequiereGIE
				FROM @Trn_TraEspReservas
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspResAnexo))
				begin
				INSERT INTO Trn_TraEspResAnexo(
				TipDoc,Reserva,IdCia,NomCliente,TelCliente,emlCliente,DireccionCli,Observacion,
				NombArchivo,DescripCarga,Clausulas,Responsable
				)
				SELECT 
				@TipDoc,@Documento,@IdCia,NomCliente,TelCliente,emlCliente,DireccionCli,Observacion,
				NombArchivo,DescripCarga,Clausulas,Responsable
				FROM @Trn_TraEspResAnexo
				end

				IF(EXISTS(SELECT * FROM @Trn_TraEspResDetalle))
				begin
				INSERT INTO Trn_TraEspResDetalle(
			    TipDoc,Reserva,IdCia,Item,ItemCnt,IdVehiculo,CdTipVeh,IdConductor,IdRuta,CdTipRuta,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,
			    Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,DiasDisp,VrDia,Parada,CdTipServicio,EstadoItem,
				VrMonitor,CantMonitor,VrRecorrido,NumDias,TipoTarifa,IdColegio,TipFac,Factura,IdCiaFac,FechaFac,TipCum,Cumplido,IdCiaCum,FechaCum,Codigo,Itinerario,VLargo,
				IdOtroSi,EsItemPME
	            ) 
			    SELECT 
			    @TipDoc,@Documento,@IdCia,Item,ItemCnt,IdVehiculo,CdTipVeh,IdConductor,IdRuta,CdTipRuta,NumPasajeros,PesoNeto,VrCobro,VrPagos,Referencia1,
			    Referencia2,Referencia3,EsRutaCliente,CdCiuOrigen,DirOrigen,FecOrigen,CdCiuDestino,DirDestino,FecDestino,DiasDisp,VrDia,Parada,CdTipServicio,EstadoItem,
				VrMonitor,CantMonitor,VrRecorrido,NumDias,TipoTarifa,IdColegio,TipFac,Factura,IdCiaFac,FechaFac,TipCum,Cumplido,IdCiaCum,FechaCum,isnull(Codigo, null),
				Itinerario,VLargo,IdOtroSi,EsItemPME
			    FROM @Trn_TraEspResDetalle
				end

			 END

			--DELETE RECORDS
			IF(@operacion = 'd')
			BEGIN
			 declare @Reserva int
			 select @TipDoc = TipDoc, @IdCia = IdCia,  @Reserva = Reserva from @Trn_TraEspReservas
				 DELETE FROM Trn_TraEspResDetalle WHERE TipDoc = @TipDoc and Reserva = @Reserva and IdCia = @IdCia
				 DELETE FROM Trn_TraEspResAnexo WHERE TipDoc = @TipDoc and Reserva = @Reserva and IdCia = @IdCia
				 DELETE FROM Trn_TraEspReservas WHERE TipDoc = @TipDoc and Reserva = @Reserva and IdCia = @IdCia
			END

			--ANULAR RECORDS
			IF(@operacion = 'a')
			BEGIN
				declare @FecDev smalldatetime 
			  select @TipDoc = TipDoc, @IdCia = IdCia,  @Documento = Reserva, @FecDev = FecDev from @Trn_TraEspReservas
			  UPDATE Trn_TraEspReservas SET IdEstado = '9999',Anulado = '1', FecDev = @FecDev  WHERE TipDoc = @TipDoc and Reserva = @Documento and IdCia = @IdCia

			  UPDATE Trn_TraEspContratoDet
			  SET TipRes = 'RES', NumRes = 0, IdCiaRes = '00',ItemRes = 0
			  FROM Trn_TraEspContratoDet cd
			  WHERE cd.TipRes = @TipDoc  and cd.NumRes = @Documento and cd.IdCiaRes = @IdCia

			  --actualizar el valor de presupuesto del contrato cuando se anula una reserva
			  UPDATE Trn_TraEspContratos
			  SET VrSaldoPresup = p.VrSaldoPresup + r.VrCobro
			  FROM Trn_TraEspContratos p 
			  JOIN Trn_TraEspReservas r on r.TipDoc = @TipDoc and r.Reserva = @Documento and r.IdCia = @IdCia
			  WHERE p.TipDoc = r.TipDocCnt  and p.Contrato = r.Contrato and p.IdCia = r.IdCiaCnt

			  UPDATE Trn_TraEspContratos
			  SET IdEstado = '0001'
			  FROM Trn_TraEspContratos p
			  JOIN Trn_TraEspReservas r on r.TipDoc = @TipDoc and r.Reserva = @Documento and r.IdCia = @IdCia
			  WHERE p.TipDoc = r.TipDocCnt  and p.Contrato = r.Contrato and p.IdCia = r.IdCiaCnt and p.VrSaldoPresup > 0 and p.IdEstado = '9998'
			  ------------------------------------
			END

			--ACTUALIZAR DETALLES DE CONTRATOS
			IF(@operacion = 'i')
			BEGIN
			  UPDATE Trn_TraEspContratoDet
			  SET TipRes = @TipDoc, NumRes = @Documento, IdCiaRes = @IdCia,ItemRes = d.Item
			  FROM Trn_TraEspContratoDet cd, @Trn_TraEspResDetalle d, @Trn_TraEspReservas r 
			  WHERE cd.TipDoc = r.TipDocCnt  and cd.Contrato = r.Contrato and cd.IdCia = r.IdCiaCnt and cd.Item = d.ItemCnt

			  --actualizar el valor de presupuestro del contrato, luego de insertar una reserva
			  UPDATE Trn_TraEspContratos
			  SET VrSaldoPresup = p.VrSaldoPresup - r.VrCobro
			  FROM Trn_TraEspContratos p, @Trn_TraEspReservas r 
			  WHERE p.TipDoc = r.TipDocCnt  and p.Contrato = r.Contrato and p.IdCia = r.IdCiaCnt

			  UPDATE Trn_TraEspContratos
			  SET IdEstado = '9998'
			  FROM Trn_TraEspContratos p, @Trn_TraEspReservas r 
			  WHERE p.TipDoc = r.TipDocCnt  and p.Contrato = r.Contrato and p.IdCia = r.IdCiaCnt and p.VrSaldoPresup = 0
			  ----------------------------------------
			END

			IF(@operacion = 'u')
			BEGIN

			--actualiza los items de un contrato con los que se relacionan en el tipo de datos nuevo
			  UPDATE Trn_TraEspContratoDet
			  SET TipRes = 'RES', NumRes = 0, IdCiaRes = '00',ItemRes = 0
			  FROM Trn_TraEspContratoDet cd, @Detalle d, @Trn_TraEspReservas r 
			  WHERE cd.TipDoc = r.TipDocCnt  and cd.Contrato = r.Contrato and cd.IdCia = r.IdCiaCnt and cd.Item = d.ItemCnt

			  UPDATE Trn_TraEspContratoDet
			  SET TipRes = @TipDoc, NumRes = @Documento, IdCiaRes = @IdCia,ItemRes = d.Item
			  FROM Trn_TraEspContratoDet cd, @Trn_TraEspResDetalle d, @Trn_TraEspReservas r 
			  WHERE cd.TipDoc = r.TipDocCnt  and cd.Contrato = r.Contrato and cd.IdCia = r.IdCiaCnt and cd.Item = d.ItemCnt

			  --actualizar el valor de presupuestro del contrato
			  if(@vranterior <> (select VrCobro from @Trn_TraEspReservas))
			  begin
				  UPDATE Trn_TraEspContratos
				  SET VrSaldoPresup = (p.VrSaldoPresup + @vranterior) - r.VrCobro
				  FROM Trn_TraEspContratos p, @Trn_TraEspReservas r 
				  WHERE p.TipDoc = r.TipDocCnt  and p.Contrato = r.Contrato and p.IdCia = r.IdCiaCnt
			  end 

			  UPDATE Trn_TraEspContratos
			  SET IdEstado = '9998'
			  FROM Trn_TraEspContratos p, @Trn_TraEspReservas r 
			  WHERE p.TipDoc = r.TipDocCnt  and p.Contrato = r.Contrato and p.IdCia = r.IdCiaCnt and p.VrSaldoPresup = 0


			END

			SELECT @Documento

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_TraEspSedes]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyy): 27/03/2018
-- Description:	Insertar CRUD Trn_TraEspSedes.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_TraEspSedes]
	@Trn_TraEspSedes dataTypeTrn_TraEspSedes READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspSedes
	@operacion varchar(1)
AS
	BEGIN TRAN
		BEGIN TRY

			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN
			   IF(EXISTS(SELECT * FROM @Trn_TraEspSedes))
			   begin
			   UPDATE Trn_TraEspSedes
			   SET 
			   IdColegio = t2.IdColegio, IdSede = t2.IdSede, NomSede = t2.NomSede, Inactivo = t2.Inactivo
		       FROM Trn_TraEspSedes t1
			   JOIN @Trn_TraEspSedes t2 ON t1.IdColegio = t2.IdColegio and t1.IdSede = t2.IdSede 
			   end
			END

		    --INSERT NO-EXISTE RECORDS
			IF(@operacion = 'i')
			 BEGIN
				IF(EXISTS(SELECT * FROM @Trn_TraEspSedes))
				begin
				INSERT INTO Trn_TraEspSedes(
				IdColegio,IdSede,NomSede,Inactivo
				)
				SELECT 
				IdColegio,IdSede,NomSede,Inactivo
				FROM @Trn_TraEspSedes
				end
			 END

			 --DELETE RECORDS
			 IF(@operacion = 'd')
			 BEGIN
				 DECLARE @idcol varchar(4) DECLARE @idsede varchar(4)
				 SELECT @idcol = idcolegio, @idsede = idsede FROM @Trn_TraEspSedes
				 DELETE FROM Trn_TraEspSedes WHERE idcolegio = @idcol and idsede = @idsede
			 END

			SELECT '1'

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehConductor]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 25/04/2016
-- Description:	Insertar/Actualizar/eliminar Trn_VehConductor.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_VehConductor]
	@Trn_VehConductor dataTypeTrn_VehConductor READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = ISNULL(MAX(Numero),0) FROM Trn_VehConductor WHERE IdVehiculo = (select IdVehiculo from @Trn_VehConductor)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Trn_VehConductor
			 SET
			 IdVehiculo = t2.IdVehiculo,Numero = t2.Numero,Fecha = t2.Fecha,IdPropietario = t2.IdPropietario,
			 IdConductor = t2.IdConductor,IdCondNuevo = t2.IdCondNuevo,Observacion = t2.Observacion,
			 TimeSys = t2.TimeSys,IdUsuario = t2.IdUsuario
		     FROM Trn_VehConductor t1
			 JOIN @Trn_VehConductor t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.Numero = t2.Numero
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Trn_VehConductor(
			 IdVehiculo,Numero,Fecha,IdPropietario,IdConductor,IdCondNuevo,Observacion,TimeSys,IdUsuario
			 )
			 SELECT 
			 IdVehiculo,(@item+1),Fecha,IdPropietario,IdConductor,IdCondNuevo,Observacion,TimeSys,IdUsuario
			 FROM @Trn_VehConductor
			 WHERE (IdVehiculo + Convert(varchar,(@item+1))) NOT IN(SELECT (IdVehiculo + Convert(varchar,Numero)) FROM Trn_VehConductor)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id VARCHAR (10)
			 declare @Numero int

			 SELECT @id = IdVehiculo, @item = Numero  FROM @Trn_VehConductor
			 DELETE FROM Trn_VehConductor WHERE IdVehiculo = @id and Numero = @item
		 END

		 IF(@operacion = 'i' or @operacion = 'u')
		 BEGIN
			 --Actualizar tabla de Vehiculos
			 UPDATE Vehiculos SET IdConductor = (SELECT IdCondNuevo FROM @Trn_VehConductor) WHERE IdVehiculo = (SELECT IdVehiculo FROM @Trn_VehConductor)
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehLecturas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 26/08/2016
-- Description:	Insertar/Actualizar Trn_VehLecturas.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_VehLecturas]
	@Trn_VehLecturas dataTypeTrn_VehLecturas READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 
		
		declare @tipo varchar(3)
		declare @item int
		declare @num int 

		SELECT @item = isnull(MAX(Item),0) FROM Trn_VehLecturas WHERE TipDoc = (select TipDoc from @Trn_VehLecturas) and IdCia = (select IdCia from @Trn_VehLecturas) and pVehiculo = (select pVehiculo from @Trn_VehLecturas) and Numero = (select Numero from @Trn_VehLecturas)
		
		if(@item = 0)
		begin
		 SELECT @num = MAX(Numero) + 1, @item = 1 FROM Trn_VehLecturas WHERE TipDoc = (select TipDoc from @Trn_VehLecturas) and IdCia = (select IdCia from @Trn_VehLecturas)
		end
		
		select @tipo = TipoUnidad from @Trn_VehLecturas

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Trn_VehLecturas
			 SET 
			 TipDoc = t2.TipDoc,Numero = t2.Numero,IdCia = t2.IdCia,
			 Item = t2.Item,Fecha = t2.Fecha,TipoUnidad = t2.TipoUnidad,
			 pVehiculo = t2.pVehiculo,KmsAnterior = t2.KmsAnterior,
			 KmsActual = t2.KmsActual,Kms2Anterior = t2.Kms2Anterior,
			 Kms2Actual = t2.Kms2Actual,TipoLectura = t2.TipoLectura,
			 Observacion = t2.Observacion,TimeSys = t2.TimeSys,
			 IdUsuario = t2.IdUsuario
		     FROM Trn_VehLecturas t1
			 JOIN @Trn_VehLecturas t2 ON t1.pVehiculo = t2.pVehiculo and t1.Numero = t2.Numero and t1.Item = t2.Item and t1.IdCia = t2.IdCia
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Trn_VehLecturas(
			 TipDoc,Numero,IdCia,Item,Fecha,TipoUnidad,pVehiculo,
			 KmsAnterior,KmsActual,Kms2Anterior,Kms2Actual,TipoLectura,
			 Observacion,TimeSys,IdUsuario
			 )
			 SELECT 
			 TipDoc,@num,IdCia,@item,Fecha,TipoUnidad,pVehiculo,
			 KmsAnterior,KmsActual,Kms2Anterior,Kms2Actual,TipoLectura,
			 Observacion,TimeSys,IdUsuario
			 FROM @Trn_VehLecturas
			 WHERE (pVehiculo + Convert(varchar,(@num)) + IdCia + Convert(varchar,@item)) NOT IN(SELECT (pVehiculo + Convert(varchar,Numero) + IdCia + Convert(varchar,Item)) FROM Trn_VehLecturas)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 SELECT @id = pVehiculo FROM @Trn_VehLecturas
			 DELETE FROM Trn_VehLecturas WHERE pVehiculo = @id and Numero = @num and Item = @item
		 END

		 IF(@operacion = 'u' or @operacion = 'i')
		 BEGIN
			if(@tipo = 'V')
			begin
			 --Actualizar la tabla Vehiculos
		     UPDATE Vehiculos SET KmActual = (Select KmsActual from @Trn_VehLecturas) FROM Vehiculos where IdVehiculo = (Select pVehiculo from @Trn_VehLecturas)
			end

			if(@tipo = 'R')
			begin
			 --Actualizar la tabla Veh-Remolques
		     UPDATE VehRemolq SET Kilmetraje = (Select KmsActual from @Trn_VehLecturas) FROM VehRemolq where IdRemque = (Select pVehiculo from @Trn_VehLecturas)
			end
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehNumOrden]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 26/08/2016
-- Description:	Insertar/Actualizar Trn_VehNumOrden.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_VehNumOrden]
	@Trn_VehNumOrden dataTypeTrn_VehNumOrden READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Numero),0) FROM Trn_VehNumOrden WHERE IdVehiculo = (select IdVehiculo from @Trn_VehNumOrden)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Trn_VehNumOrden
			 SET 
			 IdVehiculo = t2.IdVehiculo,Numero = t2.Numero,Fecha = t2.Fecha,
			 NumOrden = t2.NumOrden,NuevoNum = t2.NuevoNum,Observacion = t2.Observacion,
			 TimeSys = t2.TimeSys,IdUsuario = t2.IdUsuario
		     FROM Trn_VehNumOrden t1
			 JOIN @Trn_VehNumOrden t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.Numero = t2.Numero 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Trn_VehNumOrden(
			 IdVehiculo,Numero,Fecha,NumOrden,NuevoNum,Observacion,TimeSys,IdUsuario
			 )
			 SELECT 
			 IdVehiculo,(@item+1),Fecha,NumOrden,NuevoNum,Observacion,TimeSys,IdUsuario
			 FROM @Trn_VehNumOrden
			 WHERE (IdVehiculo + Convert(varchar,(@item+1))) NOT IN(SELECT (IdVehiculo + Convert(varchar,Numero)) FROM Trn_VehNumOrden)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 SELECT @id = IdVehiculo, @item = Numero FROM @Trn_VehNumOrden
			 DELETE FROM Trn_VehNumOrden WHERE IdVehiculo = @id and Numero = @item
		 END

		 IF(@operacion = 'u' or @operacion = 'i')
		 BEGIN
		 --Actualizar la tabla Vehiculos
		     UPDATE Vehiculos SET NumVeh = (Select NuevoNum from @Trn_VehNumOrden), FechaUpdate = current_timestamp FROM Vehiculos where IdVehiculo = (Select IdVehiculo from @Trn_VehNumOrden)
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsTrn_VehTraspasos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 17/08/2016
-- Description:	Insertar/Actualizar Trn_VehTraspasos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsTrn_VehTraspasos]
	@Trn_VehTraspasos dataTypeTrn_VehTraspasos READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Numero),0) FROM Trn_VehTraspasos WHERE IdVehiculo = (select IdVehiculo from @Trn_VehTraspasos)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Trn_VehTraspasos
			 SET 
			 IdVehiculo = t2.IdVehiculo,Numero = t2.Numero,
			 Fecha = t2.Fecha,IdPpd = t2.IdPpd,IdPropietario = t2.IdPropietario,
			 IdPoseedor = t2.IdPoseedor,IdPropNuevo = t2.IdPropNuevo,
			 IdPoseeNuevo = t2.IdPoseeNuevo,IdNewPpd = t2.IdNewPpd,IdGrupo = t2.IdGrupo,
			 VrComercial = t2.VrComercial,VrCupo = t2.VrCupo,VrAsegurado = t2.VrAsegurado,
			 Observacion = t2.Observacion,TipoAfil = t2.TipoAfil,TipoAfilNew = t2.TipoAfilNew,
			 TimeSys = t2.TimeSys,IdUsuario = t2.IdUsuario
		     FROM Trn_VehTraspasos t1
			 JOIN @Trn_VehTraspasos t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.Numero = t2.Numero 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Trn_VehTraspasos(
			 IdVehiculo,Numero,Fecha,IdPpd,IdPropietario,IdPoseedor,
			 IdPropNuevo,IdPoseeNuevo,IdNewPpd,IdGrupo,VrComercial,VrCupo,
			 VrAsegurado,Observacion,TipoAfil,TipoAfilNew,TimeSys,IdUsuario
			 )
			 SELECT 
			 IdVehiculo,(@item+1),Fecha,IdPpd,IdPropietario,IdPoseedor,
			 IdPropNuevo,IdPoseeNuevo,IdNewPpd,IdGrupo,VrComercial,VrCupo,
			 VrAsegurado,Observacion,TipoAfil,TipoAfilNew,TimeSys,IdUsuario
			 FROM @Trn_VehTraspasos
			 WHERE (IdVehiculo + Convert(varchar,(@item+1))) NOT IN(SELECT (IdVehiculo + Convert(varchar,Numero)) FROM Trn_VehTraspasos)

			 UPDATE vehiculos 
			 SET IdPropietario = IdPropNuevo, IdPoseedor = IdPoseeNuevo,IdPpd = IdNewPpd
			 FROM vehiculos v
			 join @Trn_VehTraspasos vt on v.IdVehiculo = vt.IdVehiculo	
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 declare @num int
			 SELECT @id = IdVehiculo, @num = Numero FROM @Trn_VehTraspasos
			 DELETE FROM Trn_VehTraspasos WHERE IdVehiculo = @id and Numero = @num
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsUpdateEstadoItem]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Diego Fernando Mantilla Vega
-- Create date(dd/MM/yyyy): 08/11/2017
-- Description:	Actualizar el EstadoItem de Trn_TraEspOrdenReservas
--				para las reservas con ordenes de pago antes de la 
--				fecha descrita en este procedimiento. 
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsUpdateEstadoItem]
AS
	BEGIN TRAN
		BEGIN TRY		 

		UPDATE TE
		SET TE.EstadoItem = ISNULL(V.Estado, 'NOPROGRAMADA')
		FROM Trn_TraEspOrdenReservas TE
		LEFT JOIN (SELECT TipDocRes, Reserva, IdCiaRes, ItemRes, 'PROGRAMADA' as Estado FROM Trn_TraEspProgramaDet E JOIN Trn_TraEspPrograma P ON (E.TipDoc = P.TipDoc and E.Programa = P.Programa and E.IdCia = P.IdCia) WHERE E.Cumplido=1 and P.Anulado = 0) V 
		ON TE.TipRes = V.TipDocRes and TE.Reserva = V.Reserva and TE.IdCiaRes = V.IdCiaRes and TE.ItemRes = V.ItemRes

		--Actualizar las reservasdet al estado XLIQUIDAR, las que cumplan con la condición de que la fecha sea igual al dia actual
--Actualizar las reservasdet al estado XLIQUIDAR, las que cumplan con la condición de que la fecha sea igual al dia actual
  UPDATE TE
  SET TE.EstadoItem = 'XLIQUIDAR'
  FROM Trn_TraEspOrdenReservas TE
  JOIN Trn_TraEspResDetalle t1 ON TE.TipRes = t1.TipDoc and TE.Reserva = t1.Reserva and TE.IdCiaRes = t1.IdCia and TE.ItemRes = t1.Item
  JOIN Trn_TraEspProgramaDet t2 ON t1.TipDoc = t2.TipDocRes and t1.Reserva = t2.Reserva and t1.IdCia = t2.IdCiaRes and t1.Item = t2.ItemRes
  where (CURRENT_TIMESTAMP >= Convert(date,t1.FecDestino))

		UPDATE TE
		SET TE.EstadoItem = ISNULL(V.EstadoItemRes, 
		CASE WHEN V.EstadoItem='LIQUIDADA' then 
		'XLIQUIDAR' 
		WHEN V.ESTADOITEM='LIQUIDADA' AND V.ANULADO = 1 THEN 'XLIQUIDAR' ELSE V.Estado END)
		FROM Trn_TraEspOrdenReservas TE
		JOIN (SELECT R.TipRes, R.Reserva, R.IdCiaRes, R.ItemRes, 'FACTURADA' as Estado, R.EstadoItem,C.EstadoItemRes, F.ANULADO
		FROM Trn_TraEspFacReservas R
		JOIN TRN_FACTURAS AS F ON  R.TipDoc = F.TipDoc and R.Factura = F.Factura and R.idcia= R.idcia

		LEFT JOIN Trn_TraEspCumReservas C ON (R.TipRes = C.TipRes and R.Reserva = C.Reserva and R.IdCiaRes = C.IdCiaRes and R.ItemRes = C.ItemRes)) V 
		ON TE.TipRes = V.TipRes and TE.Reserva = V.Reserva and TE.IdCiaRes = V.IdCiaRes and TE.ItemRes = V.ItemRes

				SELECT * FROM Trn_TraEspOrdenReservas
				COMMIT TRAN
---ROLLBACK TRAN
		END TRY
        BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVeh_Contrato]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 03/05/2016
-- Description:	Insertar/Actualizar/Eliminar Veh_Contrato.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsVeh_Contrato]
	@Veh_Contrato dataTypeVeh_Contrato READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Veh_Contrato
			 SET 
			 NumContrato = t2.NumContrato, IdVehiculo = t2.IdVehiculo, IdAdmon = t2.IdAdmon,
			 IdTipCon = t2.IdTipCon, FecIngreso = t2.FecIngreso,FecRetiro = t2.FecRetiro, 
			 FecVigencia = t2.FecVigencia, Observaciones = t2.Observaciones, NumPagare = t2.NumPagare, 
			 ArchPagare = t2.ArchPagare, FecUpdate = t2.FecUpdate, IdUsuario = t2.IdUsuario 
		     FROM Veh_Contrato t1
			 JOIN @Veh_Contrato t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.NumContrato = t2.NumContrato
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Veh_Contrato(
			 NumContrato, IdVehiculo, IdAdmon, IdTipCon, FecIngreso, 
			 FecRetiro, FecVigencia, Observaciones, NumPagare, ArchPagare, 
			 FecUpdate, IdUsuario 
			 )
			 SELECT 
			 NumContrato, IdVehiculo, IdAdmon, IdTipCon, FecIngreso, 
			 FecRetiro, FecVigencia, Observaciones, NumPagare, ArchPagare, 
			 FecUpdate, IdUsuario  
			 FROM @Veh_Contrato
			 WHERE (IdVehiculo + Convert(varchar,NumContrato)) NOT IN(SELECT (IdVehiculo + Convert(varchar,NumContrato)) FROM Veh_Contrato)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 declare @num int
			 SELECT @id = IdVehiculo, @num = NumContrato FROM @Veh_Contrato
			 DELETE FROM Veh_Contrato WHERE IdVehiculo = @id and NumContrato = @num
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehConductores]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 16/08/2016
-- Description:	Insertar/Actualizar VehConductores.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsVehConductores]
	@VehConductores dataTypeVehConductores READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Item),0) FROM VehConductores WHERE IdVehiculo = (select IdVehiculo from @VehConductores)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE VehConductores
			 SET 
			 IdVehiculo = t2.IdVehiculo,Item = t2.Item,CedConductor = t2.CedConductor,
			 TipoCond = t2.TipoCond,FechaIng = t2.FechaIng,EstadoCond = t2.EstadoCond
		     FROM VehConductores t1
			 JOIN @VehConductores t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.Item = t2.Item 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO VehConductores(
			 IdVehiculo,Item,CedConductor,TipoCond,FechaIng,EstadoCond
			 )
			 SELECT 
			 IdVehiculo,(@item+1),CedConductor,TipoCond,FechaIng,1
			 FROM @VehConductores
			 WHERE (IdVehiculo + Convert(varchar,(@item+1))) NOT IN(SELECT (IdVehiculo + Convert(varchar,Item)) FROM VehConductores)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 SELECT @id = IdVehiculo FROM @VehConductores
			 DELETE FROM VehConductores WHERE idvehiculo = @id and Item = @item
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehiculos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 02/05/2016
-- Description:	Insertar/Actualizar/Eliminar Vehiculos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeInsVehiculos]
	@Vehiculos dataTypeVehiculos READONLY, 
	@VehAnexo dataTypeVehAnexo READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE Vehiculos
			 SET 
			 IdVehiculo = t2.IdVehiculo, NumVeh = t2.NumVeh, ClaseVeh = t2.ClaseVeh, IdTipoVeh = t2.IdTipoVeh, IdMarca = t2.IdMarca, IdLinea = t2.IdLinea,
			 IdColor = t2.IdColor, IdTipoMot = t2.IdTipoMot, IdCrceria = t2.IdCrceria,  Modelo = t2.Modelo, FecRep = t2.FecRep, Config = t2.Config,
			 VehArtic = t2.VehArtic, NumLlan = t2.NumLlan, NumLlans = t2.NumLlans, IdCat = t2.IdCat, CdCatv = t2.CdCatv, ClaseMat = t2.ClaseMat,
			 Cilind = t2.Cilind, CapTanq = t2.CapTanq, IdCom = t2.IdCom, IdLub = t2.IdLub, IdTlla = t2.IdTlla, IdMarlla = t2.IdMarlla,
			 PesoVacio = t2.PesoVacio, PesoMax = t2.PesoMax, NumMotor = t2.NumMotor, SerieChasis = t2.SerieChasis, NumSerie = t2.NumSerie, CdRemque = t2.CdRemque,
			 Longitud = t2.Longitud, CarrAlto = t2.CarrAlto, CarrAncho = t2.CarrAncho,  CarrLargo = t2.CarrLargo, CarrCapac = t2.CarrCapac, UndCapc = t2.UndCapc,
			 Comptmtos = t2.Comptmtos, CapComp = t2.CapComp, PasjerosPie = t2.PasjerosPie, PasjerosSen = t2.PasjerosSen, NitEmpresa = t2.NitEmpresa, IdPropietario = t2.IdPropietario,
			 IdPoseedor = t2.IdPoseedor, IdConductor = t2.IdConductor, IdPpd = t2.IdPpd, TipoAfil = t2.TipoAfil, Adquisc = t2.Adquisc, NitProv = t2.NitProv, 
			 FecCompra = t2.FecCompra, VrComcial = t2.VrComcial, VrAseg = t2.VrAseg, VrAvaludo = t2.VrAvaludo, VidaUtil = t2.VidaUtil, FecSalida = t2.FecSalida, 
			 NContrato = t2.NContrato, IdAdmon = t2.IdAdmon, IdNiv = t2.IdNiv, IdGrupo = t2.IdGrupo, CdGrupR = t2.CdGrupR, CdTarifa = t2.CdTarifa, 
			 FecIngreso = t2.FecIngreso, FecVigencia = t2.FecVigencia, FecRetiro = t2.FecRetiro, NumSoat = t2.NumSoat, FecSoat = t2.FecSoat, VigSoat = t2.VigSoat, 
			 NitEmpSoat = t2.NitEmpSoat, TarjProp = t2.TarjProp, FecTProp = t2.FecTProp, VigTProp = t2.VigTProp, CdLugTp = t2.CdLugTp, Ulttramite = t2.Ulttramite, 
			 RespCivil = t2.RespCivil, FecRCivil = t2.FecRCivil, VigRCivil = t2.VigRCivil, RegNalCarga = t2.RegNalCarga, FecRegNal = t2.FecRegNal, VigRegNal = t2.VigRegNal, 
			 RevTecMec = t2.RevTecMec, FecTecMec = t2.FecTecMec, VigTecMec = t2.VigTecMec, CertGases = t2.CertGases, FecCertGas = t2.FecCertGas, VigCertGas = t2.VigCertGas, 
			 TarjOper = t2.TarjOper, FecTarjOper = t2.FecTarjOper, VigTarjOper = t2.VigTarjOper, KmInicial = t2.KmInicial, KmActual = t2.KmActual, Km2Actual = t2.Km2Actual, 
			 Regtradora = t2.Regtradora, CentInicial = t2.CentInicial, CentFinal = t2.CentFinal, VrLmtCred = t2.VrLmtCred, VrSaldoAct = t2.VrSaldoAct, Descripcion = t2.Descripcion, 
			 Observacion = t2.Observacion, CdCenSer = t2.CdCenSer, CdLocal = t2.CdLocal, Ubicacion = t2.Ubicacion, PathFoto = t2.PathFoto, FecPriServ = t2.FecPriServ, 
			 FecUltServ = t2.FecUltServ,FecUltAcc = t2.FecUltAcc,TieneAcc = t2.TieneAcc, FecPagImp = t2.FecPagImp, IdEstado = t2.IdEstado, Inactivo = t2.Inactivo, 
			 FechaAdd = t2.FechaAdd, FechaUpdate = t2.FechaUpdate, IdUsuario = t2.IdUsuario, ValorCupo = t2.ValorCupo, ObligaTProd = t2.ObligaTProd, GarantiaAcc = t2.GarantiaAcc, 
			 DocCompleta = t2.DocCompleta, CertMovilizacion = t2.CertMovilizacion, FecCertMovil = t2.FecCertMovil, VigCertMovil = t2.VigCertMovil, CdRutaHab = t2.CdRutaHab, 
			 DeclaracImp = t2.DeclaracImp, TipoIngreso = t2.TipoIngreso, IdOrgTra = t2.IdOrgTra, GPSoperador = t2.GPSoperador,  GPSUsuario = t2.GPSUsuario, GPSClave = t2.GPSClave,
			 CantFiltros = t2.CantFiltros,GPSIdOper=t2.GPSIdOper
			 FROM Vehiculos t1
			 JOIN @Vehiculos t2 ON t1.Idvehiculo = t2.IdVehiculo
			 where t1.IdVehiculo = t2.IdVehiculo

			 UPDATE VehAnexo
			 SET 
			 IdVehiculo = t2.IdVehiculo,
			 PolizaRCE = t2.PolizaRCE,
			 FecEmisionRCE = t2.FecEmisionRCE,
			 FecVigenciaRCE = t2.FecVigenciaRCE,
			 appPyP = t2.appPyP
			 FROM VehAnexo t1
			 JOIN @VehAnexo t2 ON t1.Idvehiculo = t2.IdVehiculo
			 where t1.IdVehiculo = t2.IdVehiculo
			 --Inserta los que no existen
			 INSERT INTO VehAnexo(
			 IdVehiculo,PolizaRCE,FecEmisionRCE,FecVigenciaRCE,appPyP
	         ) 
			 SELECT 
			 IdVehiculo,PolizaRCE,FecEmisionRCE,FecVigenciaRCE,appPyP
			 FROM @VehAnexo
			 WHERE IdVehiculo NOT IN(SELECT IdVehiculo FROM VehAnexo)
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO Vehiculos(
			 IdVehiculo,NumVeh,ClaseVeh,IdTipoVeh,IdMarca,IdLinea,IdColor,IdTipoMot,IdCrceria,Modelo,FecRep,Config,VehArtic,NumLlan,
			 NumLlans,IdCat,CdCatv,ClaseMat,Cilind,CapTanq, IdCom,IdLub,IdTlla,IdMarlla,PesoVacio,PesoMax,
			 NumMotor,SerieChasis,NumSerie,CdRemque,Longitud,CarrAlto,CarrAncho,CarrLargo,CarrCapac,UndCapc,Comptmtos,CapComp,
			 PasjerosPie,PasjerosSen,NitEmpresa,IdPropietario,IdPoseedor,IdConductor,IdPpd,TipoAfil,Adquisc,NitProv,FecCompra,VrComcial,
			 VrAseg,VrAvaludo,VidaUtil,FecSalida,NContrato,IdAdmon,IdNiv,IdGrupo,CdGrupR,CdTarifa,FecIngreso,FecVigencia,
			 FecRetiro,NumSoat,FecSoat,VigSoat,NitEmpSoat,TarjProp,FecTProp,VigTProp,CdLugTp,Ulttramite,RespCivil,FecRCivil,
			 VigRCivil,RegNalCarga,FecRegNal,VigRegNal,RevTecMec,FecTecMec,VigTecMec,CertGases,FecCertGas,VigCertGas,TarjOper,FecTarjOper,
			 VigTarjOper,KmInicial,KmActual,Km2Actual,Regtradora,CentInicial,CentFinal,VrLmtCred,VrSaldoAct,Descripcion,Observacion,CdCenSer,
			 CdLocal,Ubicacion,PathFoto,FecPriServ,FecUltServ,FecUltAcc,TieneAcc,FecPagImp,IdEstado,Inactivo,FechaAdd,FechaUpdate,
			 IdUsuario,ValorCupo,ObligaTProd,GarantiaAcc,DocCompleta,CertMovilizacion,FecCertMovil,VigCertMovil,CdRutaHab,DeclaracImp,TipoIngreso,IdOrgTra,
			 GPSoperador,GPSUsuario,GPSClave, CantFiltros,GPSIdOper
			 )
			 SELECT 
			 IdVehiculo,NumVeh,ClaseVeh,IdTipoVeh,IdMarca,IdLinea,IdColor,IdTipoMot,IdCrceria,Modelo,FecRep,Config,VehArtic,NumLlan,
			 NumLlans,IdCat,CdCatv,ClaseMat,Cilind,CapTanq, IdCom,IdLub,IdTlla,IdMarlla,PesoVacio,PesoMax,
			 NumMotor,SerieChasis,NumSerie,CdRemque,Longitud,CarrAlto,CarrAncho,CarrLargo,CarrCapac,UndCapc,Comptmtos,CapComp,
			 PasjerosPie,PasjerosSen,NitEmpresa,IdPropietario,IdPoseedor,IdConductor,IdPpd,TipoAfil,Adquisc,NitProv,FecCompra,VrComcial,
			 VrAseg,VrAvaludo,VidaUtil,FecSalida,NContrato,IdAdmon,IdNiv,IdGrupo,CdGrupR,CdTarifa,FecIngreso,FecVigencia,
			 FecRetiro,NumSoat,FecSoat,VigSoat,NitEmpSoat,TarjProp,FecTProp,VigTProp,CdLugTp,Ulttramite,RespCivil,FecRCivil,
			 VigRCivil,RegNalCarga,FecRegNal,VigRegNal,RevTecMec,FecTecMec,VigTecMec,CertGases,FecCertGas,VigCertGas,TarjOper,FecTarjOper,
			 VigTarjOper,KmInicial,KmActual,Km2Actual,Regtradora,CentInicial,CentFinal,VrLmtCred,VrSaldoAct,Descripcion,Observacion,CdCenSer,
			 CdLocal,Ubicacion,PathFoto,FecPriServ,FecUltServ,FecUltAcc,TieneAcc,FecPagImp,IdEstado,Inactivo,FechaAdd,FechaUpdate,
			 IdUsuario,ValorCupo,ObligaTProd,GarantiaAcc,DocCompleta,CertMovilizacion,FecCertMovil,VigCertMovil,CdRutaHab,DeclaracImp,TipoIngreso,IdOrgTra,
			 GPSoperador,GPSUsuario,GPSClave, CantFiltros,GPSIdOper
			 FROM @Vehiculos
			 WHERE IdVehiculo NOT IN(SELECT IdVehiculo FROM Vehiculos)

			 INSERT INTO VehAnexo(
			 IdVehiculo,PolizaRCE,FecEmisionRCE,FecVigenciaRCE,appPyP
			 )
			 SELECT 
			 IdVehiculo,PolizaRCE,FecEmisionRCE,FecVigenciaRCE,appPyP
			 FROM @VehAnexo
			 WHERE IdVehiculo NOT IN(SELECT IdVehiculo FROM VehAnexo)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id VARCHAR (10)
			 SELECT @id = IdVehiculo FROM @Vehiculos
			 DELETE FROM VehAnexo WHERE IdVehiculo = @id
			 DELETE FROM Vehiculos WHERE IdVehiculo = @id
		 END

	SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehPolizas]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar VehPolizas.
-- =============================================
create PROCEDURE [dbo].[paWcfSeInsVehPolizas]
	@VehPolizas dataTypeVehPolizas READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE VehPolizas
			 SET 
			 IdVehiculo = t2.IdVehiculo,IdClase = t2.IdClase,Numero = t2.Numero,
			 FecEmision = t2.FecEmision,FecVigencia = t2.FecVigencia,
			 NitCompania = t2.NitCompania,Valor = t2.Valor,Comntarios = t2.Comntarios,
			 DiasAviso = t2.DiasAviso
		     FROM VehPolizas t1
			 JOIN @VehPolizas t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.IdClase = t2.IdClase 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN
			 INSERT INTO VehPolizas(
			 IdVehiculo,IdClase,Numero,FecEmision,
			 FecVigencia,NitCompania,Valor,
			 Comntarios,DiasAviso
			 )
			 SELECT 
			 IdVehiculo,IdClase,Numero,FecEmision,
			 FecVigencia,NitCompania,Valor,
			 Comntarios,DiasAviso
			 FROM @VehPolizas
			 WHERE (IdVehiculo + IdClase) NOT IN(SELECT (IdVehiculo + IdClase) FROM VehPolizas)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 DECLARE @idcl varchar(4)
			 SELECT @id = IdVehiculo, @idcl = IdClase FROM @VehPolizas
			 DELETE FROM VehPolizas WHERE idvehiculo = @id and IdClase = @idcl
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeInsVehPropietarios]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Joe Alexander Núñez Yaguna
-- Create date(dd/MM/yyyy): 21/04/2016
-- Description:	Insertar/Actualizar VehPropietarios.
-- =============================================
create PROCEDURE [dbo].[paWcfSeInsVehPropietarios]
	@VehPropietarios dataTypeVehPropietarios READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 

		declare @item int 
		SELECT @item = isnull(MAX(Item),0) FROM VehPropietarios WHERE IdVehiculo = (select IdVehiculo from @VehPropietarios)

		--UPDATE SI-EXISTE RECORDS
		 IF(@operacion = 'u')
		 BEGIN
			 UPDATE VehPropietarios
			 SET 
			 IdVehiculo = t2.IdVehiculo,Item = t2.Item,NitPropietario = t2.NitPropietario,
			 PorcPartic = t2.PorcPartic,FechaIng = t2.FechaIng,EstadoProp = t2.EstadoProp
		     FROM VehPropietarios t1
			 JOIN @VehPropietarios t2 ON t1.IdVehiculo = t2.IdVehiculo and t1.Item = t2.Item 
		 END
 
		 --INSERT NO-EXISTE RECORDS
		 IF(@operacion = 'i')
		 BEGIN			 
			 INSERT INTO VehPropietarios(
			 IdVehiculo,Item,NitPropietario,PorcPartic,FechaIng,EstadoProp
			 )
			 SELECT 
			 IdVehiculo,(@item + 1),NitPropietario,PorcPartic,FechaIng,EstadoProp
			 FROM @VehPropietarios
			 WHERE (IdVehiculo + Convert(varchar,(@item+1)))NOT IN(SELECT (IdVehiculo + Convert(varchar,Item)) FROM VehPropietarios)
		 END

		 --DELETE RECORDS
		 IF(@operacion = 'd')
		 BEGIN
			 DECLARE @id varchar(10)
			 SELECT @id = IdVehiculo FROM @VehPropietarios
			 DELETE FROM VehPropietarios WHERE IdVehiculo = @id and Item = @item
		 END

		SELECT '1'

	COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLis_DirTe]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 2/1/2016
-- Description:	Listar Direcciones Territoriales para reporte
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLis_DirTe]
AS
SELECT '' as IdDTE, '' as Descripcion
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLis_NovPgr]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 13/03/2017
-- Description:	Listar Novedades de Programación para reporte
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLis_NovPgr]
AS
SELECT '' AS IdNovedad, '' AS Novedad, '' AS Tipo, '' AS IdEstado,CAST('' AS BIT) AS Inactivo
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLis_VehiculosPza]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 14/03/2017
-- Description:	Imprimir reporte de pólizas de vehiculo por consultas=>Vehículo
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLis_VehiculosPza]
AS
SELECT  '' AS IdVehiculo,'' AS NumVeh, '' AS ClaseVeh, '' AS IdTipoVeh,'' AS TipoVehiculo, '' AS IdMarca, '' AS Marca, ''AS IdLinea,
'' AS LineaVeh, '' AS IdColor, '' AS NomColor, '' AS IdTipoMot, '' AS TipoMotor, '' AS IdCrceria, '' AS TipoCar, '' AS Modelo,
CAST('' AS datetime) AS FecRep, '' AS Config, CAST ('' AS BIT) AS VehArtic, CAST ('' AS INT) AS NumLlan, CAST ('' AS INT) AS NumLlans,
'' AS IdCat, '' AS Catpeaje, '' AS CdCatv, '' AS ClaseMat, '' AS Cilind, '' AS CapTanq, '' AS IdCom, '' AS TipoComb, '' AS IdLub,
'' AS TipoLub, '' AS IdTlla, '' AS TipoLlanta, '' AS IdMarlla, '' AS MarcaLlantas, '' AS PesoVacio, '' AS PesoMax, '' AS NumMotor,
'' AS SerieChasis, '' AS NumSerie, '' AS CdRemque, '' AS Longitud, '' AS CarrAlto,'' AS CarrAncho,'' AS CarrLargo, '' AS CarrCapac,
'' AS UndCapc, CAST ('' AS INT) AS Comptmtos, '' AS CapComp, CAST('' AS INT) AS PasjerosPie, CAST('' AS INT) AS PasjerosSen, '' AS NitEmpresa,
'' AS Empresa, '' AS IdPropietario, '' AS Propietario, '' AS IdPoseedor,'' AS Poseedor, '' AS IdConductor, '' AS Conductor, '' AS IdPpd, '' AS TipoProp, 
CAST('' AS BIT) AS VehPropio, '' AS Adquisc, '' AS NitProv, '' AS Proveedor, CAST('' AS datetime) AS FecCompra, CAST('' AS money) AS VrComcial, CAST('' AS money) AS  VrAseg,
CAST('' AS money) AS VrAvaludo, CAST('' AS INT) AS VidaUtil, CAST('' AS datetime) AS FecSalida, CAST('' AS INT) AS NContrato, '' AS IdAdmon, '' AS TipoAdmon, '' AS IdNiv, 
'' AS NivelServicio, '' AS IdGrupo, '' AS GrupoProp, '' AS CdGrupR, '' AS CdTarifa, CAST('' AS datetime) AS FecIngreso, CAST('' AS datetime) AS FecVigencia, 
CAST('' AS datetime) AS FecRetiro, '' AS NumSoat, CAST('' AS datetime) AS FecSoat, CAST('' AS datetime) AS VigSoat, '' AS NitEmpSoat,
'' AS CiaAsegurdora, '' AS TarjProp, CAST('' AS datetime) AS FecTProp, CAST('' AS datetime) AS VigTProp, '' AS CdLugTp, '' AS LugarTarjProp,
'' AS Ulttramite, '' AS RespCivil, CAST('' AS datetime) AS FecRCivil, CAST('' AS datetime) AS VigRCivil, '' AS RegNalCarga,
CAST('' AS datetime) AS FecRegNal, CAST('' AS datetime) AS VigRegNal, '' AS KmInicial, '' AS KmActual, '' AS Km2Actual, '' AS Descripcion,
''AS Observacion, '' AS CdCenSer, '' AS CentroServ, '' AS CdLocal, '' AS CiuUbicacion, '' AS CodDpto, '' AS Departamento, '' AS Ubicacion,
CAST('' AS datetime) AS FecPriServ, CAST('' AS datetime) AS FecUltServ, '' AS Regtradora, '' AS CentInicial, '' AS CentFinal, 
CAST('' AS money) AS VrLmtCred,  CAST('' AS money) AS VrSaldoAct,  CAST('' AS datetime) AS FecUltAcc, CAST('' AS BIT) AS TieneAcc, 
CAST('' AS datetime) AS FecPagImp, '' AS IdEstado, '' AS Estado,  CAST('' AS BIT) AS Inactivo, '' AS IdUsuario, '' AS Usuario,
CAST('' AS datetime) AS FechaAdd, CAST('' AS datetime) AS FechaUpdate, '' AS NColor, CAST('' AS BIT) AS OutDemand, '' AS TipoAfil,
'' AS RevTecMec, CAST('' AS datetime) AS FecTecMec, CAST('' AS datetime) AS VigTecMec, '' AS CertGases, CAST('' AS datetime) AS FecCertGas,
CAST('' AS datetime) AS VigCertGas, '' AS TarjOper, CAST('' AS datetime) AS FecTarjOper, CAST('' AS datetime) AS VigTarjOper , '' AS Licencia,
'' AS LugarLic, '' AS CatLicencia, CAST('' AS datetime) AS VigLicencia,
--información de polizas
'' AS IdClase, '' AS ClasePoliza, '' AS Numero, CAST('' AS datetime) AS FecEmision, CAST('' AS datetime) AS FecVencePoliza, '' AS NitCompania, 
'' AS NombreCia, CAST('' AS money) AS Valor, '' AS Comntarios, CAST('' AS INT) AS DiasAviso, '' AS PolizaRCE, CAST('' AS datetime) AS FecEmisionRCE,
CAST('' AS datetime) AS FecVigenciaRCE
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspAntAbonos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/06/2017
-- Description:	Imprimir anticipo abonos en ODP
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspAntAbonos]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Documento,'' AS IdCia, CAST('' AS INT) AS Item, CAST('' AS datetime) AS Fecha, '' AS TipAnt, CAST('' AS INT) AS Anticipo,
'' AS IdCiaAnt, CAST('' AS Money) AS VrAbono,  CAST('' AS Money) AS VrAnticipo, CAST('' AS Money) AS VrAbonado, CAST ('' AS Money) AS VsSaldo,
''AS  TipoAplica, ''AS Detalle, '' AS CdCuentaAnt, '' AS Observacion, '' AS IdVehiculo

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspAnticiposRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 25/07/2017
-- Description:	Imprimir anticipos para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspAnticiposRel]
AS
--Encabezado
SELECT '' AS TipDoc, CAST('' AS INT) AS Anticipo, '' AS IdCia, '' AS Compania, CAST('' AS datetime) AS Fecha, '' AS IdConcepto, '' AS TipRes, 
CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, '' AS IdVehiculo, '' AS IdPoseedor,'' AS NomPoseedor, '' AS IdConductor,
'' AS NomConductor, CAST('' AS Money) AS VrAnticipo, CAST('' AS Money) AS VrAbonado,  CAST('' AS Money) AS VrSaldo, '' AS Modalidad, '' AS TipoPago,
'' AS NumCheque, CAST('' AS datetime) AS FecCheque, '' AS IdCta, '' AS NumeroCta, '' AS IdBanco, '' AS Banco, '' AS IdCuenta, '' AS Beneficiario,
'' AS CedBenef, CAST('' AS INT) AS  Cantidad, CAST('' AS datetime) AS FechaVence, CAST('' AS INT) AS  NumPresAnt, '' AS TipCom, CAST('' AS INT) AS  Comprobante,
'' AS IdCiaCom, CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS datetime) AS FecDev, '' AS Observacion, '' AS IdEstado, '' AS Estado,
'' AS OrigenAdd, CAST('' AS datetime) AS TimeSys, CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario, CAST('' AS INT) AS PreAnticipo
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCauRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 25/07/2017
-- Description:	Imprimir causaciones para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCauRel]
AS
--Encabezado
SELECT CAST('' AS INT) AS Causacion, '' AS CdCia, '' AS Compania, CAST('' AS datetime) AS Fecha, '' AS CdConcepto, '' AS Concepto, '' AS IdProv,
'' AS RazonSocial, '' AS Factura, CAST('' AS Money) AS VrTotal, CAST('' AS Money) AS VrOtros, CAST('' AS Money) AS VrNeto, '' AS TipCom,
CAST('' AS INT) AS  Comprobante, '' AS IdCiaCom, CAST('' AS BIT) AS  Anulado, CAST('' AS INT) AS NumDev, CAST('' AS datetime) AS FecDev,
'' AS  Observacion,  '' AS CdEstado, '' AS OrigenAdd, CAST('' AS datetime) AS TimeSys, CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,
'' AS CdUsuario, '' AS Usuario
           
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCauRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 25/07/2017
-- Description:	Imprimir detalle causaciones para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCauRelDet]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
--Detalle de CCE
SELECT '' as TipCau, CAST('' AS INT) AS NumCausac, '' AS CdCia, '' AS Compania, CAST('' AS INT) AS Item, '' AS CdConcCausac, '' AS ConcCausac, '' AS DetDescripcion,
'' AS TipConcept, CAST('' AS Money) AS VrDebito, CAST('' AS Money) AS VrCredito, '' AS CdCuenta, '' AS NomCuenta, '' AS pVehiculo, '' AS NitTercero,
'' AS Razon_Social, '' AS CdCCosto, '' AS CCosto, '' AS CdSubCos, '' AS SubCosto, '' AS TipoAfiVehic,  CAST('' AS Money) AS VrBase, 
CAST(@VrDef AS DECIMAL(14,4)) AS  TarifBase, '' AS TipDocRef, CAST('' AS INT) AS DocRef, '' AS TipFac, '' AS DetFactura, '' AS IdCiaFac,
CAST('' AS INT) AS ItemFac, CAST('' AS DATETIME) AS FecVence,  CAST('' AS INT) AS NumLiquida, '' AS CiaLiquida, CAST('' AS Money) AS VrAbonado,
CAST('' AS INT) AS EstadoReg
END        
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCausacionLiq]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 01/08/2017
-- Description:	Imprimir Formato de Liquidaciones y traer las casuaciones de otros pagos
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCausacionLiq]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
 --CONSULTA PARA TRAER OTROS PAGOS QUE SE REALIZARON EN LA LIQUIDACION
'' AS TipDoc, CAST('' AS INT) AS Causacion, '' AS IdCia, CAST('' AS DATETIME) AS Fecha, CAST('' AS DATETIME) AS FecVence, ''AS IdProv,
'' AS IdConcepto, '' AS Descripcion, '' AS TipoConc, CAST('' AS MONEY) AS VrCredito, '' AS CdCuenta, '' AS NitTercero, '' AS pVehiculo, 
'' AS TipoAfiVehic, '' AS TipFac, ''AS Factura, '' AS IdCiaFac, CAST('' AS INT) AS ItemFac, ''AS TipCom, CAST('' AS INT) AS Comprobante,
'' AS IdCiaCom, CAST('' AS INT) AS  Item, CAST('' AS BIT) AS EsEgreso, '' AS DetAbono, CAST('' AS DATETIME) AS FecEgr, CAST('' AS MONEY) AS VrAbono,
'' AS TipLiq, CAST('' AS INT) AS  Liquidacion, '' AS IdCiaLiq, CAST('' AS DATETIME) AS  FecIniOdp, CAST('' AS DATETIME) AS  FecFinOdp
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspComFacturaNit]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 03/08/2017
-- Description:	Imprimir Formato de Liquidaciones ComFacturaNit
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspComFacturaNit]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipFac, CAST('' AS INT) AS Factura, '' AS IdCia, CAST('' AS INT) AS Item,  CAST('' AS MONEY) AS  ValorSaldo, CAST('' AS MONEY) AS VrFactura,
CAST('' AS MONEY) AS VrAbonado, '' AS  TipDoc,  '' AS Documento, '' AS IdCiaDoc, '' AS TipRef, '' AS DocRef, '' AS IdCiaRef, CAST('' AS DATETIME) AS FecEmision,
CAST('' AS DATETIME) AS FecVence, '' AS IdCuent, '' AS NomCuenta, '' AS TipCom,CAST('' AS INT) AS Comprobante, CAST('' AS INT) AS ItemCom, '' AS Referencia,
'' AS Detalle, '' AS IdProveedor, '' AS RazonSocial, '' AS pVehiculo, '' AS VehPropio, CAST('' AS INT) EstadoApr, CAST('' AS MONEY) AS MontoAprob
 END


GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspContratoFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/04/2019
-- Description:	Imprimir Formato de Contrato de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspContratoFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
--Encabezado
'' AS TipDoc, CAST('' AS INT) AS Contrato, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, CAST('' AS DATETIME) AS FechaInicio, CAST('' AS DATETIME) AS FechaFin,
'' AS IdCliente, '' AS RazonSocial, '' AS UnionTemporal, '' AS IdAgencia, '' AS Agencia, '' AS IdVend, '' AS NomVendedor,'' AS IdTarifCom, '' AS IdForma, CAST('' AS BIT) AS Plazos,
'' AS  TipoPago, '' AS Modalidad, '' AS TipoLiquid, '' AS CodTarRet, '' AS CodTarIca, CAST('' AS MONEY) AS  VrPresupuesto, CAST('' AS MONEY) AS  VrSaldoPresup, CAST('' AS MONEY) AS  VrCobro,
CAST('' AS MONEY) AS  VrCargos, CAST('' AS MONEY) AS  VrRetencion, CAST('' AS MONEY) AS  VrReteIca, CAST('' AS MONEY) AS  VrDctos, CAST('' AS MONEY) AS VrIva, '' AS CdDescuento,
CAST(@VrDef AS DECIMAL(14,4)) AS Cantidad, CAST(@VrDef AS DECIMAL(14,4)) AS CantPasajeros, '' AS IdMneda, '' AS Mneda, CAST(@VrDef AS DECIMAL(14,4)) AS Peso, CAST('' AS INT) AS NumAprob,
''AS IdCiaApr, CAST('' AS DATETIME) AS FecAprob, '' AS TipOdp, CAST('' AS INT) AS NumOdp, ''AS IdCiaOdp, CAST('' AS DATETIME) AS FechaOdp, '' AS TipFac, CAST('' AS INT) AS Factura, 
''AS IdCiaFac, CAST('' AS DATETIME) AS FechaFac, '' AS OrigenAdd, CAST('' AS BIT) AS EsLicitacion, CAST('' AS BIT) AS Anulado, CAST('' AS DATETIME) AS FecDev, '' AS Observacion,
'' AS IdEstado, '' AS  Estado, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario, '' AS CdCarga,  '' AS IdGrupo,
'' AS Grupo, '' AS IdRutaG, '' AS RutaG,
-- Datos de anexo
'' AS TipContrato, '' AS IdContrato, '' AS IdObjCOE, '' AS ObjContrato, '' AS NomCliente, '' AS TelCliente, '' AS emlCliente, '' AS DireccionCli, '' AS Observacion, '' AS NombArchivo, 
'' AS DescripCarga, '' AS Clausulas,  '' AS Responsable, '' AS NombreResp,
--Datos de detalles
CAST('' AS INT) AS Item, '' AS IdHorario, '' AS TipPed, CAST('' AS INT) AS Pedido, '' AS CiaPed, CAST('' AS INT) AS ItemPed, '' AS IdVehiculo, '' AS CdTipVeh, '' AS TipoVehiculo,
CAST('' AS INT) AS NumPasajeros, CAST(@VrDef AS DECIMAL(14,4)) AS PesoNeto, CAST('' AS MONEY) AS VrUnitario, CAST('' AS MONEY) AS VrPago, '' AS IdRuta, '' AS Ruta,
'' AS Referencia1, '' AS Referencia2, ''AS Referencia3, CAST('' AS BIT) AS EsRutaCliente, '' AS CdCiuOrigen, '' AS CiuOrigenD, '' AS DeptOrigen, '' AS DirOrigen, CAST('' AS DATETIME) AS FecOrigen,
'' AS CdCiuDestino, '' AS  CiuDestinoD, '' AS  DeptDestino, '' AS DirDestino, CAST('' AS DATETIME) AS FecDestino, CAST('' AS INT) AS DiasDisp, CAST('' AS MONEY) AS  VrDia, '' AS Parada,
'' AS CdTipRuta, '' AS CdTipServicio, '' AS TipRes, CAST('' AS INT) AS NumRes, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS INT) AS Cantveh, CAST('' AS BIT) AS Retorno,
CAST('' AS MONEY) AS VrMonitor, CAST('' AS INT) AS CantMonitor, CAST('' AS MONEY) AS VrMaxRec, CAST('' AS INT) AS NumDias, '' AS TipoTarifa,  '' AS IdColegio, '' AS NomColegio, '' AS Codigo,
'' AS Itinerario, CAST('' AS BIT) AS VLargo, CAST('' AS INT) AS IdOtroSi,  CAST('' AS BIT) AS ItemAnuladoOS, CAST('' AS BIT) AS ProcEstudte,
--Datos de conceptos
'' AS TipDocC, CAST('' AS INT) AS DocumentoC, '' AS IdCiaC, CAST('' AS INT) AS Itemc, '' AS Descripcion, CAST(@VrDef AS DECIMAL(14,4)) AS Tarifa, '' AS TipoConc, '' AS RubroConcep, CAST('' AS INT) AS Cantidadc,
CAST('' AS MONEY) AS VrUnitarioc, CAST(@VrDef AS DECIMAL(14,4)) AS TarifIva, '' AS IdConcepto, '' AS CdCuenta, '' AS NitTercero, '' AS  NombreTerc, '' AS CdTipoEscc, '' AS TipEsc, CAST('' AS DATETIME) AS FechaNov, 
CAST('' AS MONEY) AS VrBase, '' AS TipoTarif, '' AS RefConc, CAST('' AS BIT) AS Fijos, CAST('' AS INT) AS IncBaseRet, '' AS Referencia2c, '' AS Referencia3c, CAST('' AS INT) AS ItemDoc,
--Datos del cliente
'' AS TipoId, '' AS Dv, ''AS CodCliente, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail,
'' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona, '' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupoClie, '' AS GrupoClie
 END

         
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspContratoRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 01/03/2017
-- Description:	Imprimir contratos para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspContratoRel]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Contrato,'' IdCia,'' AS Compania,'' AS CdCarga,'' AS DescripCarga,CAST('' AS datetime) AS Fecha, CAST('' AS datetime) AS FechaInicio,CAST('' AS datetime) AS FechaFin,
'' AS UnionTemporal,'' AS IdCliente,'' AS RazonSocial,'' AS IdAgencia, '' AS CodAgencia,'' AS Agencia,'' AS DirAgncia,'' AS TelAgncia,CAST('' AS Money) AS VrCupo,CAST('' AS Money) AS VrSaldo,
'' AS NomCliente,'' AS TelCliente, '' AS emlCliente , '' AS DireccionCli,'' AS IdVend,''  AS NomVendedor,'' AS IdTarifCom, '' AS TipContrato,
'' AS IdContrato, '' AS IdObjCOE,'' AS ObjContrato,  '' AS IdForma, '' AS IdMneda, '' AS Mneda,'' AS  Plazos,'' AS  TipoPago,'' AS  Modalidad, '' AS  TipoLiquid, '' AS  CodTarRet,
'' AS  CodTarIca, CAST('' AS Money) AS VrPresupuesto,CAST('' AS Money) AS  VrSaldoPresup,CAST('' AS Money) AS  VrCobro,CAST('' AS Money) AS  VrCargos,CAST('' AS Money) AS  VrRetencion, CAST('' AS Money) AS  VrReteIca,
CAST('' AS Money) AS  VrDctos, CAST('' AS Money) AS  VrIva, CAST('' AS INT) AS  Cantidad,CAST('' AS INT) AS CantPasajeros, '' AS  NumAprob,'' AS IdCiaApr,CAST('' AS datetime) AS FecAprob,
'' AS TipOdp, CAST('' AS INT) AS  NumOdp, '' AS IdCiaOdp,CAST('' AS datetime) AS FechaOdp, '' AS TipFac, CAST('' AS INT) AS  Factura, '' AS IdCiaFac,CAST('' AS datetime) AS FechaFac,
'' AS OrigenAdd, CAST('' AS bit) AS EsLicitacion, CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev,'' AS  Observacion, '' AS  Clausulas, '' AS  Responsable,
'' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys, CAST('' AS datetime) AS FecUpdate,'' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario, '' AS IdGrupo, '' AS Grupo, '' AS IdRutaG, '' AS  RutaG

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspContratoRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 01/03/2017
-- Description:	Imprimir contratos para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspContratoRelDet]
AS
--Encabezado
SELECT '' AS TipDoc, CAST('' AS INT) AS Contrato, '' AS IdCia, '' AS Compania, CAST('' as datetime) AS Fecha, CAST('' as datetime) AS FecInicio, CAST('' as datetime) AS FechaFin,
'' AS UnionTemporal,'' AS IdCliente,'' AS RazonSocial,'' AS IdAgencia,'' AS Agencia, '' AS IdVend,''  AS NomVendedor,'' AS IdTarifCom, '' AS TipContrato, '' AS IdForma,
'' AS  Plazos,'' AS  TipoPago,'' AS  Modalidad, '' AS  TipoLiquid, '' AS  CodTarRet, '' AS  CodTarIca, 
CAST('' AS Money) AS VrPresupuesto,CAST('' AS Money) AS  VrSaldoPresup,CAST('' AS Money) AS  VrCobro,CAST('' AS Money) AS  VrCargos,
CAST('' AS Money) AS  VrRetencion, CAST('' AS Money) AS  VrReteIca, CAST('' AS Money) AS  VrDctos, CAST('' AS Money) AS  VrIva,
'' AS CdDescuento, CAST('' AS INT) AS  Cantidad,CAST('' AS INT) AS CantPasajeros, '' AS IdMneda,'' AS Mneda,'' AS Peso, '' AS  NumAprob,'' AS IdCiaApr,CAST('' AS datetime) AS FecAprob,
'' AS TipOdp, CAST('' AS INT) AS  NumOdp, '' AS IdCiaOdp,CAST('' AS datetime) AS FechaOdp, '' AS TipFac, CAST('' AS INT) AS  Factura, '' AS IdCiaFac,CAST('' AS datetime) AS FechaFac,
'' AS OrigenAdd, CAST('' AS bit) AS EsLicitacion, CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev,'' AS  Observacion,
'' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys, CAST('' AS datetime) AS FecUpdate,'' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario, '' AS CdCarga,
--Anexos
'' AS TipContrato, '' AS IdContrato, '' AS IdObjCOE, '' AS ObjContrato,'' AS NomCliente, '' AS TelCliente, '' AS emlCliente,'' AS DireccionCli,
'' AS Observacion,''  AS NombArchivo,'' AS DescripCarga, '' AS Clausulas, '' AS Responsable,
--Detalles
CAST('' AS INT) AS Item, '' AS IdHorario,'' AS TipPed, CAST('' AS INT) AS Pedido, '' AS CiaPed, CAST('' AS INT) AS ItemPed, '' AS IdVehiculo,
'' AS CdTipVeh, '' AS TipoVehiculo, CAST('' AS INT) AS NumPasajeros, '' AS PesoNeto, CAST('' AS Money) AS VrUnitario, CAST('' AS Money) AS VrPago, '' AS IdRuta,
'' AS Ruta, '' AS  Referencia1, '' AS Referencia2, '' AS Referencia3, CAST('' AS BIT) AS EsRutaCliente, '' AS CdCiuOrigen, '' as CiuOrigenD, '' AS DeptOrigen, '' AS DirOrigen, 
CAST('' AS datetime) AS FecOrigen, '' AS CdCiuDestino, '' AS  CiuDestinoD,'' AS DeptDestino, '' AS DirDestino,CAST('' AS datetime) AS FecDestino, CAST('' AS INT) AS  DiasDisp,
CAST('' AS Money) AS VrDia, '' AS Parada, '' AS CdTipRuta, '' AS CdTipServicio,'' AS TipRes,CAST('' AS INT) AS NumRes, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS INT) AS Cantveh,
CAST('' AS BIT) AS Retorno, CAST('' AS MONEY) AS VrMonitor, CAST('' AS INT) AS CantMonitor, CAST('' AS MONEY) AS VrMaxRec, CAST('' AS INT) AS NumDias, '' AS TipoTarifa, 
''AS IdColegio, '' AS NomColegio, '' AS Itinerario, CAST('' AS BIT) AS VLargo,
--Conceptos
'' AS TipoDocC, '' AS DocumentoC,''  AS IdCiaC, CAST('' AS INT) AS Itemc, '' AS Descripcion,'' AS Tarifa, '' AS TipoConc, '' AS RubroConcep, 
CAST('' AS INT) AS Cantidadc, CAST('' AS Money) AS VrUnitarioc, '' AS TarifIva, '' AS IdConcepto, '' AS CdCuenta, '' AS NitTercero,
'' AS NombreTerc,'' AS CdTipoEscc, '' AS TipEsc, CAST('' AS datetime) AS FechaNov, CAST('' AS Money) AS VrBase, ''  AS TipoTarif, '' AS RefConc,
'' AS Fijos, '' AS IncBaseRet, '' AS Referencia2c,'' AS Referencia3c,
--Datos del cliente
'' AS TipoId, '' AS Dv, '' AS Codigo, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail, '' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona,
'' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupo, '' AS GrupoClie
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspCumplidosFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 27/09/2017
-- Description:	Imprimir Formato de cumplido de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspCumplidosFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc,  CAST('' AS INT) AS Cumplido, '' AS IdCia, '' AS Compania,  CAST('' AS DATETIME) AS Fecha,'' AS TipResE, CAST('' AS INT) AS ReservaE, 
'' AS IdCiaResE, CAST('' AS INT) AS ItemResE, CAST('' AS DATETIME) AS FecReserva, '' AS IdClieFac, '' AS Cliente, '' AS TipFac, 
CAST('' AS INT) AS Factura, '' AS IdCiaFac, '' AS CdRuta,  '' AS Ruta, '' AS CdOrigen, '' AS CiudadOrigen,
'' AS CdDestino, '' AS CiudadDestino, CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev, 
'' AS TipoComp, CAST('' AS INT) AS NumComp,  '' AS CodConcepto,  '' AS Observacion, 
'' AS IdEstado, '' AS Estado, '' AS OrigenAdd, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, 
'' AS IdUsuario, '' AS ObservAnulado, '' AS CdCenCosto, '' AS CdSubCenCos, CAST('' AS MONEY) AS VrPago,  CAST('' AS MONEY) AS VrCobro,  
CAST('' AS MONEY) AS VrAfiliados,  CAST('' AS MONEY) AS VrPropios, CAST('' AS MONEY) AS VrTotalServ,  CAST('' AS MONEY) AS VrTotalPagos, 
'' AS CodTarRtc,  CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS VrReteCree, CAST('' AS MONEY) AS VrNeto,
--Detalle
 CAST('' AS INT) AS Item, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, 
 '' AS EstadoItemRes, CAST('' AS MONEY) AS VrRecorridos, '' AS IdVehiculo,'' AS IdPoseedor, '' AS NomPoseedor,
 '' AS IdConductor,'' AS NomConductor,  '' AS TipoAfil
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevAntRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 25/07/2017
-- Description:	Imprimir devolución anticipos para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevAntRel]
AS
--Encabezado
SELECT CAST('' AS INT) AS Devolucion, '' AS IdCia, '' AS Compania, CAST('' AS datetime) AS FechaDev, '' AS IdConcepto, '' AS Concepto, '' AS TipDoc, 
CAST('' AS INT) AS Anticipo, '' AS IdCiaDoc,  CAST('' AS datetime) AS FecDoc, '' AS TipDoc, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, 
'' AS IdVehiculo, '' AS NitPoseedor,'' AS Poseedor, '' AS CedConductor, '' AS Conductor,  CAST('' AS Money) AS VrDevolucion, '' AS CdCta, '' AS NumeroCta, '' AS IdBanco, 
'' AS Banco, '' AS CdCuenta, '' AS TipoPago, '' AS NumCheque, CAST('' AS datetime) AS FecCheque,  '' AS Beneficiario, '' AS Modalidad, CAST('' AS Money) AS VrAnticipo, 
CAST('' AS Money) AS VrAbonado,  CAST('' AS Money) AS SaldoActual, '' AS ModdDev, '' AS Origen_Add, '' AS TipCom, CAST('' AS INT) AS  Comprobante, '' AS IdCiaCom,
'' AS NumCheque, CAST('' AS datetime) AS FecCheque, '' AS IdCta, '' AS NumeroCta, '' AS IdBanco, '' AS Banco, '' AS IdCuenta, '' AS Beneficiario,
'' AS CedBenef, CAST('' AS INT) AS  Cantidad, CAST('' AS datetime) AS FechaVence, CAST('' AS INT) AS  NumPresAnt, '' AS TipCom, CAST('' AS INT) AS  Comprobante,
'' AS IdCiaCom, '' AS Observacion, '' AS IdEstado, CAST('' AS datetime) AS TimeSys,  '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevCauRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 25/07/2017
-- Description:	Imprimir devolución causaciones para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevCauRel]
AS
--Encabezado
SELECT CAST('' AS INT) AS Devolucion, '' AS CdCia, '' AS Compania, CAST('' AS datetime) AS Fecha, '' AS CdConcepto, '' AS Concepto, 
'' AS TipDoc, CAST('' AS INT) AS Causacion, '' AS IdCiaDoc,  CAST('' AS datetime) AS FecDoc, '' AS IdProv, '' AS RazonSocial, '' AS Factura, 
CAST('' AS Money) AS VrTotal, CAST('' AS Money) AS VrOtros, CAST('' AS Money) AS VrNeto, '' AS ModdDev, '' AS OrigenAddM, '' AS TipCom,
CAST('' AS INT) AS  Comprobante, '' AS IdCiaCom, '' AS Observ, '' AS CdEstado, CAST('' AS datetime) AS TimeSys, CAST('' AS datetime) AS FecUpdate,
'' AS IdCiaCrea, '' AS CdUsuario, '' AS Usuario
           
           
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevCumFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 04/10/2017
-- Description:	Imprimir Formato de Devolución de Generaciones de Ingresos de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevCumFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDev, '' AS TipoDoc, CAST('' AS INT) AS Devolucion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto, '' AS TipDoc,
CAST('' AS INT) AS Cumplido, '' AS IdCiaDoc,  CAST('' AS DATETIME) AS FecDoc, '' AS ModdDev, '' AS OrigenAdd, '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, 
'' AS Observacion, CAST('' AS DATETIME) AS TimeSys, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario,
--DatosCumplido
CAST('' AS DATETIME) AS FechaCum, '' AS TipResE, CAST('' AS INT) AS ReservaE, '' AS IdCiaResE, CAST('' AS INT) AS ItemResE, '' AS TipFac,
CAST('' AS INT) AS Factura, '' AS IdCiaFac, '' AS IdClieFac, '' AS Cliente, '' AS CdRuta, '' AS Ruta, '' AS CdOrigen, '' AS CiuOrigen, 
'' AS CdDestino, '' AS CiuDestino, CAST('' AS BIT) AS Anulado, '' AS TipoComp,  CAST('' AS INT) AS NumComp, '' AS CodConcepto, '' AS ConceptoCum, '' AS ObservCum,
CAST('' AS MONEY) AS VrPago,  CAST('' AS MONEY) AS VrCobro,  CAST('' AS MONEY) AS VrAfiliados,  CAST('' AS MONEY) AS VrPropios,  CAST('' AS MONEY) AS VrTotalServ, 
CAST('' AS MONEY) AS VrTotalPagos, '' AS CodTarRtc,  CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS VrReteCree,  CAST('' AS MONEY) AS VrNeto,
--Detalles CumplidosReservas
CAST('' AS INT) AS Item, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, '' AS EstadoItemRes, CAST('' AS MONEY) AS VrRecorridos,
'' AS IdVehiculo, '' AS IdPoseedor, '' AS  NomPoseedor, '' AS IdConductor, '' AS  NomConductor, '' AS TipoAfil
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevFacFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 22/09/2017
-- Description:	Imprimir Formato de Devolución de Factura de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevFacFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDev, '' AS TipoDoc, CAST('' AS INT) AS Devolucion, '' AS CdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS DescConcepto, '' AS TipoFac,
CAST('' AS INT) AS NumFactura, '' AS IdCiaDoc,  CAST('' AS DATETIME) AS FecDoc, '' AS IdCliente, ''  AS NomCliente, '' AS Cod_Agencia, '' AS NomAgencia, '' AS Cod_Agencia,
CAST('' AS MONEY) AS VrSubTotal, CAST('' AS MONEY) AS VrDcto, CAST('' AS MONEY) AS VrIva, CAST('' AS MONEY) AS VrRetFte, CAST('' AS MONEY) AS VrRetIca, CAST('' AS MONEY) AS VrReteIVA,
CAST('' AS MONEY) AS VrFletes,  CAST('' AS MONEY) AS VrOtros,  CAST('' AS MONEY) AS VrCargos,  CAST('' AS MONEY) AS VrOtrDcto,  CAST('' AS MONEY) AS VrCostos,  CAST('' AS MONEY) AS VrSobretasa,
CAST('' AS MONEY) AS VrImpGlobal,  CAST('' AS MONEY) AS VrFaltantes, CAST('' AS MONEY) AS VrAnticipos, CAST('' AS MONEY) AS VrNeto, CAST('' AS MONEY) AS CantTotal, CAST('' AS MONEY) AS BaseImp,
CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS VrReteCREE, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, '' AS CodTarRtc, '' AS CdVend, '' AS Vendedor, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaCom,
'' AS CdLocEnv, '' AS CiudadEnvio,  CAST('' AS INT) AS Pedido, '' AS IdCiaPed,  CAST('' AS INT) AS Cotizacion, '' AS IdCiaCot, CAST('' AS DATETIME) AS FecPedido, '' AS Modalidad, '' AS ModdDev,
'' AS TipCom, '' AS TipoCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, '' AS Observ, CAST('' AS DATETIME) AS TimeSys, '' AS IdCiaCrea, '' AS CdUsuario, '' AS Usuario, '' AS Leyenda,
----detalles
CAST('' AS INT) AS  Item, CAST('' AS DATETIME) AS FechaFact, '' AS TipRes, CAST('' AS INT) AS Reserva, ''AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS DATETIME) AS FecReserva, '' AS Descripcion,
CAST('' AS INT) AS Cantidad, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrUnitario, CAST('' AS MONEY) AS VrCosto, '' AS UndTarifa, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIva,
CAST('' AS MONEY) AS VrImpuesto, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaDct, CAST('' AS MONEY) AS VrDescuento, '' AS DocCliente, '' AS Referencia1, '' AS Referencia2, '' AS Referencia3,
'' AS CdConcepto, '' AS CdCCosto, '' AS CdSubCos, '' AS NitTercero, '' AS CdAgencia, '' AS pVehiculo, '' AS TipoAfiVehic, '' AS IdOrigen, '' AS IdDestino, CAST('' AS BIT) AS Anulado,
'' AS TipDocRef,  CAST('' AS INT) AS NumDocRef, '' AS IdCiaRef, CAST('' AS DATETIME) AS FecDocRef, '' AS CodTarDct,
----Información del cliente
'' AS TercTipo, '' AS  TercDv, '' AS TercCodigo, '' AS TercNomCial, '' AS TercSigal, '' AS TercDireccion, '' AS TercCdCiudad, '' AS NomCiudad, '' AS CdDep, '' AS TercDpto, '' AS TercTelefono,
'' AS TercFax, '' AS TercEmail, '' AS TercSitioWeb, '' AS CdSector, '' AS SectorEco, '' AS CdRegimen, '' AS Regimen, '' AS TercTipEnte,  '' AS NitRepLeg, '' AS NomRepLeg, '' AS ClieNitContac,
'' AS ClieNomContacto, '' AS ClieTelContac, '' AS ClieEmailContac, '' AS CargContac, CAST('' AS INT) AS DiasEntga, ''  AS CdSubzona, '' AS Subzona, '' AS Zona, '' AS CdGrupoCli, '' AS GrupoClie,
CAST('' AS BIT) AS ExcIva, CAST('' AS BIT) AS LiqFletes, CAST('' AS BIT) AS Autoret, CAST('' AS MONEY) AS VrCupo, CAST('' AS MONEY) AS VrSaldo, '' AS AgeDireccion, '' AS AgeTelefono, '' AS AgeFax,
'' AS AgeIdCiudad, '' AS AgeCiudad, '' AS AgeCodDep, '' AS AgeDpto, '' AS AgeReferencia,
--FACE
'' AS EstadoFE, '' AS PrefijoFace, CAST('' AS INT) AS NumFace, '' AS CUFE, '' AS ResolucionFace, '' AS RangoNum, '' AS FecVigencia, CAST('' AS IMAGE) AS QR, CAST('' AS DATETIME) AS FechaValidacion,
--FACE Información de la factura devuelta
'' AS CUFEFac, CAST('' AS DATETIME) AS FecValidaFac, '' AS PrefijoFACEFac
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevFacturasRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/11/2017
-- Description:	Imprimir Listados de Devoluciones de Factura de Transporte de Especial
-- =============================================
create PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevFacturasRel]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDev, CAST('' AS INT) AS Devolucion, '' AS IdCia, CAST('' AS DATETIME) AS Fecha, '' AS CdConcepto, '' AS Concepto, 
'' AS TipDoc, CAST('' AS INT) AS Factura, '' AS IdCiaDoc, CAST('' AS DATETIME) AS FecDoc, '' AS IdCliente,''  AS NomCliente, 
'' AS IdAgencia, CAST('' AS MONEY) AS VrSubTotal, CAST('' AS MONEY) AS VrDescuento, CAST('' AS MONEY) AS VrImpuesto, 
CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteICA, CAST('' AS MONEY) AS VrReteIVA, CAST('' AS MONEY) AS VrFletes,  CAST('' AS MONEY) AS VrOtros,
CAST('' AS MONEY) AS VrCargos, CAST('' AS MONEY) AS VrOtrDcto, CAST('' AS MONEY) AS  VrCostos, CAST('' AS MONEY) AS VrSobretasa, CAST('' AS MONEY) AS VrImpGlobal, CAST('' AS MONEY) AS VrFaltantes,
CAST('' AS MONEY) AS VrAnticipos, CAST('' AS MONEY) AS VrNeto, CAST('' AS MONEY) AS VrAplicado, CAST(@VrDef AS DECIMAL(14,4)) AS Cantidad, CAST(@VrDef AS DECIMAL(14,4)) AS CantPuntos, 
CAST(@VrDef AS DECIMAL(14,4)) AS PuntosAcum, CAST(@VrDef AS DECIMAL(14,4)) AS BaseImp, CAST(@VrDef AS DECIMAL(14,4)) AS BaseRet, CAST(@VrDef AS DECIMAL(14,4)) AS BaseIca, 
CAST(@VrDef AS DECIMAL(14,4)) AS BaseRiv, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIva, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRiv, '' AS CodTarIva, '' AS CodTarRet, '' AS CodTarIca, '' AS CodTarRiv, '' AS IdCCosto, '' AS IdSubCos, '' AS IdVend, '' AS Vendedor,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaCom, '' AS CodTarCom, '' AS DirEnvio, '' AS IdLocEnv, CAST('' AS INT) AS DiasEntraga, '' AS NitContac, '' AS NomContac, '' AS TelContac,
'' AS emlContac, '' AS CargoContac, '' AS IdForma, '' AS DetallePago, CAST('' AS BIT) AS MulPlazos,  '' AS IdPlazo, '' AS CdMney, '' AS NitEmpTrans, '' AS EmpTrans,
'' AS pVehiculo, '' AS CdConductor, CAST('' AS INT) AS KmtVehic, '' AS CdRuta, '' AS TipPed, CAST('' AS INT) AS Pedido,  '' AS IdCiaPed,  '' AS TipRem, CAST('' AS INT) AS Remision, 
'' AS IdCiaRem, '' AS TipCot, CAST('' AS INT) AS Cotizacion, '' AS IdCiaCot, CAST('' AS DATETIME) AS FecPedido, CAST('' AS INT) AS AutzaMora, CAST('' AS INT) AS AutzaCupo,
'' AS Modalidad, '' AS CodAutoRet, '' AS OrigenAdd, '' AS TipCom,  CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, CAST('' AS INT) AS ZonaFrontera, CAST(@VrDef AS DECIMAL(14,4)) AS PesoTotal,
CAST(@VrDef AS DECIMAL(14,4)) AS UnidTotal, CAST(@VrDef AS DECIMAL(14,4)) AS VolTotal, CAST(@VrDef AS DECIMAL(14,4)) AS CantFalt, CAST('' AS MONEY) AS VrCostoRem, CAST('' AS MONEY) AS VrCostoAfi,
CAST('' AS MONEY) AS VrImpCons, CAST('' AS MONEY) AS VrReteCREE, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, '' AS CodTarRtc, CAST('' AS MONEY) AS BaseIvaObsq, CAST('' AS MONEY) AS VrIvaObsequio,
CAST('' AS MONEY) AS VrImpCarbono, CAST('' AS BIT) AS Parqueadero, CAST('' AS DATETIME) AS FecCuotaParq, CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev,
'' AS Observ, '' AS CdEstado, '' AS Estado, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuari, '' AS Usuario
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevGenRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 30/11/2017
-- Description:	Imprimir Devoluciones Generaciones de Ingresos
-- =============================================
create PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevGenRel]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
CAST('' AS INT) AS Devolucion, '' AS IdCia, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS TipDoc, CAST('' AS INT) AS Cumplido,
'' AS IdCiaDoc, CAST('' AS DATETIME) AS FecDoc, '' AS ModdDev, '' AS OrigenAdd, '' AS TipCom,  CAST('' AS INT) AS Comprobante, '' AS IdCiaCom,
'' AS Observacion, CAST('' AS DATETIME) AS TimeSys, '' AS IdCiaCrea, '' AS IdUsuario
END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevLiq]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 28/11/2017
-- Description:	Imprimir listados de devoluciones de liquidaciones
-- =============================================
create PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevLiq]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDev, CAST('' AS INT) AS Devolucion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto, 
'' AS TipDoc, CAST('' AS INT) AS Liquidacion, '' AS IdCiaDoc, CAST('' AS DATETIME) AS FecDoc, '' AS IdVehiculo, '' AS IdPoseedor,
''  AS Poseedor, '' AS IdConductor, '' AS Conductor, CAST('' AS MONEY) AS VrTotal, '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom,
'' AS ModdDev, '' AS Observacion, '' AS IdEstado, '' AS OrigenAdd, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, 
'' AS IdUsuario, '' AS Usuario
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevLiqRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 28/11/2017
-- Description:	Imprimir listados de devoluciones de liquidaciones
-- =============================================
create PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevLiqRel]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDev, CAST('' AS INT) AS Devolucion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto, 
'' AS TipDoc, CAST('' AS INT) AS Liquidacion, '' AS IdCiaDoc, CAST('' AS DATETIME) AS FecDoc, '' AS IdVehiculo, '' AS IdPoseedor,
''  AS Poseedor, '' AS IdConductor, '' AS Conductor, CAST('' AS MONEY) AS VrTotal, '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom,
'' AS ModdDev, '' AS Observacion, '' AS IdEstado, '' AS OrigenAdd, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, 
'' AS IdUsuario, '' AS Usuario
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevLiquidaFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 06/09/2017
-- Description:	Imprimir Formato de Devolución de Liquidaciones de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevLiquidaFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDev, '' AS TipoDoc, CAST('' AS INT) AS Devolucion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, 
'' AS Concepto, '' AS TipDoc, CAST('' AS INT) AS Liquidacion, ''AS IdCiaDoc, CAST('' AS DATETIME) AS FecDoc, '' AS IdVehiculo, '' AS IdPoseedor,
'' AS Poseedor, '' AS IdConductor, '' AS NomConductor, CAST('' AS MONEY) AS VrTotal, '' AS ModdDev, '' AS TipCom, CAST('' AS INT) AS Comprobante,
''AS IdCiaCom, '' AS Observacion,  CAST('' AS DATETIME) AS TimeSys, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario, '' AS Leyenda,
CAST('' AS INT) AS Item, '' AS TipCau, CAST('' AS INT) AS Causacion, '' AS IdCiaCau, CAST('' AS INT) AS ItemCau, CAST('' AS DATETIME) AS FechaCau,
'' AS CdConcCausac, '' AS Descripcion, CAST('' AS MONEY) AS VrAbono, '' AS NitPoseedor, '' AS NomPoseedor, '' AS pVehiculo, CAST('' AS BIT) AS EsVence,
'' AS TipOdp,  CAST('' AS INT) AS OrdenPago, '' AS IdCiaOdp, '' AS TipRes,  CAST('' AS INT) AS Reserva, '' AS IdCiaRes,  CAST('' AS MONEY) AS VrSaldoOrden,
'' AS CdCuenta, '' AS CdCuePagar, '' AS NumFactura,  '' AS CdCCosto, '' AS CCosto, '' AS CdSubCos, '' AS SubCosto,
--Datos Liquidacion
'' AS  IdConceptoLq, '' AS ConceptoLq,
--datos del poseedor
'' AS TercTipId, ''  AS TercDv, ''  AS TercCodigo, '' AS TercNomCial, '' AS TercDireccion, '' AS TercCdCiudad, '' AS NomCiudad, '' AS TercTelefono, '' AS TercEmail,
'' AS NumVeh, '' AS CdTipVeh, '' AS TipoVehiculo, '' AS CdMarca, '' AS MarcaVeh, '' AS CdLinVeh, '' AS LineaVeh, '' AS CdColor, '' AS NomColor, '' AS CdCarr, '' AS TipoCar, '' AS Modelo,
'' AS Config, CAST(@VrDef AS DECIMAL(14,4)) AS PesoVacio, CAST(@VrDef AS DECIMAL(14,4)) PesoMax, ''AS NumMotor, '' AS SerieChasis, '' AS NumSerie, '' AS CdRemque, '' AS NitEmpresa, 
'' AS VehNomEmpresa, '' AS CdTipProp, '' AS TipoProp, '' AS VehPropio, '' AS TipoAfil, '' AS NumSoat, CAST('' AS DATETIME) FecSoat, CAST('' AS DATETIME) AS VigSoat,
'' AS NitEmpSoat, '' AS CertGases,  CAST('' AS DATETIME) FecCertGas,  CAST('' AS DATETIME) AS VigCertGas, '' AS VehDescripcion
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevOdpFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 07/07/2017
-- Description:	Imprimir Orden de Pago
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevOdpFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDev, CAST('' AS INT) AS Devolucion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto, '' AS TipDoc,
CAST('' AS INT) AS OrdPago, ''AS IdCiaDoc, CAST('' AS DATETIME) AS FecDoc, ''AS IdVehiculo, '' AS NumVeh, '' AS IdPropietario, '' AS  Propietario,
'' AS IdPoseedor, '' AS Poseedor, '' AS IdConductor, '' AS  Conductor, CAST('' AS BIT) AS CxPagar, '' AS ModdDev, '' AS TipCom, '' AS TipoCom,
CAST('' AS INT) AS Comprobante, '' AS IdCiaCom,'' AS Observacion, '' AS IdEstado, '' AS OrigenAdd, CAST('' AS DATETIME) AS TimeSys,
CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario,
--Orden Reserva
'' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento,  
CAST('' AS MONEY) AS VrRetencion,  CAST('' AS MONEY) AS VrReteIca, CAST('' AS MONEY) AS VrReteCree, CAST('' AS MONEY) AS VrAnticipos,  
CAST('' AS MONEY) AS VrOtrosDctos,  CAST('' AS MONEY) AS VrImpuestos,  CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto,
CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS BaseIca, CAST('' AS MONEY) AS BaseCree, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca,
CAST(@VrDef AS DECIMAL(14,4)) AS  TarifaRtc, '' AS Referencia,  CAST('' AS MONEY) AS VrConcPagos,  CAST('' AS MONEY) AS VrConcDctos,  CAST('' AS MONEY) AS VrConcFondo,
CAST('' AS MONEY) AS VrConcSeguro,  CAST('' AS MONEY) AS VrConcAporte,  CAST('' AS MONEY) AS VrConcImpuesto, CAST('' AS MONEY) AS VrRecCaja, CAST('' AS MONEY) AS VrSeguros,
CAST('' AS MONEY) AS VrFondos, CAST('' AS MONEY) AS VrAportes,
  --Datos de OPAGO
'' AS  Modalidad, '' AS IdConcOP, '' AS ConcOP, CAST('' AS INT) AS Cantidad,
--DATOS RESERVA
CAST('' AS MONEY) AS  VrPagos,
            --Datos del vehiculo
'' AS TipoId, ''AS Dv, '' AS IdLocal, '' AS Localidad, '' AS Direccion, '' AS Telefono, '' AS TelMovil, '' AS e_mail, '' AS IdLugar, '' AS Localidad,
'' AS IdTipoVeh, '' AS TipoVehiculo, '' AS IdMarca,'' AS Marca, '' AS Modelo, '' AS Config, '' AS TipoAfil, '' AS Descripcion
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspDevOdpRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 26/07/2017
-- Description:	Imprimir Devoluciones Orden de Pago
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspDevOdpRel]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
CAST('' AS INT) AS Devolucion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto,
'' AS TipDoc, CAST('' AS INT) AS OrdPago, '' AS IdCiaDoc, CAST('' AS DATETIME) AS FecDoc, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, 
'' AS IdVehiculo, '' AS NumVeh, '' AS IdPoseedor, ''  AS Poseedor, '' AS IdConductor, '' AS Conductor, CAST('' AS BIT) AS CxPagar,
CAST('' AS DATETIME) AS FechaVence, CAST('' AS BIT) AS LiqReservas, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento,
CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteIca, CAST('' AS MONEY) AS VrReteCree, CAST('' AS MONEY) AS VrAnticipos,
CAST('' AS MONEY) AS VrOtrosDctos, CAST('' AS MONEY) AS VrImpuestos, CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto,
CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS BaseIca, CAST('' AS MONEY) AS BaseCree, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet,
'' AS NumCheque, '' AS Referencia, '' AS ModdDev, '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, '' AS Observacion, 
'' AS IdEstado, '' AS Estado, CAST('' AS DATETIME) AS TimeSys,CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario
END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFacturaFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 28/08/2017
-- Description:	Imprimir Formato de Factura de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFacturaFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS Tip_Doc, '' AS TipoDoc, CAST('' AS INT) AS NumFactura, '' AS CdCia, '' AS Compania, CAST('' AS DATETIME) AS FechaDoc, '' AS CdConcepto, '' AS DescConcepto, '' AS IdCliente,
''  AS NomCliente, '' AS IdAgenc, '' AS NomAgencia, '' AS Cod_Agencia, CAST('' AS DATETIME) AS FechaVence, CAST('' AS MONEY) AS VrSubTotal, CAST('' AS MONEY) AS VrDcto,
CAST('' AS MONEY) AS VrIva, CAST('' AS MONEY) AS VrRetFte, CAST('' AS MONEY) AS VrRetIca, CAST('' AS MONEY) AS VrReteIVA, CAST('' AS MONEY) AS VrFletes,  CAST('' AS MONEY) AS VrOtros,
CAST('' AS MONEY) AS VrCargos, CAST('' AS MONEY) AS VrOtrDcto, CAST('' AS MONEY) AS  VrCostos, CAST('' AS MONEY) AS VrSobretasa, CAST('' AS MONEY) AS VrImpGlobal, CAST('' AS MONEY) AS VrFaltantes,
CAST('' AS MONEY) AS VrAnticipos, CAST('' AS MONEY) AS VrNeto, CAST('' AS MONEY) AS VrAplicado, CAST(@VrDef AS DECIMAL(14,4)) AS CantTotal, CAST(@VrDef AS DECIMAL(14,4)) AS PesoTotal, 
CAST(@VrDef AS DECIMAL(14,4)) AS UnidTotal, CAST(@VrDef AS DECIMAL(14,4)) AS VolTotal, CAST(@VrDef AS DECIMAL(14,4)) AS CantFalt, CAST('' AS MONEY) AS VrCostoRem, CAST('' AS MONEY) AS VrCostoAfi,
CAST('' AS MONEY) AS BaseImp, CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS BaseIca, CAST('' AS MONEY) AS BaseRiv, CAST(@VrDef AS DECIMAL(14,4)) AS TarifIva, CAST(@VrDef AS DECIMAL(14,4)) AS TarifRet,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifIca, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRiv, '' AS NitVend, '' AS Vendedor, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaCom,  '' AS  CodiTarIva, '' AS CodiTarRet,
'' AS CodiTarIca, '' AS CodiTarRiv, '' AS DirEnvio, '' AS IdCiuEnvio,
'' AS CiudadEnvio, CAST('' AS INT) AS DiasEntraga, '' AS FacNitContac, '' AS FacNomContac, '' AS FacTelContac, '' AS FacEmailContac, '' AS CargoContac, '' AS  CdForma, '' AS DetallePago,
CAST('' AS BIT) AS MulPlazos, '' AS CdPlazo, '' AS Plazo, CAST('' AS INT) AS NVmto, CAST('' AS INT) AS DiasPago, '' AS NitEmpTrans, '' AS EmpTrans, '' AS TipPed, CAST('' AS INT) AS Pedido, '' AS IdCiaPed,
'' AS TipRemision, CAST('' AS INT) AS NumRemision, '' AS TipCot, CAST('' AS INT) AS NumCotizacion, '' AS CiaCotiza, CAST('' AS DATETIME) AS FecPedido,  CAST('' AS INT) AS AutzaMora, CAST('' AS INT) AS AutzaCupo,
'' AS Modalidad, CAST(@VrDef AS DECIMAL(14,4)) AS KmtVehic, '' AS TipCom, ''AS TipoCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, CAST('' AS BIT) AS FacAnulado, CAST('' AS INT) AS NumDev,
CAST('' AS DATETIME) AS FecDev, '' AS Observ, CAST('' AS MONEY) AS VrReteCREE, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, '' AS CodiTarRtc, '' AS CdEstado, CAST('' AS DATETIME) AS Fec_Add, 
CAST('' AS DATETIME) AS Fec_Update, '' AS IdCiaCrea, '' AS CdUsuario, '' AS Usuario, '' AS Leyenda,
--detalles de la reserva
CAST('' AS INT) AS Item, CAST('' AS INT) AS TipoReg, CAST('' AS DATETIME) AS FechaFact, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS DATETIME) AS FecReserva,
'' AS Descripcion, CAST(@VrDef AS DECIMAL(14,4)) AS  Cantidad, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrUnitario, CAST('' AS MONEY) AS VrCosto, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIva,
CAST('' AS MONEY) AS VrImpuesto, CAST(@VrDef AS DECIMAL(14,4))  AS TarifaDct, CAST('' AS MONEY) AS VrDescuento, '' AS DocCliente, '' AS Referencia1, '' AS Referencia2,
--26-05-2021.Yaqueline Lizarazo Diaz. Se agrega campo para mostrar el nombre del estudiante, correspondiente al documento de la Referencia2.
'' AS NomEstudiante,
'' AS Referencia3, '' AS CdConceptoD,
'' AS CdCCosto, '' AS CdSubCos, '' AS NitTercero, '' AS CdAgencia,  '' AS pVehiculo, '' AS IdOrigen, '' AS IdDestino, CAST('' AS BIT) AS Anulado, '' AS TipDocRef, CAST('' AS INT) AS NumDocRef,
'' AS IdCiaRef, CAST('' AS DATETIME) AS FecDocRef, '' AS CodTarDct, '' AS CodTarRet, '' AS CodTarIca,  CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet, CAST('' AS MONEY) AS VrRetencion, CAST('' AS BIT) AS Anulado, '' AS TipDocRef, 
CAST('' AS INT) AS NumDocRef, '' AS IdCiaRef, CAST('' AS DATETIME) AS FecDocRef,  '' AS CodTarDct, '' AS CodTarRet, '' AS CodTarIca,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet,  CAST('' AS MONEY) AS VrRetencion, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca,  CAST('' AS MONEY) AS VrReteIca,
--26-05-2021.Yaqueline Lizarazo Diaz. Se agrega campo para identificar si es una reserva de ESTUDIANTES.
CAST('' AS BIT) AS EsItemPME,
--AuxFactura
'' AS Resolucion, '' AS Rango, CAST('' AS DATETIME) AS FechaResl, ''AS Prefijo, '' AS TipDocPf, '' AS PreFactura, '' AS IdCiaPf,    
--Información del cliente
'' AS TercTipo, '' AS TercDv, '' AS TercCodigo, '' AS TercNomCial, '' AS TercSigal, '' AS TercDireccion, '' AS TercCdCiudad, '' AS NomCiudad, '' AS CdDep, '' AS TercDpto, '' AS TercTelefono, '' AS TercFax,
'' AS TercEmail, '' AS TercSitioWeb, '' AS CdSector, '' AS SectorEco, '' AS CdRegimen, '' AS Regimen, '' AS TercTipEnte, '' AS NitRepLeg, '' AS NomRepLeg, '' AS ClieNitContac, '' AS ClieNomContacto, '' AS ClieTelContac,
'' AS ClieEmailContac, '' AS CargContac, CAST('' AS INT) AS DiasEntga, '' AS CdSubzona, '' AS Subzona, '' AS Zona, '' AS CdGrupoCli, '' AS GrupoClie, CAST('' AS BIT) AS ExcIva, CAST('' AS BIT) AS LiqFletes,
CAST('' AS BIT) AS Autoret, CAST('' AS MONEY) AS VrCupo, CAST('' AS MONEY) AS VrSaldo, '' AS AgeDireccion, '' AS AgeTelefono, '' AS AgeFax, '' AS AgeIdCiudad, '' AS AgeCiudad, '' AS AgeCodDep, ''AS AgeDpto,
'' AS AgeReferencia,
--Memo
CAST('' AS INT) AS cantimp, '' AS Comentarios,
--FACE
'' AS EstadoFE, '' AS PrefijoFace, CAST('' AS INT) AS NumFace, '' AS CUFE, '' AS ResolucionFace, '' AS RangoNum, '' AS FecVigencia, CAST('' AS IMAGE) AS QR, CAST('' AS DATETIME) AS FechaValidacion
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFacturasRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/11/2017
-- Description:	Imprimir Listados de Factura de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFacturasRel]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Factura, '' AS IdCia, CAST('' AS DATETIME) AS Fecha, '' AS CdConcepto, '' AS Concepto, '' AS IdCliente,
''  AS NomCliente, '' AS IdAgencia, CAST('' AS DATETIME) AS FechaVence, CAST('' AS MONEY) AS VrSubTotal, CAST('' AS MONEY) AS VrDescuento,
CAST('' AS MONEY) AS VrImpuesto, CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteICA, CAST('' AS MONEY) AS VrReteIVA, CAST('' AS MONEY) AS VrFletes,  CAST('' AS MONEY) AS VrOtros,
CAST('' AS MONEY) AS VrCargos, CAST('' AS MONEY) AS VrOtrDcto, CAST('' AS MONEY) AS  VrCostos, CAST('' AS MONEY) AS VrSobretasa, CAST('' AS MONEY) AS VrImpGlobal, CAST('' AS MONEY) AS VrFaltantes,
CAST('' AS MONEY) AS VrAnticipos, CAST('' AS MONEY) AS VrNeto, CAST('' AS MONEY) AS VrAplicado, CAST(@VrDef AS DECIMAL(14,4)) AS Cantidad, CAST(@VrDef AS DECIMAL(14,4)) AS CantPuntos, 
CAST(@VrDef AS DECIMAL(14,4)) AS PuntosAcum, CAST(@VrDef AS DECIMAL(14,4)) AS BaseImp, CAST(@VrDef AS DECIMAL(14,4)) AS BaseRet, CAST(@VrDef AS DECIMAL(14,4)) AS BaseIca, 
CAST(@VrDef AS DECIMAL(14,4)) AS BaseRiv, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIva, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRiv, '' AS CodTarIva, '' AS CodTarRet, '' AS CodTarIca, '' AS CodTarRiv, '' AS IdCCosto, '' AS IdSubCos, '' AS IdVend, '' AS Vendedor,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaCom, '' AS CodTarCom, '' AS DirEnvio, '' AS IdLocEnv, CAST('' AS INT) AS DiasEntraga, '' AS NitContac, '' AS NomContac, '' AS TelContac,
'' AS emlContac, '' AS CargoContac, '' AS IdForma, '' AS DetallePago, CAST('' AS BIT) AS MulPlazos,  '' AS IdPlazo, '' AS CdMney, '' AS NitEmpTrans, '' AS EmpTrans,
'' AS pVehiculo, '' AS CdConductor, CAST('' AS INT) AS KmtVehic, '' AS CdRuta, '' AS TipPed, CAST('' AS INT) AS Pedido,  '' AS IdCiaPed,  '' AS TipRem, CAST('' AS INT) AS Remision, 
'' AS IdCiaRem, '' AS TipCot, CAST('' AS INT) AS Cotizacion, '' AS IdCiaCot, CAST('' AS DATETIME) AS FecPedido, CAST('' AS INT) AS AutzaMora, CAST('' AS INT) AS AutzaCupo,
'' AS Modalidad, '' AS CodAutoRet, '' AS OrigenAdd, '' AS TipCom,  CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, CAST('' AS INT) AS ZonaFrontera, CAST(@VrDef AS DECIMAL(14,4)) AS PesoTotal,
CAST(@VrDef AS DECIMAL(14,4)) AS UnidTotal, CAST(@VrDef AS DECIMAL(14,4)) AS VolTotal, CAST(@VrDef AS DECIMAL(14,4)) AS CantFalt, CAST('' AS MONEY) AS VrCostoRem, CAST('' AS MONEY) AS VrCostoAfi,
CAST('' AS MONEY) AS VrImpCons, CAST('' AS MONEY) AS VrReteCREE, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, '' AS CodTarRtc, CAST('' AS MONEY) AS BaseIvaObsq, CAST('' AS MONEY) AS VrIvaObsequio,
CAST('' AS MONEY) AS VrImpCarbono, CAST('' AS BIT) AS Parqueadero, CAST('' AS DATETIME) AS FecCuotaParq, CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev,
'' AS Observ, '' AS CdEstado, '' AS Estado, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuari, '' AS Usuario
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFacturasRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/11/2017
-- Description:	Imprimir Listados de Detalle de Factura de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFacturasRelDet]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipoDoc, CAST('' AS INT) AS Factura, '' AS IdCia, CAST('' AS INT) AS Item, CAST('' AS INT) AS TipoReg, CAST('' AS DATETIME) AS FechaFact, 
'' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS DATETIME) AS FecReserva, '' AS Descripcion,
CAST(@VrDef AS DECIMAL(14,4)) AS Cantidad, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrUnitario, CAST('' AS MONEY) AS VrCosto,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIva, CAST('' AS MONEY) AS VrImpuesto, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaDct, 
CAST('' AS MONEY) AS VrDescuento, '' AS DocCliente, '' AS Referencia1, '' AS Referencia2,  '' AS Referencia3, '' AS CdConcepto, '' AS CdCCosto,
'' AS CdSubCos, '' AS NitTercero, '' AS CdAgencia, '' AS pVehiculo, '' AS TipoAfiVehic, '' AS IdOrigen, '' AS CiuOrigen, '' AS DeptOrigen,
'' AS IdDestino, '' AS CiuDestino, '' AS DeptDestino, CAST('' AS BIT) AS Anulado, '' AS TipDocRef, CAST('' AS INT) AS NumDocRef, '' AS IdCiaRef,
CAST('' AS DATETIME) AS FecDocRef, '' AS CodTarDct, '' AS CodTarRet, '' AS CodTarIca, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet,
CAST('' AS MONEY) AS VrRetencion, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca, CAST('' AS MONEY) AS VrReteIca, '' AS EstadoItem
END
            
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecCond]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 12/12/2018
-- Description:	Imprimir Subreporte de conductores en FUEC de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecCond]
AS
BEGIN
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Fuec, '' AS IdCia, CAST('' AS INT) AS ItemC, '' AS CedConductor, '' as Conductor, '' AS LicenciaC, CAST('' AS DATETIME) AS FecLicenciaC, CAST('' AS DATETIME) AS VigLicenciaC,
 '' AS TelefonoC, '' AS TelMovilC
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 08/09/2017
-- Description:	Imprimir Formato de FUEC de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
--Encabezado
''	AS TipDoc, CAST('' AS INT) AS Fuec, '' AS IdCia, '' AS Compania, '' AS Numero, CAST('' AS DATETIME) AS Fecha, CAST('' AS DATETIME) AS FechaInicio,
CAST('' AS DATETIME) AS FechaFin, '' AS CdCarga,'' AS IdVehiculo, '' AS NumVeh, '' AS Modelo, '' AS TarjOper,'' AS IdTipoVeh, '' AS TipoVehiculo, '' AS TipoAfil, '' AS Marca,
'' AS Itinerario,
--datos conductor principal
'' AS IdConductor, '' AS NomConductor, '' AS Licencia, CAST('' AS DATETIME) AS FecLicencia, CAST('' AS DATETIME) AS VigLicencia, '' AS Telefono, '' AS TelMovil,
--datos conductor remplazo 1
--'' AS IdConductor2, '' AS  NomConductor2, '' AS  Licencia2, CAST('' AS DATETIME) AS  FecLicencia2, CAST('' AS DATETIME) AS  VigLicencia2,
--datos conductor remplazo 2
--'' AS IdConductor3, '' AS  NomConductor3, '' AS Licencia3, CAST('' AS DATETIME) AS FecLicencia3, CAST('' AS DATETIME) AS VigLicencia3,
'' AS IdPoseedor, '' AS NomPoseedor, '' AS IdRuta, '' AS CdTipRuta, '' AS IdOrigen, '' AS CiuOrigen, '' AS DeptOrigen, '' AS IdDestino,
'' AS CiuDestino, '' AS DeptDestino, '' AS Modalidad, CAST(@VrDef AS DECIMAL(14,4)) AS CantPasajeros, '' AS CodTarRet, '' AS CodTarIca,
CAST('' AS MONEY) AS  VrPresupuesto, CAST('' AS MONEY) AS  VrCobro, CAST('' AS MONEY) AS VrPagos, CAST('' AS MONEY) AS VrCargos, CAST('' AS MONEY) AS VrDctos,
CAST('' AS MONEY) AS VrIva, CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteIca, CAST(@VrDef AS DECIMAL(14,4)) AS Cantidad,
CAST(@VrDef AS DECIMAL(14,4)) AS Peso, ''AS TipDocPgr, CAST('' AS INT) AS NumPgr, '' AS IdCiaPgr, CAST('' AS INT) AS ItemPgr, ''AS TipDocCnt,
CAST('' AS INT) AS Contrato, '' AS CiaCnt, CAST('' AS INT) AS Consecutivo, '' AS OrigenAdd, CAST('' AS BIT) AS Anulado, CAST('' AS DATETIME) AS FecDev,
'' AS IdEstado, '' AS Estado, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario,
--datos anexos
'' AS TipContrato, '' AS IdContrato,'' AS ObjContrato, '' AS DescripCarga, '' AS Observacion, '' AS RespViaje, CAST('' AS BIT) AS VehConvenio, 
'' AS EmpresaVehCon, '' AS Empresa,
--datos de detalles
CAST('' AS INT) AS Item, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS INT) AS NumPasajeros,
CAST(@VrDef AS DECIMAL(14,4)) AS PesoNeto, CAST('' AS MONEY) AS VrCobroD, CAST('' AS MONEY) AS VrPagosD, '' AS Referencia1, '' AS Referencia2, '' AS Referencia3,
'' AS CdTipServicio, CAST('' AS BIT) AS EsRutaCliente, CAST(@VrDef AS DECIMAL(14,4)) AS Kilometros, '' AS DirOrigen, CAST('' AS DATETIME) AS FecOrigen,
'' AS DirDestino, CAST('' AS DATETIME) AS FecDestino
--datos conductores
--CAST('' AS INT) AS ItemC, '' AS CedConductor, '' as Conductor, '' AS LicenciaC, CAST('' AS DATETIME) AS FecLicenciaC, CAST('' AS DATETIME) AS VigLicenciaC
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 07/03/2017
-- Description:	Imprimir fuec's para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecRel]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Fuec,'' IdCia,'' AS Compania, '' AS Numero,'' AS TipContrato, '' AS IdContrato, '' AS ObjContrato,
'' AS CdCarga,'' AS DescripCarga,CAST('' AS datetime) AS Fecha, CAST('' AS datetime) AS FechaInicio,CAST('' AS datetime) AS FechaFin, '' AS IdVehiculo, 
'' AS TipoVehiculo, '' AS IdConductor, '' AS NomConductor, '' AS IdConductor2, '' AS NomConductor2, '' AS IdConductor3, '' AS NomConductor3,
'' AS IdPoseedor, '' AS NomPoseedor, '' AS IdRuta, '' AS CdTipRuta,  '' AS IdOrigen, '' AS CiuOrigen, '' AS DeptOrigen, '' AS  IdDestino,
'' AS CiuDestino, '' AS DeptDestino, '' AS Modalidad, CAST('' AS INT) AS CantPasajeros, '' AS CodTarRet, '' AS CodTarIca, CAST('' AS MONEY) AS VrPresupuesto,
CAST('' AS MONEY) AS VrCobro, CAST('' AS MONEY) AS VrPagos, CAST('' AS MONEY) AS VrDctos, CAST('' AS MONEY) AS VrIva, CAST('' AS MONEY) AS VrRetencion,
CAST('' AS MONEY) AS VrReteIca,  CAST('' AS MONEY) AS Cantidad, '' AS Peso, '' AS Observacion, '' AS TipDocPgr, CAST('' AS INT) AS NumPgr, '' AS IdCiaPgr,
CAST('' AS INT) AS ItemPgr, '' AS TipDocCnt, CAST('' AS INT) AS Contrato, '' AS CiaCnt, '' AS OrigenAdd, CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev,
'' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys, CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspFuecRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 07/03/2017
-- Description:	Imprimir fuec's para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspFuecRelDet]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Fuec,'' IdCia,'' AS Compania, '' AS Numero, CAST('' AS datetime) AS Fecha, CAST('' AS datetime) AS FechaInicio,
CAST('' AS datetime) AS FechaFin, '' AS CdCarga, '' AS IdVehiculo, '' AS NumVeh, '' AS IdTipoVeh, '' AS TipoVehiculo, '' AS TipoAfil,
--Datos conductor principal
'' AS IdConductor, '' AS  NomConductor,  '' AS Licencia,  CAST('' AS datetime) AS FecLicencia,  CAST('' AS datetime) AS VigLicencia,
--Datos conductor Alterno 1
'' AS IdConductor2, '' AS  NomConductor2,  '' AS Licencia2,  CAST('' AS datetime) AS FecLicencia2,  CAST('' AS datetime) AS VigLicencia2,
--Datos conductor Alterno 2
'' AS IdConductor3, '' AS  NomConductor3,  '' AS Licencia3,  CAST('' AS datetime) AS FecLicencia3,  CAST('' AS datetime) AS VigLicencia3,
'' AS IdPoseedor, '' AS NomPoseedor, '' AS IdRuta, '' AS CdTipRuta,  '' AS IdOrigen, '' AS CiuOrigen, '' AS DeptOrigen, '' AS  IdDestino,
'' AS CiuDestino, '' AS DeptDestino, '' AS Modalidad, CAST('' AS INT) AS CantPasajeros, '' AS CodTarRet, '' AS CodTarIca, CAST('' AS MONEY) AS VrPresupuesto,
CAST('' AS MONEY) AS VrCobro, CAST('' AS MONEY) AS VrPagos, CAST('' AS MONEY) AS VrCargos, CAST('' AS MONEY) AS VrDctos, CAST('' AS MONEY) AS VrIva, 
CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteIca,  CAST('' AS MONEY) AS Cantidad, '' AS Peso, '' AS TipDocPgr, CAST('' AS INT) AS NumPgr,
'' AS IdCiaPgr, CAST('' AS INT) AS ItemPgr, '' AS TipDocCnt, CAST('' AS INT) AS Contrato, '' AS CiaCnt, '' AS OrigenAdd, CAST('' AS bit) AS Anulado, 
CAST('' AS datetime) AS FecDev, '' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys, CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario,
--Datos anexos
'' AS TipContrato, '' AS IdContrato, '' AS ObjContrato, '' AS DescripCarga, '' AS Observacion,
--Datos de detalles
CAST('' AS INT) AS Item, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS INT) AS NumPasajeros,
'' AS PesoNeto, CAST('' AS MONEY) AS VrCobro, CAST('' AS MONEY) AS VrPagos, '' AS Referencia1, '' AS Referencia2, '' AS Referencia3, '' AS CdTipServicio,
CAST('' AS BIT) AS EsRutaCliente, '' AS Kilometros, '' AS DirOrigen, CAST('' AS datetime) AS FecOrigen, '' AS DirDestino, CAST('' AS datetime) AS FecDestino

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspGenRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 30/11/2017
-- Description:	Imprimir listados de Generaciones de Ingresos
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspGenRel]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Cumplido, '' AS IdCia, '' Compania, CAST('' AS DATETIME) AS Fecha, '' AS TipRes, CAST('' AS INT) AS Reserva,
'' AS IdCiaRes, CAST('' AS INT) AS ItemRes, '' AS TipFac, CAST('' AS INT) AS Factura, '' AS IdCiaFac, '' AS IdClieFac, '' AS RazonSocial,
'' AS CdRuta, '' AS CdOrigen, '' AS CiuOrigen, '' AS CdDestino, '' AS CiuDestino, CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev, 
'' AS TipoComp, CAST('' AS INT) AS NumComp, '' AS CodConcepto, '' AS Observacion, '' AS IdEstado, '' AS OrigenAdd, CAST('' AS DATETIME) AS TimeSys, 
CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS ObservAnulado, '' AS CdCenCosto, '' AS CdSubCenCos, CAST('' AS MONEY) AS VrPago, 
CAST('' AS MONEY) AS VrCobro, CAST('' AS MONEY) AS VrAfiliados, CAST('' AS MONEY) AS VrPropios, CAST('' AS MONEY) AS VrTotalServ, CAST('' AS MONEY) AS VrTotalPagos, 
'' AS CodTarRtc, CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS VrReteCree, CAST('' AS MONEY) AS VrNeto,
 --Datos del cliente
'' AS TipoId, '' AS Dv, '' AS Codigo, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail, '' AS NitRepLeg,
'' AS NomRepLeg, '' AS IdGrupo
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspGenRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 30/11/2017
-- Description:	Imprimir listados de Generaciones de Ingresos
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspGenRelDet]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Cumplido, '' AS IdCia, '' AS Compania, CAST('' AS INT) AS Item, '' AS Estado,
'' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, '' AS EstadoItemRes,
--Datos de Reserva
'' AS CdCiuOrigen, '' AS CiuOrigen, '' AS CdCiuDestino, '' AS CiuDestino, CAST('' AS MONEY) AS VrRecorridos,
'' AS IdVehiculo, '' AS IdPoseedor, '' AS NomPoseedor, '' AS IdConductor, '' AS NomConductor, '' AS TipoAfil
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaDedFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 02/08/2017
-- Description:	Imprimir Formato de Liquidaciones de Especial Deducciones
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaDedFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Liquidacion, '' AS IdCia, '' AS Compania, CAST('' AS INT) AS Item, '' AS  TipCau,  CAST('' AS INT) AS Causacion,
'' AS IdCiaCau, CAST('' AS INT) AS ItemCau,  CAST('' AS DATETIME) AS FechaCau, '' AS IdConcepto, ''AS Descripcion,  CAST('' AS MONEY) AS VrAbono,
'' AS NitPoseedor, ''  AS NomPoseedor, '' AS pVehiculo, CAST('' AS BIT) AS EsVence, '' AS TipOdp, CAST('' AS INT) AS OrdenPago, '' AS IdCiaOdp,
'' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS DATETIME) AS FechaRes, CAST('' AS MONEY) AS VrSaldoOrden, '' AS CdCuenta,
'' AS CdCuePagar, '' AS NumFactura, '' AS CdCCosto, '' AS CCosto, '' AS CdSubCos, '' AS SubCosto,
--Datos del detalle(esto se maneja en buses)
'' AS CauDescripcion, CAST('' AS MONEY) AS VrTotalDed, CAST('' AS INT) AS  EstadoReg, CAST('' AS MONEY) AS  VrTotAbonado, '' AS TipFac,
--datos del poseedor
'' AS TercTipId, '' AS TercDv, '' AS TercCodigo, '' AS TercDireccion, '' AS TercCdCiudad, '' AS NomCiudad, '' AS TercTelefono , ''  AS TercEmail,
'' AS NumVeh, '' AS CdTipVeh, '' AS TipoVehiculo, '' AS CdMarca, '' AS MarcaVeh, '' AS CdColor, '' AS NomColor, '' AS Modelo, '' AS Config,
CAST(@VrDef AS DECIMAL(14,4)) AS PesoVacio, CAST(@VrDef AS DECIMAL(14,4)) AS PesoMax, '' AS NumMotor, '' AS SerieChasis, '' AS NumSerie,
''AS CdRemque, ''AS NitEmpresa, '' AS VehNomEmpresa, '' AS TipoAfil, '' AS VehDescripcion
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaEgrFac]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 02/08/2017
-- Description:	Imprimir Formato de Liquidaciones Abonos
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaEgrFac]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCia, CAST('' AS INT) AS Item,  CAST('' AS DATETIME) AS  Fecha,'' AS  TipFac,  
'' AS Factura, '' AS IdCiaFac, CAST('' AS INT) AS ItemFac,  CAST('' AS DATETIME) AS FechaCau,
'' AS IdProveedor, ''  AS Proveedor, '' AS IdCuenta, CAST('' AS MONEY) AS VrAbono, CAST('' AS BIT) AS EsEgreso, CAST('' AS INT) AS ItemCom,
'' AS pVehiculo, CAST('' AS BIT) AS VehPropio, '' AS TipDev, CAST('' AS INT) AS NumDev, '' AS DetAbono
 END


GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 01/08/2017
-- Description:	Imprimir Formato de Liquidaciones de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Liquidacion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto, '' AS IdVehiculo, '' AS IdPoseedor,
''  AS Poseedor, '' AS IdConductor, '' AS NomConductor, CAST('' AS MONEY) AS VrTotal, CAST('' AS BIT) AS CxPagar, '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom,
CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev, '' AS Observacion, '' AS IdEstado, '' AS Estado,
CAST('' AS DATETIME) AS FecIniCau, CAST('' AS DATETIME) AS FecFinCau, CAST('' AS DATETIME) AS FecIniOdp, CAST('' AS DATETIME) AS FecFinOdp, '' AS ModLiquida,
CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario,
--datos de la orden
'' AS TipOdp, CAST('' AS INT) AS OrdPago, '' AS IdCiaOdp, '' AS NomCiaOrden, CAST('' AS DATETIME)  AS FechaOdp, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes,
CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento, CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS  VrReteIca, CAST('' AS MONEY) AS  VrReteCree,
CAST('' AS MONEY) AS  VrAnticipos, CAST('' AS MONEY) AS  VrOtrosDctos, CAST('' AS MONEY) AS  VrImpuestos,  CAST('' AS MONEY) AS VrAportes,  CAST('' AS MONEY) AS VrFondos, CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto,
CAST('' AS MONEY) AS  BaseRet, CAST('' AS MONEY) AS  BaseIca, CAST('' AS MONEY) AS  BaseCree, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet,  CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, '' AS CodTarRet, '' AS CodTarIca, '' AS CodTarRtc,  CAST('' AS BIT) AS  CxPagar, CAST('' AS MONEY) MulPlazos, '' AS  IdPlazo, '' AS Plazo,
CAST('' AS INT) AS NVmto, CAST('' AS DATETIME) AS FechaVence, CAST('' AS MONEY) AS  VrConcPagos,CAST('' AS MONEY) AS  VrConcDctos,CAST('' AS MONEY) AS  VrConcFondo, CAST('' AS MONEY) AS  VrConcSeguro,
CAST('' AS MONEY) AS VrConcAporte, CAST('' AS MONEY) AS  VrConcImpuesto, CAST('' AS MONEY) AS VrRecCaja, CAST('' AS MONEY) AS VrReteCREE, '' AS NumCheque, '' AS Referencia,
'' AS CdCiuOrigen, '' AS  CiuOrigen, '' AS CodDepOrigen, '' AS DptoOrigen, '' AS CdCiuDestino, '' AS CiuDestino, ''  AS CodDepDestino, '' AS DptoDestino,  '' AS IdRuta, '' AS Ruta,
--datos del poseedor
'' AS TercTipId, ''  AS TercDv, ''  AS TercCodigo, '' AS TercNomCial, '' AS TercDireccion, '' AS TercCdCiudad, '' AS NomCiudad, '' AS TercTelefono, '' AS TercEmail,
'' AS NumVeh, '' AS CdTipVeh, '' AS TipoVehiculo, '' AS CdMarca, '' AS MarcaVeh, '' AS CdLinVeh, '' AS LineaVeh, '' AS CdColor, '' AS NomColor, '' AS CdCarr, '' AS TipoCar, '' AS Modelo,
'' AS Config, CAST(@VrDef AS DECIMAL(14,4)) AS PesoVacio, CAST(@VrDef AS DECIMAL(14,4)) PesoMax, ''AS NumMotor, '' AS SerieChasis, '' AS NumSerie, '' AS CdRemque, '' AS NitEmpresa, 
'' AS VehNomEmpresa, '' AS CdTipProp, '' AS TipoProp, '' AS VehPropio, '' AS TipoAfil, '' AS NumSoat, CAST('' AS DATETIME) FecSoat, CAST('' AS DATETIME) AS VigSoat,
'' AS NitEmpSoat, '' AS CertGases,  CAST('' AS DATETIME) FecCertGas,  CAST('' AS DATETIME) AS VigCertGas, '' AS VehDescripcion,  CAST('' AS DATETIME) AS FecRes, '' AS NumCtaProveedor,
'' AS ClaseCuenta,  '' AS NitContac, '' AS NomContac, '' AS Banco,
--Datos del cliente la factura
'' AS IdCliente,  '' AS RazonSocialCli
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaOtrFmtCauDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 03/08/2017
-- Description:	Imprimir Formato de Liquidaciones de Especial Otros Pagos
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaOtrFmtCauDet]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
CAST('' AS INT) AS Item, '' AS TipCau,  CAST('' AS INT) AS Causacion, '' AS IdCiaCau, CAST('' AS INT) AS ItemCau, '' AS Factura,  '' AS Descripcion, 
CAST('' AS MONEY)  AS VrTotal, CAST('' AS MONEY) AS  VrFactura,  '' AS CdCuenta, '' AS pVehiculo
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspLiquidaRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 28/11/2017
-- Description:	Imprimir listados de liquidaciones
-- =============================================
create PROCEDURE [dbo].[paWcfSeLisTrn_TraEspLiquidaRel]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Liquidacion, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto, '' AS IdVehiculo, '' AS IdPoseedor,
''  AS Poseedor, '' AS IdPropietario, '' AS Propietario,  '' AS IdTipoVeh, '' AS TipoVehiculo, '' AS TipoAfil, '' AS IdConductor, '' AS Conductor,
CAST('' AS MONEY) AS VrTotal, CAST('' AS BIT) AS CxPagar, '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom,
CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev, '' AS Observacion, '' AS IdEstado,
CAST('' AS DATETIME) AS FecIniCau, CAST('' AS DATETIME) AS FecFinCau, CAST('' AS DATETIME) AS FecIniOdp, CAST('' AS DATETIME) AS FecFinOdp, 
'' AS ModLiquida, '' AS OrigenAdd, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, 
'' AS IdUsuario, '' AS Usuario
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspListaPasaFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 16/01/2020
-- Description:	Imprimir Formato de Lista de pasajeros de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspListaPasaFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
CAST('' AS INT) AS IdLista, '' AS Documento, '' AS Apellidos, '' AS Nombres, '' AS IdResponsable, '' AS Responsable, CAST(@VrDef AS DECIMAL(14,4)) AS VrPago, CAST(@VrDef AS DECIMAL(14,4)) AS Porcentaje, 
'' AS Cargo, CAST('' AS BIT) AS EsMonitor, CAST('' AS BIT) AS EsEstudiante, '' AS Telefono, '' AS TipDoc, CAST('' AS INT) AS Contrato, '' AS IdCia, ''AS IdCliente, '' AS  NomCliente, CAST('' AS DATETIME) AS FechaInicio,
CAST('' AS DATETIME) AS FechaFin, '' AS CodObjContrato, '' AS ObjetoContrato, CAST('' AS INT) AS Item, CAST('' AS DATETIME) AS FecOrigen, CAST('' AS DATETIME) AS FecDestino, CAST('' AS INT) AS NumPasajeros, CAST('' AS BIT) AS EsItemPME, '' AS IdColegio, 
'' AS NomColegio, '' AS IdVehiculo, CAST('' AS DATETIME) AS Fecha, '' AS IdEstado, CAST('' AS DATETIME) AS FecUpdate, '' AS IdUsuario, '' AS Usuario,
--AdmRegistro
'' AS NitRepLegal, '' AS RepLegal, '' AS CiudadReplegal, '' AS NitEmpresa, '' AS NomEmpresa, '' AS CiudadEmpresa
 END

         
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspListaPasaResFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/01/2020
-- Description:	Imprimir Formato de Lista de pasajeros de reserva de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspListaPasaResFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
CAST('' AS INT) AS IdLista, '' AS Documento, '' AS Apellidos, '' AS Nombres, '' AS IdResponsable, '' AS Responsable, CAST(@VrDef AS DECIMAL(14,4)) AS VrPago, CAST(@VrDef AS DECIMAL(14,4)) AS Porcentaje, 
'' AS Cargo, CAST('' AS BIT) AS EsMonitor, CAST('' AS BIT) AS EsEstudiante, '' AS Telefono, '' AS TipDoc, CAST('' AS INT) AS Reserva, '' AS IdCia, ''AS IdCliente, '' AS  NomCliente, CAST('' AS DATETIME) AS FechaInicio,
CAST('' AS DATETIME) AS FechaFin, CAST('' AS INT) AS Item, CAST('' AS DATETIME) AS FecOrigen, CAST('' AS DATETIME) AS FecDestino, CAST('' AS INT) AS NumPasajeros, CAST('' AS BIT) AS EsItemPME, '' AS IdColegio, 
'' AS NomColegio, '' AS IdVehiculo, CAST('' AS DATETIME) AS Fecha, '' AS IdEstado, CAST('' AS DATETIME) AS FecUpdate, '' AS IdUsuario, '' AS Usuario,
--AdmRegistro
'' AS NitRepLegal, '' AS RepLegal, '' AS CiudadReplegal, '' AS NitEmpresa, '' AS NomEmpresa, '' AS CiudadEmpresa
 END

         
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspNovResFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Heiman Daza Tamayo
-- Create date(dd/MM/yyyy): 10/10/2018
-- Description:	Imprimir Formato de novedades de reserva de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspNovResFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT
--Datos de la Novedad
'' AS TipDoc, '' AS Documento, '' AS IdCia, CAST('' AS INT) AS Item,'' AS IdConcepto,'' AS Descripcion,
CAST('' AS INT) AS Cantidad, CAST('' AS MONEY) AS VrUnitario,CAST('' AS MONEY) AS VrTotal, '' AS RubroConcep,
'' AS TipoConc,'' AS NitTercero,'' AS RazonSocial,'' AS CdTipoEsc,'' AS TipoEscolta,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifIva,'' AS Concepto,'' AS CdCuenta,
CAST(@VrDef AS DECIMAL(14,4)) AS Tarifa,CAST('' AS DATETIME) AS FechaNov,CAST('' AS MONEY) AS VrBase,'' AS TipoTarif,'' AS RefConc,
CAST('' AS INT) AS Fijos,CAST('' AS MONEY) AS IncBaseRet,'' AS Referencia2,'' AS Referencia3,CAST('' AS INT) AS ItemDoc
END



GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 26/07/2017
-- Description:	Imprimir Orden de Pago Neto
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDet]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipoDoc, CAST('' AS INT) AS OrdPago, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto,
'' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS DATETIME) AS FechaRes,
'' AS CdCiuOrigen, '' AS CiuOrigen, '' AS CodDepOrigen, '' AS DptoOrigen, '' AS CdCiuDestino, '' AS CiuDestino, '' AS CodDepDestino,
'' AS DptoDestino, '' AS IdRuta, '' AS Ruta, '' AS IdVehiculo, '' AS NumVeh, '' AS IdPropietario, '' AS Propietario, '' AS IdPoseedor,
''  AS Poseedor, '' AS IdConductor, '' AS NomConductor, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento, 
CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteIca, CAST('' AS MONEY) AS VrReteCree, CAST('' AS MONEY) AS VrAnticipos, 
CAST('' AS MONEY) AS VrOtrosDctos, CAST('' AS MONEY) AS VrImpuestos, CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto, 
CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS BaseIca, CAST('' AS MONEY) AS BaseCree, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet, 
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, CAST('' AS BIT) AS CxPagar, CAST('' AS BIT) AS MulPlazos,
'' AS CdPlazo, '' AS Plazo, CAST('' AS INT) AS DiasPago, CAST('' AS DATETIME) AS FechaVence,  '' AS TipCom, CAST('' AS INT) AS Comprobante,
'' AS IdCiaCom, CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev, '' AS Observacion, '' AS IdCiaCrea, 
'' AS IdUsuario, '' AS Usuario, '' AS TipEgr, CAST('' AS INT) AS Egreso, '' AS IdCiaEgr, '' AS NumCheque, '' AS Referencia, 
CAST('' AS MONEY) AS VrConcPagos, CAST('' AS MONEY) AS VrConcDctos, CAST('' AS MONEY) AS VrConcFondo, CAST('' AS MONEY) AS VrConcSeguro, 
CAST('' AS MONEY) AS VrConcAporte, CAST('' AS MONEY) AS VrConcImpuesto, CAST('' AS MONEY) AS VrRecCaja, CAST('' AS MONEY) AS VrSeguros,  
CAST('' AS MONEY) AS VrFondos, CAST('' AS MONEY) AS VrAportes,
--COMFACTURA
CAST('' AS MONEY) AS VrTotalFac, CAST('' AS MONEY) AS VrTotalAbo, CAST('' AS MONEY) AS VrSaldo,
---Encabezado de factura
'' AS TipFac,  CAST('' AS INT) AS Factura, '' AS CiaFac,
--Detalle de factura
CAST('' AS MONEY) VrServicioFact
END



GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDetRen]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 30/1/2017
-- Description:	Imprimir Orden de Pago Neto Rentabilidad de Reservas
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOPagoNetoDetRen]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipoDoc, CAST('' AS INT) AS OrdPago, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto,
'' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS DATETIME) AS FechaRes,
'' AS CdCiuOrigen, '' AS CiuOrigen, '' AS CodDepOrigen, '' AS DptoOrigen, '' AS CdCiuDestino, '' AS CiuDestino, '' AS CodDepDestino,
'' AS DptoDestino, '' AS IdRuta, '' AS Ruta, '' AS IdVehiculo, '' AS NumVeh, '' AS IdPropietario, '' AS Propietario, '' AS IdPoseedor, 
''  AS Poseedor, '' AS IdConductor, '' AS NomConductor,
CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento, CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteIca, 
CAST('' AS MONEY) AS VrReteCree, CAST('' AS MONEY) AS VrAnticipos, CAST('' AS MONEY) AS VrOtrosDctos, CAST('' AS MONEY) AS VrImpuestos, 
CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto, CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS BaseIca, 
CAST('' AS MONEY) AS BaseCree, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca, 
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, CAST('' AS BIT) AS CxPagar, CAST('' AS BIT) AS MulPlazos, '' AS CdPlazo, '' AS Plazo,
CAST('' AS INT) AS DiasPago, CAST('' AS DATETIME) AS FechaVence,  '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, 
CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev, CAST('' AS DATETIME) AS FecDev, '' AS Observacion, '' AS IdCiaCrea, 
'' AS IdUsuario, '' AS Usuario, '' AS TipEgr, CAST('' AS INT) AS Egreso, '' AS IdCiaEgr, '' AS NumCheque, '' AS Referencia, 
CAST('' AS MONEY) AS VrConcPagos, CAST('' AS MONEY) AS VrConcDctos, CAST('' AS MONEY) AS VrConcFondo, CAST('' AS MONEY) AS VrConcSeguro, 
CAST('' AS MONEY) AS VrConcAporte, CAST('' AS MONEY) AS VrConcImpuesto, CAST('' AS MONEY) AS VrRecCaja, CAST('' AS MONEY) AS VrSeguros,  
CAST('' AS MONEY) AS VrFondos, CAST('' AS MONEY) AS VrAportes, CAST('' AS INT) AS EdoLiqCausac, '' AS EstadoItem,
--Datos del vehiculo
'' AS TercTipId, '' AS TercDv, '' AS  TercCdCiudad, '' AS NomCiudad, '' AS DirPoseedor, '' AS TelPoseedor, '' AS TelMovilPosee, 
'' AS emailPoseedor, '' AS IdIcaOdp, '' AS CiudadICaOdp, '' AS IdLugarLic, '' AS LugarLicencia, '' AS CdTipVeh, '' AS TipoVehiculo,
'' AS CdMarca, '' AS MarcaVeh, '' AS Modelo, '' AS Config, '' AS TipoAfil, '' AS VehDescripcion,    
---Encabezado de factura
'' AS TipFac,  CAST('' AS INT) AS Factura, '' AS CiaFac,
--Detalle de factura
CAST('' AS MONEY) VrServicioFact
END


GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOPagoRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 26/07/2017
-- Description:	Imprimir Consecutivo Orden de Pago
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOPagoRelDet]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
CAST('' AS INT) AS OrdPago, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, 
CAST('' AS INT) AS ItemRes, '' AS IdVehiculo, '' AS NumVeh, '' AS IdPropietario, '' AS Propietario, '' AS NitPoseedor, ''  AS Poseedor,
'' AS CedConductor, '' AS Conductor, CAST('' AS BIT) AS LiqReservas, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento,
CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteIca, CAST('' AS MONEY) AS VrReteCree, CAST('' AS MONEY) AS VrAnticipos,
CAST('' AS MONEY) AS VrOtrosDctos, CAST('' AS MONEY) AS VrImpuestos, CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto,
CAST('' AS MONEY) AS BaseRet, CAST('' AS MONEY) AS BaseIca, CAST('' AS MONEY) AS BaseCree, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet,
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, '' AS CodTarRet, '' AS CodTarIca, '' AS CodTarRtc,
CAST('' AS BIT) AS CxPagar, CAST('' AS BIT) AS MulPlazos, '' AS IdPlazo, '' AS Plazo, CAST('' AS INT) AS NVmto, CAST('' AS DATETIME) AS FechaVence,
CAST('' AS MONEY) AS VrConcPagos, CAST('' AS MONEY) AS VrConcDctos, CAST('' AS MONEY) AS VrConcFondo, CAST('' AS MONEY) AS VrConcSeguro, 
CAST('' AS MONEY) AS VrConcAporte, CAST('' AS MONEY) AS VrConcImpuesto, CAST('' AS MONEY) AS VrRecCaja, CAST('' AS MONEY) AS VrReteCREE, '' AS CdForma,
'' AS CdCenCosto, '' AS CdSubCenCos, CAST('' AS MONEY) AS VrSeguros, CAST('' AS MONEY) AS VrFondos, CAST('' AS MONEY) AS VrAportes, '' AS IdConcepto,
'' AS Concepto, '' AS Modalidad, '' AS TipEgr, CAST('' AS INT) AS Egreso, '' AS IdCiaEgr, CAST('' AS DATETIME) AS FechaEgr, '' AS NumCheque,
'' AS Referencia, '' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom, CAST('' AS BIT) AS Anulado, CAST('' AS INT) AS NumDev,
CAST('' AS DATETIME) AS FecDev, '' AS Observacion, '' AS IdEstado, '' AS Estado, '' AS OrigenAdd, CAST('' AS DATETIME) AS TimeSys,
CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario,
--Datos de Orden_Reserva_Prog
'' AS TipPgr, CAST('' AS INT) AS Programa, '' AS IdCiaPgr, CAST('' AS INT) AS ItemPgr, CAST('' AS MONEY) AS VrRecorrido
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOrdenPagoLta]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 02/11/2017
-- Description:	Imprimir log de ordenes de pago de reservas masivo para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOrdenPagoLta]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
--Encabezado
SELECT CAST('' AS INT) AS Numero, CAST('' AS DATETIME) AS Fecha, CAST('' AS INT) AS EstadoProc, '' AS Observacion, CAST('' AS DATETIME) AS TimeSys, 
'' AS IdUsuario, '' AS Nombre, CAST('' AS INT) AS Item, '' AS TipDoc, CAST('' AS INT) AS Orden, '' AS IdCia, '' AS IdConcepto, '' AS TipoCom, 
CAST('' AS INT) AS Comprobante, '' AS TipRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, '' AS IdOrigen, '' AS CiuOrigen, 
'' AS IdDestino, '' AS CiuDestino, '' AS IdRuta, '' AS Ruta, '' AS IdVehiculo, '' AS IdConductor, '' AS IdPropietario, '' AS IdPoseedor, 
CAST('' AS INT) AS Cumplido, '' AS IdCiaCum, CAST('' AS INT) AS EstadoReg, CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento, 
CAST('' AS MONEY) AS VrRetencion, CAST('' AS MONEY) AS VrReteIca, CAST('' AS MONEY) AS VrReteCREE, CAST('' AS MONEY) AS VrAnticipos, CAST('' AS MONEY) AS VrOtrosDctos, 
CAST('' AS MONEY) AS VrImpuestos, CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRet, 
CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc, '' AS CodTarRet, '' AS CodTarIca, '' AS CodTarRtc, 
CAST('' AS MONEY) AS VrConcPagos, CAST('' AS MONEY) AS VrConcDctos, CAST('' AS MONEY) AS VrConcFondo, CAST('' AS MONEY) AS VrConcSeguro, 
CAST('' AS MONEY) AS VrConcAporte, CAST('' AS MONEY) AS VrConcImpuesto, CAST('' AS MONEY) AS VrRecCaja, '' AS CdForma, '' AS IdCCosto, '' AS IdSubCos,
 CAST('' AS MONEY) AS VrSeguros, CAST('' AS MONEY) AS VrFondos, CAST('' AS MONEY) AS VrAportes, '' AS Comentarios
END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOrdPagoFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/06/2017
-- Description:	Imprimir Orden de Pago
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOrdPagoFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
--Trn_TraEspOrdenPago
'' AS TipDoc, CAST('' AS INT) AS OrdPago, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha, '' AS IdConcepto, '' AS Concepto, '' AS Modalidad,
CAST('' AS BIT) AS LiqReservas,  CAST('' AS BIT) AS  CxPagar,  CAST('' AS BIT) AS MulPlazos, '' AS IdPlazo, '' AS Plazo, ''AS DiasPago,  CAST('' AS DATETIME) AS FechaVence,
'' AS TipCom, CAST('' AS INT) AS Comprobante, '' AS IdCiaCom,  CAST('' AS BIT) AS Anulado,  CAST('' AS INT) AS NumDev,  CAST('' AS DATETIME) AS  FecDev, '' AS Observacion, 
'' AS IdEstado, '' AS Estado,  CAST('' AS DATETIME) AS TimeSys,  CAST('' AS DATETIME) AS FecUpdate,  '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario,
--Orden reservas
'' AS TipRes,  CAST('' AS INT) AS Reserva, '' AS IdCiaRes,  CAST('' AS INT) AS ItemRes, '' AS IdRuta, '' AS Ruta, CAST(@VrDef AS DECIMAL(14,4)) AS  Distkmt, 
'' AS IdVehiculo, '' AS NumVeh, '' AS IdTipoVeh, '' AS TipoVehiculo, '' AS TipoAfil,'' AS IdConductor, '' AS NomConductor, '' AS IdPropietario,'' AS Propietario, '' AS IdPoseedor, '' AS Poseedor,
 CAST('' AS MONEY) AS VrServicio, CAST('' AS MONEY) AS VrDescuento,  CAST('' AS MONEY) AS VrRetencion,  CAST('' AS MONEY) AS VrReteIca, CAST('' AS MONEY) AS VrReteCree,  
CAST('' AS MONEY) AS VrAnticipos,  CAST('' AS MONEY) AS VrOtrosDctos,  CAST('' AS MONEY) AS VrImpuestos,  CAST('' AS MONEY) AS VrOtrosPagos, CAST('' AS MONEY) AS VrNeto, CAST('' AS MONEY) AS BaseRet,
CAST('' AS MONEY) AS BaseIca, CAST('' AS MONEY) AS BaseCree, CAST(@VrDef AS DECIMAL(14,4)) AS  TarifaRet, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaIca, CAST(@VrDef AS DECIMAL(14,4)) AS TarifaRtc,
''AS CodTarRet, '' AS CodTarIca, ''AS CodTarRtc, '' AS TipEgr, CAST('' AS INT) AS Egreso, '' AS IdCiaEgr, CAST('' AS DATETIME) AS FechaEgr, '' AS NumCheque, '' AS Referencia,
CAST('' AS MONEY) AS VrConcPagos, CAST('' AS MONEY) AS VrConcDctos, CAST('' AS MONEY) AS VrConcFondo, CAST('' AS MONEY) AS VrConcSeguro, CAST('' AS MONEY) AS VrConcAporte, CAST('' AS MONEY) AS VrConcImpuesto,
CAST('' AS MONEY) AS VrRecCaja, CAST('' AS MONEY) AS VrReteCREE, '' AS CdForma, '' AS CdCenCosto, '' AS CdSubCenCos, CAST('' AS MONEY) AS VrSeguros, CAST('' AS MONEY) AS VrFondos, CAST('' AS MONEY) AS VrAportes,
'' AS TipPgr, CAST('' AS INT) AS Programa, '' AS IdCiaPgr, CAST('' AS INT) AS ItemPgr,CAST('' AS MONEY) AS VrRecorrido,
--Trn_TraEspConceptos
CAST('' AS INT) AS Item, '' AS IdConc, '' AS Descripcion , CAST('' AS INT) AS Cantidad, 
CAST('' AS MONEY) AS VrUnitario, CAST('' AS MONEY)  AS VrTotal, '' AS RubroConcep,  '' AS TipoConc, '' AS NitTercero, '' AS RazonSocial, '' AS CdTipoEsc,
'' AS TipoEscolta, CAST('' AS MONEY) AS TarifIva, '' AS ConcG,'' AS CdCuenta, CAST(@VrDef AS DECIMAL(14,4)) AS Tarifa, CAST('' AS DATETIME) AS FechaNov, 
CAST('' AS MONEY) AS VrBase, '' AS TipoTarif, '' AS RefConc, CAST('' AS BIT) AS Fijos, CAST('' AS INT) AS IncBaseRet, '' AS Referencia2, '' AS Referencia3,
--ComFactura
'' AS TipFac, CAST('' AS INT) AS Factura, '' AS IdCiaF, CAST('' AS INT) AS ItemF, '' AS IdProveedor, '' AS IdCuentaF,
CAST('' AS DATETIME) AS FecEmision, CAST('' AS DATETIME) AS FecVence, CAST('' AS MONEY) AS VrFactura, CAST('' AS MONEY) AS VrAbonado,
'' AS TipComF, CAST('' AS INT) AS ComprobanteF, CAST('' AS MONEY) AS ItemCom, '' AS ReferenciaF, '' AS Detalle, '' AS pVehiculo,  CAST('' AS BIT) AS VehPropio,
'' AS TipRef, '' AS DocRef, '' AS IdCiaRef,  CAST('' AS INT) AS EstadoApr,
--Anticipos_Abonos
'' AS ItemAnt,  CAST('' AS DATETIME) AS FechaAnt, '' AS TipAnt,  CAST('' AS INT) AS Anticipo,
'' AS IdCiaAnt,  '' AS Placa, '' AS ObsAnt, CAST('' AS MONEY) AS VrAbono,  CAST('' AS MONEY) AS VrAnticipo,  CAST('' AS MONEY) AS VrAbonadoAnt,  CAST('' AS MONEY) AS VsSaldo, '' AS TipoAplica,
'' AS DetalleAnt, '' AS CdCuentaAnt,
--DetCuentas
'' AS ConceptoDC,  CAST('' AS INT) AS ItemDC, '' AS IdCuenta,  CAST('' AS MONEY) AS Valor, '' AS DetalleDC,  CAST('' AS MONEY) AS VrBaseDC, '' AS  IdTercero, '' AS RazonSocialDC,
'' AS CodAgncia, '' AS CdCCosto, ''AS CCosto, '' AS CdSubCos, '' AS SubCosto, '' AS PlacaDC, '' AS TipFacDC,  CAST('' AS INT) AS FacturaDC, '' AS IdCiaFac,  CAST('' AS INT) AS ItemFac,
 CAST('' AS DATETIME) AS FecVenceDC, '' AS Cheque, '' AS CodConc, '' AS ReferenciaDC, '' AS CiuOrigen, ''AS Localidad,  CAST('' AS MONEY) AS  VrTarifa, '' AS TipoTarifDC	
 END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOtroSiFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 12/07/2019
-- Description:	Imprimir Formato OtroSí
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOtroSiFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT CAST('' AS INT) AS IdOtroSi, CAST('' AS datetime) AS Fecha, CAST('' AS BIT) AS Adicion, CAST('' AS BIT) AS CFecha, CAST('' AS BIT) AS Items, CAST('' AS BIT) AS Aplicado, 
CAST('' AS datetime) AS TimeSys, '' AS Observacion, '' AS IdUsuario, '' AS Usuario, CAST('' AS BIT) AS Anulado, CAST('' AS datetime) AS FecDev,
--Datos COE
'' AS IdCliente, '' AS NomCliente,  '' AS Responsable, '' AS NombreResp, CAST('' AS INT) AS CantPasajeros, '' AS CdCarga,  CAST('' AS BIT) AS EsLicitacion, 
CAST('' AS datetime) AS FechaInicio, '' AS IdObjCOE, '' AS ObjContrato,  CAST('' AS datetime) AS FecContrato, '' AS Modalidad, '' AS IdGrupo,
--Detalle
'' AS TipDocCnt, CAST('' AS INT) AS ContratoOS, '' AS IdCiaCnt, CAST('' AS datetime) AS FechaFinAnt, CAST('' AS datetime) AS FechaFinNew, CAST('' AS Money) AS VrPpto,
CAST('' AS Money) AS VrSaldoPpo, CAST('' AS Money) AS VrAdicionPpto,
--Detalle De Items COE
'' AS TipDoc, CAST('' AS INT) AS Contrato, '' AS IdCia, CAST('' AS INT) AS Item, '' AS IdHorario, '' AS TipPed, CAST('' AS INT) AS Pedido, '' AS CiaPed, 
CAST('' AS INT) AS ItemPed, '' AS IdVehiculo, '' AS CdTipVeh, '' AS TipoVehiculo, CAST('' AS INT) AS NumPasajeros, CAST(@VrDef AS DECIMAL(14,4)) AS PesoNeto, 
CAST('' AS Money) AS VrUnitario, CAST('' AS Money) AS VrPago, '' AS IdRuta,'' AS Ruta, '' AS Referencia1, '' AS Referencia2, '' AS Referencia3, 
CAST('' AS BIT) AS EsRutaCliente, '' AS CdCiuOrigen, '' AS CiuOrigenD, '' AS DeptOrigen, '' AS DirOrigen, CAST('' AS datetime) AS FecOrigen, '' AS CdCiuDestino, 
'' AS CiuDestinoD, '' AS DeptDestino, '' AS DirDestino, CAST('' AS datetime) AS FecDestino, CAST('' AS INT) AS DiasDisp, CAST('' AS Money) AS VrDia, '' AS Parada, 
'' AS CdTipRuta, '' AS CdTipServicio, '' AS TipRes, CAST('' AS INT) AS NumRes, '' AS IdCiaRes, CAST('' AS INT) AS ItemRes, CAST('' AS INT) AS CantVeh, 
CAST('' AS BIT) AS Retorno, CAST('' AS Money) AS VrMonitor, CAST('' AS INT) AS CantMonitor, CAST('' AS Money) AS VrMaxRec, CAST('' AS INT) AS NumDias, '' AS TipoTarifa,
'' AS IdColegio, '' AS NomColegio, '' AS Codigo, '' AS Itinerario, CAST('' AS BIT) AS VLargo, CAST('' AS INT) AS IdOtroSiDet, CAST('' AS BIT) AS ItemAnuladoOS
END

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspOtroSiRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 12/07/2019
-- Description:	Imprimir Listado OtroSí
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspOtroSiRel]
AS
SELECT '' AS IdOtroSi, CAST('' AS datetime) AS Fecha, CAST('' AS BIT) AS Adicion, CAST('' AS BIT) AS CFecha, CAST('' AS BIT) AS Items, CAST('' AS BIT) AS Aplicado, 
CAST('' AS datetime) AS TimeSys, '' AS IdUsuario, '' AS Usuario, CAST('' AS BIT) AS Anulado, CAST('' AS datetime) AS FecDev,
--Detalle
'' AS TipDocCnt, CAST('' AS INT) AS Contrato, '' AS IdCiaCnt, CAST('' AS datetime) AS FechaFinAnt, CAST('' AS datetime) AS FechaFinNew, CAST('' AS Money) AS VrPpto, 
CAST('' AS Money) AS VrSaldoPpo, CAST('' AS Money) AS VrAdicionPpto

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPedidoFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 29/04/2019
-- Description:	Imprimir Formato de Pedido de Transporte de Especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPedidoFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
--Encabezado
'' AS TipDoc, CAST('' AS INT) AS Pedido, '' AS IdCia, '' AS Compania, CAST('' AS DATETIME) AS Fecha,CAST('' AS DATETIME) AS FechaVence, CAST('' AS DATETIME) AS FecInicio,
CAST('' AS DATETIME) AS FecFinal,'' AS IdCliente, '' AS RazonSocial, '' AS IdAgencia, '' AS CodAgencia, '' AS Agencia, '' AS DirAgncia, '' AS TelAgncia,'' AS Referencia, 
'' AS IdVend, '' AS NomVendedor, '' AS TipoContrato, '' AS  TipoPago, CAST('' AS DATETIME) AS Vigencia, '' AS IdTarifCom, '' AS Modalidad, CAST('' AS MONEY) AS  VrCobro,
CAST('' AS MONEY) AS VrEditado, CAST('' AS MONEY) AS  VrPagos, CAST('' AS MONEY) AS VrCargos, CAST('' AS MONEY) AS  VrDctos, CAST('' AS MONEY) AS VrIva, '' AS CdDescuento,
CAST(@VrDef AS DECIMAL(14,4)) AS Cantidad, CAST(@VrDef AS DECIMAL(14,4)) AS CantPasajeros, CAST('' AS INT) AS NumAprob, ''AS IdCiaApr, CAST('' AS DATETIME) AS FecAprob,
'' AS OrigenAdd, CAST('' AS BIT) AS Anulado, CAST('' AS DATETIME) AS FecDev, '' AS Observacion, CAST('' AS MONEY) AS Presupuesto, CAST('' AS MONEY) AS Peso, '' AS IdMneda,
'' AS Mneda, CAST('' AS BIT) AS EsLicitacion, '' AS IdEstado, '' AS  Estado, CAST('' AS DATETIME) AS TimeSys, CAST('' AS DATETIME) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario,
'' AS Usuario,'' AS CdCarga, CAST('' AS INT) AS CantDias,
-- Datos de anexo
'' AS NomCliente, '' AS DirCliente, '' AS NomContacto, '' AS TelContacto, '' AS emlContacto, '' AS emlCliente, '' AS DescripCarga, '' AS Clausulas,
--Datos de detalles
CAST('' AS INT) AS Item, '' AS CdTipVeh, '' AS TipoVehiculo, CAST('' AS INT) AS NumPasajeros, '' AS Parada, CAST(@VrDef AS DECIMAL(14,4)) AS PesoNeto, CAST('' AS MONEY) AS VrUnitario,
'' AS IdRuta, '' AS Ruta,'' AS Referencia1, '' AS Referencia2, ''AS Referencia3,CAST('' AS BIT) AS EsRutaCliente, '' AS CdCiuOrigen, '' AS CiuOrigenD, '' AS DeptOrigen, '' AS DirOrigen,
CAST('' AS DATETIME) AS FecOrigen,'' AS CdCiuDestino, '' AS  CiuDestinoD, '' AS  DeptDestino, '' AS DirDestino, CAST('' AS DATETIME) AS FecDestino, '' AS CdTipRuta, '' AS CdTipServicio,
CAST('' AS INT) AS DiasDisp, CAST('' AS MONEY) AS  VrDia, '' AS TipCtn, CAST('' AS INT) AS  NumCnt, '' AS IdCiaCnt, CAST('' AS INT) AS ItemCnt, CAST('' AS INT) AS Cantveh, CAST('' AS BIT) AS Retorno,
CAST('' AS MONEY) AS VrMonitor, CAST('' AS INT) AS CantMonitor, '' AS TipoTarifa, CAST('' AS INT) AS Dias, '' AS Itinerario, CAST('' AS BIT) AS VLargo, CAST('' AS INT) AS ItemPpalRet,
'' AS CiaPpalRet, CAST('' AS MONEY) AS  VrPago,
--Datos de conceptos
'' AS TipoDoc, CAST('' AS INT) AS Documento, '' AS IdCiaC, CAST('' AS INT) AS Itemc, '' AS Descripcion, CAST(@VrDef AS DECIMAL(14,4)) AS Tarifa, '' AS TipoConc, '' AS RubroConcep, CAST('' AS INT) AS Cantidadc,
CAST('' AS MONEY) AS VrUnitarioc, CAST(@VrDef AS DECIMAL(14,4)) AS TarifIva, '' AS IdConcepto, '' AS CdCuenta, '' AS NitTercero, '' AS  NombreTerc, '' AS CdTipoEscc, '' AS TipEsc, CAST('' AS DATETIME) AS FechaNov, 
CAST('' AS MONEY) AS VrBase, '' AS TipoTarif, '' AS RefConc, CAST('' AS BIT) AS Fijos, CAST('' AS INT) AS IncBaseRet, '' AS Referencia2c, '' AS Referencia3c, CAST('' AS INT) AS ItemDoc,
--Datos del cliente
'' AS TipoId, '' AS Dv, ''AS Codigo, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail,
'' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona, '' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupo, '' AS GrupoClie
 END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPedidoRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 23/02/2017
-- Description:	Imprimir cotizaciones para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPedidoRel]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Pedido,'' IdCia,'' AS Compania,'' AS CdCarga,'' AS DescripCarga,CAST('' AS datetime) AS Fecha,CAST('' AS datetime) AS FechaVence,CAST('' AS datetime) AS FecInicio,CAST('' AS datetime) AS FecFinal,
'' AS IdCliente,'' AS RazonSocial,'' AS IdAgencia, '' AS CodAgencia,'' AS Agencia,'' AS DirAgncia,'' AS TelAgncia,CAST('' AS Money) AS VrCupo,CAST('' AS Money) AS VrSaldo,
'' AS NomCliente,'' AS DirCliente,'' AS NomContacto,'' AS TelContacto, '' AS emlContacto,'' AS IdVend,''  AS NomVendedor,'' AS IdTarifCom,'' AS Modalidad,
'' AS TipoContrato,'' AS  TipoPago,'' AS  Vigencia, CAST('' AS Money) AS VrCobro,CAST('' AS Money) AS  VrEditado,CAST('' AS Money) AS  VrPagos,CAST('' AS Money) AS  VrCargos,CAST('' AS Money) AS  VrDctos,CAST('' AS Money) AS  VrIva,
'' AS  CdDescuento,CAST('' AS INT) AS  Cantidad,CAST('' AS INT) AS CantPasajeros, '' AS  NumAprob,'' AS IdCiaApr,CAST('' AS datetime) AS FecAprob,CAST('' AS Money) AS Presupuesto,'' AS Peso,'' AS IdMneda,'' AS Mneda,
CAST('' AS bit) AS EsLicitacion, CAST('' AS datetime) AS FecDev,'' AS  Observacion,'' AS IdEstado,'' AS Estado,CAST('' AS datetime) TimeSys, CAST('' AS datetime) AS FecUpdate,
'' AS OrigenAdd,CAST('' AS bit) AS Anulado,'' AS IdCiaCrea, '' AS IdUsuario,'' AS Usuario
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPedidoRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 24/02/2017
-- Description:	Imprimir detalles de cotizaciones para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPedidoRelDet]
AS
--Encabezado
SELECT '' AS TipDoc, CAST('' AS INT) AS Pedido, '' AS IdCia, '' AS Compania, CAST('' as datetime) AS Fecha, CAST('' as datetime) AS FechaVence, 
CAST('' as datetime) AS FecInicio, CAST('' as datetime) AS FecFinal, '' AS IdCliente, '' AS RazonSocial, '' AS IdAgencia, '' AS CodAgencia, '' AS Agencia,
'' AS DirAgncia, '' AS TelAgncia, '' AS Referencia, '' AS IdVend, '' AS NomVendedor, '' AS TipoContrato, '' AS TipoPago, CAST('' AS INT) AS Vigencia,
'' AS IdTarifCom, '' AS Modalidad, CAST('' AS Money) AS VrCobro, CAST('' AS Money) AS VrEditado, CAST('' AS Money) AS VrPagos, CAST('' AS Money) AS VrCargos,
CAST('' AS Money) AS VrDctos,CAST('' AS Money) AS VrIva, '' AS CdDescuento, CAST('' AS INT) AS Cantidad, CAST('' AS INT) AS CantPasajeros,
 '' AS NumAprob, '' AS IdCiaApr,CAST('' AS datetime) AS FecAprob, CAST('' AS bit) AS Anulado,CAST('' AS datetime) AS FecDev,'' AS Observacion,
CAST('' AS Money) AS Presupuesto,'' AS Peso,'' AS IdMneda, '' AS Mneda, CAST('' AS bit) AS EsLicitacion, '' AS IdEstado, '' AS Estado,
CAST('' AS datetime) AS TimeSys, CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea, '' AS IdUsuario, '' AS Usuario, '' AS CdCarga,
--Anexos
'' AS NomCliente,'' AS DirCliente,''  AS NomContacto,'' AS TelContacto,'' AS emlContacto, '' AS emlCliente,'' AS DescripCarga, '' AS Clausulas,
--Detalles
CAST('' AS INT) AS Item, '' AS CdTipVeh, '' AS TipoVehiculo, CAST('' AS INT) AS NumPasajeros,
'' AS Parada,'' AS PesoNeto, CAST('' AS Money) AS VrUnitario, '' AS IdRuta, '' AS Ruta, '' AS  Referencia1, '' AS Referencia2, '' AS Referencia3, 
CAST('' AS BIT) AS EsRutaCliente, '' AS CdCiuOrigen, '' as CiuOrigenD, '' AS DeptOrigen, ''AS DirOrigen, CAST('' AS datetime) AS FecOrigen,
'' AS CdCiuDestino, '' AS  CiuDestinoD,'' AS DeptDestino, '' AS DirDestino,CAST('' AS datetime) AS FecDestino, '' AS CdTipRuta, '' AS CdTipServicio, 
CAST('' AS INT) AS  DiasDisp,CAST('' AS Money) AS VrDia,'' AS TipCtn,CAST('' AS INT) AS NumCnt, '' AS IdCiaCnt, CAST('' AS INT) AS ItemCnt,
CAST('' AS bit) AS VLargo, CAST('' AS INT) AS ItemPpalRet, '' AS CiaPpalRet,
--Conceptos
'' AS TipoDoc, '' AS Documento,''  AS IdCiaC, CAST('' AS INT) AS Itemc, '' AS Descripcion,'' AS Tarifa, '' AS TipoConc, '' AS RubroConcep, 
CAST('' AS INT) AS Cantidadc, CAST('' AS Money) AS VrUnitarioc, '' AS TarifIva, '' AS IdConcepto, '' AS CdCuenta, '' AS NitTercero,
'' AS NombreTerc,'' AS CdTipoEscc, '' AS TipEsc, CAST('' AS datetime) AS FechaNov, CAST('' AS Money) AS VrBase, ''  AS TipoTarif, '' AS RefConc,
'' AS Fijos, '' AS IncBaseRet, '' AS Referencia2c,'' AS Referencia3c,
--Datos del cliente
'' AS TipoId, '' AS Dv, '' AS Codigo, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail, '' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona,
'' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupo, '' AS GrupoClie




GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPgrFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 01/05/2019
-- Description:	Imprimir Programación
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPgrFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
--Encabezado
SELECT '' AS TipDoc, CAST('' AS INT) AS Programa,'' IdCia,'' AS Compania, CAST('' AS datetime) AS Fecha, '' AS OrigenAdd,
CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev, '' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys,
CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario,
--Detalles
CAST('' AS INT) AS Item, CAST('' AS datetime) AS FechaInicio, CAST('' AS datetime) AS FechaFin,'' AS TipDocRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, 
CAST('' AS INT) AS ItemRes, CAST('' AS datetime) AS eFechaIniRes, CAST('' AS datetime) AS eFechaFinRes, '' AS IdEstadoRes, '' AS EstadoItemRes, '' Modalidad,
'' AS IdOrigen, '' AS CiuOrigen, '' AS DeptOrigen, '' AS IdDestino, '' AS CiuDestino, '' AS DeptDestino, '' AS IdVehiculo, '' AS NumVeh, ''   AS TipoAfil,
'' AS CdTipVeh, '' AS TipoVehiculo, '' AS ClaseMat, '' AS IdConductor, '' AS NomConductor, CAST('' AS INT) AS NumPasajeros,  '' AS TipDocFuec, 
CAST('' AS INT) AS NumFuec, '' AS IdCiaFuec,  '' AS TipDocOdp, CAST('' AS INT) AS NumOdp, '' AS IdCiaOdp, CAST('' AS datetime) FechaOdp,
'' AS IdNovedad, '' AS Novedad, CAST('' AS BIT) AS Cumplido, CAST('' AS datetime) AS FecIniCump, CAST('' AS datetime) AS FecFinCump,
CAST('' AS MONEY) AS VrCobro, CAST('' AS MONEY) AS VrPagos, CAST('' AS INT) AS DiasDisp, '' AS Parada, '' AS CdTipServicio, '' AS DirOrigen, ''  AS DirDestino,
'' AS IdRuta, '' AS Ruta, '' AS CdTipRuta, CAST(@VrDef AS DECIMAL(14,4)) AS PesoNeto, '' AS EstadoItem, CAST('' AS money) AS VrMonitor,
CAST('' AS INT) AS CantMonitor, CAST('' AS money) AS VrRecorrido, '' AS Observacion, CAST('' AS BIT) AS VLargo,
--Datos de la reserva
'' AS IdCliente, '' AS Cliente, '' AS TipoId, '' AS Dv, '' AS Codigo, '' AS NomCial, '' AS Direccion, '' AS CiuCliente, '' AS Telefono, '' AS e_mail, '' AS EstadoRes,
'' AS IdAgencia, '' AS Agencia , '' AS Modalidad, '' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona, '' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupo, '' AS GrupoClie,
CAST('' AS datetime) AS FechaIniRes, CAST('' AS datetime) AS FechaFinRes, '' AS TipFac, CAST('' AS INT) AS Factura, CAST('' AS INT) AS IdCiaFac, CAST('' AS datetime) AS FechaFac, '' AS ObsReserva, '' AS NombreResp
END
          
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPgrRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 03/03/2017
-- Description:	Imprimir programación para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPgrRel]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Programa,'' IdCia,'' AS Compania, CAST('' AS datetime) AS Fecha, '' AS OrigenAdd,
CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev, '' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys,
CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspPgrRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 06/03/2017
-- Description:	Imprimir programación para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspPgrRelDet]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Programa,'' IdCia,'' AS Compania, CAST('' AS datetime) AS Fecha, '' AS OrigenAdd,
CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev, '' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys,
CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario,
--Detalles
CAST('' AS INT) AS Item, CAST('' AS datetime) AS FechaInicio, CAST('' AS datetime) AS FechaFin,'' AS TipDocRes, CAST('' AS INT) AS Reserva, '' AS IdCiaRes, 
CAST('' AS INT) AS ItemRes, CAST('' AS datetime) AS FechaIniRes, CAST('' AS datetime) AS FechaFinRes, '' AS IdEstadoRes, '' AS EstadoItemRes, '' AS Modalidad, '' AS IdOrigen,
'' AS CiuOrigen, '' AS DeptOrigen, '' AS IdDestino, '' AS CiuDestino, '' AS DeptDestino, '' AS IdVehiculo, '' AS NumVeh, '' AS TipoAfil, '' AS CdTipVeh, '' AS TipoVehiculo,
'' AS IdConductor, '' AS NomConductor, CAST('' AS INT) AS NumPasajeros, '' AS TipDocFuec, CAST('' AS INT) AS NumFuec, '' AS IdCiaFuec, '' AS TipDocOds, 
CAST('' AS INT) AS NumOds, '' AS IdCiaOds, '' AS IdNovedad, '' AS Novedad, CAST('' AS BIT) AS Cumplido, CAST('' AS datetime) AS FecIniCump, CAST('' AS datetime) AS FecFinCump,
CAST('' AS MONEY) AS VrCobro, CAST('' AS MONEY) AS VrPagos, CAST('' AS INT) AS DiasDisp, '' AS Parada, '' AS CdTipServicio, '' AS DirOrigen, ''  AS DirDestino,
'' AS IdRuta, '' AS Ruta, '' AS CdTipRuta, '' AS PesoNeto, '' AS EstadoItem, CAST('' AS money) AS VrRecorrido,
--Datos de la reserva
'' AS IdCliente, '' AS Cliente, '' AS TipoId, '' AS Dv, '' AS Codigo, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail, '' AS EstadoRes,
'' AS IdAgencia, '' AS Agencia , '' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona, '' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupo, '' AS GrupoClie
          
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspProgramaPers]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 11/05/2017
-- Description:	Imprimir listado de auxiliares o moniotres
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspProgramaPers]
AS
--Detalle
SELECT '' AS TipDoc,  CAST('' AS INT) AS Programa, '' AS IdCia, CAST('' AS INT) AS  Item, '' AS IdVehiculo, '' AS Nit, '' AS RazonSocial,
'' AS IdNovedad, '' AS Novedad, CAST('' AS BIT) AS Cumplido, '' AS IdRuta, '' AS Ruta

GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspReservasFmt]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 30/04/2019
-- Description:	Imprimir reservas en serie
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspReservasFmt]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
--Encabezado
SELECT '' AS TipDoc, CAST('' AS INT) AS Reserva,'' IdCia,'' AS Compania, '' AS TipDocCnt, CAST('' AS INT) AS Contrato, '' AS IdCiaCnt, CAST('' AS Money) AS VrPresupuesto,
CAST('' AS Money) AS VrSaldoPresup, '' AS IdCliente,'' AS RazonSocial,CAST('' AS datetime) AS Fecha, CAST('' AS datetime) AS FechaInicio,CAST('' AS datetime) AS FechaFin,
'' AS EstadoRes, '' AS IdAgencia,'' AS Agencia, '' AS IdMneda, '' AS Mneda, '' AS CdCarga,'' AS Modalidad, '' AS TipoLiquid, '' AS TipFac, CAST('' AS INT) AS  Factura,
'' AS IdCiaFac,CAST('' AS datetime) AS FechaFac, '' AS TipFuec, CAST('' AS INT) AS  NumFuec, '' AS IdCiaFuec,CAST('' AS Money) AS  TotalCobro,CAST('' AS Money) AS  TotalPagos, 
'' AS OrigenAdd,CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev, '' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys, CAST('' AS datetime) AS FecUpdate,
'' AS IdCiaCrea, '' AS IdUsuario,'' AS Usuario, '' AS IdGrupo,'' AS Grupo, ''AS IdRutaG, '' AS RutaG,
--Anexos
'' AS NomCliente, '' AS TelCliente, '' AS emlCliente,'' AS DireccionCli,
'' AS Observacion,''  AS NombArchivo,'' AS DescripCarga, '' AS Clausulas, '' AS Responsable,
--Detalles
CAST('' AS INT) AS Item, CAST('' AS INT) AS ItemCnt, '' AS IdVehiculo, '' AS NumVeh, '' AS ClaseMat, '' AS CdTipVeh, '' AS TipoVehiculo,'' AS TipoAfil, '' AS IdMarca, '' AS Marca,
'' AS TarjOper, '' AS Modelo, '' AS IdPropietario,'' AS NomPropietario, '' AS IdPoseedor,'' AS NomPoseedor, '' AS IdConductor,'' AS NomConductor, '' AS IdRuta, '' AS Ruta, 
'' AS CdTipRuta, CAST('' AS INT) AS NumPasajeros, CAST(@VrDef AS DECIMAL(14,4)) AS PesoNeto, CAST('' AS Money) AS VrCobro, CAST('' AS Money) AS VrPagos, '' AS Referencia1, 
'' AS Referencia2, '' AS Referencia3, CAST('' AS BIT) AS EsRutaCliente, '' AS CdCiuOrigen, '' as CiuOrigenD, '' AS DeptOrigen, '' AS DirOrigen, CAST('' AS datetime) AS FecOrigen, 
'' AS CdCiuDestino, '' AS  CiuDestinoD,'' AS DeptDestino, '' AS DirDestino,CAST('' AS datetime) AS FecDestino, CAST('' AS INT) AS  DiasDisp, CAST('' AS Money) AS VrDia, '' AS Parada, 
'' AS CdTipServicio, '' AS EstadoItem, CAST('' AS MONEY) AS VrMonitor, CAST('' AS INT) AS CantMonitor, CAST('' AS MONEY) AS VrRecorrido, CAST('' AS INT) AS NumDias, '' AS TipoTarifa, 
'' AS IdColegio, '' AS NomColegio, '' AS TFac, CAST('' AS INT) AS Fact, '' AS CiaFact, CAST('' AS datetime) AS FecFac, '' AS TipCum, CAST('' AS INT) AS Cumplido, '' AS IdCiaCum, 
CAST('' AS datetime) AS FechaCum, '' AS Codigo, '' AS Itinerario, CAST('' AS BIT) AS VLargo, CAST('' AS BIT) AS IdOtroSi, CAST('' AS BIT) AS ProcEstudte,
--Datos del cliente
'' AS TipoId, '' AS Dv, '' AS Codigo, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail, '' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona,
'' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupoClie, '' AS GrupoClie,
--Detalles programación  Se suprime porque duplica los ítems ya que una reserva puede estar enmuchas programaciones
--'' AS TipDocPgr, CAST('' AS INT) AS Programa, '' AS IdCiaPgr, CAST('' AS INT) AS ItemPgr, CAST('' AS datetime) AS FecInicPgr,  CAST('' AS datetime) AS FecFinPgr,
--Datos de Ruta
CAST(@VrDef AS DECIMAL(14,4)) AS Distkmt
END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspReservasRel]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 02/03/2017
-- Description:	Imprimir reservas para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspReservasRel]
AS
SELECT '' AS TipDoc, CAST('' AS INT) AS Reserva,'' IdCia,'' AS Compania, '' AS TipDocCnt, CAST('' AS INT) AS Contrato, '' AS IdCiaCnt,
'' AS CdCarga,'' AS DescripCarga,CAST('' AS datetime) AS Fecha, CAST('' AS datetime) AS FechaInicio,CAST('' AS datetime) AS FechaFin,
'' AS IdCliente,'' AS RazonSocial,'' AS IdAgencia, '' AS CodAgencia,'' AS Agencia,'' AS DirAgncia,'' AS TelAgncia,CAST('' AS Money) AS VrCupo,
CAST('' AS Money) AS VrSaldo, '' AS NomCliente,'' AS TelCliente, '' AS emlCliente , '' AS DireccionCli,'' AS IdMneda, '' AS Mneda, '' AS EstadoRes,
'' AS Modalidad,'' AS  TipoLiquid,  '' AS TipFac, CAST('' AS INT) AS  Factura, '' AS IdCiaFac,CAST('' AS datetime) AS FechaFac, '' AS TipOdp, 
CAST('' AS INT) AS  NumOdp, '' AS IdCiaOdp,CAST('' AS datetime) AS FechaOdp, '' AS TipFuec, CAST('' AS INT) AS NumFuec, '' AS IdCiaFuec,
CAST('' AS Money) AS  VrCobro,CAST('' AS Money) AS  VrPagos, '' AS OrigenAdd, CAST('' AS bit) AS Anulado, CAST('' AS datetime) AS FecDev,
'' AS Observacion, '' AS NombArchivo, '' AS Clausulas, '' AS Responsable, '' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys,
CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,'' AS IdUsuario,'' AS Usuario
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_TraEspReservasRelDet]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 02/03/2017
-- Description:	Imprimir reservas para informes
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_TraEspReservasRelDet]
AS
--Encabezado
SELECT '' AS TipDoc, CAST('' AS INT) AS Reserva,'' IdCia,'' AS Compania, '' AS TipDocCnt, CAST('' AS INT) AS Contrato, '' AS IdCiaCnt, CAST('' AS Money) AS VrPresupuesto,
CAST('' AS Money) AS VrSaldoPresup, '' AS IdCliente,'' AS RazonSocial,CAST('' AS datetime) AS Fecha, CAST('' AS datetime) AS FechaInicio,CAST('' AS datetime) AS FechaFin,
'' AS EstadoRes, '' AS IdAgencia,'' AS Agencia, '' AS IdMneda, '' AS Mneda, '' AS CdCarga,'' AS Modalidad, '' AS TipoLiquid, '' AS TipFac, CAST('' AS INT) AS  Factura,
'' AS IdCiaFac,CAST('' AS datetime) AS FechaFac, '' AS TipOdp, CAST('' AS INT) AS  NumOdp, '' AS IdCiaOdp,CAST('' AS datetime) AS FechaOdp,'' AS TipFuec,
CAST('' AS INT) AS NumFuec, '' AS IdCiaFuec, CAST('' AS Money) AS  TotalCobro,CAST('' AS Money) AS  TotalPagos, '' AS OrigenAdd,CAST('' AS bit) AS Anulado,
CAST('' AS datetime) AS FecDev, '' AS IdEstado,'' AS Estado, CAST('' AS datetime) TimeSys, CAST('' AS datetime) AS FecUpdate, '' AS IdCiaCrea,
'' AS IdUsuario,'' AS Usuario,
--Anexos
'' AS NomCliente, '' AS TelCliente, '' AS emlCliente,'' AS DireccionCli,
'' AS Observacion,''  AS NombArchivo,'' AS DescripCarga, '' AS Clausulas, '' AS Responsable,
--Detalles
CAST('' AS INT) AS Item, CAST('' AS INT) AS ItemCnt, '' AS IdVehiculo,'' AS CdTipVeh, '' AS TipoVehiculo,'' AS TipoAfil, '' AS IdPropietario,'' AS NomPropietario,
'' AS IdPoseedor,'' AS NomPoseedor, '' AS IdConductor,'' AS NomConductor, '' AS IdRuta, '' AS Ruta, '' AS CdTipRuta, CAST('' AS INT) AS NumPasajeros, '' AS PesoNeto, 
CAST('' AS Money) AS VrCobro, CAST('' AS Money) AS VrPagos, '' AS Referencia1, '' AS Referencia2, '' AS Referencia3, '' AS TipOdp, CAST('' AS INT) AS  NumOdp, 
'' AS IdCiaOdp,CAST('' AS datetime) AS FechaOdp, CAST('' AS BIT) AS EsRutaCliente, '' AS CdCiuOrigen, '' as CiuOrigenD, '' AS DeptOrigen, '' AS DirOrigen, 
CAST('' AS datetime) AS FecOrigen, '' AS CdCiuDestino, '' AS  CiuDestinoD,'' AS DeptDestino, '' AS DirDestino,CAST('' AS datetime) AS FecDestino, CAST('' AS INT) AS  DiasDisp,
CAST('' AS Money) AS VrDia, '' AS Parada, '' AS CdTipServicio, '' AS EstadoItem, CAST('' AS MONEY) AS VrMonitor, CAST('' AS INT) AS CantMonitor, CAST('' AS MONEY) AS VrRecorrido,
CAST('' AS INT) AS NumDias, '' AS TipoTarifa, '' AS IdColegio, '' AS NomColegio, '' AS TFac, CAST('' AS INT) AS Fact, '' AS CiaFact, CAST('' AS datetime) AS FecFac,
'' AS TipCum, CAST('' AS INT) AS Cumplido, '' AS IdCiaCum, CAST('' AS datetime) AS FechaCum, '' AS Codigo,
--Datos del cliente
'' AS TipoId, '' AS Dv, '' AS Codigo, '' AS NomCial, '' AS Direccion, '' AS Telefono, '' AS e_mail, '' AS NitRepLeg, '' AS NomRepLeg, '' AS IdSzona,
'' AS Subzona, '' AS IdZona, '' AS Zona, '' AS IdGrupo, '' AS GrupoClie,
--Detalles programación
'' AS TipDocPgr, CAST('' AS INT) AS Programa, '' AS IdCiaPgr, CAST('' AS INT) AS ItemPgr, CAST('' AS datetime) AS FecInicPgr,  CAST('' AS datetime) AS FecFinPgr,
--Datos de Ruta
'' AS Distkmt,
--Fecha Día para reporte estimado horas
CAST('' AS datetime) FechaDia
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_VenceAbonos]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 25/09/2017
-- Description:	Imprimir SubReporte de vencimientos-Abonos en devolución de factura crédito de transporte especial
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeLisTrn_VenceAbonos]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
 '' AS TipRec, CAST('' AS INT) AS Recibo, '' AS IdCia, '' AS Item, '' AS Fecha,
 '' AS TipDoc, CAST('' AS INT) AS Factura, '' AS IdCiaFac, CAST('' AS INT) AS ItemFac, 
 CAST('' AS MONEY) AS VrAbono, CAST('' AS MONEY) AS VrDescto, CAST('' AS MONEY) VrBaseCms, ''  AS IdCliente,
'' AS IdAgncia, '' AS IdVend, CAST(@VrDef AS DECIMAL(14,4)) AS Comision, '' AS Detalle, CAST('' AS DATETIME) AS FecPago,  
 '' AS TipoAplica, CAST('' AS DATETIME) AS TimeSys
--datos del vencimiento
--CAST('' AS DATETIME) AS FechaFac, CAST('' AS DATETIME) AS FechaVence, CAST('' AS MONEY) AS VrFactura, CAST('' AS MONEY) AS TotalAbonos,
--CAST(@VrDef AS DECIMAL(14,4)) AS TarifDcto, '' AS TipoDcto, '' AS TipoBase, CAST('' AS DATETIME) AS FecLmtDcto, '' AS CdConcepto, '' AS Concepto,
--'' AS Referncia, '' AS DetalleVecmto, '' AS TipRef, CAST('' AS INT) AS DocRef, '' AS IdCiaRef, CAST('' AS DATETIME) AS FecUltPago,
--CAST('' AS INT) AS NumNota, '' AS IdCiaNot, CAST(@VrDef AS DECIMAL(14,4)) AS TarifInt, CAST('' AS DATETIME) AS FecLiqMora
END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeLisTrn_VencimientosDoc]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa
-- Create date(dd/MM/yyyy): 30/08/2017
-- Description:	Imprimir SubReporte de vencimientos en factura crédito de transporte especial
-- =============================================
create PROCEDURE [dbo].[paWcfSeLisTrn_VencimientosDoc]
AS
BEGIN
DECLARE @VrDef VARCHAR(1) = '1'
SELECT 
'' AS TipDoc, CAST('' AS INT) AS Factura,'' AS IdCia,'' AS Compania, CAST('' AS INT) AS Item, CAST('' AS datetime) AS Fecha, 
CAST('' AS datetime) AS FechaVence,  CAST('' AS money) AS VrFactura, CAST('' AS money) AS VrAbonado, '' AS IdCliente, '' AS IdAgencia,
'' AS IdVend, CAST(@VrDef AS DECIMAL(14,4)) AS Comision, CAST(@VrDef AS DECIMAL(14,4)) AS TarifDcto, CAST('' AS char) AS TipoDcto, 
'' AS TipoBase, CAST('' AS datetime) AS FecLmtDcto, '' AS IdConcepto, '' AS Referencia, '' AS Detalle, '' AS TipRef, CAST('' AS INT) AS DocRef,
'' AS IdCiaRef, CAST('' AS datetime) AS FecUltPago,	 CAST('' AS INT) AS NumNota, '' AS IdCiaNot, CAST(@VrDef AS DECIMAL(14,4)) AS TarifInt,
CAST('' AS smalldatetime) AS FecLiqMora, CAST('' AS smalldatetime) AS FecPlazoCal
END
GO
/****** Object:  StoredProcedure [dbo].[paWcfSeUpdateItemTrn_TraEspPrograma]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	John Jairo Roa Castañeda
-- Create date(dd/MM/yyy): 11/03/2019
-- Description:	Insertar CRUD Programacion de vehiculos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfSeUpdateItemTrn_TraEspPrograma]
	@Trn_TraEspPrograma dataTypeTrn_TraEspPrograma READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspPrograma
	@Trn_TraEspProgramaDet dataTypeTrn_TraEspProgramaDet READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspProgramaDet
	@Trn_TraEspProgramaPers dataTypeTrn_TraEspProgramaPers READONLY,--Tipo de dato definido por el usuario que representa la tabla Trn_TraEspProgramaPers
	@operacion varchar(1)
AS
DECLARE @Documento INT --Esta variable guarda el número de consecutivo del Reserva/Cotización
DECLARE @TipDoc VARCHAR(3) --Esta variable guarda el tipo de documento del Reserva/Cotización
DECLARE @IdCia VARCHAR(4) --Esta variable guarda la compañia del Reserva/Cotización
declare @IdEstado varchar(4)
declare @item int 
declare @kmp varchar 
	BEGIN TRAN
		BEGIN TRY
			--UPDATE SI-EXISTE RECORDS
			IF(@operacion = 'u')
			BEGIN

			IF(EXISTS(SELECT * FROM @Trn_TraEspPrograma))
			begin
			   UPDATE Trn_TraEspPrograma
			   SET 
			   TipDoc = t2.TipDoc,Programa = t2.Programa,IdCia = t2.IdCia,
			   Fecha = t2.Fecha,OrigenAdd = t2.OrigenAdd,Anulado = t2.Anulado,
			   FecDev = t2.FecDev,IdEstado = t2.IdEstado,TimeSys = t2.TimeSys,
			   FecUpdate = t2.FecUpdate,IdCiaCrea = t2.IdCiaCrea,IdUsuario = t2.IdUsuario
		       FROM Trn_TraEspPrograma t1
			   JOIN @Trn_TraEspPrograma t2 ON t1.TipDoc = t2.TipDoc and t1.Programa = t2.Programa and t1.IdCia = t2.IdCia
			end

			   IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaDet))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Programa FROM @Trn_TraEspProgramaDet
			   select @item =  isnull(MAX(Item),0) from Trn_TraEspProgramaDet where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia

			   --se actuallizan los que vienen en el tipo de dato y coincidan con los que estan el la tabla
			   UPDATE Trn_TraEspProgramaDet
			   SET 
			   TipDoc = t2.TipDoc,Programa = t2.Programa,IdCia = t2.IdCia,Item = t2.Item,
			   FechaInicio = t2.FechaInicio,FechaFin = t2.FechaFin,TipDocRes = t2.TipDocRes,
			   Reserva = t2.Reserva,IdCiaRes = t2.IdCiaRes,ItemRes = t2.ItemRes,IdOrigen = t2.IdOrigen,
			   IdDestino = t2.IdDestino,IdVehiculo = t2.IdVehiculo,
			   CdTipVeh = t2.CdTipVeh,IdConductor = t2.IdConductor,NumPasajeros = t2.NumPasajeros,TipDocFuec = t2.TipDocFuec,
			   NumFuec = t2.NumFuec,IdCiaFuec = t2.IdCiaFuec,TipDocOdp = t2.TipDocOdp,NumOdp = t2.NumOdp,
			   IdCiaOdp = t2.IdCiaOdp,FechaOdp=t2.FechaOdp,IdNovedad = t2.IdNovedad,Novedad = t2.Novedad,Cumplido = t2.Cumplido,FecIniCump = t2.FecIniCump, FecFinCump = t2.FecFinCump,
			   VrCobro = t2.VrCobro, VrPagos = t2.VrPagos,DiasDisp= t2.DiasDisp,Parada= t2.Parada,CdTipServicio= t2.CdTipServicio,
			   DirOrigen= t2.DirOrigen,DirDestino= t2.DirDestino,IdRuta= t2.IdRuta,CdTipRuta= t2.CdTipRuta,PesoNeto= t2.PesoNeto,EstadoItem=t2.EstadoItem,
			   VrMonitor=t2.VrMonitor,CantMonitor=t2.CantMonitor,VrRecorrido= t2.VrRecorrido, Observacion= t2.Observacion,VLargo = t2.VLargo
		       FROM Trn_TraEspProgramaDet t1
			   JOIN @Trn_TraEspProgramaDet t2 ON t1.TipDoc = t2.TipDoc and t1.Programa = t2.Programa and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   WHERE t1.TipDoc = t2.TipDoc and t1.Programa = t2.Programa and t1.IdCia = t2.IdCia and t1.Item = t2.Item
			   --Actualizar estado de vehiculo CUANDO NO TIENE NOVEDAD
			   UPDATE Vehiculos
			   SET IdEstado = '0002'
			   FROM Vehiculos v
			   JOIN @Trn_TraEspProgramaDet pd ON v.IdVehiculo = pd.IdVehiculo and pd.IdNovedad = '0' and pd.Cumplido = 0
			   WHERE v.IdVehiculo = pd.IdVehiculo 


			   --Actualizar estado de vehiculo CUANDO TENGA NOVEDAD DE TIPO VEHICULO
			   ----DECLARE @IDNOV VARCHAR(4)
			   ----SELECT @IDNOV = IdNovedad FROM @Trn_TraEspProgramaDet
			   ----IF(UPPER((select Tipo from TiposNovPgr where IdNovedad = @IDNOV)) = 'VEHICULO')
			   ----BEGIN
				  ---- UPDATE Vehiculos
				  ---- SET IdEstado = (select IdEstado from TiposNovPgr where IdNovedad = pd.IdNovedad and Tipo = 'VEHICULO')
				  ---- FROM Vehiculos v
				  ---- JOIN @Trn_TraEspProgramaDet pd ON v.IdVehiculo = pd.IdVehiculo and pd.IdNovedad != '0' and pd.Cumplido = 0
				  ---- WHERE v.IdVehiculo = pd.IdVehiculo 
			   ----END

			    declare @acveh varchar(11)
			    declare @acidnov varchar(4)
				--declare @acItem int
				
				DECLARE acvehic CURSOR
				FOR SELECT IdVehiculo,IdNovedad FROM @Trn_TraEspProgramaDet where IdNovedad != '0' and Cumplido = 0
				OPEN acvehic
				FETCH NEXT FROM acvehic INTO @acveh,@acidnov
				WHILE @@FETCH_STATUS = 0
				BEGIN
				   UPDATE Vehiculos
				   SET IdEstado = tn.IdEstado
				   FROM Vehiculos v, TiposNovPgr tn
				   WHERE v.IdVehiculo = @acveh and tn.IdNovedad = @acidnov and tn.Tipo = 'VEHICULO'
				FETCH NEXT FROM acvehic INTO @acveh,@acidnov
				END
				CLOSE acvehic
				DEALLOCATE acvehic

			   --ACTUALIZAR RESERVAS 
			   ----UPDATE Trn_TraEspResDetalle
			   ----SET EstadoItem = 'PROGRAMADA'
			   ----FROM Trn_TraEspResDetalle p
			   ----JOIN @Trn_TraEspProgramaDet d ON p.TipDoc = d.TipDocRes  and p.Reserva = d.Reserva and p.IdCia = d.IdCiaRes and p.Item = d.ItemRes
			   ----WHERE d.TipDoc = @TipDoc and d.Programa = @Documento and d.IdCia = @IdCia and d.IdNovedad = '0' and d.Cumplido = 0

			   	declare @acReserva int
				declare @acCiaRes varchar(2)
				declare @acItem int
				
				DECLARE acres CURSOR
				FOR SELECT Reserva,IdCiaRes,ItemRes FROM @Trn_TraEspProgramaDet where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia and IdNovedad = '0' and Cumplido = 0
				OPEN acres
				FETCH NEXT FROM acres INTO @acReserva,@acCiaRes,@acItem
				WHILE @@FETCH_STATUS = 0
				BEGIN
					UPDATE Trn_TraEspResDetalle
					SET EstadoItem = 'PROGRAMADA'
					FROM Trn_TraEspResDetalle p
					WHERE  p.TipDoc = 'RES' and p.Reserva = @acReserva and p.IdCia = @acCiaRes and p.Item = @acItem
					-- Fecha:20/11/2017 Se desactiva esta condición porque al entrar 2 usuarios a hacer la misma operación queda desactualizado 
					-- el número de consecutivo que se obtiene en el software y se actualizaría reservas del primera operación, en este caso, quedaría mal para la segunada transacción.
					--WHERE d.TipDoc = @TipDoc and d.Programa = @Documento and d.IdCia = @IdCia
				FETCH NEXT FROM acres INTO @acReserva,@acCiaRes,@acItem
				END
				CLOSE acres
				DEALLOCATE acres

			   --ACTUALIZAR Vehiculos en ProgramaPers 
			   UPDATE Trn_TraEspProgramaPers
			   SET IdVehiculo = d.IdVehiculo
			   FROM Trn_TraEspProgramaPers p
			   JOIN @Trn_TraEspProgramaDet d ON p.TipDoc = d.TipDoc  and p.Programa = d.Programa and p.IdCia = d.IdCia and p.Item = d.Item
			   WHERE p.TipDoc = d.TipDoc and p.Programa = d.Programa and p.IdCia = d.IdCia and p.Item= d.Item and d.IdNovedad = '0' and d.Cumplido = 0

			   end

			   IF(EXISTS(SELECT * FROM @Trn_TraEspProgramaPers))
			   begin
			   SELECT TOP 1 @TipDoc = TipDoc, @IdCia = IdCia, @Documento = Programa, @item = Item FROM @Trn_TraEspProgramaPers
			
			  --Eliminar los registros
			   delete from Trn_TraEspProgramaPers where TipDoc = @TipDoc and Programa = @Documento and IdCia = @IdCia and Item = @item 
			   --Inserta los que no existen
			   INSERT INTO Trn_TraEspProgramaPers(
			   TipDoc,Programa,IdCia,Item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
	           ) 
			   SELECT 
			   @TipDoc,@Documento,@IdCia,@item,IdVehiculo,Nit,IdNovedad,Novedad,Cumplido,IdRuta
			   FROM @Trn_TraEspProgramaPers
			   			   
			   end

			END
			SELECT @Documento

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
			RAISERROR(
			@ErrorMessage, -- Message text.
			@ErrorSeverity, -- Severity.
			@ErrorState -- State.
			);
		END CATCH
RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[paWcfUpdateKmVehs]    Script Date: 13/07/2021 10:40:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	John Jairo Roa Castañeda
-- Create date(dd/MM/yyyy): 08/03/2018
-- Description:	Actualizar Kilometraje de Vehículos.
-- =============================================
CREATE PROCEDURE [dbo].[paWcfUpdateKmVehs]
	@UpdateKmVehs dataTypeUpdateKmVehs READONLY, 
	@operacion varchar(1)
AS
BEGIN TRAN
	BEGIN TRY		 
		--UPDATE SI-EXISTE RECORDS
		IF(@operacion = 'u')
			BEGIN
				UPDATE Vehiculos
				SET 
				KmActual = t2.KmActual, FechaUpdate = t2.FechaUpdate
				FROM Vehiculos t1
				JOIN @UpdateKmVehs t2 ON t1.Idvehiculo = t2.IdVehiculo
				where t1.IdVehiculo = t2.IdVehiculo and t2.KmActual >= t1.KmActual
			END
		SELECT '1'
		COMMIT TRAN
	END TRY
    BEGIN CATCH
		ROLLBACK TRAN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();
		RAISERROR(
		@ErrorMessage, -- Message text.
		@ErrorSeverity, -- Severity.
		@ErrorState -- State.
		);
	END CATCH
RETURN 0
GO
