USE [dbSyscomCRM]
GO
/****** Object:  StoredProcedure [dbo].[updateBodegasAnularCerrarContrato]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[updateBodegasAnularCerrarContrato]
GO
/****** Object:  StoredProcedure [dbo].[spUpsertTipoDanio]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpsertTipoDanio]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateUsuarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateUsuarios]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTipo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateTipo]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTextos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateTextos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTemporales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateTemporales]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTarifasBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateTarifasBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTarifaRutas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateTarifaRutas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateSucursales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateSucursales]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateSoportePago]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateSoportePago]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateSolicitudes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateSolicitudes]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateServicios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateServicios]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateServicioPqrsDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateServicioPqrsDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateServicioPqrs]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateServicioPqrs]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateServicioCliente]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateServicioCliente]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateServ_Radicado]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateServ_Radicado]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateRutas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateRutas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateRangos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateRangos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateRadicados]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateRadicados]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateProveedores]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateProveedores]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePropietarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdatePropietarios]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdatePersonal]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePermisos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdatePermisos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePerfiles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdatePerfiles]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateParametros]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateParametros]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOrdenServicio]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateOrdenServicio]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateNovedades]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateNovedades]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateMaterialesArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateMaterialesArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateMateriales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateMateriales]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLogTraficoDetalles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateLogTraficoDetalles]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLogTrafico]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateLogTrafico]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLogSeguimientos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateLogSeguimientos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLogPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateLogPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLogBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateLogBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateHist_CotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateHist_CotMaterialesArticulo]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateHist_Cotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateHist_Cotizaciones]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateHist_CotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateHist_CotBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateHist_CotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateHist_CotArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateEstadosCuenta]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateEstadosCuenta]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateEmpresas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateEmpresas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCotMaterialesArticulo]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCotizaciones]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCotDocumentos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCotDocumentos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCotClientes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCotClientes]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCotBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCotArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateConductores]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateConductores]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCompanias]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCompanias]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateClientes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateClientes]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCarteraTarifas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCarteraTarifas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCarteraCerrado]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateCarteraCerrado]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodKardex]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodKardex]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodIPC]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodIPC]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodEstadoCuentas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodEstadoCuentas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodContratos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodContratos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodContratoIPC]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodContratoIPC]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodContBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodContBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodContArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodContArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateBodCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateBodCartera]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatebodCarSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdatebodCarSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateAgendas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spUpdateAgendas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertVisitas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertVisitas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertUsuarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertUsuarios]
GO
/****** Object:  StoredProcedure [dbo].[spInsertTipo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertTipo]
GO
/****** Object:  StoredProcedure [dbo].[spInsertTextos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertTextos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertTarifasBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertTarifasBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertTarifaRutas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertTarifaRutas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertSucursales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertSucursales]
GO
/****** Object:  StoredProcedure [dbo].[spInsertSoportePago]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertSoportePago]
GO
/****** Object:  StoredProcedure [dbo].[spInsertSolicitudes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertSolicitudes]
GO
/****** Object:  StoredProcedure [dbo].[spInsertSolicitudAsesor]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertSolicitudAsesor]
GO
/****** Object:  StoredProcedure [dbo].[spInsertServicios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertServicios]
GO
/****** Object:  StoredProcedure [dbo].[spInsertServicioPqrsSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertServicioPqrsSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spInsertServicioPqrsDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertServicioPqrsDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spInsertServicioPqrs]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertServicioPqrs]
GO
/****** Object:  StoredProcedure [dbo].[spInsertServicioClienteSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertServicioClienteSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spInsertServicioCliente]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertServicioCliente]
GO
/****** Object:  StoredProcedure [dbo].[spInsertServ_Radicado]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertServ_Radicado]
GO
/****** Object:  StoredProcedure [dbo].[spInsertSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spInsertRutas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertRutas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertRutaPrecinto]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertRutaPrecinto]
GO
/****** Object:  StoredProcedure [dbo].[spInsertRoles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertRoles]
GO
/****** Object:  StoredProcedure [dbo].[spInsertRestricciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertRestricciones]
GO
/****** Object:  StoredProcedure [dbo].[spInsertRegLlamadas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertRegLlamadas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertRangos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertRangos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertProveedores]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertProveedores]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPropietarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertPropietarios]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPreoperacional]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertPreoperacional]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPostVenta]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertPostVenta]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPermisos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertPermisos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPerfiles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertPerfiles]
GO
/****** Object:  StoredProcedure [dbo].[spInsertParametros]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertParametros]
GO
/****** Object:  StoredProcedure [dbo].[spInsertOrdenServicio]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertOrdenServicio]
GO
/****** Object:  StoredProcedure [dbo].[spInsertNovedades]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertNovedades]
GO
/****** Object:  StoredProcedure [dbo].[spInsertMaterialesArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertMaterialesArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertMateriales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertMateriales]
GO
/****** Object:  StoredProcedure [dbo].[spInsertLogVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertLogVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertLogTraficoDetalles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertLogTraficoDetalles]
GO
/****** Object:  StoredProcedure [dbo].[spInsertLogTrafico]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertLogTrafico]
GO
/****** Object:  StoredProcedure [dbo].[spInsertLogSeguimientos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertLogSeguimientos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertLogPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertLogPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spInsertLogBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertLogBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHistoricoLogVehiculo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHistoricoLogVehiculo]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHistoricoLogPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHistoricoLogPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHist_CotRequisiciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHist_CotRequisiciones]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHist_CotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHist_CotMaterialesArticulo]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHist_Cotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHist_Cotizaciones]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHist_CotEmpaques]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHist_CotEmpaques]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHist_CotConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHist_CotConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHist_CotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHist_CotBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertHist_CotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertHist_CotArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertFacturaCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertFacturaCartera]
GO
/****** Object:  StoredProcedure [dbo].[spInsertEventos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertEventos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertEmpresas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertEmpresas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertDisponibilidad]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertDisponibilidad]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotTotales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotTotales]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotRequisiciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotRequisiciones]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotMaterialesArticulo]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotizaciones]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotEmpaques]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotEmpaques]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotDocumentos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotDocumentos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCotArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertConductores]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertConductores]
GO
/****** Object:  StoredProcedure [dbo].[spInsertConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCompanias]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCompanias]
GO
/****** Object:  StoredProcedure [dbo].[spInsertClientes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertClientes]
GO
/****** Object:  StoredProcedure [dbo].[spInsertClaseDoc]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertClaseDoc]
GO
/****** Object:  StoredProcedure [dbo].[spInsertCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertCartera]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodPagos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodPagos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodKardex]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodKardex]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodIPC]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodIPC]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodEstadoCuentas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodEstadoCuentas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodContratos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodContratos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodContratoIPC]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodContratoIPC]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodContBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodContBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodContArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodContArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodCodigoSalida]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodCodigoSalida]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodCodigoEntrada]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodCodigoEntrada]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodCartera]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodCarSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodCarSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBodAbonos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBodAbonos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertBitacora]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertBitacora]
GO
/****** Object:  StoredProcedure [dbo].[spInsertArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertarRecaudosDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertarRecaudosDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spInsertarRecaudos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertarRecaudos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertarAnticiposDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertarAnticiposDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spInsertarAnticipos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertarAnticipos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertarAbonosDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertarAbonosDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spInsertarAbonos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertarAbonos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertAgendasSeguimientos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertAgendasSeguimientos]
GO
/****** Object:  StoredProcedure [dbo].[spInsertAgendas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spInsertAgendas]
GO
/****** Object:  StoredProcedure [dbo].[spGetWebServices]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetWebServices]
GO
/****** Object:  StoredProcedure [dbo].[spGetVisitas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetVisitas]
GO
/****** Object:  StoredProcedure [dbo].[spGetVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spGetUsuarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetUsuarios]
GO
/****** Object:  StoredProcedure [dbo].[spGetUnidades]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetUnidades]
GO
/****** Object:  StoredProcedure [dbo].[spGetTotalRechazo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTotalRechazo]
GO
/****** Object:  StoredProcedure [dbo].[spGetTotalMeses]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTotalMeses]
GO
/****** Object:  StoredProcedure [dbo].[spGetTotalFases]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTotalFases]
GO
/****** Object:  StoredProcedure [dbo].[spGetTotalCotizacion]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTotalCotizacion]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoVolumen]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoVolumen]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoServicioVehiculo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoServicioVehiculo]
GO
/****** Object:  StoredProcedure [dbo].[spGetTiposDanio]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTiposDanio]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipos]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoOperarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoOperarios]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoOperacion]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoOperacion]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoIdent]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoIdent]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoDocumentos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoDocumentos]
GO
/****** Object:  StoredProcedure [dbo].[spGetTipoArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTipoArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spGetTextos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTextos]
GO
/****** Object:  StoredProcedure [dbo].[spGetTarifasBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTarifasBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spGetTarifaRutas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetTarifaRutas]
GO
/****** Object:  StoredProcedure [dbo].[spGetSucursales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetSucursales]
GO
/****** Object:  StoredProcedure [dbo].[spGetSubgrupos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetSubgrupos]
GO
/****** Object:  StoredProcedure [dbo].[spGetSoportePago]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetSoportePago]
GO
/****** Object:  StoredProcedure [dbo].[spGetSolicitudes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetSolicitudes]
GO
/****** Object:  StoredProcedure [dbo].[spGetSolicitudAsesor]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetSolicitudAsesor]
GO
/****** Object:  StoredProcedure [dbo].[spGetServicios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServicios]
GO
/****** Object:  StoredProcedure [dbo].[spGetServicioPqrsSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServicioPqrsSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spGetServicioPqrsDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServicioPqrsDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spGetServicioPqrs]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServicioPqrs]
GO
/****** Object:  StoredProcedure [dbo].[spGetServicioClienteSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServicioClienteSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spGetServicioCliente]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServicioCliente]
GO
/****** Object:  StoredProcedure [dbo].[spGetServ_Responsable]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServ_Responsable]
GO
/****** Object:  StoredProcedure [dbo].[spGetServ_Recepcion]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServ_Recepcion]
GO
/****** Object:  StoredProcedure [dbo].[spGetServ_Radicado]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServ_Radicado]
GO
/****** Object:  StoredProcedure [dbo].[spGetServ_EstadoPqrs]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServ_EstadoPqrs]
GO
/****** Object:  StoredProcedure [dbo].[spGetServ_Clases]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServ_Clases]
GO
/****** Object:  StoredProcedure [dbo].[spGetServ_ClasePqrs]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServ_ClasePqrs]
GO
/****** Object:  StoredProcedure [dbo].[spGetServ_CausasOrigen]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetServ_CausasOrigen]
GO
/****** Object:  StoredProcedure [dbo].[spGetSeguimientos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetSeguimientos]
GO
/****** Object:  StoredProcedure [dbo].[spGetSeguimientoCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetSeguimientoCartera]
GO
/****** Object:  StoredProcedure [dbo].[spGetRutas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRutas]
GO
/****** Object:  StoredProcedure [dbo].[spGetRutaPrecinto]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRutaPrecinto]
GO
/****** Object:  StoredProcedure [dbo].[spGetRolesUsuario]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRolesUsuario]
GO
/****** Object:  StoredProcedure [dbo].[spGetRoles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRoles]
GO
/****** Object:  StoredProcedure [dbo].[spGetRol]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRol]
GO
/****** Object:  StoredProcedure [dbo].[spGetRestricciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRestricciones]
GO
/****** Object:  StoredProcedure [dbo].[spGetRegLLamadas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRegLLamadas]
GO
/****** Object:  StoredProcedure [dbo].[spGetRangos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetRangos]
GO
/****** Object:  StoredProcedure [dbo].[spGetProveedores]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetProveedores]
GO
/****** Object:  StoredProcedure [dbo].[spGetPropietarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPropietarios]
GO
/****** Object:  StoredProcedure [dbo].[spGetPreoperacional]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPreoperacional]
GO
/****** Object:  StoredProcedure [dbo].[spGetPostVenta]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPostVenta]
GO
/****** Object:  StoredProcedure [dbo].[spGetPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spGetPermisosSecurity]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPermisosSecurity]
GO
/****** Object:  StoredProcedure [dbo].[spGetPermisos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPermisos]
GO
/****** Object:  StoredProcedure [dbo].[spGetPerfiles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPerfiles]
GO
/****** Object:  StoredProcedure [dbo].[spGetParametros]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetParametros]
GO
/****** Object:  StoredProcedure [dbo].[spGetPaises]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetPaises]
GO
/****** Object:  StoredProcedure [dbo].[spGetOrdenServicio]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetOrdenServicio]
GO
/****** Object:  StoredProcedure [dbo].[spGetNovedades]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetNovedades]
GO
/****** Object:  StoredProcedure [dbo].[spGetMotivoAtencion]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetMotivoAtencion]
GO
/****** Object:  StoredProcedure [dbo].[spGetModulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetModulos]
GO
/****** Object:  StoredProcedure [dbo].[spGetMetodosPago]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetMetodosPago]
GO
/****** Object:  StoredProcedure [dbo].[spGetMaterialesArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetMaterialesArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spGetMateriales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetMateriales]
GO
/****** Object:  StoredProcedure [dbo].[spGetMarcas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetMarcas]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogTraficoDetalles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogTraficoDetalles]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogTrafico]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogTrafico]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogSeguimientos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogSeguimientos]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogPersonalAutorizacion]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogPersonalAutorizacion]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spGetLogActividad]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetLogActividad]
GO
/****** Object:  StoredProcedure [dbo].[spGetInformacionBodega]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetInformacionBodega]
GO
/****** Object:  StoredProcedure [dbo].[spGetInfoCarteraPDF]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetInfoCarteraPDF]
GO
/****** Object:  StoredProcedure [dbo].[spGetHistoricoLogVehiculo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHistoricoLogVehiculo]
GO
/****** Object:  StoredProcedure [dbo].[spGetHistoricoLogPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHistoricoLogPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spGetHist_CotRequisiciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHist_CotRequisiciones]
GO
/****** Object:  StoredProcedure [dbo].[spGetHist_CotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHist_CotMaterialesArticulo]
GO
/****** Object:  StoredProcedure [dbo].[spGetHist_Cotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHist_Cotizaciones]
GO
/****** Object:  StoredProcedure [dbo].[spGetHist_CotEmpaques]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHist_CotEmpaques]
GO
/****** Object:  StoredProcedure [dbo].[spGetHist_CotConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHist_CotConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spGetHist_CotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHist_CotBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spGetHist_CotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetHist_CotArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spGetGestiones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetGestiones]
GO
/****** Object:  StoredProcedure [dbo].[spGetFormasPago]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetFormasPago]
GO
/****** Object:  StoredProcedure [dbo].[spGetEventos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetEventos]
GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosVehiculo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetEstadosVehiculo]
GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosTipoServicio]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetEstadosTipoServicio]
GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosCotizacion]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetEstadosCotizacion]
GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetEstadosBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spGetEmpresas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetEmpresas]
GO
/****** Object:  StoredProcedure [dbo].[spGetDisponibilidad]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetDisponibilidad]
GO
/****** Object:  StoredProcedure [dbo].[spGetDepartamentos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetDepartamentos]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotTotales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotTotales]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotRequisiciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotRequisiciones]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotMaterialesArticulo]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotizaciones]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotEmpaques]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotEmpaques]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotDocumentos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotDocumentos]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spGetCotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCotArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spGetConductores]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetConductores]
GO
/****** Object:  StoredProcedure [dbo].[spGetConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spGetCompanias]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCompanias]
GO
/****** Object:  StoredProcedure [dbo].[spGetClientesMora]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetClientesMora]
GO
/****** Object:  StoredProcedure [dbo].[spGetClientes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetClientes]
GO
/****** Object:  StoredProcedure [dbo].[spGetClasesDoc]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetClasesDoc]
GO
/****** Object:  StoredProcedure [dbo].[spGetCiudades]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCiudades]
GO
/****** Object:  StoredProcedure [dbo].[spGetCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetCartera]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodPeriodicidad]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodPeriodicidad]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodPagosAnexos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodPagosAnexos]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodPagos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodPagos]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodKardex]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodKardex]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodIPC]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodIPC]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodEstadoCuentas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodEstadoCuentas]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodContratos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodContratos]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodContratoIPC]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodContratoIPC]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodContBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodContBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodContArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodContArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCodigoSalida]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodCodigoSalida]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCodigoEntrada]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodCodigoEntrada]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodCartera]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCarSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodCarSeguimiento]
GO
/****** Object:  StoredProcedure [dbo].[spGetBodAbonos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBodAbonos]
GO
/****** Object:  StoredProcedure [dbo].[spGetBitacora]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetBitacora]
GO
/****** Object:  StoredProcedure [dbo].[spGetArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spGetAreas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetAreas]
GO
/****** Object:  StoredProcedure [dbo].[spGetAgendasSeguimientos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetAgendasSeguimientos]
GO
/****** Object:  StoredProcedure [dbo].[spGetAgendas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spGetAgendas]
GO
/****** Object:  StoredProcedure [dbo].[spEraseSolicitudes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spEraseSolicitudes]
GO
/****** Object:  StoredProcedure [dbo].[spEraseCotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spEraseCotizaciones]
GO
/****** Object:  StoredProcedure [dbo].[spEditarCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spEditarCartera]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteUsuarios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteUsuarios]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteTextos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteTextos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteTemporales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteTemporales]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteTarifaRutas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteTarifaRutas]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteSucursales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteSucursales]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteServicios]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteServicios]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteServicioPqrsDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteServicioPqrsDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteRoles]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteRoles]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteRestricciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteRestricciones]
GO
/****** Object:  StoredProcedure [dbo].[spDeletePersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeletePersonal]
GO
/****** Object:  StoredProcedure [dbo].[spDeletePermisos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeletePermisos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteNovedades]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteNovedades]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteMaterialesArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteMaterialesArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteMateriales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteMateriales]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteLogVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteLogVehiculos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteLogPersonal]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteLogPersonal]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteHistoricosCot]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteHistoricosCot]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteDisponibilidad]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteDisponibilidad]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotTotales]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteCotTotales]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotRequisiciones]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteCotRequisiciones]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteCotMaterialesArticulo]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotEmpaques]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteCotEmpaques]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotConceptos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteCotConceptos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteCotBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteCotArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteConductores]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteConductores]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteClientes]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteClientes]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodKardex]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteBodKardex]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodContBodegas]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteBodContBodegas]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodContArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteBodContArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteArticulos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spDeleteArticulos]
GO
/****** Object:  StoredProcedure [dbo].[spConsultarInfoBodegaDetalle]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spConsultarInfoBodegaDetalle]
GO
/****** Object:  StoredProcedure [dbo].[spConsultarInfoBodega]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spConsultarInfoBodega]
GO
/****** Object:  StoredProcedure [dbo].[spConsultarCartera]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spConsultarCartera]
GO
/****** Object:  StoredProcedure [dbo].[spConsultarAbonos]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spConsultarAbonos]
GO
/****** Object:  StoredProcedure [dbo].[spCancelOrdenServicio]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spCancelOrdenServicio]
GO
/****** Object:  StoredProcedure [dbo].[spAnularAbono]    Script Date: 05/02/2025 16:01:20 ******/
DROP PROCEDURE [dbo].[spAnularAbono]
GO
/****** Object:  StoredProcedure [dbo].[spAnularAbono]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Juan Andres Martinez
-- Create date:  Enero 2023
-- Description:	 Anular Abono
-- =============================================
CREATE   PROCEDURE [dbo].[spAnularAbono]
@idCartera INT,
@idAbono INT,
@estado INT
AS
BEGIN TRANSACTION
SET NOCOUNT ON;
		BEGIN TRY

		--DECLARE @ValorAbonos INT
		--SET @ValorAbonos = (SELECT CONVERT(INT,ValorAbono) FROM Bod.Abonos WHERE IdAbono = @idAbono)

		--DECLARE @SaldoCartera INT
		--DECLARE @PagoCartera INT

		--SET @SaldoCartera = (SELECT CONVERT(INT,Saldo) FROM Bod.Cartera WHERE IdCartera = @idCartera)
		--SET @PagoCartera = (SELECT CONVERT(INT,PagoTotal) FROM Bod.Cartera WHERE IdCartera = @idCartera)


		--UPDATE Bod.Abonos SET Anulado = 1 WHERE IdAbono = @idAbono

		--UPDATE Bod.Cartera SET Saldo = CONVERT(VARCHAR,(@SaldoCartera + @ValorAbonos)), PagoTotal = CONVERT(VARCHAR,(@PagoCartera - @ValorAbonos)), Estado = @estado WHERE IdCartera = @idCartera

		COMMIT TRANSACTION
		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
GO
/****** Object:  StoredProcedure [dbo].[spCancelOrdenServicio]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 2024-07-26
-- Description:	Anular Documentos
-- =============================================
CREATE   PROCEDURE [dbo].[spCancelOrdenServicio]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdOrden int = null,
	@IdCotizacion int = null,
	@IdContrato int = null,
	@IdCartera int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Anulacion completa
		BEGIN
			
			UPDATE [dbo].[OrdenServicio]     SET EstadoOrden = 2      WHERE IdOrden      = @IdOrden  --Orden Servicio
			UPDATE [dbo].[Cotizacion]        SET IdEstadoCot = '8'    WHERE IdCotizacion = @IdCotizacion  --Cotizacion
			UPDATE [dbo].[Bodegas_Contratos] SET EstadoContrato = '2' WHERE IdContrato   = @IdContrato  --Contrato
			UPDATE [dbo].[Bodegas_Cartera]   SET Estado = 2           WHERE IdCartera    = @IdCartera  --Cartera
		END

	IF @Opcion = 2  -- Actualizar Estado
		BEGIN
			UPDATE [dbo].[OrdenServicio]     SET EstadoOrden = 2   WHERE IdOrden      = @IdOrden  --Orden Servicio
			UPDATE [dbo].[Cotizacion]        SET IdEstadoCot = '8' WHERE IdCotizacion = @IdCotizacion  --Cotizacion
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spConsultarAbonos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Juan Andres Martinez
-- Create date:  Enero 2023
-- Description:	 Consultar Abono
-- =============================================
CREATE   PROCEDURE [dbo].[spConsultarAbonos]
@IdCartera INT
AS
BEGIN TRANSACTION
SET NOCOUNT ON;

	BEGIN TRY
		--SELECT 
		--	A.IdAbono,
		--	A.FechaAbono,
		--	A.HoraAbono,
		--	A.Descripcion,
		--	A.ValorAbono,
		--	--M.Descripcion AS MedioPago,
		--	--F.Descripcion AS FormaPago,
		--	A.Anulado,
		--	A.ReciboPago
		--FROM Bod.Abonos AS A
		----JOIN Bod.Abono_Detalle AS AD ON A.IdAbono = AD.IdAbono
		----JOIN Metodos_Pago AS M ON AD.IdMedioPago = M.IdMetodosPago
		----JOIN Formas_Pago AS F ON AD.IdFormaPago = F.IdFormaPago
		--WHERE A.IdCartera = @IdCartera
	COMMIT TRANSACTION
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
GO
/****** Object:  StoredProcedure [dbo].[spConsultarCartera]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Juan Andres Martinez
-- Create date:  Enero 2023
-- Description:	 Consultar Cartera
-- =============================================
CREATE   PROCEDURE [dbo].[spConsultarCartera]--
@Contrato VARCHAR(30),
@Identificacion VARCHAR(20),
@IdSucursal INT,
@Nombres VARCHAR(100)
AS
BEGIN TRANSACTION
SET NOCOUNT ON;

	BEGIN TRY

		--IF(@Contrato <> '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.Inactivo,
		--		TP.Descripcion AS TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		C.Archivo,
		--		C.Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CO.NumeroContrato = @Contrato AND
		--		CO.IdSucursal = @IdSucursal
		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE IF(@Identificacion <> '' AND @Contrato <> '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.Inactivo,
		--		TP.Descripcion AS TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		C.Archivo,
		--		C.Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CL.Identificacion = @Identificacion AND
		--		CO.NumeroContrato = @Contrato AND
		--		CO.IdSucursal = @IdSucursal

		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE IF(@Identificacion <> '' AND @Nombres <> '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.Inactivo,
		--		TP.Descripcion AS TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		C.Archivo,
		--		C.Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CL.Identificacion = @Identificacion AND
		--		CL.Nombres = @Nombres AND
		--		CO.IdSucursal = @IdSucursal

		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE IF(@Identificacion <> '' AND @Nombres = '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.Inactivo,
		--		TP.Descripcion AS TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '2' THEN 'Pendiente Factura'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		C.Archivo,
		--		C.Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CL.Identificacion = @Identificacion AND
		--		CO.IdSucursal = @IdSucursal

		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE IF(@Nombres <> '' AND @Identificacion = '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.Inactivo,
		--		TP.Descripcion AS TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		C.Archivo,
		--		C.Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CL.Nombres = @Nombres AND
		--		CO.IdSucursal = @IdSucursal

		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		-- END

	COMMIT TRANSACTION
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
GO
/****** Object:  StoredProcedure [dbo].[spConsultarInfoBodega]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Juan Andres Martinez
-- Create date:  Enero 2023
-- Description:	 Consultar Info Bodega
-- =============================================
CREATE   PROCEDURE [dbo].[spConsultarInfoBodega]--
@IdSucursal INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statementB.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT BDG.IdBodega,
		   BDG.Nombre,
		   BDG.Estado,
		   CASE WHEN BDG.CapacidadFinal = '0' THEN '0' ELSE '1' END AS Disponible,
		   COUNT(CBG.IdCttBodega) AS Ocupantes

	FROM Bodegas AS BDG
			JOIN [dbo].[Sucursales] as SUC ON BDG.IdSucursal = SUC.IdSucursal
			LEFT JOIN [dbo].[Bodegas_ContratoBodegas] AS CBG  ON CBG.IdBodega = BDG.IdBodega 

	WHERE SUC.IdSucursal = @IdSucursal 

	GROUP BY BDG.IdBodega, BDG.Nombre, BDG.Estado, BDG.Disponible, BDG.CapacidadFinal

	ORDER BY BDG.IdBodega
END
GO
/****** Object:  StoredProcedure [dbo].[spConsultarInfoBodegaDetalle]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Juan Andres Martinez
-- Create date:  Enero 2023
-- Description:	 Consultar Info Bodega Detalle
-- =============================================

CREATE   PROCEDURE [dbo].[spConsultarInfoBodegaDetalle]--
@IdBodega int,
@Disponible int
AS
BEGIN TRANSACTION
SET NOCOUNT ON;
	BEGIN TRY
	IF(@Disponible = 1)
	BEGIN
		SELECT B.Nombre
			  ,B.Capacidad
			  ,B.CapacidadFinal
			  ,CONCAT(B.Largo,' x ',B.Ancho,' x ', B.Alto) as Medidas
			  ,C.NumeroContrato
			  ,C.FechaInicio
			  ,C.HoraInicio
			  ,C.FechaFin
			  ,C.HoraFin
			  ,TP.Descripcion AS TipoDocumento
			  ,CL.Identificacion
			  ,CL.Nombres AS Cliente
			  ,CB.Ocupacion
			  ,SUM(CONVERT(INT,CA.ValorCuota)) as TotalPagar
			  ,SUM(CONVERT(INT,CA.PagoTotal)) as Pagado
			  ,SUM(CONVERT(INT,CA.Saldo)) as Saldos

		FROM Bodegas AS B
				INNER JOIN Sucursales as S ON B.IdSucursal = S.IdSucursal
				INNER JOIN [dbo].[Bodegas_ContratoBodegas] as CB  ON CB.IdBodega = B.IdBodega 
				INNER JOIN [dbo].[Bodegas_Contratos] as C ON C.IdContrato = CB.IdContrato
				INNER JOIN [dbo].[Clientes] as CL ON C.IdCliente = CL.IdCliente
				INNER JOIN [dbo].[TipoDocumentos] as TP ON CL.TipoIdent = TP.IdTipoDoc
				LEFT  JOIN [dbo].[Bodegas_Cartera] as CA ON CA.IdContrato = C.IdContrato

		WHERE B.IdBodega = @IdBodega 
		
		GROUP BY B.Nombre,
				 B.Capacidad,
				 B.CapacidadFinal,
				 B.Largo,
				 B.Ancho,
				 B.Alto,
				 C.NumeroContrato,
				 C.FechaInicio,
				 C.HoraInicio,
				 C.FechaFin,
				 C.HoraFin,
				 TP.Descripcion,
				 CL.Identificacion,
				 CL.Nombres,
				 CB.Ocupacion
		END
		ELSE
		BEGIN
			SELECT B.Nombre
				  ,CONCAT(B.Largo,' x ',B.Ancho,' x ', B.Alto) as Medidas
				  ,B.Estado
				  ,B.Capacidad

			FROM Sucursales AS S
					INNER JOIN Bodegas AS B ON S.IdSucursal = B.IdSucursal

			WHERE B.IdBodega = @IdBodega
		END

	COMMIT TRANSACTION
	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
GO
/****** Object:  StoredProcedure [dbo].[spDeleteArticulos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 05/09/2021
-- Description:	Eliminar Articulos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteArticulos]
	-- Add the parameters for the stored procedure here
	@IdArticulo Int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE  FROM [dbo].[Articulos] WHERE IdArticulo = @IdArticulo
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodContArticulos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 18/10/2022
-- Description:	Eliminar contrato-Articulos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteBodContArticulos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCont_Articulo int = null,
	@IdCotizacion int = null,
	@IdContrato int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Elimina por Codigo del Articulo
		BEGIN
			--Eliminar Bodega del contrato.
			DELETE FROM [dbo].[Bodegas_ContratoArticulos] WHERE IdCont_Articulo = @IdCont_Articulo

		END

	IF @Opcion = 2  -- Elimina Toda la tabla
		BEGIN
			DELETE FROM [dbo].[Bodegas_ContratoArticulos] WHERE IdCotizacion = @IdCotizacion and IdContrato = @IdContrato
			
		END
	
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodContBodegas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 18/01/2023
-- Description:	Eliminar contrato-bodega
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteBodContBodegas]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCttBodega int = null,
	@IdContrato int = null,
	@IdBodega int = null,
	@Ocupacion varchar(20) = null,
	@Disponible varchar(20) = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Elimina por Codigo del Articulo
		BEGIN
			DECLARE 
				@DisponibleBodega FLOAT,
				@OcupacionBodega FLOAT,
				@OcupacionCubiculo FLOAT
	
			-- Informacion del Cubiculo.
			SELECT
				@IdBodega = IdBodega,
				@OcupacionCubiculo = Ocupacion 
			FROM 
				Bodegas_ContratoBodegas 
			WHERE 
				IdCttBodega = @IdCttBodega
			
			-- Informacion de la Bodega.
			SELECT	
				@DisponibleBodega = Disponible,
				@OcupacionBodega = Ocupacion
			FROM 
				Bodegas 
			WHERE 
				IdBodega = @IdBodega

			--Actualizar Bodegas. 
			UPDATE 
				Bodegas
			SET 
				Disponible     = (@DisponibleBodega + @OcupacionBodega),
				Ocupacion      = (@OcupacionBodega - @OcupacionCubiculo), 
				CapacidadFinal = (@DisponibleBodega + @OcupacionBodega), 
				Estado         = 1	 
			WHERE 
				IdBodega = @IdBodega

			DELETE FROM [dbo].[Bodegas_ContratoBodegas] 
			WHERE IdCttBodega = @IdCttBodega
		END

	IF @Opcion = 2  -- Elimina Toda la tabla
		BEGIN
			DELETE FROM [dbo].[Bodegas_ContratoBodegas] 
			WHERE IdContrato = @IdContrato
		END
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodegas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date:  24/09/2021
-- Description:	Eliminar bodega
-- =============================================
CREATE   PROCEDURE[dbo].[spDeleteBodegas]
	-- Add the parameters for the stored procedure here
	@IdBodega int
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DELETE FROM [dbo].[Bodegas] WHERE IdBodega = @IdBodega 
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteBodKardex]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 16/03/2023
-- Description:	Eliminar Kardex
-- =============================================
CREATE PROCEDURE [dbo].[spDeleteBodKardex]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdKardex int = null,
	@IdContrato int = null,
	@IdCotizacion int = null,
	@IdContArticulo int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Elimina por Codigo del Articulo
		BEGIN
			--Eliminar Articulo del Kardex
			DELETE FROM [dbo].[Bodegas_KardexArticulos] WHERE IdKardex = @IdKardex

			--Eliminar Articulo de la bodega
			DELETE FROM [dbo].[Bodegas_ContratoArticulos] WHERE IdCont_Articulo = @IdContArticulo

		END

	IF @Opcion = 2  -- Elimina Toda la tabla
		BEGIN
			DELETE FROM [dbo].[Bodegas_KardexArticulos] WHERE IdCotizacion = @IdCotizacion and IdContrato = @IdContrato
			
		END
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteClientes]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 23/09/2021
-- Description:	Borrar Clientes
-- ================================================
CREATE   PROCEDURE [dbo].[spDeleteClientes]
	-- Add the parameters for the stored procedure here
	@IdCliente int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Clientes] WHERE IdCliente = @IdCliente
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteConductores]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 26/04/2023
-- Description:	Eliminar conductores
-- =============================================
CREATE PROCEDURE [dbo].[spDeleteConductores]
	-- Add the parameters for the stored procedure here
	@IdConductor int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Conductores] WHERE IdConductor = @IdConductor
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 14/02/2022
-- Description:	Eliminar Cotizacion-Articulos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteCotArticulos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCot_Articulo int = null,
	@IdCotizacion int = null,
	@IdSolicitud int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Elimina por Codigo del Articulo
		BEGIN
			DELETE FROM [dbo].[Cotizacion_Articulos] WHERE IdCot_Articulo = @IdCot_Articulo
		END

	IF @Opcion = 2  -- Elimina Toda la tabla
		BEGIN
			DELETE FROM [dbo].[Cotizacion_Articulos] WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
			DELETE FROM [dbo].[Cotizacion_MaterialesArticulo] WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
			DELETE FROM [dbo].[Cotizacion_Requisicion] WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
		END
	
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 07/03/2022
-- Description:	Eliminar Cotizacion-Bodegas
-- =============================================
CREATE   PROCEDURE[dbo].[spDeleteCotBodegas]
	-- Add the parameters for the stored procedure here
	@IdCot_Bodega int,
	@IdBodega int = null,
	@IdCotizacion int = null
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--Borra el registro de Cotizacion-Bodega
	DELETE FROM [dbo].[Cotizacion_Bodegas] WHERE IdCot_Bodega = @IdCot_Bodega 

	--Borra el registro de Contrato-Bodega
	DELETE FROM [dbo].[Bodegas_ContratoBodegas] WHERE IdBodega = @IdBodega AND IdCotizacion = @IdCotizacion

	--Actualizar Estado de la Bodega
	UPDATE [dbo].[Bodegas] SET Estado = '1' WHERE IdBodega = @IdBodega
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotConceptos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 14/02/2022
-- Description:	Eliminar Cotizacion-Articulos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteCotConceptos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdServicioCot int = null,
	@IdCotizacion int = null,
	@IdSolicitud int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Elimina por Codigo del Articulo
		BEGIN
			DELETE FROM [dbo].[Cotizacion_Conceptos] WHERE IdServicioCot = @IdServicioCot
		END

	IF @Opcion = 2  -- Elimina Toda la tabla
		BEGIN
			DELETE FROM [dbo].[Cotizacion_Conceptos] WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotEmpaques]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 26/04/2022
-- Description:	Eliminar Cotizacion-Empaques
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteCotEmpaques]
	-- Add the parameters for the stored procedure here
	@IdCot_Empaque Int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here	
	DELETE FROM [dbo].[Cotizacion_Empaques] WHERE IdCot_Empaque = @IdCot_Empaque
	
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 04/03/2022
-- Description:	borrar Cotizacion Mat-Art
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteCotMaterialesArticulo]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCot_MatArt int = null,
	@IdCot_Articulo int = null,
	@IdCotizacion int = null,
	@IdSolicitud int = null

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here	
	IF @Opcion = 1  -- Elimina por Codigo del Articulo
		BEGIN
			IF @IdCot_Articulo IS NOT NULL AND @IdCot_MatArt IS NULL
				BEGIN
					DELETE FROM [dbo].[Cotizacion_MaterialesArticulo] WHERE IdCot_Articulo = @IdCot_Articulo and IdSolicitud = @IdSolicitud
				END
			
			IF @IdCot_Articulo IS NULL AND @IdCot_MatArt IS NOT NULL
				BEGIN
					DELETE FROM [dbo].[Cotizacion_MaterialesArticulo] WHERE IdCot_MatArt = @IdCot_MatArt and IdSolicitud = @IdSolicitud
				END
		END

	IF @Opcion = 2  -- Elimina Toda la tabla
		BEGIN
			DELETE FROM [dbo].[Cotizacion_MaterialesArticulo] WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
			DELETE FROM [dbo].[Cotizacion_Requisicion] WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
			UPDATE [dbo].[Cotizacion_Articulos] SET Ctrl_Empaque = 0 WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotRequisiciones]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 02/05/2022
-- Description:	Eliminar Cotizacion Requisicion
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteCotRequisiciones]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdCotizacion Int,
	@Clase Int = null,
	@IdSolicitud int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Eliminar por cotizacion
		BEGIN
			IF @Clase IS NOT NULL and @IdSolicitud IS NOT NULL
				BEGIN
					DELETE FROM [dbo].[Cotizacion_Requisicion] 
						   WHERE IdCotizacion = @IdCotizacion AND Clase =  @Clase AND IdSolicitud = @IdSolicitud
				END

			IF @Clase IS NULL and @IdSolicitud IS NOT NULL
				BEGIN
					DELETE FROM [dbo].[Cotizacion_Requisicion] 
						   WHERE IdCotizacion = @IdCotizacion AND IdSolicitud = @IdSolicitud
				END

			IF @Clase IS NOT NULL and @IdSolicitud IS NULL
				BEGIN
					DELETE FROM [dbo].[Cotizacion_Requisicion] 
						   WHERE IdCotizacion = @IdCotizacion AND Clase =  @Clase
				END

			IF @Clase IS NULL and @IdSolicitud IS NULL
				BEGIN
					DELETE FROM [dbo].[Cotizacion_Requisicion] 
						   WHERE IdCotizacion = @IdCotizacion 
				END
		END

	IF @Opcion = 2  -- Eliminar para dejar solo pelex
		BEGIN
			DELETE FROM [dbo].[Cotizacion_Requisicion] 
				WHERE IdCotizacion = @IdCotizacion and 
					  Clase = @Clase and
					  IdSolicitud = @IdSolicitud and
					  IdMaterial <> '18'
		END


END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteCotTotales]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 18/04/2022
-- Description:	Eliminar Cotizacion-Totales
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteCotTotales]
	-- Add the parameters for the stored procedure here
	@IdCotizacion Int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Cotizacion_Servicios] WHERE IdCotizacion = @IdCotizacion
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteDisponibilidad]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 01/10/2021
-- Description:	Eliminar Disponibilidad
-- ==============================================
CREATE   PROCEDURE [dbo].[spDeleteDisponibilidad]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdDisponibilidad Int,
	@IdVehiculo Int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Eliminar por Material
	  BEGIN
		DELETE  FROM  [dbo].[Disponibilidad_Vehiculos] WHERE IdDisponibilidad = @IdDisponibilidad
	  END

	IF @Opcion = 2 -- Eliminar por articulo
	  BEGIN
		DELETE  FROM  [dbo].[Disponibilidad_Vehiculos] WHERE IdVehiculo = @IdVehiculo
	  END

END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteHistoricosCot]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 20-03-2024
-- Description:	Eliminar historicos Cotizacion
-- =============================================
CREATE PROCEDURE [dbo].[spDeleteHistoricosCot]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCotizacion int = null,
	@IdSolicitud int = null,
	@CodVerifica int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Elimina por Codigo del Articulo
		BEGIN
			DELETE FROM [dbo].[Hist_Cotizacion_Articulos]          WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud and CodVerificacion = @CodVerifica
			DELETE FROM [dbo].[Hist_Cotizacion_Bodegas]            WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud and CodVerificacion = @CodVerifica
			DELETE FROM [dbo].[Hist_Cotizacion_Conceptos]          WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud and CodVerificacion = @CodVerifica
			DELETE FROM [dbo].[Hist_Cotizacion_Empaques]           WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud and CodVerificacion = @CodVerifica
			DELETE FROM [dbo].[Hist_Cotizacion_MaterialesArticulo] WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud and CodVerificacion = @CodVerifica
			DELETE FROM [dbo].[Hist_Cotizacion_Requisicion]        WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud and CodVerificacion = @CodVerifica
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteLogPersonal]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 14/12/2022
-- Description:	Eliminar Logistica-Vehiculos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteLogPersonal]
	-- Add the parameters for the stored procedure here
	@IdPersonalLog Int,
	@IdCotizacion int = null,
	@IdEvento int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Logistica_Personal] WHERE IdPersonalLog = @IdPersonalLog

	-- Actualizar
	UPDATE [dbo].[Agenda]                 SET Personal = 1   WHERE IdEvento = @IdEvento and IdCotizacion = @IdCotizacion
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteLogVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 14/12/2022
-- Description:	Eliminar Logistica-Vehiculos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteLogVehiculos]
	-- Add the parameters for the stored procedure here
	@IdVehiculosLog Int,
	@IdCotizacion int = null,
	@IdEvento int = null,
	@Rolconductor int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Logistica_Vehiculos] WHERE IdVehiculosLog = @IdVehiculosLog

	-- Actualizar
	UPDATE [dbo].[Logistica_Seguimientos] SET IdVehiculo = 1 WHERE IdEvento = @IdEvento and IdCotizacion = @IdCotizacion
	UPDATE [dbo].[Agenda]                 SET Vehiculo = 1   WHERE IdEvento = @IdEvento and IdCotizacion = @IdCotizacion
	
	-- Borrar Control Trafico Detalle
	DELETE FROM [dbo].[Logistica_TraficoDetalles] WHERE IdCotizacion = @IdCotizacion

	--Borrar Personal
	DELETE FROM [dbo].[Logistica_Personal] WHERE IdEvento = @IdEvento and IdCotizacion = @IdCotizacion and Rol = @Rolconductor
	
END

GO
/****** Object:  StoredProcedure [dbo].[spDeleteMateriales]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 06/09/2021
-- Description:	Eliminar Materiales
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteMateriales] 
	-- Add the parameters for the stored procedure here
	@IdMaterial Int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Materiales] WHERE IdMaterial = @IdMaterial
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteMaterialesArticulos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 06/09/2021
-- Description:	Eliminar Materiales-Articulos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteMaterialesArticulos] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdMaterial int = null,
	@IdArticulo int = null,
	@IdMatArticulo int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here	
	IF @Opcion = 1  -- Eliminar por Material
	  BEGIN
		DELETE FROM [dbo].[Materiales_Articulo] WHERE IdMaterial = @IdMaterial
	  END

	IF @Opcion = 2 -- Eliminar por articulo
	  BEGIN
		DELETE FROM [dbo].[Materiales_Articulo] WHERE IdArticulo = @IdArticulo
	  END

	IF @Opcion = 3 -- Eliminar por Material y articulo
	  BEGIN
		DELETE FROM [dbo].[Materiales_Articulo] WHERE IdMaterial = @IdMaterial and IdArticulo = @IdArticulo
	  END

	IF @Opcion = 4 -- Eliminar por Id
	  BEGIN
		DELETE FROM [dbo].[Materiales_Articulo] WHERE IdMatArticulo = @IdMatArticulo 
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteNovedades]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 18-07-2023
-- Description:	Procedimiento para eliminarr las novedades
-- =============================================
CREATE PROCEDURE [dbo].[spDeleteNovedades] 
	-- Add the parameters for the stored procedure here
	@IdNovedad int
		
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Novedades]
      WHERE IdNovedad=@IdNovedad;

END

GO
/****** Object:  StoredProcedure [dbo].[spDeletePermisos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 02/08/2021
-- Description:	Borrar Permisos
-- =============================================
CREATE   PROCEDURE [dbo].[spDeletePermisos]
	-- Add the parameters for the stored procedure here
	@IdPermiso Int

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Permisos] WHERE IdPermiso = @IdPermiso

END

GO
/****** Object:  StoredProcedure [dbo].[spDeletePersonal]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 06/04/2022
-- Description:	Borrar Personal
-- =============================================
CREATE   PROCEDURE [dbo].[spDeletePersonal]
	-- Add the parameters for the stored procedure here
	@IdPersonal int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Personal] WHERE IdPersonal = @IdPersonal
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteRestricciones]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 01/10/2021
-- Description:	Eliminar Restricciones
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteRestricciones]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdRestriccion Int,
	@IdVehiculo Int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Eliminar por Material
	  BEGIN
		DELETE  FROM  [dbo].[Restricciones_Vehiculos] WHERE IdRestriccion = @IdRestriccion
	  END

	IF @Opcion = 2 -- Eliminar por articulo
	  BEGIN
		DELETE  FROM  [dbo].[Restricciones_Vehiculos] WHERE IdVehiculo = @IdVehiculo
	  END

END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteRoles]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 30/09/2021
-- Description:	Procedimiento almacenado para eliminar roles
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteRoles] 
	-- Add the parameters for the stored procedure here
	@IdPerfil as int,
	@IdUsuario as int
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	delete from Roles where IdPerfil=@IdPerfil and IdUsuario=@IdUsuario
	
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteServicioPqrsDetalle]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Fabian Esteban Becerra G.
-- Create date: 15/10/2024
-- Description:	Inactivar el servicio PQRS detalle.
-- =============================================
CREATE PROCEDURE [dbo].[spDeleteServicioPqrsDetalle] 
	@IdServicioPqrsDet INT
AS
BEGIN
	SET NOCOUNT ON;

    UPDATE ServicioPqrsDetalle
	SET Inactivo = 1 
	WHERE IdServicioDetalle = @IdServicioPqrsDet
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteServicios]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 02/09/2021
-- Description:	Eliminar Servicios
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteServicios] 
	-- Add the parameters for the stored procedure here
	@IdServicio Int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Servicios] WHERE IdServicio = @IdServicio
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteSucursales]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 20/09/2021
-- Description:	Borrar Sucursales
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteSucursales] 
	-- Add the parameters for the stored procedure here
	@IdSucursal Int

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Sucursales] WHERE IdSucursal = @IdSucursal
END








GO
/****** Object:  StoredProcedure [dbo].[spDeleteTarifaRutas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 25/05/2023
-- Description:	Borrar Tarifa Rutas
-- =============================================
CREATE PROCEDURE [dbo].[spDeleteTarifaRutas]
	-- Add the parameters for the stored procedure here
	@IdTarifa int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Tarifa_Rutas] WHERE IdTarifa = @IdTarifa
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteTemporales]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 12/04/2022
-- Description:	Borrar Archivos Temporales
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteTemporales] 
	-- Add the parameters for the stored procedure here
	@IdCotizacion int,
	@IdSolicitud int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
    -- Insert statements for procedure here
	DELETE FROM Cotizacion_Articulos          WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
	DELETE FROM Cotizacion_MaterialesArticulo WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
	DELETE FROM Cotizacion_Conceptos          WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
	DELETE FROM Cotizacion_Empaques           WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
	DELETE FROM Cotizacion_Requisicion        WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
	DELETE FROM Cotizacion_Bodegas            WHERE IdCotizacion = @IdCotizacion and IdSolicitud = @IdSolicitud
		
	
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteTextos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date:  26/01/2022
-- Description:	Eliminar Texto
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteTextos]
	-- Add the parameters for the stored procedure here
	@IdTexto int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE FROM [dbo].[Textos] WHERE IdTexto = @IdTexto
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteUsuarios]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 06/10/2021
-- Description:	Procedimiento para ianctivar el usuario
-- =============================================
CREATE   PROCEDURE [dbo].[spDeleteUsuarios] 
	-- Add the parameters for the stored procedure here
	@IdUsuario as int
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	UPDATE [dbo].[Usuarios]
		   SET 
			   [Estado]  =  'I'
			   
		    WHERE IdUsuario =  @IdUsuario;
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteVehiculos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 29/09/2021
-- Description:	Eliminar Vehiculos
-- =============================================

CREATE   PROCEDURE [dbo].[spDeleteVehiculos] 
	-- Add the parameters for the stored procedure here
	@IdVehiculo Int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DELETE  FROM [dbo].[Vehiculos] WHERE IdVehiculo = @IdVehiculo
END
GO
/****** Object:  StoredProcedure [dbo].[spEditarCartera]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		JUAN ANDRES MARTINEZ
-- Create date: ENERO 2023
-- Description:	EDITAR CARTERA
-- =============================================
CREATE   PROCEDURE [dbo].[spEditarCartera]--
@idCartera INT,
@Saldo VARCHAR(30),
@PagoTotal VARCHAR(30),
@Intereses VARCHAR(30),
@Descuentos VARCHAR(30),
@Estado INT,
@Inactivo BIT = NULL
AS
BEGIN TRANSACTION
		BEGIN TRY

		--if(@Inactivo IS NULL)
		--BEGIN
		--	UPDATE Bod.Cartera SET Saldo = @Saldo, PagoTotal = @PagoTotal,Estado = @Estado,Intereses = @Intereses,Descuentos = @Descuentos WHERE IdCartera = @idCartera
		--END
		--ELSE
		--BEGIN
		--	UPDATE Bod.Cartera SET Inactivo = @Inactivo WHERE IdCartera = @idCartera
		--END
		COMMIT TRANSACTION
		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
GO
/****** Object:  StoredProcedure [dbo].[spEraseCotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 12/04/2022
-- Description:	Cambiar de estado Cotizaciones
-- =============================================
CREATE   PROCEDURE [dbo].[spEraseCotizaciones] 
	-- Add the parameters for the stored procedure here
	@IdCotizacion int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	UPDATE [dbo].[Cotizacion] SET IdEstadoCot = 7 Where IdCotizacion = @IdCotizacion
END
GO
/****** Object:  StoredProcedure [dbo].[spEraseSolicitudes]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 12/04/2022
-- Description:	Cambiar de estado Solicitudes
-- =============================================
CREATE   PROCEDURE [dbo].[spEraseSolicitudes] 
	-- Add the parameters for the stored procedure here
	@IdSolicitud int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	UPDATE [dbo].[Solicitudes] SET Estado = 3 Where IdSolicitud = @IdSolicitud
	UPDATE [dbo].[Solicitud_Asesor] SET Estado = '0' WHERE IdSolicitud = @IdSolicitud	
END
GO
/****** Object:  StoredProcedure [dbo].[spGetAgendas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 22/04/2022
-- Description:	Buscar Agenda
-- =============================================
CREATE   PROCEDURE [dbo].[spGetAgendas]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdEvento int = null,
	@IdUsuario int = null, 
	@IdCia int = null,
	@FechaEvento varchar(10) = null,
	@Servicio int = null,
	@IdCotizacion int = null,
	@CtrlAgenda int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE
	@MesAnterior varchar(10) = CONVERT(varchar,(DATEADD(mm,-6,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))),23),
	@MesSiguiente varchar(10) = CONVERT(varchar,(DATEADD(mm,0,DATEADD(mm,3,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)))),23),
	@Fact int = 0
	
	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT  AG.IdEvento
					,AG.title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textcolor
					,AG.[end]
					,AG.Vehiculo
					,AG.Personal
					,AG.IdUsuario
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.TipoServicioCot
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
						END AS NombreServ

			FROM [dbo].[Agenda] as AG

			WHERE AG.CtrlAgenda = ISNULL(@CtrlAgenda,AG.CtrlAgenda) and
				  AG.FechaIni   between @MesAnterior AND @MesSiguiente
		END

	IF @Opcion = 2 --Consulta por usuario
		BEGIN 
			SELECT  AG.IdEvento
					--,CONCAT('Orden Mudanza No.', ' ', AG.title) as title
					,CASE WHEN AG.IdOrden = 0 
						THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion) 
						ELSE CONCAT('Orden Mudanza No.', ' ', AG.title) 
					 END as title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textColor
					,AG.[end]
					,AG.IdOrden
					,AG.IdCotizacion
					,AG.Vehiculo
					,AG.IdUsuario
					,AG.Personal
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.TipoServicioCot
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
					END AS NombreServ

					--ORDEN SERVICIO
					,OS.FechaOrden
					,OS.HoraOrden
					,OS.EstadoOrden
					,OS.NumRequisicion

					--COTIZACION
					,CT.IdCotizacion
					,CT.IdCliente
					,CT.IdUsuario
					,CT.IdSolicitud
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen
					,CT.Barrio_Destino
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CASE CT.IdCia
						WHEN '8'  THEN '#F5B7B1'
						WHEN '9'  THEN '#D2B4DE'
						WHEN '10' THEN '#AED6F1'
						WHEN '11' THEN '#ABEBC6'
						WHEN '12' THEN '#F9E79F'
						WHEN '13' THEN '#D5DBDB'
						WHEN '14' THEN '#ABB2B9'
						ELSE '0' 
					END AS ColorSuc

					--CIUDADES
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino

			FROM [dbo].[Agenda] as AG
 	    			LEFT  JOIN [dbo].[OrdenServicio] as OS on AG.IdCotizacion = OS.IdCotizacion and AG.IdOrden = OS.IdOrden
					INNER JOIN [dbo].[Cotizacion] as CT on AG.IdCotizacion = CT.IdCotizacion
					INNER JOIN [dbo].[Ciudades] as ORG on CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST on CT.Ciudad_Destino = DST.IdCiudad

			WHERE AG.CtrlAgenda <> 2  and
				  AG.IdUsuario  = ISNULL(@IdUsuario,AG.IdUsuario) and
				  AG.FechaIni   between @MesAnterior AND @MesSiguiente

		END

	IF @Opcion = 3 --Consulta por IdEvento
		BEGIN 
			SELECT  AG.IdEvento
					--,CONCAT('Orden Mudanza No.', ' ', AG.title) as title
					,CASE WHEN AG.IdOrden = 0 
						THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion) 
						ELSE CONCAT('Orden Mudanza No.', ' ', AG.title) 
					 END as title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textColor
					,AG.[end]
					,AG.IdOrden
					,AG.IdCotizacion
					,AG.Vehiculo
					,AG.Personal
					,AG.IdUsuario
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.TipoServicioCot
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.TipoServicioCot
						WHEN '1'  THEN '#F5B7B1'
						WHEN '2'  THEN '#D2B4DE'
						WHEN '3'  THEN '#AED6F1'
						WHEN '4'  THEN '#ABEBC6'
						WHEN '5'  THEN '#F9E79F'
						WHEN '6'  THEN '#D5DBDB'
						WHEN '7'  THEN '#ABB2B9'
						WHEN '8'  THEN '#8EECF5'
						WHEN '9'  THEN '#9FAFFF'
						WHEN '10' THEN '#FF9688'
						ELSE '0' 
					 END AS ColorNew
					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
					 END AS NombreServ

					--ORDEN DE SERVICIO
					,OS.FechaOrden
					,OS.HoraOrden
					,OS.EstadoOrden
					,OS.NumOrden
					,OS.NumInventario
					,OS.NumRequisicion

					--COTIZACION
					,CT.IdCotizacion
					,CT.IdCliente
					,CT.IdUsuario
					,CT.IdSolicitud
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen
					,CT.Barrio_Destino
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.Remesa
					,CT.Manifiesto
					,CASE CT.IdCia
						WHEN '8'  THEN '#F5B7B1'
						WHEN '9'  THEN '#D2B4DE'
						WHEN '10' THEN '#AED6F1'
						WHEN '11' THEN '#ABEBC6'
						WHEN '12' THEN '#F9E79F'
						WHEN '13' THEN '#D5DBDB'
						WHEN '14' THEN '#ABB2B9'
						ELSE '0' 
					 END AS ColorSuc

					--COMPANIA
					,CIA.CodSyscom as Compania
			
					--CLIENTES
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.TipoCliente
					,CL.Nombres as NombreCliente
					,CL.Apellidos as ApellidoCliente
					,CONCAT(CL.Nombres, ' ',CL.Apellidos) as NomCliente

					--USUARIOS
					,US.Nombres as NombreAsesor
					,US.Apellidos as ApellidoAsesor
					,CONCAT(US.Apellidos, ' ', US.Nombres) as NomAsesor

					--TIPOSERVICIOS
					,TS.IdTipo
					,TS.Nombre as NomServicio

					--CIUDADES
					,ORG.Nombre as CiudadOrigen
					,ORG.Compania as CiaOrigen
					,DST.Nombre as CiudadDestino
					,DST.Compania as CiaDestino

					--TOTALES POR CONCEPTO
					,RTA.[1] as Concepto1
					,RTA.[2] as Concepto2
					,RTA.[3] as Concepto3
					,RTA.[4] as Concepto4
					,RTA.[5] as Concepto5
					,RTA.[6] as Concepto6
					,RTA.[7] as Concepto7
					,RTA.[8] as Concepto8
					,RTA.[9] as Concepto9
					,RTA.[10] as Concepto10
					,RTA.[11] as Concepto11
					,RTA.[12] as Concepto12
					,RTA.[13] as Concepto13
					,RTA.[14] as Concepto14
					,RTA.[15] as Concepto15
					,RTA.[16] as Concepto16
					,RTA.[17] as Concepto17
					,RTA.[18] as Concepto18
					,RTA.[19] as Concepto19
					,RTA.[20] as Concepto20
					,RTA.[21] as Concepto21
					,RTA.[22] as Concepto22

			FROM [dbo].[Agenda] as AG
					LEFT  JOIN [dbo].[OrdenServicio] as OS on AG.IdCotizacion = OS.IdCotizacion and AG.IdOrden = OS.IdOrden
		 			INNER JOIN [dbo].[Cotizacion] as CT on AG.IdCotizacion = CT.IdCotizacion 
		 			INNER JOIN [dbo].[Clientes] as CL on CT.IdCliente = CL.IdCliente 
		 			INNER JOIN [dbo].[Usuarios] as US on CT.IdUsuario = US.IdUsuario  
		 			INNER JOIN [dbo].[TipoServicio] as TS on CT.TipoServ = TS.IdTipo 
					INNER JOIN [dbo].[Compania] as CIA on CT.IdCia = CIA.IdCia 
					INNER JOIN [dbo].[Ciudades] as ORG on CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST on CT.Ciudad_Destino = DST.IdCiudad
					JOIN (SELECT * FROM (SELECT [IdConceptoPDF], [IdCotizacion],[ValorServicio] FROM [dbo].[Cotizacion_Servicios]) AS ST 
						PIVOT(AVG([ValorServicio]) FOR [IdConceptoPDF] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22])) AS PT) as RTA
						ON CT.IdCotizacion = RTA.IdCotizacion

			WHERE AG.IdEvento     between ISNULL(@IdEvento,AG.IdEvento) and ISNULL(@IdEvento,AG.IdEvento) and
				  AG.Servicio     between ISNULL(@Servicio,AG.Servicio) and ISNULL(@Servicio,AG.Servicio) and	
				  AG.IdCotizacion between ISNULL(@IdCotizacion,AG.IdCotizacion) and ISNULL(@IdCotizacion,AG.IdCotizacion) and	
				  AG.IdCia        between ISNULL(@IdCia,AG.IdCia) and ISNULL(@IdCia,AG.IdCia) and	
				  AG.CtrlAgenda   = ISNULL(@CtrlAgenda,AG.CtrlAgenda) and
				  AG.FechaIni     between @MesAnterior AND @MesSiguiente
		END

	IF @Opcion = 4 --Consulta por compañia para Agendamiento Servicio
		BEGIN 
			SELECT  AG.IdEvento
					--,CONCAT('Orden Mudanza No.', ' ', AG.title,'-',CIA.CodSyscom ) as title
					,CASE WHEN CT.Almacenamiento = 0 
						THEN CASE WHEN AG.IdOrden = 0 
								THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion,' - ','ALM') 
								ELSE CONCAT('Orden Mudanza No.', ' ', AG.title,' - ','ALM')
								END
						ELSE CASE WHEN AG.IdOrden = 0 
								THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion) 
								ELSE CONCAT('Orden Mudanza No.', ' ', AG.title)
								END
					 END as title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textColor
					,AG.[end]
					,AG.IdOrden
					,AG.IdCotizacion
					,AG.Vehiculo
					,AG.IdUsuario
					,AG.Personal
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.TipoServicioCot
						WHEN '1'  THEN '#F5B7B1'
						WHEN '2'  THEN '#D2B4DE'
						WHEN '3'  THEN '#AED6F1'
						WHEN '4'  THEN '#ABEBC6'
						WHEN '5'  THEN '#F9E79F'
						WHEN '6'  THEN '#D5DBDB'
						WHEN '7'  THEN '#ABB2B9'
						WHEN '8'  THEN '#8EECF5'
						WHEN '9'  THEN '#9FAFFF'
						WHEN '10' THEN '#FF9688'
						ELSE '0' 
					 END AS ColorNew
					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
					 END AS NombreServ

					--ORDEN SERVICIO
					,OS.FechaOrden
					,OS.HoraOrden
					,OS.EstadoOrden
					,OS.NumRequisicion

					--COTIZACION
					,CT.IdCotizacion
					,CT.IdCliente
					,CT.IdUsuario
					,CT.IdSolicitud
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen
					,CT.Barrio_Destino
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente

					 --CIUDADES
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino

					--COMPANIA
					,CIA.CodSyscom as Compania

			FROM [dbo].[Agenda] as AG
 	    			LEFT  JOIN [dbo].[OrdenServicio] OS on AG.IdCotizacion = OS.IdCotizacion and AG.IdOrden = OS.IdOrden
					INNER JOIN [dbo].[Cotizacion] as CT on AG.IdCotizacion = CT.IdCotizacion
					INNER JOIN [dbo].[Ciudades] as ORG on CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST on CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Compania] as CIA on CT.IdCia = CIA.IdCia 

			WHERE AG.CtrlAgenda <= @CtrlAgenda and
			      AG.IdCia      = ISNULL(@IdCia,AG.IdCia) and
				  AG.FechaIni   between @MesAnterior AND @MesSiguiente
		END

	IF @Opcion = 5 --Consulta por Fecha Especifica para programacion
		BEGIN 
			SELECT  AG.IdEvento
					--,CONCAT('Orden Mudanza No.', ' ', AG.title) as title
					,CASE WHEN AG.IdOrden = 0 
						THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion) 
						ELSE CONCAT('Orden Mudanza No.', ' ', AG.title) 
					 END as title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textColor
					,AG.[end]
					,AG.IdOrden
					,AG.IdCotizacion
					,AG.Vehiculo
					,AG.Personal
					,AG.IdUsuario
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.TipoServicioCot
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.TipoServicioCot
						WHEN '1'  THEN '#F5B7B1'
						WHEN '2'  THEN '#D2B4DE'
						WHEN '3'  THEN '#AED6F1'
						WHEN '4'  THEN '#ABEBC6'
						WHEN '5'  THEN '#F9E79F'
						WHEN '6'  THEN '#D5DBDB'
						WHEN '7'  THEN '#ABB2B9'
						WHEN '8'  THEN '#8EECF5'
						WHEN '9'  THEN '#9FAFFF'
						WHEN '10' THEN '#FF9688'
						ELSE '0' 
					 END AS ColorNew
					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
					 END AS NombreServ

					--ORDEN DE SERVICIO
					,OS.FechaOrden
					,OS.HoraOrden
					,OS.EstadoOrden
					,OS.NumOrden
					,OS.NumInventario
					,OS.NumRequisicion

					--COTIZACION
					,CT.IdCotizacion
					,CT.IdCliente
					,CT.IdUsuario
					,CT.IdSolicitud
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen
					,CT.Barrio_Destino
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.Remesa
					,CT.Manifiesto
					,CASE CT.IdCia
						WHEN '8'  THEN '#F5B7B1'
						WHEN '9'  THEN '#D2B4DE'
						WHEN '10' THEN '#AED6F1'
						WHEN '11' THEN '#ABEBC6'
						WHEN '12' THEN '#F9E79F'
						WHEN '13' THEN '#D5DBDB'
						WHEN '14' THEN '#ABB2B9'
						ELSE '0' 
					 END AS ColorSuc

					--COMPANIA
					,CIA.CodSyscom as Compania
			
					--CLIENTES
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.TipoCliente
					,CL.Nombres as NombreCliente
					,CL.Apellidos as ApellidoCliente
					,CONCAT(CL.Nombres, ' ',CL.Apellidos) as NomCliente

					--USUARIOS
					,US.Nombres as NombreAsesor
					,US.Apellidos as ApellidoAsesor
					,CONCAT(US.Apellidos, ' ', US.Nombres) as NomAsesor

					--TIPOSERVICIOS
					,TS.Nombre as NomServicio

					--CIUDADES
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino

					,@Fact as Fact

					--LOG_VEHICULOS
					,LV.Placa

					--CONDUCTOR
					,CONCAT(CD.Nombres, ' ', CD.Apellidos) as NomConductor

					--PERSONAL
					,RTA.[1]
					,RTA.[2]
					,RTA.[3]
					,RTA.[4]
					,RTA.[5]
					,RTA.[6] 
					,CONCAT(AX1.Nombres, ' ', AX1.Apellidos) as Aux1
					,CONCAT(AX2.Nombres, ' ', AX2.Apellidos) as Aux2
					,CONCAT(AX3.Nombres, ' ', AX3.Apellidos) as Aux3
					,CONCAT(AX4.Nombres, ' ', AX4.Apellidos) as Aux4
					,CONCAT(CTT.Nombres, ' ', CTT.Apellidos) as Cont

					--VARIOS
					,CONCAT(OS.NumOrden,'-',CIA.CodSyscom) as OrdenNum
			
			FROM [dbo].[Agenda] as AG
					LEFT JOIN [dbo].[OrdenServicio] as OS ON  AG.IdOrden = OS.IdOrden
		 			INNER JOIN [dbo].[Cotizacion] as CT ON AG.IdCotizacion = CT.IdCotizacion 
					INNER JOIN [dbo].[Compania] as CIA ON OS.Compania = CIA.IdCia 
		 			INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente 
		 			INNER JOIN [dbo].[Usuarios] as US ON CT.IdUsuario = US.IdUsuario 
		 			INNER JOIN [dbo].[TipoServicio] as TS ON CT.TipoServ = TS.IdTipo 
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					LEFT JOIN (SELECT * FROM (SELECT IdCotizacion, IdPersonal, CtrlPersonal, Servicio FROM [dbo].[Logistica_Personal]) AS LP 
							PIVOT(AVG([IdPersonal]) FOR [CtrlPersonal] IN ([1],[2],[3],[4],[5],[6])) AS PT) as RTA
							ON AG.IdCotizacion = RTA.IdCotizacion and AG.Servicio = RTA.Servicio
		 			LEFT JOIN [dbo].[Logistica_Vehiculos] as LV ON AG.IdCotizacion = LV.IdCotizacion and AG.Servicio = LV.Servicio
		 			LEFT JOIN [dbo].[Vehiculos] as VH ON LV.IdVehiculo = VH.IdVehiculo 
		 			LEFT JOIN [dbo].[Conductores] as CD ON RTA.[1] = CD.IdConductor 
		 			LEFT JOIN [dbo].[Personal] as AX1 ON RTA.[2] = AX1.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as AX2 ON RTA.[3] = AX2.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as AX3 ON RTA.[4] = AX3.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as AX4 ON RTA.[5] = AX4.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as CTT ON RTA.[6] = CTT.IdPersonal 

			WHERE AG.CtrlAgenda = ISNULL(@CtrlAgenda,AG.CtrlAgenda) and
				  AG.IdCia      = ISNULL(@IdCia,AG.IdCia) and
				  AG.FechaIni   = ISNULL(@FechaEvento,AG.FechaIni) 
				
		END

	IF @Opcion = 6 --Consulta contador de eventos
		BEGIN 
			SELECT COUNT(IdEvento) as Contador 
			FROM [dbo].[Agenda] as AG 
			WHERE AG.IdCia    = ISNULL(@IdCia,AG.IdCia) and
				  AG.FechaIni = ISNULL(@FechaEvento,AG.FechaIni) 
		END

	IF @Opcion = 7 --Consulta por compañia y Fecha
		BEGIN
			SELECT  AG.IdEvento
					--,CONCAT('Orden Mudanza No.', ' ', AG.title) as title
					,CASE WHEN AG.IdOrden = 0 
						THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion) 
						ELSE CONCAT('Orden Mudanza No.', ' ', AG.title) 
					 END as title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textColor
					,AG.[end]
					,AG.IdOrden
					,AG.IdCotizacion
					,AG.Vehiculo
					,AG.Personal
					,AG.IdUsuario
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.TipoServicioCot
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.TipoServicioCot
						WHEN '1'  THEN '#F5B7B1'
						WHEN '2'  THEN '#D2B4DE'
						WHEN '3'  THEN '#AED6F1'
						WHEN '4'  THEN '#ABEBC6'
						WHEN '5'  THEN '#F9E79F'
						WHEN '6'  THEN '#D5DBDB'
						WHEN '7'  THEN '#ABB2B9'
						WHEN '8'  THEN '#8EECF5'
						WHEN '9'  THEN '#9FAFFF'
						WHEN '10' THEN '#FF9688'
						ELSE '0' 
					 END AS ColorNew
					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
					 END AS NombreServ

					--ORDEN DE SERVICIO
					,OS.FechaOrden
					,OS.HoraOrden
					,OS.EstadoOrden
					,OS.NumOrden
					,OS.NumInventario
					,OS.NumRequisicion

					--COTIZACION
					,CT.IdCotizacion
					,CT.IdCliente
					,CT.IdUsuario
					,CT.IdSolicitud
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen
					,CT.Barrio_Destino
					,CT.IdCia
					,CT.Remesa
					,CT.Manifiesto
					,CASE CT.IdCia
						WHEN '8'  THEN '#F5B7B1'
						WHEN '9'  THEN '#D2B4DE'
						WHEN '10' THEN '#AED6F1'
						WHEN '11' THEN '#ABEBC6'
						WHEN '12' THEN '#F9E79F'
						WHEN '13' THEN '#D5DBDB'
						WHEN '14' THEN '#ABB2B9'
						ELSE '0' 
					 END AS ColorSuc

					--COMPANIA
					,CIA.CodSyscom as Compania
			
					--CLIENTES
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.TipoCliente
					,CL.Nombres as NombreCliente
					,CL.Apellidos as ApellidoCliente
					,CONCAT(CL.Nombres, ' ',CL.Apellidos) as NomCliente

					--USUARIOS
					,US.Nombres as NombreAsesor
					,US.Apellidos as ApellidoAsesor
					,CONCAT(US.Apellidos, ' ', US.Nombres) as NomAsesor

					--TIPOSERVICIOS
					,TS.Nombre as NomServicio

					--CIUDADES
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino

					,@Fact as Fact

					--LOG_VEHICULOS
					,LV.Placa

					--CONDUCTOR
					,CONCAT(CD.Nombres, ' ', CD.Apellidos) as NomConductor

					--PERSONAL
					,RTA.[1]
					,RTA.[2]
					,RTA.[3]
					,RTA.[4]
					,RTA.[5]
					,RTA.[6] 
					,CONCAT(AX1.Nombres, ' ', AX1.Apellidos) as Aux1
					,CONCAT(AX2.Nombres, ' ', AX2.Apellidos) as Aux2
					,CONCAT(AX3.Nombres, ' ', AX3.Apellidos) as Aux3
					,CONCAT(AX4.Nombres, ' ', AX4.Apellidos) as Aux4
					,CONCAT(CTT.Nombres, ' ', CTT.Apellidos) as Cont

					--VARIOS
					,CONCAT(OS.NumOrden,'-',CIA.CodSyscom) as OrdenNum
			
			FROM [dbo].[Agenda] as AG
					INNER JOIN [dbo].[OrdenServicio] as OS on AG.IdCotizacion = OS.IdCotizacion and AG.IdOrden = OS.IdOrden
		 			INNER JOIN [dbo].[Cotizacion] as CT on AG.IdCotizacion = CT.IdCotizacion 
					INNER JOIN [dbo].[Compania] as CIA on OS.Compania = CIA.IdCia 
		 			INNER JOIN [dbo].[Clientes] as CL on CT.IdCliente = CL.IdCliente 
		 			INNER JOIN [dbo].[Usuarios] as US on CT.IdUsuario = US.IdUsuario 
		 			INNER JOIN [dbo].[TipoServicio] as TS on CT.TipoServ = TS.IdTipo 
					INNER JOIN [dbo].[Ciudades] as ORG on CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST on CT.Ciudad_Destino = DST.IdCiudad
					LEFT JOIN (SELECT * FROM (SELECT IdCotizacion, IdPersonal, CtrlPersonal FROM [dbo].[Logistica_Personal]) AS LP 
							PIVOT(AVG([IdPersonal]) FOR [CtrlPersonal] IN ([1],[2],[3],[4],[5],[6])) AS PT) as RTA
							ON AG.IdCotizacion = RTA.IdCotizacion
		 			LEFT JOIN [dbo].[Logistica_Vehiculos] as LV on AG.IdCotizacion = LV.IdCotizacion 
		 			LEFT JOIN [dbo].[Vehiculos] as VH on LV.IdVehiculo = VH.IdVehiculo 
		 			LEFT JOIN [dbo].[Conductores] as CD on RTA.[1] = CD.IdConductor 
		 			LEFT JOIN [dbo].[Personal] as AX1 on RTA.[2] = AX1.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as AX2 on RTA.[3] = AX2.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as AX3 on RTA.[4] = AX3.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as AX4 on RTA.[5] = AX4.IdPersonal 
		 			LEFT JOIN [dbo].[Personal] as CTT on RTA.[6] = CTT.IdPersonal 

			WHERE AG.CtrlAgenda   = ISNULL(@CtrlAgenda,AG.CtrlAgenda) and
				  AG.CiaEncargada = ISNULL(@IdCia,AG.CiaEncargada) and
				  AG.FechaIni     = ISNULL(@FechaEvento,AG.FechaIni)
		END

	IF @Opcion = 8 --Consulta por compañia para Programacion Servicio
		BEGIN 
			SELECT  AG.IdEvento
					--,CONCAT('Orden Mudanza No.', ' ', AG.title,'-',CIA.CodSyscom ) as title
					,CASE WHEN AG.IdOrden = 0 
						THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion) 
						ELSE CONCAT('Orden Mudanza No.', ' ', AG.title) 
					 END as title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textColor
					,AG.[end]
					,AG.IdOrden
					,AG.IdCotizacion
					,AG.Vehiculo
					,AG.IdUsuario
					,AG.Personal
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.TipoServicioCot
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.TipoServicioCot
						WHEN '1'  THEN '#F5B7B1'
						WHEN '2'  THEN '#D2B4DE'
						WHEN '3'  THEN '#AED6F1'
						WHEN '4'  THEN '#ABEBC6'
						WHEN '5'  THEN '#F9E79F'
						WHEN '6'  THEN '#D5DBDB'
						WHEN '7'  THEN '#ABB2B9'
						WHEN '8'  THEN '#8EECF5'
						WHEN '9'  THEN '#9FAFFF'
						WHEN '10' THEN '#FF9688'
						ELSE '0' 
					 END AS ColorNew
					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
					 END AS NombreServ

					--ORDEN SERVICIO
					,OS.FechaOrden
					,OS.HoraOrden
					,OS.EstadoOrden
					,OS.NumRequisicion

					--COTIZACION
					,CT.IdCotizacion
					,CT.IdCliente
					,CT.IdUsuario
					,CT.IdSolicitud
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen
					,CT.Barrio_Destino
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente

					 --CIUDADES
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino

					--COMPANIA
					,CIA.CodSyscom as Compania

			FROM [dbo].[Agenda] as AG
 	    			LEFT  JOIN [dbo].[OrdenServicio] OS on AG.IdCotizacion = OS.IdCotizacion and AG.IdOrden = OS.IdOrden
					INNER JOIN [dbo].[Cotizacion] as CT on AG.IdCotizacion = CT.IdCotizacion
					INNER JOIN [dbo].[Ciudades] as ORG on CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST on CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Compania] as CIA on CT.IdCia = CIA.IdCia 

			WHERE AG.CtrlAgenda = @CtrlAgenda and
			      AG.IdCia      = ISNULL(@IdCia,AG.IdCia) and
				  AG.FechaIni   between @MesAnterior AND @MesSiguiente
		END

	IF @Opcion = 9 --Consulta por Fecha Especifica para logistica
		BEGIN 
			SELECT  AG.IdEvento
					--,CONCAT('Orden Mudanza No.', ' ', AG.title) as title
					,CASE WHEN AG.IdOrden = 0 
						THEN CONCAT('Cotización No.', ' ', AG.IdCotizacion) 
						ELSE CONCAT('Orden Mudanza No.', ' ', AG.title) 
					 END as title
					,AG.descripcion
					,AG.[start]
					,AG.color
					,AG.textColor
					,AG.[end]
					,AG.IdOrden
					,AG.IdCotizacion
					,AG.Vehiculo
					,AG.Personal
					,AG.IdUsuario
					,AG.IdCia
					,AG.FechaIni
					,AG.EstadoEvento
					,AG.Servicio
					,AG.FechaRecogida
					,AG.HoraRecogida
					,AG.FechaEntrega
					,AG.HoraEntrega
					,AG.IdCiudadOrigen
					,AG.IdCiudadDestino
					,AG.CiaEncargada
					,AG.CtrlAgenda
					,AG.CtrlConfirmacion
					,AG.TipoServicioCot
					,AG.NumRemesa
					,AG.NumManifiesto

					,CASE AG.TipoServicioCot
						WHEN '1'  THEN '#F5B7B1'
						WHEN '2'  THEN '#D2B4DE'
						WHEN '3'  THEN '#AED6F1'
						WHEN '4'  THEN '#ABEBC6'
						WHEN '5'  THEN '#F9E79F'
						WHEN '6'  THEN '#D5DBDB'
						WHEN '7'  THEN '#ABB2B9'
						WHEN '8'  THEN '#8EECF5'
						WHEN '9'  THEN '#9FAFFF'
						WHEN '10' THEN '#FF9688'
						ELSE '0' 
					 END AS ColorNew
					,CASE AG.Servicio
						WHEN '1' THEN 'LOCAL'
						WHEN '2' THEN 'CARGUE'
						WHEN '3' THEN 'DESCARGUE'
						WHEN '4' THEN 'RECOGIDA'
						WHEN '5' THEN 'ENTREGA'
						WHEN '6' THEN 'CARGUE BODEGA'
						WHEN '7' THEN 'DESCARGUE BODEGA'
						WHEN '8' THEN 'EMPAQUE'
						WHEN '9' THEN 'INTERNACIONAL'
						WHEN '10' THEN 'ALMACENAMIENTO'
						ELSE '0' 
					 END AS NombreServ

					--ORDEN DE SERVICIO
					,OS.FechaOrden
					,OS.HoraOrden
					,OS.EstadoOrden
					,OS.NumOrden
					,OS.NumInventario
					,OS.NumRequisicion

					--COTIZACION
					,CT.IdCotizacion
					,CT.IdCliente
					,CT.IdUsuario
					,CT.IdSolicitud
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen
					,CT.Barrio_Destino
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.Remesa
					,CT.Manifiesto	
					,CASE CT.IdCia
						WHEN '8'  THEN '#F5B7B1'
						WHEN '9'  THEN '#D2B4DE'
						WHEN '10' THEN '#AED6F1'
						WHEN '11' THEN '#ABEBC6'
						WHEN '12' THEN '#F9E79F'
						WHEN '13' THEN '#D5DBDB'
						WHEN '14' THEN '#ABB2B9'
						ELSE '0' 
					 END AS ColorSuc

					--COMPANIA
					,CIA.CodSyscom as Compania
			
					--CLIENTES
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.TipoCliente
					,CL.Nombres as NombreCliente
					,CL.Apellidos as ApellidoCliente
					,CONCAT(CL.Nombres, ' ',CL.Apellidos) as NomCliente

					--USUARIOS
					,US.Nombres as NombreAsesor
					,US.Apellidos as ApellidoAsesor
					,CONCAT(US.Apellidos, ' ', US.Nombres) as NomAsesor

					--TIPOSERVICIOS
					,TS.Nombre as NomServicio

					--CIUDADES
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino

					--VARIOS
					,CONCAT(OS.NumOrden,'-',CIA.CodSyscom) as OrdenNum
			
			FROM [dbo].[Agenda] as AG
					LEFT JOIN [dbo].[OrdenServicio] as OS on  AG.IdOrden = OS.IdOrden
		 			INNER JOIN [dbo].[Cotizacion] as CT on AG.IdCotizacion = CT.IdCotizacion 
					LEFT  JOIN [dbo].[Compania] as CIA on OS.Compania = CIA.IdCia 
		 			INNER JOIN [dbo].[Clientes] as CL on CT.IdCliente = CL.IdCliente 
		 			INNER JOIN [dbo].[Usuarios] as US on CT.IdUsuario = US.IdUsuario 
		 			INNER JOIN [dbo].[TipoServicio] as TS on CT.TipoServ = TS.IdTipo 
					INNER JOIN [dbo].[Ciudades] as ORG on CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST on CT.Ciudad_Destino = DST.IdCiudad

			WHERE AG.CtrlAgenda = ISNULL(@CtrlAgenda,AG.CtrlAgenda) and
				  AG.IdCia      = ISNULL(@IdCia,AG.IdCia) and
				  AG.FechaIni   = ISNULL(@FechaEvento,AG.FechaIni)
				
		END

	IF @Opcion = 10 --Consulta Fecha Anterior
		BEGIN 
			SELECT (CONVERT(varchar,(DATEADD(DAY, 1, EOMONTH((DATEADD(month, -1, GETDATE())), -1))))) as FecAnteriorIni 
			      ,(CONVERT(varchar,(EOMONTH((DATEADD(month, -1, GETDATE())))))) as FecAnteriorFin
				  ,(CONVERT(varchar,(DATENAME(WEEKDAY, GETDATE())))) as DiaSemana
				  ,(CONVERT(varchar,(DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))))) as FecActualIni
				  ,(MONTH(CONVERT(varchar,(DATEADD(DAY, 1, EOMONTH((DATEADD(month, -1, GETDATE())), -1)))))) as MesAnterior
				  ,(MONTH(CONVERT(varchar,(DATEADD(DAY, 1, EOMONTH(GETDATE(), -1)))))) as MesActual
		END

END
GO
/****** Object:  StoredProcedure [dbo].[spGetAgendasSeguimientos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 12/02/2024
-- Description:	Buscar AgendaSeguimientos
-- ===============================================
CREATE PROCEDURE [dbo].[spGetAgendasSeguimientos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdEvento int = null,
	@IdCotizacion int = null,
	@FechaIni varchar(10) = null,
	@FechaFin varchar(10) = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
	  BEGIN 
		 SELECT AGS.IdSegAgenda
			   ,AGS.IdEvento
			   ,AGS.IdCotizacion
			   ,AGS.FechaSeg
			   ,AGS.HoraSeg
			   ,AGS.ObservaSeg

		 FROM [dbo].[Agenda_Seguimiento] as AGS

	  END

	IF @Opcion = 2 --Consulta por Parametro
	  BEGIN 
		 SELECT AGS.IdSegAgenda
			   ,AGS.IdEvento
			   ,AGS.IdCotizacion
			   ,AGS.FechaSeg
			   ,AGS.HoraSeg
			   ,AGS.ObservaSeg

		 FROM [dbo].[Agenda_Seguimiento] as AGS

		 WHERE AGS.IdEvento     between ISNULL(@IdEvento,AGS.IdEvento) and ISNULL(@IdEvento,AGS.IdEvento) and 
			   AGS.IdCotizacion between ISNULL(@IdCotizacion,AGS.IdCotizacion) and ISNULL(@IdCotizacion,AGS.IdCotizacion) and  
			   AGS.FechaSeg     between ISNULL(@FechaIni, AGS.FechaSeg) and ISNULL(@FechaFin, AGS.FechaSeg)  
	  END
END

GO
/****** Object:  StoredProcedure [dbo].[spGetAreas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 02/09/2021
-- Description:	Procedimiento para consultar las areas de la empresa 
-- =============================================
CREATE   PROCEDURE [dbo].[spGetAreas]
	-- Add the parameters for the stored procedure here
	@Opcion as int
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion=1 
		BEGIN
			SELECT IdArea
				   ,Nombre COLLATE Cyrillic_General_CI_AI as Nombre 
			
			FROM [dbo].[Area]
		END
END




GO
/****** Object:  StoredProcedure [dbo].[spGetArticulos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- ALTER date: 05/09/2021
-- Description:	Buscar Articulos
-- =============================================
CREATE   PROCEDURE [dbo].[spGetArticulos] 
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdArticulo Int=null,
	@Nombre varchar(125)=null,
	@Descripcion varchar(255)=null,
	@Clase varchar(50)=null

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT ART.IdArticulo
				  ,ART.Nombre 
				  ,ART.Descripcion 
				  ,ART.Material 
				  ,ART.Clase
				  ,CASE ART.Material
					WHEN '0' THEN 'CON MATERIAL'
					WHEN '1' THEN 'SIN MATERIAL'
				   END AS NomMaterial
				  ,ART.IdTipoArticulo
				  ,TAR.Descripcion as NomTipoArt
				  ,TAR.CodSyscom as CodTipoArt
		
			FROM [dbo].[Articulos] as ART
					LEFT JOIN [dbo].[Tipo_Articulos] as TAR ON ART.IdTipoArticulo = TAR.IdTipoArticulo
		
			ORDER BY ART.Nombre ASC
	  END

	IF @Opcion = 2 -- Consultar por Tipo
	  BEGIN
			SELECT ART.IdArticulo
				  ,ART.Nombre 
				  ,ART.Descripcion
				  ,ART.Material
				  ,ART.Clase
				  ,CASE ART.Material
					WHEN '0' THEN 'CON MATERIAL'
					WHEN '1' THEN 'SIN MATERIAL'
				   END AS NomMaterial
				  ,ART.IdTipoArticulo
				  ,TAR.Descripcion as NomTipoArt
				  ,TAR.CodSyscom as CodTipoArt
		
			FROM [dbo].[Articulos] as ART
					LEFT JOIN [dbo].[Tipo_Articulos] as TAR ON ART.IdTipoArticulo = TAR.IdTipoArticulo
		
			WHERE ART.IdArticulo = @IdArticulo
		
			ORDER BY ART.Nombre ASC
	  END

	IF @Opcion = 3 -- Consultar por Parametro
		BEGIN
			SELECT ART.IdArticulo
				  ,ART.Nombre 
				  ,ART.Descripcion
				  ,ART.Material
				  ,ART.Clase
				  ,CASE ART.Material
					WHEN '0' THEN 'CON MATERIAL'
					WHEN '1' THEN 'SIN MATERIAL'
				   END AS NomMaterial
				  ,ART.IdTipoArticulo
				  ,TAR.Descripcion as NomTipoArt
				  ,TAR.CodSyscom as CodTipoArt
			
			FROM [dbo].[Articulos] as ART
					LEFT JOIN [dbo].[Tipo_Articulos] as TAR ON ART.IdTipoArticulo = TAR.IdTipoArticulo
			
			WHERE ART.Nombre like CONCAT('%',ISNULL(@Nombre,ART.Nombre),'%')
			
			ORDER BY ART.Nombre ASC
	  END
END

GO
/****** Object:  StoredProcedure [dbo].[spGetBitacora]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 02/08/2021
-- Description:	datos de la bitacora
-- =============================================
CREATE   PROCEDURE [dbo].[spGetBitacora]
	-- Add the parameters for the stored procedure here
	@Opcion as int,
	@IdEvento as int = null,
	@FechaIni as varchar(10) = null,
	@FechaFin as varchar(10) = null,
	@IdUsuario as int = null
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.

	IF @Opcion=1  --buscar todos los eventos de todos los usuarios entre fechas
		BEGIN	
			SELECT BT.IdEvento
				  ,BT.Fecha
				  ,BT.Hora
				  ,BT.IdUsuario
				  ,BT.Documento
				  ,UPPER(BT.Descripcion) as Descripcion
				  ,CONCAT(US.Nombres, ' ', US.Apellidos) as NombreUsuario
				  ,US.Identificacion
			  
			FROM [dbo].[Bitacora] as BT, 
				 [dbo].[Usuarios] as US

			WHERE BT.IdUsuario = US.IdUsuario 
		END
		  
	IF @Opcion=2 --buscar todos los eventos de un usuario en particular entre esas fechas
		BEGIN
			SELECT BT.IdEvento
				  ,BT.Fecha
				  ,BT.Hora
				  ,BT.IdUsuario
				  ,BT.Documento
				  ,UPPER(BT.Descripcion) as Descripcion
				  ,CONCAT(US.Nombres, ' ', US.Apellidos) as NombreUsuario
				  ,US.Identificacion
			
			FROM [dbo].[Bitacora] as BT, 
				 [dbo].[Usuarios] as US
			
			WHERE BT.IdUsuario = @IdUsuario and
				  BT.IdUsuario = US.IdUsuario
		END

	IF @Opcion=3 --buscar un evento entre fechas
		BEGIN
			IF @IdEvento IS NOT NULL and @IdUsuario IS NOT NULL
				BEGIN 
					SELECT BT.IdEvento
						  ,BT.Fecha
						  ,BT.Hora
						  ,BT.IdUsuario
						  ,BT.Documento
						  ,UPPER(BT.Descripcion) as Descripcion
						  ,CONCAT(EV.Nombre, ' - ', EV.Descripcion) COLLATE Cyrillic_General_CI_AI as NombreEvento
						  ,CONCAT(US.Nombres, ' ', US.Apellidos) as NombreUsuario
						  ,US.Identificacion
		 
					FROM [dbo].[Bitacora] as BT, 
						 [dbo].[Usuarios] as US, 
						 [dbo].[Eventos] as EV

					WHERE BT.IdUsuario = @IdUsuario and 
						  BT.IdEvento  = @IdEvento and 
						  BT.IdUsuario = US.IdUsuario and
						  BT.IdEvento  = EV.IdEvento and
						  BT.Fecha between @FechaIni and @FechaFin 
				END
			  
			IF @IdEvento IS NOT NULL and @IdUsuario IS NULL
				BEGIN 
					SELECT BT.IdEvento
						  ,BT.Fecha
						  ,BT.Hora
						  ,BT.IdUsuario
						  ,BT.Documento
						  ,UPPER(BT.Descripcion) as Descripcion
						  ,CONCAT(EV.Nombre, ' - ', EV.Descripcion) COLLATE Cyrillic_General_CI_AI as NombreEvento
						  ,CONCAT(US.Nombres, ' ', US.Apellidos) as NombreUsuario
						  ,US.Identificacion
		 
					FROM [dbo].[Bitacora] as BT, 
						 [dbo].[Usuarios] as US, 
						 [dbo].[Eventos] as EV

					WHERE BT.IdEvento  = @IdEvento and 
						  BT.IdUsuario = US.IdUsuario and
						  BT.IdEvento  = EV.IdEvento and 
						  BT.Fecha between @FechaIni and @FechaFin  
				END

			IF @IdEvento IS NULL and @IdUsuario IS NOT NULL
				BEGIN 
					SELECT BT.IdEvento
						  ,BT.Fecha
						  ,BT.Hora
						  ,BT.IdUsuario
						  ,BT.Documento
						  ,UPPER(BT.Descripcion) as Descripcion
						  ,CONCAT(EV.Nombre, ' - ', EV.Descripcion) COLLATE Cyrillic_General_CI_AI as NombreEvento
						  ,CONCAT(US.Nombres, ' ', US.Apellidos) as NombreUsuario
						  ,US.Identificacion
		 
					FROM [dbo].[Bitacora] as BT, 
						 [dbo].[Usuarios] as US, 
						 [dbo].[Eventos] as EV

					WHERE BT.IdUsuario = @IdUsuario and 
						  BT.IdUsuario = US.IdUsuario and
						  BT.IdEvento  = EV.IdEvento and 
						  BT.Fecha between @FechaIni and @FechaFin  
				END
			  
			IF @IdEvento IS NULL and @IdUsuario IS NULL
				BEGIN 
					SELECT BT.IdEvento
					  	  ,BT.Fecha
						  ,BT.Hora
						  ,BT.IdUsuario
						  ,BT.Documento
						  ,UPPER(BT.Descripcion) as Descripcion
						  ,CONCAT(EV.Nombre, ' - ', EV.Descripcion) COLLATE Cyrillic_General_CI_AI as NombreEvento
						  ,CONCAT(US.Nombres, ' ', US.Apellidos) as NombreUsuario
						  ,US.Identificacion
		 
					FROM [dbo].[Bitacora] as BT, 
						 [dbo].[Usuarios] as US, 
						 [dbo].[Eventos] as EV

					WHERE BT.IdUsuario = US.IdUsuario and
						  BT.IdEvento = EV.IdEvento and
						  BT.Fecha between @FechaIni and @FechaFin  
				END
		END   	
END

GO
/****** Object:  StoredProcedure [dbo].[spGetBodAbonos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Sergio Rendón Gómez
-- Create date:  Enero 2023
-- Description:	 Buscar Abonos
-- =============================================
CREATE   PROCEDURE [dbo].[spGetBodAbonos] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdAbono int = null,
	@IdCartera int = null,
	@IdContrato int = null,
	@Estado int = null,
	@FechaIni varchar(10) = null,
	@FechaFin varchar(10) = null

AS
BEGIN TRY
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statementB.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT AB.IdAbono
				   ,AB.IdCartera
				   ,AB.IdContrato
				   ,AB.FechaAbono
				   ,AB.HoraAbono
				   ,AB.ValorAbono
				   ,AB.SaldoCartera
				   ,AB.Descripcion
				   ,AB.EstadoAbono
				   ,AB.IdFormaPago
				   ,AB.IdMedioPago
				   ,AB.ReciboPago
				   ,FP.Nombre as FormaPago
				   ,MP.Nombre as MedioPago
				   ,CT.IdCliente
				   ,CONCAT(CL.Nombres,' ',CL.Apellidos) as NombreCliente

			FROM [dbo].[Bodegas_CarteraAbonos] AS AB
					INNER JOIN [dbo].[Formas_Pago] as FP ON AB.IdFormaPago = FP.IdFormaPago
					INNER JOIN [dbo].[Metodos_Pago] as MP ON AB.IdMedioPago = MP.IdMetodosPago
					INNER JOIN [dbo].[Bodegas_Contratos] as CT ON AB.IdContrato = CT.IdContrato
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente

		END 

	IF @Opcion = 2 --Consulta por parametros
		BEGIN 
			SELECT AB.IdAbono
				   ,AB.IdCartera
				   ,AB.IdContrato
				   ,AB.FechaAbono
				   ,AB.HoraAbono
				   ,AB.ValorAbono
				   ,AB.SaldoCartera
				   ,AB.Descripcion
				   ,AB.EstadoAbono
				   ,AB.IdFormaPago
				   ,AB.IdMedioPago
				   ,AB.ReciboPago
				   ,FP.Nombre as FormaPago
				   ,MP.Nombre as MedioPago
				   ,CT.IdCliente
				   ,CONCAT(CL.Nombres,' ',CL.Apellidos) as NombreCliente
				   
			FROM [dbo].[Bodegas_CarteraAbonos] AS AB
					INNER JOIN [dbo].[Formas_Pago] as FP ON AB.IdFormaPago = FP.IdFormaPago
					INNER JOIN [dbo].[Metodos_Pago] as MP ON AB.IdMedioPago = MP.IdMetodosPago
					INNER JOIN [dbo].[Bodegas_Contratos] as CT ON AB.IdContrato = CT.IdContrato
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente

			WHERE AB.IdAbono     between ISNULL(@IdAbono,0) and ISNULL(@IdAbono,999999999) and 
				  AB.IdCartera   between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999) and 
				  AB.IdContrato  between ISNULL(@IdContrato,0) and ISNULL(@IdContrato,999999999) and 
				  AB.EstadoAbono between ISNULL(@Estado,0) and ISNULL(@Estado,9) and
				  AB.FechaAbono  between ISNULL(@FechaIni, AB.FechaAbono) and ISNULL(@FechaFin,AB.FechaAbono) 

			ORDER BY AB.IdAbono DESC

		END
		
	IF @Opcion = 3 --Consulta maximo saldo
		BEGIN 
			SELECT AB.IdAbono
				   ,AB.IdCartera
				   ,AB.IdContrato
				   ,AB.FechaAbono
				   ,AB.HoraAbono
				   ,AB.ValorAbono
				   ,AB.SaldoCartera
				   ,AB.Descripcion
				   ,AB.EstadoAbono
				   ,AB.IdFormaPago
				   ,AB.IdMedioPago
				   ,AB.ReciboPago
				   ,FP.Nombre as FormaPago
				   ,MP.Nombre as MedioPago
				   ,CT.IdCliente
				   ,CONCAT(CL.Nombres,' ',CL.Apellidos) as NombreCliente

			FROM [dbo].[Bodegas_CarteraAbonos] AS AB
					INNER JOIN [dbo].[Formas_Pago] as FP ON AB.IdFormaPago = FP.IdFormaPago
					INNER JOIN [dbo].[Metodos_Pago] as MP ON AB.IdMedioPago = MP.IdMetodosPago
					INNER JOIN [dbo].[Bodegas_Contratos] as CT ON AB.IdContrato = CT.IdContrato
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente

			WHERE AB.IdCartera   between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999) and
				  AB.IdAbono = (SELECT MAX(IdAbono) FROM [dbo].[Bodegas_CarteraAbonos] WHERE IdCartera = @IdCartera)

		END 
			
		
COMMIT TRANSACTION
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
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCarSeguimiento]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 23/11/2022
-- Description:	Buscar Seguimientos Cartera
-- =============================================
CREATE   PROCEDURE [dbo].[spGetBodCarSeguimiento]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdSeguimiento int = null,
	@IdContrato Int = null,
	@IdCartera Int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT CSG.IdSeguimiento
				  ,CSG.IdUsuario
				  ,CSG.IdContrato
				  ,CSG.IdCartera
				  ,CSG.IdCliente
				  ,CSG.DiasMora
				  ,CSG.MesesMora
				  ,CSG.TotalMora
				  ,CSG.FechaSeguimiento
				  ,CSG.Observacion
				  ,CSG.Formato
				  ,CASE CSG.Formato
					WHEN '1' THEN '1 - PRIMERA GESTION'
					WHEN '2' THEN '2 - SEGUNDA GESTION'
					WHEN '3' THEN '3 - TERCERA Y ULTIMA GESTION'
					WHEN '4' THEN '4 - ULTIMO AVISO DE COBRO'
					WHEN '5' THEN '5 - SERVICIO DE ALMACENAMIENTO'
					ELSE '0' 
				   END AS Formato
				  ,CTT.NumeroContrato
				  ,CONCAT(CLT.Nombres,' ',CLT.Apellidos) as NombreCliente
				  ,CLT.Email
				  ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreUsuario

			FROM [dbo].[Bodegas_CarteraSeguimiento] as CSG
					INNER JOIN [dbo].[Bodegas_Cartera] as CTR ON CTR.IdCartera = CSG.IdCartera
					INNER JOIN [dbo].[Clientes] as CLT ON CSG.IdCliente = CLT.IdCliente
					INNER JOIN [dbo].[Bodegas_Contratos] as CTT ON CTR.IdContrato = CTT.IdContrato
					INNER JOIN [dbo].[Usuarios] as USU ON CSG.IdUsuario = USU.IdUsuario

	  END

	IF @Opcion = 2 -- Consultar por parametro
	BEGIN
		SELECT 
			CSG.IdSeguimiento
			,CSG.IdUsuario
			,CSG.IdContrato
			,CSG.IdCartera
			,CSG.IdCliente
			,CSG.DiasMora
			,CSG.MesesMora
			,CSG.TotalMora
			,CSG.FechaSeguimiento
			,CSG.Observacion
			,CSG.Formato
			,CASE CSG.Formato
			WHEN '1' THEN '1 - PRIMERA GESTION'
			WHEN '2' THEN '2 - SEGUNDA GESTION'
			WHEN '3' THEN '3 - TERCERA Y ULTIMA GESTION'
			WHEN '4' THEN '4 - ULTIMO AVISO DE COBRO'
			WHEN '5' THEN '5 - SERVICIO DE ALMACENAMIENTO'
			ELSE '0' 
			END AS Formato
			,CONCAT(CLT.Nombres,' ',CLT.Apellidos) as NombreCliente
			,CLT.Email
			,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreUsuario
		FROM 
			[dbo].[Bodegas_CarteraSeguimiento] as CSG
			INNER JOIN [dbo].[Clientes] as CLT ON CSG.IdCliente = CLT.IdCliente
			INNER JOIN [dbo].[Bodegas_Cartera] as CTR ON CSG.IdCartera = CTR.IdCartera
			INNER JOIN [dbo].[Bodegas_Contratos] as CTT ON CSG.IdContrato = CTT.IdContrato
			INNER JOIN [dbo].[Usuarios] as USU ON CSG.IdUsuario = USU.IdUsuario
		WHERE 
			CSG.IdSeguimiento between ISNULL(@IdSeguimiento,0) and ISNULL(@IdSeguimiento,999999999) and
			CSG.IdContrato    between ISNULL(@IdContrato,0) and ISNULL(@IdContrato,999999999) and
			CSG.IdCartera     between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999) 	  
	END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCartera]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 07/03/2022
-- Description:	Buscar Cartera-Bodegas
-- =============================================
CREATE  PROCEDURE [dbo].[spGetBodCartera] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCartera int = null,
	@IdContrato int = null,
	@Estado int = null,
	@Identificacion nvarchar(20) = null,
	@Nombre varchar(125) = null,
	@Sucursal int = null,
	@FechaIni varchar(10) = null,
	@FechaFin varchar(10) = null,
	@Apellidos VARCHAR(125) = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statementB.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE	@Iva numeric(18,2),
			@Dias int = 0,
			@Meses int = 0,
			@Base int,
			@TotalIpc int,
			@Sancion int,
			@TotalIva int,
			@FechaCont varchar(10),
			@SancionIni int,
			@SancionFin int,
			@ValorDeuda int,
			@TotalSancion int,
			@FechaPeriodo varchar(10),
			@FechaDesde varchar(10),
			@FechaHasta varchar(10),
			@MesesAtraso int = 0,
			@CantMeses int = 0

	IF @Opcion = 1 --Consulta General
	BEGIN 
		SELECT 
			CTR.IdCartera
			,CTR.IdContrato 
			,CTR.IdIPC
			,CTR.FechaPago
			,CTR.HoraPago
			,CTR.ValorBodega
			,CTR.ValorSeguro
			,CTR.ValorIva
			,CTR.ValorCuota 
			,CTR.Saldo
			,CTR.Intereses
			,CTR.Descuentos
			,CTR.PagoTotal 
			,CTR.Estado
			
			--Contratos
			,CTT.NumeroContrato
			,CTT.FechaContrato
			,CTT.PagoInicial
			,CTT.ValorTotal
			,CTT.IdCliente
			,CTT.IdCotizacion
			,CTT.IdCia
			,CONCAT(CTT.NumeroContrato, '-', S.Compania) AS NumContratoCia
			
			--Clientes
			,CLT.Identificacion
			,CONCAT(CLT.Nombres,' ',CLT.Apellidos) as NombreCliente
			,CLT.Direccion
			,CLT.Telefono
			,CLT.Movil
			,CLT.Email
			
			--Cotizacion
			,CTZ.IdUsuario
			,CTZ.Ref_Personal
			,CTZ.Ref_Direccion
			,CTZ.Ref_Movil
			,CTZ.Ref_Correo
			
			--Ipc
			,IPC.Valor
			,IPC.Puntos
			
			--Calculos Cartera
			,(CTR.ValorCuota*0.015) as Sancion
			,(CTR.ValorCuota*0.19) as TotalIva
			,(select SUM(VrDeudaMes) as Deuda from Bodegas_EstadoCuentas where IdContrato = CTR.IdContrato and CtrlPago <> 1)	as ValorDeuda
			,(CONVERT(varchar,(DATEADD(MM, -1, (CONVERT(date,CTR.FechaPago)))))) as FechaIni 
			,(DATEDIFF(DAY, (CONVERT(date,CTR.FechaPago)),GETDATE())) as Dias
			,(SELECT MAX(MesesMora) FROM Bodegas_EstadoCuentas WHERE IdContrato =  CTR.IdContrato) as Meses
			,(DATEDIFF(MONTH, (CONVERT(date,FechaPago)),GETDATE())) * (CTR.ValorCuota*0.015) as TotalSancion
			
			--ContratoIPC
			,IdAjuste
			,AplicaIPC
			,AvisoCarta
			,CartaCtrl		  
		FROM 
			[dbo].[Bodegas_Cartera] as CTR
		INNER JOIN 
			[dbo].[Bodegas_Contratos] as CTT  with(nolock) ON CTR.IdContrato = CTT.IdContrato
		LEFT JOIN 
			Sucursales AS S ON S.IdSucursal = CTT.IdSucursal
		INNER JOIN 
			[dbo].[Clientes] as CLT ON CTT.IdCliente = CLT.IdCliente
		INNER JOIN 
			[dbo].[Cotizacion] as CTZ ON CTT.IdCotizacion = CTZ.IdCotizacion
		INNER JOIN 
			[dbo].[Bodegas_IPC] as IPC ON CTR.IdIPC = IPC.IdIPC
		LEFT JOIN (
			SELECT 
				MAX(AplicaHasta) as AplicaIPC, 
				MAX(CartaAviso) as AvisoCarta, 
				MAX(IdAjuste) as IdAjuste,
				MIN(CtrlCarta) as CartaCtrl, 
				IdContrato 
			FROM 
				[dbo].[Bodegas_ContratoIPC] 
			GROUP BY 
				IdContrato
		) as CIP ON CTR.IdContrato = CIP.IdContrato 
	END

	IF @Opcion = 2 --Consulta por parametro
		BEGIN
			SELECT 
				CTR.IdCartera ,CTR.IdContrato ,CTR.IdIPC,
				CTR.FechaPago, CTR.HoraPago, CTR.ValorBodega,
				CTR.ValorSeguro, CTR.ValorIva, CTR.ValorCuota,
				CTR.Saldo, CTR.Intereses, CTR.Descuentos,
				CTR.PagoTotal, CTR.Estado,
				  
				--CONTRATOS
				CTT.NumeroContrato, CTT.FechaContrato, CTT.PagoInicial,
				CTT.ValorTotal, CTT.IdCliente, CTT.IdCotizacion,
				BCE.CodEntrada AS CodigoEntrada, BCS.CodSalida AS CodigoSalida ,CTT.IdCia, 
				CONCAT(CTT.NumeroContrato, '-', S.Compania) AS NumContratoCia,

				--CONTRATOBODEGAS
				CTB.Nombre as NomBodega,
				  
				--CLIENTES
				CLT.Identificacion , CONCAT(CLT.Nombres,' ',CLT.Apellidos) as NombreCliente, CLT.Direccion,
				CLT.Telefono, CLT.Movil, CLT.Email,
				  
				--COTIZACION
				CTZ.IdUsuario, CTZ.Ref_Personal, CTZ.Ref_Direccion,
				CTZ.Ref_Movil, CTZ.Ref_Correo, CTZ.Valor_Declarado,
				CTZ.Cortesia, CTZ.FechaCortIni, CTZ.FechaCortFin,
				CTZ.TteSalida,

				--ORDEN MUDANZA
				OSM.NumInventario, OSM.NumOrden, OSM.Compania,
				  
				--IPC
				IPC.Valor,IPC.Puntos,
				  
				--CONTRATOIPC
				IdAjuste, AplicaIPC,
				AvisoCarta, CartaCtrl,

				--VARIOS
				CONCAT(OSM.NumOrden,'-',CIA.CodSyscom) as OrdenNum,
				CONCAT(CTT.NumeroContrato,'-',CIA.CodSyscom) as ContratoNum,
				CONCAT(OSM.NumInventario,'-',CIA.CodSyscom) as InventarioNum,

				--Calculos Cartera
				(
					DATEDIFF(DAY, (CONVERT(date,CTT.FechaContrato)),GETDATE())
				) as Ctt_Dias,
				(
					DATEDIFF(MONTH, (CONVERT(date,CTT.FechaContrato)),GETDATE())
				) as Ctt_Meses,
				(
					DATEDIFF(MONTH, (CONVERT(date,CTT.FechaContrato)),GETDATE())
				) / 12 as Ctt_Anos,
				(
					CONVERT(varchar,(DATEADD(YYYY, 1, (CONVERT(date,CTT.FechaContrato)))))
				) as AplicaHasta,
				(
					CONVERT(varchar,(DATEADD(MM, -1, (CONVERT(date,(DATEADD(YYYY, 1, (CONVERT(date,CTT.FechaContrato)))))))))
				) as CartaAviso,
				(
					CONVERT(varchar,(DATEADD(DD, +0, (CONVERT(date,CTT.FechaContrato)))))
				) as Fec_Desde,
				(
					CONVERT(varchar,(DATEADD(DD, +30, (CONVERT(date,CTT.FechaContrato)))))
				) as Fec_Hasta,
				(
					SELECT MAX(MesesMora) 
					FROM Bodegas_EstadoCuentas 
					WHERE IdContrato = CTR.IdContrato 
						and CtrlPago = 0
				) as Meses,
				(
					SELECT SUM(VrDeudaMes) as Deuda 
					FROM Bodegas_EstadoCuentas 
					WHERE IdContrato = CTR.IdContrato 
						and CtrlPago <> 1
				) as ValorDeuda,
				(
					CONVERT(varchar,(DATEADD(DD, +1, (CONVERT(date,(SELECT MAX(PeriodoFin) FROM Bodegas_Pagos WHERE IdCartera = @IdCartera))))))
				) as PeriodoDesde,
				(
					CONVERT(varchar,(DATEADD(MM, +1, (CONVERT(date,(SELECT MAX(PeriodoFin) FROM Bodegas_Pagos WHERE IdCartera = @IdCartera))))))
				) as PeriodoHasta,
				ABS((
					SELECT SUM(VrSaldoDeuda) 
					FROM Bodegas_EstadoCuentas 
					WHERE CtrlPago = 1 
						and IdCliente = CLT.IdCliente 
						AND CtrlCuota = (
							SELECT MAX(CtrlCuota) 
							FROM Bodegas_EstadoCuentas 
							WHERE CtrlPago = 1 
							and IdCliente = CLT.IdCliente
						)
				)) as SaldoCliente
			FROM 
				[dbo].[Bodegas_Cartera] as CTR
				INNER JOIN 
					[dbo].[Bodegas_Contratos] as CTT ON CTR.IdContrato = CTT.IdContrato
				LEFT JOIN 
					Bodegas_CodigoEntrada AS BCE ON BCE.IdEntrada = CTT.CodigoEntrada
				LEFT JOIN 
					Bodegas_CodigoSalida AS BCS ON BCS.IdSalida = CTT.CodigoSalida
				LEFT JOIN 
					Sucursales AS S ON S.IdSucursal = CTT.IdSucursal
				LEFT  JOIN 
					[dbo].[Bodegas_ContratoBodegas] as CTB ON CTR.IdContrato = CTB.IdContrato
				LEFT JOIN 
					[dbo].[Clientes] as CLT ON CTT.IdCliente = CLT.IdCliente
				LEFT JOIN 
					[dbo].[Cotizacion] as CTZ ON CTT.IdCotizacion = CTZ.IdCotizacion
				LEFT JOIN 
					[dbo].[OrdenServicio] as OSM ON CTT.IdCotizacion = OSM.IdCotizacion
				LEFT JOIN 
					[dbo].[Bodegas_IPC] as IPC ON CTR.IdIPC = IPC.IdIPC
				LEFT JOIN 
					[dbo].[Compania] as CIA on OSM.Compania = CIA.IdCia 
				LEFT JOIN 
					(
						SELECT 
							MAX(AplicaHasta) as AplicaIPC, 
							MAX(CartaAviso) as AvisoCarta, 
							MAX(IdAjuste) as IdAjuste,
							MIN(CtrlCarta) as CartaCtrl, 
							IdContrato 
						FROM 
							[dbo].[Bodegas_ContratoIPC] 
						GROUP BY 
							IdContrato
					) as CIP ON CTR.IdContrato = CIP.IdContrato 
			WHERE 
				CTR.IdCartera between ISNULL(@IdCartera,CTR.IdCartera) and ISNULL(@IdCartera,CTR.IdCartera) 
				and CTT.NumeroContrato between ISNULL(@IdContrato,0) and ISNULL(@IdContrato,999999999) 
				and CTR.Estado between ISNULL(@Estado,0) and ISNULL(@Estado,9) 
				and CLT.Identificacion = ISNULL(@Identificacion,CLT.Identificacion) 
				-- and CTT.IdSucursal between ISNULL(@Sucursal,0) and ISNULL(@Sucursal,99) 
				and (@Sucursal IS NULL OR CTT.IdSucursal = @Sucursal)
				and CLT.Nombres like CONCAT('%',ISNULL(@Nombre,CLT.Nombres),'%') 
				and CLT.Apellidos LIKE CONCAT('%', ISNULL(@Apellidos, CLT.Apellidos), '%')
				and CTT.FechaContrato between ISNULL(@FechaIni, CTT.FechaContrato) and ISNULL(@FechaFin, CTT.FechaContrato)  
		END

	IF @Opcion = 5 --Consulta Clientes Mora
	BEGIN
		DECLARE @FechaCalculo DATE = CONVERT (DATE,DATEADD(DAY,1,GETDATE()))

		SELECT 
			CTR.IdCartera
			,CTR.FechaPago
			,CTR.HoraPago
			,CTR.Saldo
			,CTR.ValorCuota 
			,CTR.PagoTotal 
			,CTR.IdContrato 
			,CTR.Estado
			,CTR.Descuentos
			,(CTR.ValorCuota*0.015) AS Sancion
			,(CTR.ValorCuota*0.19) AS TotalIva
			,(SELECT MAX(MesesMora) FROM Bodegas_EstadoCuentas WHERE IdContrato =  CTR.IdContrato) as Meses
			,(SELECT SUM(VrDeudaMes) as Deuda FROM Bodegas_EstadoCuentas WHERE IdContrato = CTR.IdContrato and CtrlPago <> 1) as ValorDeuda
			,(SELECT MAX(VrDeudaMes) FROM Bodegas_EstadoCuentas WHERE IdContrato =  CTR.IdContrato) as CuotaTotal
			,(
				DATEDIFF(
					DAY, ISNULL((
						SELECT TOP 1 Hasta
						FROM Bodegas_EstadoCuentas
						WHERE IdContrato = CTT.IdContrato
							AND CtrlPago = 0
						ORDER BY
							MesesMora DESC
					), CTR.FechaPago),
					GETDATE())
			) as Dias
			--,(CONVERT(varchar,(DATEADD(MM, -1, (CONVERT(date,CTR.FechaPago)))))) as FechaIni 
			--,(DATEDIFF(MONTH, (CONVERT(date,FechaPago)),GETDATE())) * (CTR.ValorCuota*0.015) as TotalSancion

			--Contratos
			,CTT.NumeroContrato
			,CTT.FechaContrato
			,CTT.IdCliente

			--Clientes
			,CLT.Identificacion
			,CONCAT(CLT.Nombres,' ',CLT.Apellidos) as NombreCliente
			,CLT.Movil
			,CLT.Email

			--Cartera Seguimiento
			,(SELECT TOP 1 CSG.FechaSeguimiento FROM [dbo].[Bodegas_CarteraSeguimiento] AS CSG WHERE CSG.IdCartera = CTR.IdCartera ORDER BY CSG.IdSeguimiento DESC) AS FechaSeguimiento
			,(SELECT TOP 1 CSG.Observacion FROM [dbo].[Bodegas_CarteraSeguimiento] AS CSG WHERE CSG.IdCartera = CTR.IdCartera ORDER BY CSG.IdSeguimiento DESC) AS Observacion
			,CASE (
				SELECT TOP 1 CSG.Formato 
				FROM [dbo].[Bodegas_CarteraSeguimiento] AS CSG 
				WHERE CSG.IdCartera = CTR.IdCartera 
				ORDER BY CSG.IdSeguimiento DESC
			)
				WHEN '1' THEN '1 - PRIMERA GESTION'
				WHEN '2' THEN '2 - SEGUNDA GESTION'
				WHEN '3' THEN '3 - TERCERA Y ULTIMA GESTION'
				WHEN '4' THEN '4 - ULTIMO AVISO DE COBRO'
				WHEN '5' THEN '5 - SERVICIO DE ALMACENAMIENTO'
				ELSE '0' 
			END AS Formatos,
			CONCAT(CTT.NumeroContrato, '-', S.Compania) AS ContratoSucursal
		FROM 
			[dbo].[Bodegas_Cartera] as CTR
		INNER JOIN 
			[dbo].[Bodegas_Contratos] as CTT ON CTR.IdContrato = CTT.IdContrato
		INNER JOIN 
			[dbo].[Clientes] as CLT ON CTT.IdCliente = CLT.IdCliente		
		LEFT JOIN 
			Sucursales AS S ON S.IdSucursal = CTT.IdSucursal
		WHERE 
			DATEDIFF(DAY,CONVERT(DATE, CTR.FechaPago),@FechaCalculo) > 30 AND
			CONVERT (DATE, CTR.FechaPago) < @FechaCalculo AND
			CTR.Estado = 1
	END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCodigoEntrada]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Sergio Rendón Gómez
-- Create date:  30-01-2024
-- Description:	 Buscar Codigo de Entrada
-- ===========================================
CREATE PROCEDURE [dbo].[spGetBodCodigoEntrada]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdEntrada int = null,
	@IdContrato int = null,
	@FechaEnt varchar(10) = null
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT  BCE.IdEntrada
				   ,BCE.CodEntrada	
				   ,BCE.NomEntrada
				   ,BCE.FechaEntrada
				   ,BCE.IdContrato

			FROM [dbo].[Bodegas_CodigoEntrada] as BCE
					INNER JOIN [dbo].[Bodegas_Contratos] as CTT ON BCE.IdContrato = CTT.IdContrato
					

		END 

	IF @Opcion = 2 --Consulta por parametros
		BEGIN 
			SELECT  BCE.IdEntrada
				   ,BCE.CodEntrada	
				   ,BCE.NomEntrada
				   ,BCE.FechaEntrada
				   ,BCE.IdContrato

			FROM [dbo].[Bodegas_CodigoEntrada] as BCE
					INNER JOIN [dbo].[Bodegas_Contratos] as CTT ON BCE.IdContrato = CTT.IdContrato

			WHERE BCE.IdEntrada  between ISNULL(@IdEntrada,BCE.IdEntrada) and ISNULL(@IdEntrada,BCE.IdEntrada) and 
				  BCE.IdContrato between ISNULL(@IdContrato,BCE.IdContrato) and ISNULL(@IdContrato,BCE.IdContrato)
				  


		END

	IF @Opcion = 3 --Consulta por Codigo Maximo
		BEGIN 
			SELECT MAX(CodEntrada) as CodigoMax, NomEntrada FROM [dbo].[Bodegas_CodigoEntrada] GROUP BY NomEntrada
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodCodigoSalida]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Sergio Rendón Gómez
-- Create date:  30-01-2024
-- Description:	 Buscar Codigo de Salida
-- ===========================================
CREATE PROCEDURE [dbo].[spGetBodCodigoSalida]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdSalida int = null,
	@IdContrato int = null,
	@FechaSal varchar(10) = null
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT  BCS.IdSalida
				   ,BCS.CodSalida
				   ,BCS.NomSalida
				   ,BCS.FechaSalida
				   ,BCS.IdContrato

			FROM [dbo].[Bodegas_CodigoSalida] as BCS
					INNER JOIN [dbo].[Bodegas_Contratos] as CTT ON BCS.IdContrato = CTT.IdContrato
		END 

	IF @Opcion = 2 --Consulta por parametros
		BEGIN 
			SELECT  BCS.IdSalida
				   ,BCS.CodSalida
				   ,BCS.NomSalida
				   ,BCS.FechaSalida
				   ,BCS.IdContrato

			FROM [dbo].[Bodegas_CodigoSalida] as BCS
					INNER JOIN [dbo].[Bodegas_Contratos] as CTT ON BCS.IdContrato = CTT.IdContrato

			WHERE BCS.IdSalida  between ISNULL(@IdSalida,BCS.IdSalida) and ISNULL(@IdSalida,BCS.IdSalida) and 
				  BCS.IdContrato between ISNULL(@IdContrato,BCS.IdContrato) and ISNULL(@IdContrato,BCS.IdContrato)
		END

	IF @Opcion = 3 --Consulta por Codigo Maximo
		BEGIN 
			SELECT MAX(CodSalida) as CodigoMax, NomSalida FROM [dbo].[Bodegas_CodigoSalida] GROUP BY NomSalida
		END
END

GO
/****** Object:  StoredProcedure [dbo].[spGetBodContArticulos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 18/10/2022
-- Description:	Buscar Articulos por Contrato
-- =============================================
CREATE   PROCEDURE [dbo].[spGetBodContArticulos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCont_Articulo int = null,
	@IdContrato Int = null,
	@IdCotizacion int = null,
	@IdArticulo int = null
   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT CAR.IdCont_Articulo
				  ,CAR.IdCotizacion
				  ,CAR.IdArticulo
				  ,CAR.Nombre
				  ,CAR.Descripcion
				  ,CAR.Cantidad
				  ,CAR.EstadoArticulo
				  ,CAR.Memorando
				  ,CASE CAR.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_ContratoArticulos] as CAR

			ORDER BY CAR.Nombre ASC
	  END

	IF @Opcion = 2 -- Consultar por Cotizacion
		BEGIN
			SELECT CAR.IdCont_Articulo
				  ,CAR.IdCotizacion
				  ,CAR.IdArticulo
				  ,CAR.Nombre
				  ,CAR.Descripcion
				  ,CAR.Cantidad
				  ,CAR.IdContrato
				  ,CAR.EstadoArticulo
				  ,CAR.Memorando
				  ,CASE CAR.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_ContratoArticulos] as CAR
			
			WHERE CAR.IdContrato = @IdContrato 

			ORDER BY CAR.Nombre ASC
		END

	
	IF @Opcion = 4 -- Consultar por Cotizacion y Articulo
		BEGIN
			SELECT CAR.IdCont_Articulo
				  ,CAR.IdCotizacion
				  ,CAR.IdArticulo
				  ,CAR.Nombre
				  ,CAR.Descripcion
				  ,CAR.Cantidad
				  ,CAR.IdContrato
				  ,CAR.EstadoArticulo
				  ,CAR.Memorando
				  ,CASE CAR.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_ContratoArticulos] as CAR
			
			WHERE CAR.IdCotizacion = @IdCotizacion and
				  CAR.IdArticulo   = @IdArticulo

			ORDER BY CAR.Nombre ASC
		END

	IF @Opcion = 5 -- Consultar por Cotizacion, Articulo y Solicitud
		BEGIN
			SELECT CAR.IdCont_Articulo
				  ,CAR.IdCotizacion
				  ,CAR.IdArticulo
				  ,CAR.Nombre
				  ,CAR.Descripcion
				  ,CAR.Cantidad
				  ,CAR.IdContrato
				  ,CAR.EstadoArticulo
				  ,CAR.Memorando
				  ,CASE CAR.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_ContratoArticulos] as CAR
			
			WHERE CAR.IdCotizacion = @IdCotizacion and
				  CAR.IdArticulo   = @IdArticulo and
				  CAR.IdContrato   = @IdContrato

			ORDER BY CAR.Nombre ASC
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodContBodegas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 18/01/2023
-- Description:	Buscar Bodegas por Contrato
-- =============================================
CREATE   PROCEDURE [dbo].[spGetBodContBodegas]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCttBodega int = null,
	@IdContrato Int = null,
	@IdBodega int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT CBG.IdCttBodega
				  ,CBG.IdContrato
				  ,CBG.IdBodega
				  ,CBG.IdCotizacion
				  ,CBG.IdSucursal
				  ,CBG.Nombre
				  ,CBG.Capacidad
				  ,CBG.Ocupacion  
				  ,CBG.Disponible
				  ,CBG.Largo
				  ,CBG.Ancho
				  ,CBG.Alto
				  ,CBG.Estado
				  ,CBG.CodSyscom
				  ,CBG.ValorBodega
				  ,CASE CBG.Estado
					WHEN '1' THEN 'ACTIVA'
					WHEN '2' THEN 'RESERVADA'
					WHEN '3' THEN 'OCUPADA'
					WHEN '4' THEN 'INACTIVA'
					ELSE '0' 
				   END AS EstadoBod
				  ,SUC.Nombre as NombreSuc

			FROM [dbo].[Bodegas_ContratoBodegas] as CBG,
				 [dbo].[Sucursales] as SUC

			WHERE CBG.IdSucursal = SUC.IdSucursal 
	  END

	IF @Opcion = 2 -- Consultar por Ctt-bodega
		BEGIN
			SELECT CBG.IdCttBodega
				  ,CBG.IdContrato
				  ,CBG.IdBodega
				  ,CBG.IdCotizacion
				  ,CBG.IdSucursal
				  ,CBG.Nombre
				  ,CBG.Capacidad
				  ,CBG.Ocupacion
				  ,CBG.Disponible
				  ,CBG.Largo
				  ,CBG.Ancho
				  ,CBG.Alto
				  ,CBG.Estado
				  ,CBG.CodSyscom
				  ,CBG.ValorBodega
				  ,CASE CBG.Estado
					WHEN '1' THEN 'ACTIVA'
					WHEN '2' THEN 'RESERVADA'
					WHEN '3' THEN 'OCUPADA'
					WHEN '4' THEN 'INACTIVA'
					ELSE '0' 
				   END AS EstadoBod
				  ,SUC.Nombre as NombreSuc

			FROM [dbo].[Bodegas_ContratoBodegas] as CBG,
				 [dbo].[Sucursales] as SUC
			
			WHERE CBG.IdCttBodega = @IdCttBodega and
				  CBG.IdSucursal = SUC.IdSucursal
		END

	
	IF @Opcion = 3 -- Consultar por Contrato y Bodega
		BEGIN
			SELECT CBG.IdCttBodega
				  ,CBG.IdContrato
				  ,CBG.IdBodega
				  ,CBG.IdCotizacion
				  ,CBG.IdSucursal
				  ,CBG.Nombre
				  ,CBG.Capacidad
				  ,CBG.Ocupacion
				  ,CBG.Disponible
				  ,CBG.Largo
				  ,CBG.Ancho
				  ,CBG.Alto
				  ,CBG.Estado
				  ,CBG.CodSyscom
				  ,CBG.ValorBodega
				  ,CASE CBG.Estado
					WHEN '1' THEN 'ACTIVA'
					WHEN '2' THEN 'RESERVADA'
					WHEN '3' THEN 'OCUPADA'
					WHEN '4' THEN 'INACTIVA'
					ELSE '0' 
				   END AS EstadoBod
				  ,SUC.Nombre as NombreSuc

			FROM [dbo].[Bodegas_ContratoBodegas] as CBG,
				 [dbo].[Sucursales] as SUC
			
			WHERE CBG.IdContrato = @IdContrato and
				  CBG.IdBodega   = @IdBodega and
				  CBG.IdSucursal = SUC.IdSucursal
		END

	IF @Opcion = 4 -- Consultar por Contrato
		BEGIN
			SELECT CBG.IdCttBodega
				  ,CBG.IdContrato
				  ,CBG.IdBodega
				  ,CBG.IdCotizacion
				  ,CBG.IdSucursal
				  ,CBG.Nombre
				  ,CBG.Capacidad
				  ,CBG.Ocupacion
				  ,CBG.Disponible
				  ,CBG.Largo
				  ,CBG.Ancho
				  ,CBG.Alto
				  ,CBG.Estado
				  ,CBG.CodSyscom
				  ,CBG.ValorBodega
				  ,CASE CBG.Estado
					WHEN '1' THEN 'ACTIVA'
					WHEN '2' THEN 'RESERVADA'
					WHEN '3' THEN 'OCUPADA'
					WHEN '4' THEN 'INACTIVA'
					ELSE '0' 
				   END AS EstadoBod
				  ,SUC.Nombre as NombreSuc

			FROM [dbo].[Bodegas_ContratoBodegas] as CBG,
				 [dbo].[Sucursales] as SUC
			
			WHERE CBG.IdContrato = @IdContrato and
				  CBG.IdSucursal = SUC.IdSucursal
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodContratoIPC]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Sergio Rendón Gómez
-- Create date:  30-11-2023
-- Description:	 Buscar ContratosIPC
-- =============================================
CREATE PROCEDURE [dbo].[spGetBodContratoIPC]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdAjuste int = null,
	@IdContrato int = null,
	@IdCartera int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

   -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
		BEGIN
			SELECT CIP.IdAjuste
				  ,CIP.IdContrato
				  ,CIP.IdCartera
				  ,CIP.AjusteNumero
				  ,CIP.ValorBodega 
				  ,CIP.Ipc
				  ,CIP.ValorAsegurado
				  ,CIP.ValorIpc
				  ,CIP.ValorSeguro
				  ,CIP.ValorMensual
				  ,CIP.Iva
				  ,CIP.ValorTotal
				  ,CIP.AplicaHasta
				  ,CIP.CartaAviso
				  ,CIP.CtrlCarta
				  ,CIP.DctoCarta

			FROM [dbo].[Bodegas_ContratoIPC] as CIP
		END

	IF @Opcion = 2 --Consulta por parametro
	BEGIN
	SELECT 
		CIP.IdAjuste
		,CIP.IdContrato
		,CIP.IdCartera
		,CIP.AjusteNumero
		,CIP.ValorBodega 
		,CIP.Ipc
		,CIP.ValorAsegurado
		,CIP.ValorIpc
		,CIP.ValorSeguro
		,CIP.ValorMensual
		,CIP.Iva
		,CIP.ValorTotal
		,CIP.AplicaHasta
		,CIP.CartaAviso
		,CIP.CtrlCarta
		,CIP.DctoCarta
		,(CONVERT(varchar,(DATEADD(YYYY, 1, (CONVERT(date,CIP.AplicaHasta)))))) as ProximoCambio
		,(CONVERT(varchar,(DATEADD(MM, -1, (CONVERT(date,CIP.AplicaHasta)))))) as AvisoCambio
		,BC.FechaInicio
		,BC.FechaFin
		,NumeroContrato
	FROM 
		[dbo].[Bodegas_ContratoIPC] as CIP
	LEFT JOIN 
		Bodegas_Contratos AS BC ON BC.IdContrato = CIP.IdContrato
	WHERE 
		CIP.IdAjuste between ISNULL(@IdAjuste,0) and ISNULL(@IdAjuste,999999999) 
		and CIP.IdContrato between ISNULL(@IdContrato, CIP.IdContrato) and ISNULL(@IdContrato, CIP.IdContrato) 
		and CIP.IdCartera between ISNULL(@IdCartera, CIP.IdCartera) and ISNULL(@IdCartera, CIP.IdCartera)  
	END

	IF @Opcion = 3 --Consulta por parametro
		BEGIN
			SELECT CIP.IdAjuste
				  ,CIP.IdContrato
				  ,CIP.IdCartera
				  ,CIP.AjusteNumero
				  ,CIP.ValorBodega 
				  ,CIP.Ipc
				  ,CIP.ValorAsegurado
				  ,CIP.ValorIpc
				  ,CIP.ValorSeguro
				  ,CIP.ValorMensual
				  ,CIP.Iva
				  ,CIP.ValorTotal
				  ,CIP.AplicaHasta
				  ,CIP.CartaAviso
				  ,CIP.CtrlCarta
				  ,CIP.DctoCarta
				  ,DATEPART(year, CTT.FechaContrato) as AnoInicio
				  ,DATEPART(year, CIP.AplicaHasta) as AnoProximo
				  ,(CONVERT(varchar,(DATEADD(YYYY, 1, (CONVERT(date,CIP.AplicaHasta)))))) as ProximoCambio
				  ,(CONVERT(varchar,(DATEADD(YYYY, 1, (CONVERT(date,CIP.CartaAviso)))))) as AvisoCambio 
				  --Contratos
				  ,CTT.NumeroContrato
				  ,CTT.FechaContrato
				  ,CTT.ValorTotal as VrTotalContrato
				  ,CTT.IdCliente
				  ,CTT.IdCotizacion
				  ,CTT.IdCia
				  --IPC
				  ,IPC.Valor as IndiceIpc
				  ,IPC.Puntos as PuntosIpc
				  ,IPC.ValorTotal as VrTotalIpc

			from [dbo].[Bodegas_ContratoIPC] as CIP
					INNER JOIN [dbo].[Bodegas_Contratos] as CTT ON CIP.IdContrato = CTT.IdContrato
					LEFT  JOIN [dbo].[Bodegas_Ipc] as IPC ON DATEPART(year, CIP.AplicaHasta) = IPC.Ano

			WHERE CIP.IdAjuste   between ISNULL(@IdAjuste,0) and ISNULL(@IdAjuste,999999999) and 
				  CIP.IdContrato between ISNULL(@IdContrato,0) and ISNULL(@IdContrato,999999999) and  
				  CIP.IdCartera  between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999) and
				  AjusteNumero = (SELECT MAX(AjusteNumero) FROM Bodegas_ContratoIPC WHERE IdCartera = @IdCartera OR IdContrato = @IdContrato or IdAjuste = @IdAjuste)

		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodContratos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 03/10/2022
-- Description:	Buscar Contratos
-- ==================================================
CREATE PROCEDURE [dbo].[spGetBodContratos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdContrato int = null,
	@NumeroContrato int = null,
	@IdCotizacion int = null, 
    @IdOrdenServicio int = null,
	@FechaIni varchar(10) = null,
	@FechaFin varchar(10) = null,
	@Identificacion VARCHAR(20) = NULL,
	@Nombre VARCHAR(20) = NULL,
	@IdSucursal INT = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Contratos
	BEGIN
		SELECT 
			CTT.IdContrato,
			CONCAT(CTT.NumeroContrato, '-', SUC.Compania) AS NumeroContrato,
			CTT.FechaContrato,
			CTT.HoraContrato,
			CTT.FechaInicio,
			CTT.HoraInicio,
			CTT.FechaFin,
			CTT.HoraFin,
			CTT.IdCiudadOrigen,
			CTT.IdSucursal,
			CTT.IdCliente,
			CTT.IdCotizacion,
			CTT.IdOrdenServicio,
			CTT.ValorContrato,
			CTT.PorcentajeIVA,
			CTT.ValorIVA,
			CTT.ValorDeclarado,
			CTT.ValorPoliza,
			CTT.IdPeriodicidad,
			CTT.MesesPeriodo,
			CTT.ValorTotal,
			CTT.EstadoContrato,
			CTT.Novedades,
			CTT.PagoInicial,
			CTT.CodigoEntrada,
			CTT.CodigoSalida,
			CTT.Bloqueo,
			CTT.Movimientos,
			CTT.ControlContrato,
			CTT.IdCartera,
			CTT.IdCia,	  
			--COTIZACIONES
			CTZ.IdCia,
			CTZ.Almacenamiento,
			--SUCURSALES
			SUC.Nombre as NombreSuc	 , 
			--CLIENTES
			CONCAT(CLI.Nombres, ' ',CLI.Apellidos) as NombreCli,
			CLI.Identificacion,  
			--CIUDADES
			CIU.Nombre as NombreCiu,
			--ORDEN SERVICIO
			OSM.NumOrden,
			OSM.Compania,
			OSM.NumInventario,
			--PERIODICIDAD
			PRD.Nombre as NombrePrd,
			--COMPANIA
			CIA.CodSyscom,
			CCT.CodSyscom,
			--VARIOS
			CONCAT(OSM.NumOrden,'-',CIA.CodSyscom) as OrdenServicio,
			CONCAT(CTT.IdCotizacion,'-',CCT.CodSyscom) as Cotizacion
			--,(CONVERT(varchar,(DATEADD(MM, +1, (CONVERT(date,CTT.FechaContrato)))))) as FechaDesde
		FROM 
			[dbo].[Bodegas_Contratos] as CTT
		INNER JOIN 
			[dbo].[Cotizacion] as CTZ 
			ON CTT.IdCotizacion = CTZ.IdCotizacion
		INNER JOIN 
			[dbo].[Sucursales] as SUC 
			ON CTT.IdSucursal = SUC.IdSucursal
		INNER JOIN 
			[dbo].[Clientes] as CLI 
			ON  CTT.IdCliente = CLI.IdCliente
		INNER JOIN 
			[dbo].[Ciudades] as CIU 
			ON CTT.IdCiudadOrigen = CIU.IdCiudad
		INNER JOIN 
			[dbo].[OrdenServicio] as OSM 
			ON CTT.IdOrdenServicio = OSM.IdOrden
		LEFT  JOIN 
			[dbo].[Compania] as CIA 
			ON OSM.Compania = CIA.IdCia
		LEFT  JOIN 
			[dbo].[Compania] as CCT 
			ON CTZ.IdCia = CCT.IdCia
		INNER JOIN 
			[dbo].[Bodegas_Periodicidad] as PRD 
			ON CTT.IdPeriodicidad = PRD.IdPeriodicidad
	END

	IF @Opcion = 2  -- Consula por numero de Contrato
		BEGIN
			SELECT CTT.IdContrato
				  ,CTT.NumeroContrato
				  ,CTT.FechaContrato
				  ,CTT.HoraContrato
				  ,CTT.FechaInicio
				  ,CTT.HoraInicio
				  ,CTT.FechaFin
				  ,CTT.HoraFin
				  ,CTT.IdCiudadOrigen
				  ,CTT.IdSucursal
				  ,CTT.IdCliente
				  ,CTT.IdCotizacion
				  ,CTT.IdOrdenServicio
				  ,CTT.ValorContrato
				  ,CTT.PorcentajeIVA
				  ,CTT.ValorIVA
				  ,CTT.ValorDeclarado
				  ,CTT.ValorPoliza
				  ,CTT.IdPeriodicidad
				  ,CTT.MesesPeriodo
				  ,CTT.ValorTotal
				  ,CTT.EstadoContrato
				  ,CTT.Novedades
				  ,CTT.PagoInicial
				  ,CTT.CodigoEntrada
				  ,CTT.CodigoSalida
				  ,CTT.Bloqueo
				  ,CTT.Movimientos
				  ,CTT.ControlContrato
				  ,CTT.IdCartera
				  ,CTT.IdCia
				  
				  --COTIZACIONES
				  ,CTZ.IdCia
				  ,CTZ.Almacenamiento

				  --SUCURSALES
				  ,SUC.Nombre as NombreSuc
				  ,SUC.Compania AS SucursalCompania
				  
				  --CLIENTES
				  ,CONCAT(CLI.Nombres, ' ',CLI.Apellidos) as NombreCli
				  ,CLI.Identificacion
				  
				  --CIUDADES
				  ,CIU.Nombre as NombreCiu
				  
				  --ORDEN SERVICIO
				  ,OSM.NumOrden
				  ,OSM.Compania
				  ,OSM.NumInventario

				  --COMPANIA
				  ,CIA.CodSyscom
				  ,CCT.CodSyscom 
				  ,CTO.CodSyscom as CiaContrato

				  --BODEGASCONTRATO
				  ,CBG.Nombre as NomBodega

				  --CODIGOENTRADA y CODIGOSALIDA
				  ,BCE.CodEntrada
				  ,BCS.CodSalida
				  
				  --VARIOS
				  ,CONCAT(OSM.NumOrden,'-',CIA.CodSyscom) as OrdenServicio
				  ,CONCAT(CTT.IdCotizacion,'-',CCT.CodSyscom) as Cotizacion
				  ,CONCAT(CTT.NumeroContrato,'-',SUC.Compania) as ContratoNum
				  ,PRD.Nombre as NombrePrd
				  ,(CONVERT(varchar,(DATEADD(DD, +30, (CONVERT(date,CTT.FechaContrato)))))) as FechaHasta
				  ,CASE WHEN (DAY(FechaContrato) + 5) > 30 THEN (DAY(FechaContrato) + 5) - 30 ELSE (DAY(FechaContrato) + 5) END as DiaPago
				  ,DATEPART(YEAR, CTT.FechaInicio) as AnoInicio
				  ,BIP.ValorTotal as PorcentajeIPC

			FROM [dbo].[Bodegas_Contratos] as CTT
					INNER JOIN [dbo].[Cotizacion] as CTZ ON CTT.IdCotizacion = CTZ.IdCotizacion
					INNER JOIN [dbo].[Sucursales] as SUC ON  CTT.IdSucursal = SUC.IdSucursal
				 	INNER JOIN [dbo].[Clientes] as CLI ON CTT.IdCliente = CLI.IdCliente
				 	INNER JOIN [dbo].[Ciudades] as CIU ON CTT.IdCiudadOrigen = CIU.IdCiudad
				 	INNER JOIN [dbo].[OrdenServicio] as OSM ON CTT.IdOrdenServicio = OSM.IdOrden
				 	LEFT  JOIN [dbo].[Compania] as CIA ON OSM.Compania = CIA.IdCia
				 	LEFT  JOIN [dbo].[Compania] as CCT ON CTZ.IdCia = CCT.IdCia
				 	LEFT  JOIN [dbo].[Compania] as CTO ON CTT.IdCia = CTO.IdCia
					LEFT  JOIN [dbo].[Bodegas_ContratoBodegas] as CBG ON CTT.IdContrato = CBG.IdContrato
				 	INNER JOIN [dbo].[Bodegas_Periodicidad] as PRD ON CTT.IdPeriodicidad  = PRD.IdPeriodicidad
					INNER JOIN [dbo].[Bodegas_IPC] as BIP ON DATEPART(YEAR, CTT.FechaInicio) = BIP.Ano
					LEFT  JOIN [dbo].[Bodegas_CodigoEntrada] as BCE ON CTT.CodigoEntrada = BCE.IdEntrada
					LEFT  JOIN [dbo].[Bodegas_CodigoSalida] as BCS ON CTT.CodigoSalida = BCS.IdSalida

			WHERE CTT.IdContrato = @IdContrato 
				  
		END

	IF @Opcion = 3  -- Consula por numero de Cotizacion
	BEGIN
		SELECT 
			CTT.IdContrato, 
			CONCAT(CTT.NumeroContrato, '-', SUC.Compania) AS NumeroContrato, 
			CTT.FechaContrato,
			CTT.HoraContrato, 
			CTT.FechaInicio, 
			CTT.HoraInicio,
			CTT.FechaFin, 
			CTT.HoraFin, 
			CTT.IdCiudadOrigen,
			CTT.IdSucursal, 
			CTT.IdCliente, 
			CTT.IdCotizacion,
			CTT.IdOrdenServicio, 
			CTT.ValorContrato, 
			CTT.PorcentajeIVA,
			CTT.ValorIVA, 
			CTT.ValorDeclarado, 
			CTT.ValorPoliza,
			CTT.IdPeriodicidad, 
			CTT.MesesPeriodo, 
			CTT.ValorTotal,
			CTT.EstadoContrato, 
			CTT.Novedades, 
			CTT.PagoInicial,
			CTT.CodigoEntrada, 
			CTT.CodigoSalida, 
			CTT.Bloqueo,
			CTT.Movimientos, 
			CTT.ControlContrato, 
			CTT.IdCartera,
			CTT.IdCia,  
			--COTIZACIONES
			CTZ.IdCia, CTZ.Almacenamiento,
			--SUCURSALES
			SUC.Nombre as NombreSuc,
			--CLIENTES
			CONCAT(CLI.Nombres, ' ',CLI.Apellidos) as NombreCli, CLI.Identificacion,
			--CIUDADES
			CIU.Nombre as NombreCiu,
			--ORDEN SERVICIO
			OSM.NumOrden, OSM.Compania, OSM.NumInventario,
			--PERIODICIDAD
			PRD.Nombre as NombrePrd,
			--COMPANIA
			CIA.CodSyscom, CCT.CodSyscom,
			--CODIGOENTRADA y CODIGOSALIDA
			BCE.CodEntrada, BCS.CodSalida,
			--VARIOS
			CONCAT(OSM.NumOrden,'-',CIA.CodSyscom) as OrdenServicio, CONCAT(CTT.IdCotizacion,'-',CCT.CodSyscom) as Cotizacion
		FROM 
			[dbo].[Bodegas_Contratos] as CTT
		INNER JOIN 
			[dbo].[Cotizacion] as CTZ ON CTT.IdCotizacion = CTZ.IdCotizacion
		INNER JOIN 
			[dbo].[Sucursales] as SUC ON CTT.IdSucursal = SUC.IdSucursal
		INNER JOIN 
			[dbo].[Clientes] as CLI ON  CTT.IdCliente = CLI.IdCliente
		INNER JOIN 
			[dbo].[Ciudades] as CIU ON CTT.IdCiudadOrigen = CIU.IdCiudad
		LEFT  JOIN 
			[dbo].[OrdenServicio] as OSM ON CTT.IdOrdenServicio = OSM.IdOrden
		LEFT  JOIN 
			[dbo].[Compania] as CIA ON OSM.Compania = CIA.IdCia
		LEFT  JOIN 
			[dbo].[Compania] as CCT ON CTZ.IdCia = CCT.IdCia
		LEFT  JOIN 
			[dbo].[Bodegas_Periodicidad] as PRD ON CTT.IdPeriodicidad = PRD.IdPeriodicidad
		LEFT  JOIN 
			[dbo].[Bodegas_CodigoEntrada] as BCE ON CTT.CodigoEntrada = BCE.IdEntrada
		LEFT  JOIN 
			[dbo].[Bodegas_CodigoSalida] as BCS ON CTT.CodigoSalida = BCS.IdSalida
		WHERE 
			(@Identificacion IS NULL OR CLI.Identificacion LIKE CONCAT(@Identificacion, '%'))
			AND (@Nombre IS NULL OR CONCAT(CLI.Nombres, CLI.Apellidos) LIKE CONCAT(@Nombre, '%')) 
			AND (@IdSucursal IS NULL OR CTT.IdSucursal = @IdSucursal)
			AND (@NumeroContrato IS NULL OR CTT.NumeroContrato LIKE CONCAT(@NumeroContrato, '%'))
			AND (@IdCotizacion IS NULL OR CTT.IdCotizacion =  @IdCotizacion)
			AND (@IdOrdenServicio IS NULL OR CTT.IdOrdenServicio = @IdOrdenServicio)
			AND CTT.FechaInicio BETWEEN ISNULL(@FechaIni, CTT.FechaInicio) and ISNULL(@FechaFin, CTT.FechaInicio)
	END

	IF @Opcion = 5  -- Totales Contrato
		BEGIN
			DECLARE 
			@Total1 numeric(18,2) = null,
			@Total2 numeric(18,2) = null

			SELECT  @Total1 = sum(Valor_Negociado + Valor_Iva) FROM [dbo].[Cotizacion_Conceptos] WHERE IdCotizacion = @IdCotizacion and IdServicio = 17 
			SELECT  @Total2 = sum(Valor_Negociado + Valor_Iva) FROM [dbo].[Cotizacion_Conceptos] WHERE IdCotizacion = @IdCotizacion and IdServicio = 18 

			UPDATE [dbo].[Bodegas_Contratos] SET ValorTotal = (@Total1 + @Total2) WHERE IdCotizacion = @IdCotizacion and IdContrato = @IdContrato
		END

END

GO
/****** Object:  StoredProcedure [dbo].[spGetBodegas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 06/10/2021
-- Description:	Buscar Bodegas
-- =============================================
CREATE   PROCEDURE [dbo].[spGetBodegas] 
	-- Add the parameters for the stored procedure here
	@Opcion INT,
	@IdBodega INT = NULL,
	@IdSucursal INT = NULL,
	@Nombre VARCHAR(125) = NULL,
	@IncluirInactivos BIT = 0,
	@Inactivos BIT = 0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statementB.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
	BEGIN 
		SELECT 
			BDG.IdBodega,
			BDG.IdSucursal,
			BDG.Nombre COLLATE Cyrillic_General_CI_AI as Nombre,
			BDG.Capacidad, 
			BDG.IdUnidad, 
			BDG.Largo, 
			BDG.Ancho, 
			BDG.Alto,
   			BDG.Estado, 
			BDG.Disponible,
			BDG.CodSyscom COLLATE Cyrillic_General_CI_AI as CodSyscom,
			BDG.ValorBodega,
			BDG.Ocupacion,
			BDG.CapacidadFinal,
			BDG.IdTarifaBodega,
			UND.Nombre COLLATE Cyrillic_General_CI_AI as NombreUnidad,
			SUC.Nombre COLLATE Cyrillic_General_CI_AI as NombreSucursal,
			EST.Nombre as EstadoBodega,
			TFB.ValorMetro,
			BDG.Capacidad * TFB.ValorMetro as VrTotal
		FROM 
			Bodegas as BDG
		INNER JOIN 
			Unidades as UND 
			ON BDG.IdUnidad   = UND.IdUnidad
		INNER JOIN 
			Sucursales as SUC 
			ON BDG.IdSucursal = SUC.IdSucursal
		INNER JOIN 
			Estado_Bodegas as EST 
			ON BDG.Estado = EST.IdEstadoBod
		LEFT  JOIN 
			Tarifas_Bodegas as TFB 
			ON BDG.IdTarifaBodega = TFB.IdTarifaBodega
		WHERE 
			EST.IdEstadoBod <> 4
	END

	IF @Opcion = 2 --Consulta por Bodega
	BEGIN 
		SELECT BDG.IdBodega
				,BDG.IdSucursal
				,BDG.Nombre COLLATE Cyrillic_General_CI_AI as Nombre 
				,BDG.Capacidad 
				,BDG.IdUnidad 
				,BDG.Largo 
				,BDG.Ancho 
				,BDG.Alto
   				,BDG.Estado 
				,BDG.Disponible
				,BDG.CodSyscom COLLATE Cyrillic_General_CI_AI as CodSyscom
				,BDG.ValorBodega
				,BDG.Ocupacion
				,BDG.CapacidadFinal
				,BDG.IdTarifaBodega
				,UND.Nombre COLLATE Cyrillic_General_CI_AI as NombreUnidad
				,SUC.Nombre COLLATE Cyrillic_General_CI_AI as NombreSucursal
				,EST.Nombre as EstadoBodega
				,TFB.ValorMetro
				,BDG.Capacidad * TFB.ValorMetro as VrTotal

		FROM [dbo].[Bodegas] as BDG
				INNER JOIN [dbo].[Unidades] as UND ON BDG.IdUnidad   = UND.IdUnidad
				INNER JOIN [dbo].[Sucursales] as SUC ON BDG.IdSucursal = SUC.IdSucursal
				INNER JOIN [dbo].[Estado_Bodegas] as EST ON BDG.Estado = EST.IdEstadoBod
				LEFT  JOIN [dbo].[Tarifas_Bodegas] as TFB ON BDG.IdTarifaBodega = TFB.IdTarifaBodega

		WHERE BDG.IdBodega = @IdBodega
	END

	IF @Opcion = 3 -- Consultar por Parametro
	BEGIN
		SELECT 
			BDG.IdBodega,
			BDG.IdSucursal,
			BDG.Nombre COLLATE Cyrillic_General_CI_AI as Nombre,
			BDG.Capacidad,
			BDG.IdUnidad,
			BDG.Largo,
			BDG.Ancho,
			BDG.Alto,
			BDG.Estado,
			BDG.Disponible,
			BDG.CodSyscom COLLATE Cyrillic_General_CI_AI as CodSyscom,
			BDG.ValorBodega,
			BDG.Ocupacion,
			BDG.CapacidadFinal,
			BDG.IdTarifaBodega,
			SUC.Nombre COLLATE Cyrillic_General_CI_AI as NombreSucursal,
			UND.Nombre COLLATE Cyrillic_General_CI_AI as NombreUnidad,
			CONCAT(BDG.Largo, ' x ', BDG.Ancho, ' x ',BDG.Alto) as Medidas,
			EST.Nombre as EstadoBodega
		FROM 
			[dbo].[Bodegas] as BDG
		INNER JOIN 
			[dbo].[Unidades] as UND 
			ON BDG.IdUnidad   = UND.IdUnidad
		INNER JOIN 
			[dbo].[Sucursales] as SUC 
			ON BDG.IdSucursal = SUC.IdSucursal
		INNER JOIN 
			[dbo].[Estado_Bodegas] as EST 
			ON BDG.Estado = EST.IdEstadoBod
		WHERE 
			BDG.Nombre LIKE CONCAT('%',ISNULL(@Nombre, BDG.Nombre),'%') 
			AND BDG.IdSucursal BETWEEN ISNULL(@IdSucursal, BDG.IdSucursal) AND ISNULL(@IdSucursal, BDG.IdSucursal) 
			AND BDG.Estado <= 2 
			AND ((@Inactivos = 0) OR (@Inactivos = 1 AND BDG.Estado = 4))
			AND ((@IncluirInactivos = 0) OR (@IncluirInactivos = 1 AND BDG.Estado IN (SELECT IdEstadoBod FROM Estado_Bodegas)))
			AND ((@IncluirInactivos = 0 AND @Inactivos = 0 AND BDG.Estado IN (SELECT IdEstadoBod FROM Estado_Bodegas WHERE IdEstadoBod <> 4)) OR (@Inactivos <> @IncluirInactivos))
	END

	IF @Opcion = 4 --Consulta General
	BEGIN 
		SELECT BDG.IdBodega
			    ,BDG.IdSucursal
				,BDG.Nombre COLLATE Cyrillic_General_CI_AI as Nombre 
				,BDG.Capacidad 
				,BDG.IdUnidad 
				,BDG.Largo 
				,BDG.Ancho 
				,BDG.Alto
				,BDG.Estado 
				,BDG.Disponible
				,BDG.CodSyscom COLLATE Cyrillic_General_CI_AI as CodSyscom
				,BDG.ValorBodega
				,BDG.Ocupacion
				,BDG.CapacidadFinal
				,BDG.IdTarifaBodega
				,UND.Nombre COLLATE Cyrillic_General_CI_AI as NombreUnidad
				,SUC.Nombre COLLATE Cyrillic_General_CI_AI as NombreSucursal
				,EST.Nombre as EstadoBodega

		FROM [dbo].[Bodegas] as BDG
				INNER JOIN [dbo].[Unidades] as UND ON BDG.IdUnidad   = UND.IdUnidad
				INNER JOIN [dbo].[Sucursales] as SUC ON BDG.IdSucursal = SUC.IdSucursal
				INNER JOIN [dbo].[Estado_Bodegas] as EST ON BDG.Estado = EST.IdEstadoBod

		WHERE BDG.Estado <= 2 
	END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodEstadoCuentas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Sergio Rendón Gómez
-- Create date:  2023-12-19
-- Description:	 Buscar Estado de Cuentas
-- =============================================
CREATE PROCEDURE [dbo].[spGetBodEstadoCuentas] 
	-- Add the parameters for the stored procedure here
	@Opcion int, 
	@IdCuenta int = null,
    @IdContrato int = null,
    @IdCartera int = null,
	@CtrlPago int = null,
	@FechaIni varchar(10) = null,
	@VrIva decimal(18,2) = null,
	@PorcSancion decimal(18,3) = null,
	@ValorRestar Numeric(18,0) = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here

	IF @Opcion = 1 --Consulta General
		BEGIN
			SELECT ESC.IdCuenta
				  ,ESC.IdContrato
				  ,ESC.IdCartera
				  ,ESC.IdCliente
				  ,ESC.Desde
				  ,ESC.Hasta
				  ,ESC.ValorBodega
				  ,ESC.ValorSeguro
				  ,ESC.ValorIva
				  ,ESC.ValorBaseCuenta
				  ,ESC.ValorIpcCuenta
				  ,ESC.ValorIvaCuenta
				  ,ESC.MesesMora
				  ,ESC.VrSancionCuenta
				  ,ESC.VrDeudaMes
				  ,ESC.VrAbonoDeuda
				  ,ESC.VrSaldoDeuda
				  ,ESC.VrDeudaAcumulada
				  ,ESC.CtrlPago
				  ,ESC.CtrlCuota
				  ,ESC.PorcentajeIpc

			FROM [dbo].[Bodegas_EstadoCuentas] as ESC
		END

	IF @Opcion = 2 --Consulta por parametro
	BEGIN
		SELECT 
			ESC.IdCuenta
			,ESC.IdContrato
			,ESC.IdCartera
			,ESC.IdCliente
			,ESC.Desde
			,ESC.Hasta
			,ESC.ValorBodega
			,ESC.ValorSeguro
			,ESC.ValorIva
			,ESC.ValorBaseCuenta
			,ESC.ValorIpcCuenta
			,ESC.ValorIvaCuenta
			,ESC.MesesMora
			,ESC.VrSancionCuenta
			,ESC.VrDeudaMes
			,ESC.VrAbonoDeuda
			,ESC.VrSaldoDeuda
			,ESC.VrDeudaAcumulada
			,ESC.CtrlPago
			,ESC.CtrlCuota
			,ESC.PorcentajeIpc
			,CASE 
				WHEN VrSaldoDeuda = 0 THEN VrDeudaMes 
				ELSE VrSaldoDeuda
			END AS VrDeudaCalculada
		FROM 
			[dbo].[Bodegas_EstadoCuentas] as ESC
		WHERE 
			ESC.IdCuenta   between ISNULL(@IdCuenta,0) and ISNULL(@IdCuenta,999999999) and 
			ESC.IdContrato between ISNULL(@IdContrato,0) and ISNULL(@IdContrato,999999999) and 
			ESC.IdCartera  between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999)	and
			ESC.CtrlPago   = @CtrlPago
	END

	IF @Opcion = 3 --Consulta Funcion de Creación de periodos
		BEGIN
			SELECT ESC.IdCuenta
				  ,ESC.IdContrato
				  ,ESC.IdCartera
				  ,ESC.IdCliente
				  ,ESC.Desde
				  ,ESC.Hasta
				  ,ESC.ValorBodega
				  ,ESC.ValorSeguro
				  ,ESC.ValorIva
				  ,ESC.ValorBaseCuenta
				  ,ESC.ValorIpcCuenta
				  ,ESC.ValorIvaCuenta
				  ,ESC.MesesMora
				  ,ESC.VrSancionCuenta
				  ,ESC.VrDeudaMes
				  ,ESC.VrAbonoDeuda
				  ,ESC.VrSaldoDeuda
				  ,ESC.VrDeudaAcumulada
				  ,ESC.CtrlPago
				  ,ESC.CtrlCuota
				  ,ESC.PorcentajeIpc
				  ,CuotaNumero
				  ,FechaIni
				  ,FechaFin
	
				  --Calculo Dias
				  ,CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Dias ELSE 0 END as Dias
		 
				  --Calculo Meses
				  ,CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END as Meses

				  --Base
				  ,round((CTR.ValorBodega + CTR.ValorSeguro),0) as Base

				  --Porcentaje IPC
				  ,YEAR(DT.FechaIni) as AnoIni
				  ,(SELECT ValorTotal FROM [dbo].[Bodegas_IPC] WHERE Ano = YEAR(DT.FechaIni)) as PorcIpc

				  --Total IPC
				  ,round(CASE WHEN (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END) = 0 THEN 0 ELSE (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN round((CTR.ValorBodega *(SELECT ValorTotal FROM [dbo].[Bodegas_IPC] WHERE Ano = YEAR(DT.FechaIni))/100),0) ELSE ESC.ValorIpcCuenta END) END,0) as VrIPC

				  --Total IVA
				  ,round((((CTR.ValorBodega + CTR.ValorSeguro) + 
					CASE WHEN (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END) = 0 THEN 0 ELSE (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN round((CTR.ValorBodega *(SELECT ValorTotal FROM [dbo].[Bodegas_IPC] WHERE Ano = YEAR(DT.FechaIni))/100),0) ELSE ESC.ValorIpcCuenta END) END) * 
						@VrIva),0) as TotalIva

				  --Calculo Sancion ((Base + Ipc) * MESES) * @AjusteSancion
				  ,round(CASE WHEN (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END) = 0
					THEN ESC.VrSancionCuenta
						ELSE (((CTR.ValorBodega + CTR.ValorSeguro) + 
							 (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN round((CTR.ValorBodega *(SELECT ValorTotal FROM [dbo].[Bodegas_IPC] WHERE Ano = YEAR(DT.FechaIni))/100),0) ELSE ESC.ValorIpcCuenta  END)) * 
							 (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END)) * @PorcSancion
						END,0) as Sancion

				  --DeudaPeriodo (base + ipc + Iva + Sancion)
				  ,round(
				 -- CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 	
					--THEN 
						(((CTR.ValorBodega + CTR.ValorSeguro) + 
							
						(CASE WHEN (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END) = 0 THEN 0 ELSE (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN round((CTR.ValorBodega *(SELECT ValorTotal FROM [dbo].[Bodegas_IPC] WHERE Ano = YEAR(DT.FechaIni))/100),0) ELSE ESC.ValorIpcCuenta  END) END) + 
							
						(((CTR.ValorBodega + CTR.ValorSeguro) + 

						CASE WHEN (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END) = 0 THEN 0 ELSE (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN round((CTR.ValorBodega *(SELECT ValorTotal FROM [dbo].[Bodegas_IPC] WHERE Ano = YEAR(DT.FechaIni))/100),0) ELSE ESC.ValorIpcCuenta  END) END) * 
						@VrIva) + 
							
						(CASE WHEN (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END) = 0
							THEN ESC.VrSancionCuenta
							ELSE (((CTR.ValorBodega + CTR.ValorSeguro) + 
								 (CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN round((CTR.ValorBodega *(SELECT ValorTotal FROM [dbo].[Bodegas_IPC] WHERE Ano = YEAR(DT.FechaIni))/100),0) ELSE ESC.ValorIpcCuenta  END)) * 
								(CASE WHEN ISNULL (ESC.CtrlPago,0) = 0 THEN Meses ELSE ESC.MesesMora END)) * @PorcSancion
						 END)))
					-- ELSE 0
					--END
					,0) as DeudaPeriodo 
		
			FROM (SELECT * FROM dbo.GenerarVencimientosCartera((SELECT (CONVERT(varchar,(DATEADD(MM, -1, (CONVERT(date, FechaContrato)))))) FROM Bodegas_Contratos WHERE IdContrato = @IdContrato))) as DT
					LEFT  JOIN (select * FROM Bodegas_Pagos where IdCartera = @IdCartera) as BP ON DT.FechaIni = BP.PeriodoIni and DT.FechaFin = BP.PeriodoFin
					INNER JOIN [dbo].[Bodegas_Cartera] as CTR ON CTR.IdContrato = @IdContrato
					LEFT  JOIN [dbo].[Bodegas_EstadoCuentas] as ESC ON ESC.IdContrato = @IdContrato and DT.FechaIni = ESC.Desde and DT.FechaFin = ESC.Hasta
					INNER JOIN [dbo].[Bodegas_IPC] as IPC ON CTR.IdIPC = IPC.IdIPC
		END

	IF @Opcion = 5 --Consulta por realizar pagos
	BEGIN

		DECLARE @MontoRestante DECIMAL(18, 2) = @ValorRestar;
		DECLARE @CtrlCuota INT;
		DECLARE @VrDeudaMes DECIMAL(18, 2);
		DECLARE @VrAbonoDeuda DECIMAL(18, 2);
		DECLARE @VrSaldoDeuda DECIMAL(18, 2);

		-- Ajustar el monto restante considerando el saldo a favor del último registro
		SELECT @VrSaldoDeuda = VrSaldoDeuda
		FROM Bodegas_EstadoCuentas
		WHERE IdContrato = @IdContrato
			AND CtrlCuota = (SELECT MAX(CtrlCuota) FROM Bodegas_EstadoCuentas WHERE IdContrato = @IdContrato) - 1

		IF @VrSaldoDeuda < 0
		BEGIN
			SET @MontoRestante = @MontoRestante + ABS(@VrSaldoDeuda);
			UPDATE Bodegas_EstadoCuentas
			SET VrSaldoDeuda = 0
			WHERE CtrlCuota = (SELECT MAX(CtrlCuota) FROM Bodegas_EstadoCuentas WHERE IdContrato = @IdContrato) - 1;
		END;

		WHILE @MontoRestante > 0
		BEGIN
			-- Obtener el siguiente registro con deuda pendiente
			SELECT TOP 1
				@CtrlCuota = CtrlCuota,
				@VrDeudaMes = VrDeudaMes,
				@VrAbonoDeuda = VrAbonoDeuda,
				@VrSaldoDeuda = VrDeudaMes - VrAbonoDeuda
			FROM Bodegas_EstadoCuentas
			WHERE CtrlPago = 0 AND IdContrato = @IdContrato
			ORDER BY CtrlCuota;

			-- Verificar si hay más registros pendientes
			IF @@ROWCOUNT = 0
			BEGIN
				-- Si no hay más registros, almacenar el excedente como saldo negativo
				UPDATE 
					Bodegas_EstadoCuentas
				SET 
					VrSaldoDeuda = VrSaldoDeuda - @MontoRestante
				WHERE 
					CtrlCuota = (SELECT MAX(CtrlCuota) FROM Bodegas_EstadoCuentas WHERE IdContrato = @IdContrato)
					AND IdContrato = @IdContrato
				
				SET @MontoRestante = 0;
				BREAK;
			END;

			IF @MontoRestante >= @VrSaldoDeuda
			BEGIN
				-- Pago completo del registro
				UPDATE Bodegas_EstadoCuentas
				SET VrAbonoDeuda = VrDeudaMes,
					VrSaldoDeuda = 0,
					CtrlPago = 1
				WHERE CtrlCuota = @CtrlCuota AND IdContrato = @IdContrato;

				SET @MontoRestante = @MontoRestante - @VrSaldoDeuda;
			END
			ELSE
			BEGIN
				-- Pago parcial del registro
				UPDATE Bodegas_EstadoCuentas
				SET VrAbonoDeuda = VrAbonoDeuda + @MontoRestante,
					VrSaldoDeuda = VrDeudaMes - (VrAbonoDeuda + @MontoRestante)
				WHERE CtrlCuota = @CtrlCuota AND IdContrato = @IdContrato;

				SET @MontoRestante = 0;
			END
		END;

		SELECT * FROM [dbo].[Bodegas_EstadoCuentas] WHERE IdContrato = @IdContrato;
	END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodIPC]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 2023-12-20
-- Description:	Buscar Bodegas IPC
-- =============================================
CREATE PROCEDURE [dbo].[spGetBodIPC]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdIPC int = null,
	@Ano int = null,
	@EstadoIPC int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT IPC.IdIPC
				  ,IPC.Valor
				  ,IPC.Ano
				  ,IPC.Puntos
				  ,IPC.EstadoIPC
				  ,IPC.ValorTotal
				  ,IPC.Clase
				  ,CASE IPC.EstadoIPC
					WHEN '1' THEN 'ACTIVO'
					WHEN '2' THEN 'INACTIVO'
					ELSE '0' 
				   END AS Estado

			FROM [dbo].[Bodegas_IPC] as IPC
		END
	
	IF @Opcion = 2 --Consulta por parametro
		BEGIN 
			SELECT IPC.IdIPC
				  ,IPC.Valor
				  ,IPC.Ano
				  ,IPC.Puntos
				  ,IPC.EstadoIPC
				  ,IPC.ValorTotal
				  ,IPC.Clase
				  ,CASE IPC.EstadoIPC
					WHEN '1' THEN 'ACTIVO'
					WHEN '2' THEN 'INACTIVO'
					ELSE '0' 
				   END AS Estado

			FROM [dbo].[Bodegas_IPC] as IPC

			WHERE IPC.IdIPC     between ISNULL(@IdIPC,0) and ISNULL(@IdIPC,999999999) and 
				  IPC.Ano       between ISNULL(@Ano,0) and ISNULL(@Ano,999999999) and 
				  IPC.EstadoIPC between ISNULL(@EstadoIPC,0) and ISNULL(@EstadoIPC,99)
		END

END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodKardex]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 16/03/2023
-- Description:	Buscar kardex Articulos 
-- =============================================
CREATE   PROCEDURE [dbo].[spGetBodKardex]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdKardex int = null,
	@IdCont_Articulo int = null,
	@IdContrato Int = null,
	@IdCotizacion int = null,
	@IdArticulo int = null,
	@EstadoArticulo varchar(2) = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT KDX.IdKardex
				  ,KDX.IdCont_Articulo
				  ,KDX.IdCotizacion
				  ,KDX.IdArticulo
				  ,KDX.Nombre
				  ,KDX.Descripcion
				  ,KDX.Cantidad
				  ,KDX.EstadoArticulo
				  ,KDX.Memorando
				  ,KDX.Revisado
				  ,CASE KDX.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_KardexArticulos] as KDX

			WHERE KDX.EstadoArticulo = @EstadoArticulo
	  END

	IF @Opcion = 2 -- Consultar por Contrato
		BEGIN
			SELECT KDX.IdKardex
				  ,KDX.IdCont_Articulo
				  ,KDX.IdCotizacion
				  ,KDX.IdArticulo
				  ,KDX.Nombre
				  ,KDX.Descripcion
				  ,KDX.Cantidad
				  ,KDX.IdContrato
				  ,KDX.EstadoArticulo
				  ,KDX.Memorando
				  ,KDX.Revisado
				  ,CASE KDX.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_KardexArticulos] as KDX
			
			WHERE KDX.IdContrato     = @IdContrato and
				  KDX.EstadoArticulo = @EstadoArticulo

			ORDER BY KDX.Revisado ASC
		END

	
	IF @Opcion = 4 -- Consultar por Cotizacion y Articulo
		BEGIN
			SELECT KDX.IdKardex
				  ,KDX.IdCont_Articulo
				  ,KDX.IdCotizacion
				  ,KDX.IdArticulo
				  ,KDX.Nombre
				  ,KDX.Descripcion
				  ,KDX.Cantidad
				  ,KDX.IdContrato
				  ,KDX.EstadoArticulo
				  ,KDX.Memorando
				  ,KDX.Revisado
				  ,CASE KDX.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_KardexArticulos] as KDX
			
			WHERE KDX.IdCotizacion   = @IdCotizacion and
				  KDX.IdArticulo     = @IdArticulo and
				  KDX.EstadoArticulo = @EstadoArticulo
		END

	IF @Opcion = 5 -- Consultar por Cotizacion, Articulo y Solicitud
		BEGIN
			SELECT KDX.IdKardex
				  ,KDX.IdCont_Articulo
				  ,KDX.IdCotizacion
				  ,KDX.IdArticulo
				  ,KDX.Nombre
				  ,KDX.Descripcion
				  ,KDX.Cantidad
				  ,KDX.IdContrato
				  ,KDX.EstadoArticulo
				  ,KDX.Memorando
				  ,KDX.Revisado
				  ,CASE KDX.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt

			FROM [dbo].[Bodegas_KardexArticulos] as KDX
			
			WHERE KDX.IdCotizacion   between ISNULL(@IdCotizacion,KDX.IdCotizacion) and ISNULL(@IdCotizacion,KDX.IdCotizacion) and
				  KDX.IdArticulo     between ISNULL(@IdArticulo,KDX.IdArticulo) and ISNULL(@IdArticulo,KDX.IdArticulo) and
				  KDX.IdContrato     between ISNULL(@IdContrato,KDX.IdContrato) and ISNULL(@IdContrato,KDX.IdContrato) and
				  KDX.EstadoArticulo between ISNULL(@EstadoArticulo,KDX.EstadoArticulo) and ISNULL(@EstadoArticulo,KDX.EstadoArticulo)
		END

	IF @Opcion = 6 -- Consultar por Contrato
		BEGIN
			SELECT KDX.IdKardex
				  ,KDX.IdCont_Articulo
				  ,KDX.IdCotizacion
				  ,KDX.IdArticulo
				  ,KDX.Nombre
				  ,KDX.Descripcion
				  ,KDX.Cantidad
				  ,KDX.IdContrato
				  ,KDX.EstadoArticulo
				  ,KDX.Memorando
				  ,KDX.Revisado
				  ,CASE KDX.EstadoArticulo
					WHEN '1' THEN 'CARGA INICIAL'
					WHEN '2' THEN 'INGRESO MCIA'
					WHEN '3' THEN 'SALIDA MCIA'
					ELSE '0' 
				   END AS EstadoArt
				   
			FROM [dbo].[Bodegas_KardexArticulos] as KDX
			
			WHERE KDX.IdContrato = @IdContrato
		END

	IF @Opcion = 7 -- Contar Revisados
		BEGIN
			SELECT COUNT(KDX.Revisado) as TotalRevisado  

			FROM [dbo].[Bodegas_KardexArticulos] as KDX
			
			WHERE KDX.IdContrato = @IdContrato and
				  KDX.Revisado = 1
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodPagos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Sergio Rendón Gómez
-- Create date:  2023-11-30
-- Description:	 Buscar Pagos Cartera
-- =============================================
CREATE PROCEDURE [dbo].[spGetBodPagos] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdPago int = null,
	@IdCartera int = null,
	@IdContrato int = null,
	@Estado int = null,
	@NumRecibo int = null,
	@CiaRecibo int = null,
	@Compania int = null

AS
BEGIN 
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statementB.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT PG.IdPago
				   ,PG.IdContrato
				   ,PG.IdCartera
				   ,PG.IdCotizacion
				   ,PG.IdCliente
				   ,PG.Compania
				   ,PG.FechaFactura
				   ,PG.HoraFactura
				   ,PG.FacturaNum
				   ,PG.CiaFactura
				   ,PG.ReciboNum
				   ,PG.CiaRecibo
				   ,PG.ValorBodega
				   ,PG.ValorSeguro
				   ,PG.ValorIva
				   ,PG.VrTotalBodega
				   ,PG.VrEmpaque
				   ,PG.VrServLocal
				   ,PG.VrServNacional
				   ,PG.VrSeguroTrans
				   ,PG.ValorTotal
				   ,PG.ValorSaldo
				   ,PG.PeriodoIni
				   ,PG.PeriodoFin
				   ,PG.DiasPago
				   ,PG.MesesPago
				   ,PG.IdFormaPago
				   ,PG.IdMedioPago
				   ,PG.EstadoPago
				   ,PA.ObservaPago
				   ,FP.Nombre as FormaPago
				   ,MP.Nombre as MedioPago
				   ,CT.IdCliente
				   ,CONCAT(CL.Nombres,' ',CL.Apellidos) as NombreCliente

			FROM [dbo].[Bodegas_Pagos] AS PG
					INNER JOIN [dbo].[Bodegas_PagosAnexos] as PA ON PG.IdPago = PA.IdPago
					INNER JOIN [dbo].[Formas_Pago] as FP ON PG.IdFormaPago = FP.IdFormaPago
					INNER JOIN [dbo].[Metodos_Pago] as MP ON PG.IdMedioPago = MP.IdMetodosPago
					INNER JOIN [dbo].[Bodegas_Contratos] as CT ON PG.IdContrato = CT.IdContrato
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente

		END 

	IF @Opcion = 2 --Consulta por parametros
	BEGIN 

		SELECT 
			PG.IdPago, PG.IdContrato, PG.IdCartera
			,PG.IdCotizacion, PG.IdCliente, PG.Compania
			,PG.FechaFactura, PG.HoraFactura, PG.FacturaNum
			,PG.CiaFactura, PG.ReciboNum, PG.CiaRecibo
			,CONCAT(PG.ReciboNum, '-', PG.CiaRecibo) AS FacturaNumCia
			,CONCAT(PG.FacturaNum, '-', PG.CiaFactura) AS ReciboNumCia
			,PG.ValorBodega, PG.ValorSeguro, PG.ValorIva
			,PG.VrTotalBodega, PG.VrEmpaque, PG.VrServLocal
			,PG.VrServNacional, PG.VrSeguroTrans, PG.ValorTotal
			,PG.ValorSaldo, PG.PeriodoIni, PG.PeriodoFin
			,PG.DiasPago, PG.MesesPago, PG.IdFormaPago
			,PG.IdMedioPago, PG.EstadoPago, PA.ObservaPago
			,FP.Nombre as FormaPago, MP.Nombre as MedioPago, CT.IdCliente
			,CONCAT(CL.Nombres,' ',CL.Apellidos) as NombreCliente
			,CONCAT(PG.FacturaNum, '-', (SELECT CodSyscom FROM Compania WHERE IdCia = PG.CiaFactura)) AS FacturaCia
			,CONCAT(PG.ReciboNum, '-', (SELECT CodSyscom FROM Compania WHERE IdCia = PG.CiaRecibo)) AS ReciboCia
		FROM 
			[dbo].[Bodegas_Pagos] AS PG
		INNER JOIN 
			[dbo].[Bodegas_PagosAnexos] as PA ON PG.IdPago = PA.IdPago
		INNER JOIN 
			[dbo].[Formas_Pago] as FP ON PG.IdFormaPago = FP.IdFormaPago
		INNER JOIN 
			[dbo].[Metodos_Pago] as MP ON PG.IdMedioPago = MP.IdMetodosPago
		INNER JOIN 
			[dbo].[Bodegas_Contratos] as CT ON PG.IdContrato = CT.IdContrato
		INNER JOIN 
			[dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
		WHERE 
			PG.IdPago between ISNULL(@IdPago,0) and ISNULL(@IdPago,999999999) and 
			PG.IdCartera between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999) and 
			PG.IdContrato between ISNULL(@IdContrato,0) and ISNULL(@IdContrato,999999999) and 
			PG.Compania between ISNULL(@Compania,0) and ISNULL(@Compania,99) and 
			PG.ReciboNum between ISNULL(@NumRecibo,0) and ISNULL(@NumRecibo,999999999) and 
			PG.CiaRecibo between ISNULL(@CiaRecibo,0) and ISNULL(@CiaRecibo,99) and 
			PG.EstadoPago between ISNULL(@Estado,0) and ISNULL(@Estado,9) 
		ORDER BY 
			PG.IdPago DESC

	END
		
	IF @Opcion = 3 --Consulta maximo saldo
		BEGIN 
			SELECT PG.IdPago
				   ,PG.IdContrato
				   ,PG.IdCartera
				   ,PG.IdCotizacion
				   ,PG.IdCliente
				   ,PG.Compania
				   ,PG.FechaFactura
				   ,PG.HoraFactura
				   ,PG.FacturaNum
				   ,PG.CiaFactura
				   ,PG.ReciboNum
				   ,PG.CiaRecibo
				   ,PG.ValorBodega
				   ,PG.ValorSeguro
				   ,PG.ValorIva
				   ,PG.VrTotalBodega
				   ,PG.VrEmpaque
				   ,PG.VrServLocal
				   ,PG.VrServNacional
				   ,PG.VrSeguroTrans
				   ,PG.ValorTotal
				   ,PG.ValorSaldo
				   ,PG.PeriodoIni
				   ,PG.PeriodoFin
				   ,PG.DiasPago
				   ,PG.MesesPago
				   ,PG.IdFormaPago
				   ,PG.IdMedioPago
				   ,PG.EstadoPago
				   ,PA.ObservaPago
				   ,FP.Nombre as FormaPago
				   ,MP.Nombre as MedioPago
				   ,CT.IdCliente
				   ,CONCAT(CL.Nombres,' ',CL.Apellidos) as NombreCliente

			FROM [dbo].[Bodegas_Pagos] AS PG
					INNER JOIN [dbo].[Bodegas_PagosAnexos] as PA ON PG.IdPago = PA.IdPago
					INNER JOIN [dbo].[Formas_Pago] as FP ON PG.IdFormaPago = FP.IdFormaPago
					INNER JOIN [dbo].[Metodos_Pago] as MP ON PG.IdMedioPago = MP.IdMetodosPago
					INNER JOIN [dbo].[Bodegas_Contratos] as CT ON PG.IdContrato = CT.IdContrato
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente

			WHERE PG.IdCartera   between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999) and
				  PG.IdPago = (SELECT MAX(IdPago) FROM [dbo].[Bodegas_Pagos] WHERE IdCartera = @IdCartera)

		END 
			
END
GO
/****** Object:  StoredProcedure [dbo].[spGetBodPagosAnexos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	     Sergio Rendón Gómez
-- Create date:  2023-12-05
-- Description:	 Buscar Pagos Anexos
-- =============================================
CREATE PROCEDURE [dbo].[spGetBodPagosAnexos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdPago int = null,
    @IdContrato int = null,
    @IdCartera int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 -- Consulta General
		BEGIN
			SELECT PGA.IdPagoAnexo
				  ,PGA.IdPago
				  ,PGA.IdContrato
				  ,PGA.IdCartera
				  ,PGA.ObservaPago
				  ,PGA.FacturaPago
				  ,PGA.ReciboPago

			FROM [dbo].[Bodegas_PagosAnexos] as PGA
		END

	IF @Opcion = 2 -- Consulta por parametro
		BEGIN
			SELECT PGA.IdPagoAnexo
				  ,PGA.IdPago
				  ,PGA.IdContrato
				  ,PGA.IdCartera
				  ,PGA.ObservaPago
				  ,PGA.FacturaPago
				  ,PGA.ReciboPago

			FROM [dbo].[Bodegas_PagosAnexos] as PGA

			WHERE PGA.IdPago     between ISNULL(@IdPago,0) and ISNULL(@IdPago,999999999) and 
				  PGA.IdContrato between ISNULL(@IdContrato,0) and ISNULL(@IdContrato,999999999) and 
				  PGA.IdCartera between ISNULL(@IdCartera,0) and ISNULL(@IdCartera,999999999) 
		END		 
END


GO
/****** Object:  StoredProcedure [dbo].[spGetBodPeriodicidad]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 05/10/2022
-- Description:	Buscar Periodicidad
-- ==================================================
CREATE   PROCEDURE [dbo].[spGetBodPeriodicidad]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdPeriodicidad int = null

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Contratos
		BEGIN
			SELECT PR.IdPeriodicidad
				  ,PR.Nombre

			FROM [dbo].[Bodegas_Periodicidad] as PR

			
		END

	IF @Opcion = 2  -- Consula por numero de Contrato
		BEGIN
			SELECT PR.IdPeriodicidad
				  ,PR.Nombre

			FROM [dbo].[Bodegas_Periodicidad] as PR

			WHERE PR.IdPeriodicidad = @IdPeriodicidad
				  



		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetCartera]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		JUAN ANDRES MARTINEZ
-- Create date: ENERO 2023
-- Description:	Buscar Cartera
-- =============================================

CREATE   PROCEDURE [dbo].[spGetCartera] --
@Identificacion VARCHAR(20),
@Nombres VARCHAR(100),
@Contrato VARCHAR(50),
@Sucursal INT,
--@Estado VARCHAR(2),
@Desde VARCHAR(10),
@Hasta VARCHAR(10)
AS
BEGIN TRANSACTION
		BEGIN TRY
		
		DECLARE @FechaCalculo DATE = CONVERT (DATE,DATEADD(DAY,1,GETDATE()))

		--IF(@Identificacion <> '' AND @Nombres <> '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		CO.IdPeriodicidad,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.IdIPC,
		--		C.Inactivo,
		--		TP.Descripcion as TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CO.PagoInicial,
		--		CO.FechaContrato,
		--		CO.ValorTotal,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		CASE
		--			WHEN ((DATEDIFF(DAY,CONVERT(DATE, C.FechaPago),@FechaCalculo)) > 30 ) AND C.Estado <> '3'
		--			THEN ((CONVERT(INT, C.ValorCuota) * 1.5)/100)

		--			WHEN C.Estado = '3'
		--			THEN C.Intereses
		--		END AS Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CO.IdSucursal = @Sucursal AND
		--		CL.Identificacion = @Identificacion AND
		--		CL.Nombres = @Nombres 
		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE IF(@Identificacion <> '' AND @Nombres = '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		CO.IdPeriodicidad,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.IdIPC,
		--		C.Inactivo,
		--		TP.Descripcion as TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CO.PagoInicial,
		--		CO.FechaContrato,
		--		CO.ValorTotal,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		CASE
		--			WHEN ((DATEDIFF(DAY,CONVERT(DATE, C.FechaPago),@FechaCalculo)) > 30 ) AND C.Estado <> '3'
		--			THEN ((CONVERT(INT, C.ValorCuota) * 1.5)/100)

		--			WHEN C.Estado = '3'
		--			THEN C.Intereses
		--		END AS Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CO.IdSucursal = @Sucursal AND
		--		CL.Identificacion = @Identificacion
		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE IF(@Nombres <> '' AND @Identificacion = '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		CO.IdPeriodicidad,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.IdIPC,
		--		C.Inactivo,
		--		TP.Descripcion as TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CO.PagoInicial,
		--		CO.FechaContrato,
		--		CO.ValorTotal,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		CASE
		--			WHEN ((DATEDIFF(DAY,CONVERT(DATE, C.FechaPago),@FechaCalculo)) > 30 ) AND C.Estado <> '3'
		--			THEN ((CONVERT(INT, C.ValorCuota) * 1.5)/100)

		--			WHEN C.Estado = '3'
		--			THEN C.Intereses
		--		END AS Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CO.IdSucursal = @Sucursal AND
		--		CL.Nombres = @Nombres 
		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE IF(@Contrato <> '')
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		CO.IdPeriodicidad,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.IdIPC,
		--		C.Inactivo,
		--		TP.Descripcion as TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CO.PagoInicial,
		--		CO.FechaContrato,
		--		CO.ValorTotal,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		CASE
		--			WHEN ((DATEDIFF(DAY,CONVERT(DATE, C.FechaPago),@FechaCalculo)) > 30 ) AND C.Estado <> '3'
		--			THEN ((CONVERT(INT, C.ValorCuota) * 1.5)/100)

		--			WHEN C.Estado = '3'
		--			THEN C.Intereses
		--		END AS Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		CO.IdSucursal = @Sucursal AND
		--		CO.NumeroContrato = @Contrato
		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END
		--ELSE
		--BEGIN
		--	SELECT 
		--		C.IdCartera,
		--		C.FechaPago,
		--		C.HoraPago,
		--		CO.IdPeriodicidad,
		--		P.Nombre AS Periodicidad,
		--		C.Saldo,
		--		C.ValorCuota,
		--		C.PagoTotal,
		--		C.IdIPC,
		--		C.Inactivo,
		--		TP.Descripcion as TipoDocumento,
		--		CL.Identificacion,
		--		CL.Nombres AS Cliente,
		--		CO.NumeroContrato,
		--		C.IdContrato,
		--		C.NumeroFactura,
		--		C.Estado AS NumEstado,
		--		CO.PagoInicial,
		--		CO.FechaContrato,
		--		CO.ValorTotal,
		--		CASE C.Estado
		--			WHEN '1' THEN 'No Pago'
		--			WHEN '3' THEN 'Pago'
		--			ELSE '0' 
		--		END AS Estado,
		--		CASE
		--			WHEN ((DATEDIFF(DAY,CONVERT(DATE, C.FechaPago),@FechaCalculo)) > 30 ) AND C.Estado <> '3'
		--			THEN ((CONVERT(INT, C.ValorCuota) * 1.5)/100)

		--			WHEN C.Estado = '3'
		--			THEN C.Intereses
		--		END AS Intereses,
		--		C.Descuentos
		--	FROM Bod.Cartera AS C
		--	--LEFT JOIN Bod.Abonos AS A ON A.IdCartera = C.IdCartera
		--	JOIN Bod.Contratos AS CO ON C.IdContrato = CO.IdContrato
		--	JOIN Clientes AS CL ON CO.IdCliente = CL.IdCliente
		--	JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--	JOIN Bod.Periodicidad AS P ON CO.IdPeriodicidad = P.IdPeriodicidad
		--	JOIN Bod.IPC AS IPC ON C.IdIPC = IPC.IdIPC
		--	WHERE 
		--		 CO.IdSucursal = @Sucursal AND
		--		(CO.FechaInicio BETWEEN @Desde AND @Hasta)
		--	ORDER BY CO.NumeroContrato, C.IdCartera 
		--END

		COMMIT TRANSACTION
		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
GO
/****** Object:  StoredProcedure [dbo].[spGetCiudades]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 20/09/2021
-- Description:	Buscar Ciudades
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCiudades]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdCiudad Int=null,
	@CodCiudad varchar(125)=null,
	@Nombre varchar(255)=null,
	@IdDepartamento Int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
	  BEGIN
		SELECT CD.IdCiudad
			   ,CD.CodCiudad
			   ,CD.Nombre
			   ,CD.IdDepartamento
			   ,CD.CodDane
			   ,CD.Compania

		FROM  [dbo].[Ciudades] as CD,
			  [dbo].[Departamentos] as DT

		WHERE CD.IdDepartamento = DT.IdDepartamento

		ORDER BY [Nombre]
	  END

	IF @Opcion = 2 -- Consultar por Ciudad
	  BEGIN
		SELECT  CD.IdCiudad
			   ,CD.CodCiudad
			   ,CD.Nombre
			   ,CD.IdDepartamento
			   ,CD.CodDane
			   ,CD.Compania

		FROM  [dbo].[Ciudades] as CD,
			  [dbo].[Departamentos] as DT

		WHERE CD.IdCiudad = @IdCiudad and
			  CD.IdDepartamento = DT.IdDepartamento
	  END

	IF @Opcion = 3 -- Consultar por departamento
	  BEGIN
		SELECT  CD.IdCiudad
			   ,CD.CodCiudad
			   ,CD.Nombre
			   ,CD.IdDepartamento
			   ,CD.CodDane
			   ,CD.Compania

		FROM  [dbo].[Ciudades] as CD,
			  [dbo].[Departamentos] as DT

		WHERE CD.IdDepartamento = @IdDepartamento and
			  CD.IdDepartamento = DT.IdDepartamento
		
		ORDER BY [Nombre]
	  END

	IF @Opcion = 4 -- Consultar por departamento
	  BEGIN
		SELECT  CD.IdCiudad
			   ,CD.CodCiudad
			   ,CD.Nombre
			   ,CD.IdDepartamento
			   ,DT.IdPais
			   ,CD.CodDane
			   ,CD.Compania

		FROM  [dbo].[Ciudades] as CD,
			  [dbo].[Departamentos] as DT

		WHERE CD.IdCiudad = @IdCiudad and
			  CD.IdDepartamento = DT.IdDepartamento
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetClasesDoc]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio y Stefanny
-- Create date: 26/01/2022
-- Description:	Buscar clases doc
-- =============================================
CREATE   PROCEDURE [dbo].[spGetClasesDoc] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@Nombre varchar(50) = null
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
	  BEGIN 
		 SELECT IdClaseDoc
				,Nombre 
				,Descripcion 
				
		 FROM [dbo].[Clase_Doc] 

		 ORDER BY Nombre ASC

	  END

	IF @Opcion = 2 --Consulta General
	  BEGIN 
		 SELECT IdClaseDoc
				,Nombre 
				,Descripcion 
				
		 FROM [dbo].[Clase_Doc] 

		 WHERE Nombre like CONCAT('%',@Nombre,'%')

		 ORDER BY Nombre ASC

	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetClientes]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 23/09/2021
-- Description:	Buscar Clientes
-- ================================================
CREATE   PROCEDURE [dbo].[spGetClientes] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCliente int = null,
	@TipoIdent int = null,
    @Identificacion nvarchar(20) = null,
    @TipoCliente int = null,
    @Nombres varchar(125) = null,
    @Apellidos varchar(125) = null,
	@Movil varchar(20) = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los clientes
		BEGIN
			SELECT	C.IdCliente
					,C.TipoIdent
					,C.Identificacion
					,C.TipoCliente
					,C.Nombres
					,C.Apellidos
					,C.IdEmpresa
					,C.IdCiudad
					,C.Direccion
					,C.Movil
					,C.Telefono
					,C.Email
					,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,T.Nombre as NombreDcto
					,CI.Nombre as NombreCiudad
					,CONCAT(C.Nombres, ' ', C.Apellidos) as NombreCompleto
					,LEN(C.Apellidos) as CantApellido
					,CI.CodDane

			FROM  [dbo].[Clientes] as C
					LEFT JOIN [dbo].[TipoDocumentos] as T ON T.IdTipoDoc = C.TipoIdent
					LEFT JOIN [dbo].[Ciudades] as CI ON C.IdCiudad = CI.IdCiudad 
		 END

	IF @Opcion = 2 -- Consultar por Cliente
		BEGIN
			SELECT  C.IdCliente
					,C.TipoIdent
					,C.Identificacion
					,C.TipoCliente
					,C.Nombres
					,C.Apellidos
					,C.IdEmpresa
					,C.IdCiudad
					,C.Direccion
					,C.Movil
					,C.Telefono
					,C.Email
					,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,T.Nombre as NombreDcto
					,D.IdDepartamento
					,D.IdPais
					,CI.Nombre as NombreCiudad
					,CONCAT(C.Nombres, ' ', C.Apellidos) as NombreCompleto
					,LEN(C.Apellidos) as CantApellido
					,CI.CodDane
					,E.RazonSocial as NombreEmpresa
					,E.Nit

			FROM  [dbo].[Clientes] as C
					INNER JOIN [dbo].[TipoDocumentos] as T ON T.IdTipoDoc = C.TipoIdent
					INNER JOIN [dbo].[Ciudades] as CI ON C.IdCiudad = CI.IdCiudad
					INNER JOIN [dbo].[Departamentos] as D ON D.IdDepartamento = CI.IdDepartamento 
					LEFT  JOIN [dbo].[Empresas] as E ON C.IdEmpresa = E.IdEmpresa

			WHERE C.IdCliente between ISNULL(@IdCliente,C.IdCliente) and ISNULL(@IdCliente,C.IdCliente)  
				  
		END

	IF @Opcion = 3 -- Consultar por Parametro
		BEGIN
			SELECT C.IdCliente
				  ,C.TipoIdent
				  ,C.Identificacion
				  ,C.TipoCliente
				  ,C.Nombres
				  ,C.Apellidos
				  ,C.IdEmpresa
				  ,C.IdCiudad
				  ,C.Direccion
				  ,C.Movil
				  ,C.Telefono
				  ,C.Email
				  ,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
				  ,T.Nombre as NombreDcto
				  ,D.IdDepartamento
				  ,D.IdPais
				  ,CI.Nombre as NombreCiudad
				  ,CONCAT(C.Nombres, ' ', C.Apellidos) as NombreCompleto
				  ,LEN(C.Apellidos) as CantApellido
				  ,CI.CodDane

			FROM [dbo].[Clientes] as C
					INNER JOIN [dbo].[TipoDocumentos] as T ON T.IdTipoDoc = C.TipoIdent
					INNER JOIN [dbo].[Ciudades] as CI ON C.IdCiudad = CI.IdCiudad
					INNER JOIN [dbo].[Departamentos] as D ON D.IdDepartamento = CI.IdDepartamento 

			WHERE C.IdCliente      between ISNULL(@IdCliente,C.IdCliente) and ISNULL(@IdCliente,C.IdCliente) and
				  C.Nombres        like CONCAT('%',ISNULL(@Nombres,C.Nombres),'%') and 
				  C.Apellidos      like CONCAT('%',ISNULL(@Apellidos,C.Apellidos),'%') and
				  C.Identificacion between ISNULL(@Identificacion,C.Identificacion) and ISNULL(@Identificacion,C.Identificacion) and
				  C.Movil          like CONCAT('%',ISNULL(@Movil,C.Movil),'%')  
		END				
		
	IF @Opcion = 4  -- Consula cliente
		BEGIN
			SELECT	C.IdCliente
					,C.TipoIdent
					,C.Identificacion
					,C.TipoCliente
					,C.Nombres
					,C.Apellidos
					,C.IdEmpresa
					,C.IdCiudad
					,C.Direccion
					,C.Movil
					,C.Telefono
					,C.Email
					,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,T.Nombre as NombreDcto
					,D.IdDepartamento
					,D.IdPais
					,CI.Nombre as NombreCiudad
					,CONCAT(C.Nombres, ' ', C.Apellidos) as NombreCompleto
					,LEN(C.Apellidos) as CantApellido
					,CI.CodDane

			FROM  [dbo].[Clientes] as C, 
				  [dbo].[TipoDocumentos] as T,
				  [dbo].[Ciudades] as CI,
				  [dbo].[Departamentos] as D

			WHERE C.IdCliente      = @IdCliente and
				  T.IdTipoDoc      = C.TipoIdent and
				  C.IdCiudad       = CI.IdCiudad and
				  D.IdDepartamento = CI.IdDepartamento 
	 
		 END

	IF @Opcion = 5  -- Consula cliente por movil
		BEGIN
			SELECT	C.IdCliente
					,C.TipoIdent
					,C.Identificacion
					,C.TipoCliente
					,C.Nombres
					,C.Apellidos
					,C.IdEmpresa
					,C.IdCiudad
					,C.Direccion
					,C.Movil
					,C.Telefono
					,C.Email
					,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,T.Nombre as NombreDcto
					,D.IdDepartamento
					,D.IdPais
					,CI.Nombre as NombreCiudad
					,CONCAT(C.Nombres, ' ', C.Apellidos) as NombreCompleto
					,LEN(C.Apellidos) as CantApellido
					,CI.CodDane

			FROM  [dbo].[Clientes] as C, 
				  [dbo].[TipoDocumentos] as T,
				  [dbo].[Ciudades] as CI,
				  [dbo].[Departamentos] as D

			WHERE C.IdCliente      = (SELECT MAX(IdCliente) FROM [dbo].[Clientes] WHERE Movil = @Movil) and
				  T.IdTipoDoc      = C.TipoIdent and
				  C.IdCiudad       = CI.IdCiudad and
				  D.IdDepartamento = CI.IdDepartamento 
	 
		 END

	IF @Opcion = 6  -- Consula todos los clientes
		BEGIN
			SELECT TOP 200
				   C.IdCliente
				  ,C.TipoIdent
				  ,C.Identificacion
				  ,C.TipoCliente
				  ,C.Nombres
				  ,C.Apellidos
				  ,C.IdEmpresa
				  ,C.IdCiudad
				  ,C.Direccion
				  ,C.Movil
				  ,C.Telefono
				  ,C.Email
				  ,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
				  ,T.Nombre as NombreDcto
				  ,CI.Nombre as NombreCiudad
				  ,CONCAT(C.Nombres, ' ', C.Apellidos) as NombreCompleto
				  ,LEN(C.Apellidos) as CantApellido
				  ,CI.CodDane

			FROM  [dbo].[Clientes] as C
					INNER JOIN [dbo].[TipoDocumentos] as T ON T.IdTipoDoc = C.TipoIdent
					INNER JOIN [dbo].[Ciudades] as CI ON C.IdCiudad = CI.IdCiudad

			ORDER BY C.IdCliente DESC
		 END

	IF @Opcion = 7 -- Cliente por identificacion.
	BEGIN 
		SELECT 
			C.IdCliente
			,C.TipoIdent
			,C.Identificacion
			,C.TipoCliente
			,C.Nombres
			,C.Apellidos
			,C.IdEmpresa
			,C.IdCiudad
			,C.Direccion
			,C.Movil
			,C.Telefono
			,C.Email
			,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
			,T.Nombre as NombreDcto
			,D.IdDepartamento
			,D.IdPais
			,CI.Nombre as NombreCiudad
			,CONCAT(C.Nombres, ' ', C.Apellidos) as NombreCompleto
			,LEN(C.Apellidos) as CantApellido
			,CI.CodDane
		FROM 
			[dbo].[Clientes] as C
		INNER JOIN 
			[dbo].[TipoDocumentos] as T ON T.IdTipoDoc = C.TipoIdent
		INNER JOIN 
			[dbo].[Ciudades] as CI ON C.IdCiudad = CI.IdCiudad
		INNER JOIN 
			[dbo].[Departamentos] as D ON D.IdDepartamento = CI.IdDepartamento 
		WHERE 
			C.Identificacion = @Identificacion OR C.Movil = @Movil
	END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetClientesMora]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		JUAN ANDRES MARTINEZ
-- Create date: Enero 2023
-- Description:	Eliminar clientes mora
-- =============================================
CREATE   PROCEDURE [dbo].[spGetClientesMora] --
AS
BEGIN TRANSACTION
SET NOCOUNT ON;
	BEGIN TRY
		DECLARE @FechaCalculo DATE = CONVERT (DATE,DATEADD(DAY,1,GETDATE()))

		--SELECT
		--	C.IdContrato,
		--	C.IdBodega,
		--	C.IdCliente,
		--	C.NumeroContrato,
		--	TP.Descripcion AS TipoDocumento,
		--	CL.Identificacion,
		--	CL.Nombres AS Cliente,
		--	CL.Movil,
		--	CL.Telefono,
		--	CL.Email,
		--	B.ValorBodega,
		--	C.ValorDeclarado,
		--	C.ValorContrato AS ValorContrato_Mes,
		--	(
		--		SELECT 
		--			SUM(CONVERT(INT,CT.ValorCuota))
		--		FROM Bod.Cartera AS CT
		--		JOIN Bod.Contratos AS CON ON CT.IdContrato = CON.IdContrato
		--		WHERE 
		--			CON.IdContrato = C.IdContrato
		--		GROUP BY 
		--			CON.IdContrato
		--	) AS TotalCartera,
		--	(
		--		SELECT 
		--			SUM(CONVERT(INT,CT.PagoTotal))
		--		FROM Bod.Cartera AS CT
		--		JOIN Bod.Contratos AS CON ON CT.IdContrato = CON.IdContrato
		--		WHERE 
		--			CON.IdContrato = C.IdContrato
		--		GROUP BY 
		--			CON.IdContrato
		--	) AS TotalPago,
		--	(
		--		SELECT 
		--			SUM(CONVERT(INT,CT.Saldo))
		--		FROM Bod.Cartera AS CT
		--		JOIN Bod.Contratos AS CON ON CT.IdContrato = CON.IdContrato
		--		WHERE 
		--			CON.IdContrato = C.IdContrato
		--		GROUP BY 
		--			CON.IdContrato
		--	) AS TotalSaldo,
		--	(
		--		SELECT TOP 1
		--			DATEDIFF(DAY,CONVERT(DATE, CSUB.FechaPago),@FechaCalculo)
		--		FROM Bod.Cartera AS CSUB 
		--		JOIN Bod.Contratos AS CON ON CSUB.IdContrato = CON.IdContrato
		--		WHERE 
		--			DATEDIFF(DAY,CONVERT(DATE, CSUB.FechaPago),@FechaCalculo) > 30 AND
		--			CONVERT (DATE, CSUB.FechaPago) < @FechaCalculo AND
		--			CON.IdContrato = C.IdContrato AND
		--			CSUB.Estado = 1
		--	) AS DiasMora,
		--	(
		--		SELECT TOP 1
		--			DATEDIFF(MONTH,CONVERT(DATE, CSUB.FechaPago),@FechaCalculo)
		--		FROM Bod.Cartera AS CSUB 
		--		JOIN Bod.Contratos AS CON ON CSUB.IdContrato = CON.IdContrato
		--		WHERE 
		--			DATEDIFF(DAY,CONVERT(DATE, CSUB.FechaPago),@FechaCalculo) > 30 AND
		--			CONVERT (DATE, CSUB.FechaPago) < @FechaCalculo AND
		--			CON.IdContrato = C.IdContrato AND
		--			CSUB.Estado = 1
		--	) AS MesMora,
		--	(
		--		SELECT 
		--			SUM( CONVERT(INT,CSUB.Saldo) + (CONVERT(INT,CSUB.Saldo)*0.015))
		--		FROM Bod.Cartera AS CSUB 
		--		JOIN Bod.Contratos AS CON ON CSUB.IdContrato = CON.IdContrato
		--		WHERE 
		--			DATEDIFF(DAY,CONVERT(DATE, CSUB.FechaPago),@FechaCalculo) > 30 AND
		--			CONVERT (DATE, CSUB.FechaPago) < @FechaCalculo AND
		--			CON.IdContrato = C.IdContrato AND
		--			CSUB.Estado = 1
		--		GROUP BY CON.IdContrato
		--	) AS ValorMora,
		--	(
		--		SELECT TOP 1 S.FechaSeguimiento FROM Bod.Cartera_Seguimiento AS S
		--		WHERE S.IdCliente = CL.IdCliente
		--		ORDER BY S.IdSeguimiento DESC

		--	) AS FechaSeguimiento,
		--				(
		--		SELECT TOP 1 S.Observacion FROM Bod.Cartera_Seguimiento AS S
		--		WHERE S.IdCliente = CL.IdCliente
		--		ORDER BY S.IdSeguimiento DESC

		--	) AS Observacion,
		--	(
		--		SELECT TOP 1 S.Formato FROM Bod.Cartera_Seguimiento AS S
		--		WHERE S.IdCliente = CL.IdCliente
		--		ORDER BY S.IdSeguimiento DESC

		--	) AS Formatos
		--	--SUM(CONVERT(INT,CA.ValorCuota)) AS Cartera,
		--	--SUM(CONVERT(INT,CA.PagoTotal)) AS Pagado
		--FROM Bod.Cartera AS CA
		--JOIN Bod.Contratos AS C ON CA.IdContrato = C.IdContrato
		--JOIN Bodegas AS B ON C.IdBodega = B.IdBodega
		--JOIN Clientes AS CL ON C.IdCliente = CL.IdCliente
		--JOIN TipoDocumentos AS TP ON CL.TipoIdent = TP.IdTipoDoc
		--WHERE
		--	DATEDIFF(DAY,CONVERT(DATE, CA.FechaPago),@FechaCalculo) > 30 AND
		--	CONVERT (DATE, CA.FechaPago) < @FechaCalculo AND
		--	CA.Estado = 1
		--GROUP BY 
		--	C.IdContrato,
		--	C.NumeroContrato,
		--	C.IdCliente,
		--	C.IdBodega,
		--	TP.Descripcion,
		--	CL.Identificacion,
		--	CL.Nombres,
		--	CL.Movil,
		--	CL.Telefono,
		--	B.ValorBodega,
		--	C.ValorDeclarado,
		--	C.ValorContrato,
		--	CL.Email,
		--	B.Nombre,
		--	CL.IdCliente
		COMMIT TRANSACTION
	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
GO
/****** Object:  StoredProcedure [dbo].[spGetCompanias]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 11/04/20222
-- Description:	Buscar Compañias
-- ================================================
CREATE   PROCEDURE [dbo].[spGetCompanias]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdCia Int=null,
	@NombreCia varchar(50)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos las Sucursales
		BEGIN
			SELECT CIA.IdCia
				  ,CIA.NombreCia
				  ,CIA.Sucursal
				  ,CIA.Direccion
				  ,CIA.Telefono
				  ,CIA.IdCiudad
				  ,CIA.Estado
				  ,CIA.CodSyscom
				  ,CID.Nombre

			FROM [dbo].[Compania] as CIA
					INNER JOIN [dbo].[Ciudades] as CID ON CIA.IdCiudad = CID.IdCiudad

			WHERE CIA.Estado = 'A'
		END

	IF @Opcion = 2  -- Consular por nombre
		BEGIN
			SELECT CIA.IdCia
				  ,CIA.NombreCia
				  ,CIA.Sucursal
				  ,CIA.Direccion
				  ,CIA.Telefono
				  ,CIA.IdCiudad
				  ,CIA.Estado
				  ,CIA.CodSyscom
				  ,CID.Nombre

			FROM [dbo].[Compania] as CIA
					INNER JOIN [dbo].[Ciudades] as CID ON CIA.IdCiudad = CID.IdCiudad

			WHERE LOWER(CIA.NombreCia) = LOWER(@NombreCia)and
			      CIA.Estado = 'A'
		END

	IF @Opcion = 3  -- Consula por id
		BEGIN
			SELECT CIA.IdCia
				  ,CIA.NombreCia
				  ,CIA.Sucursal
				  ,CIA.Direccion
				  ,CIA.Telefono
				  ,CIA.IdCiudad
				  ,CIA.Estado
				  ,CIA.CodSyscom
				  ,CID.Nombre

			FROM [dbo].[Compania] as CIA
					INNER JOIN [dbo].[Ciudades] as CID ON CIA.IdCiudad = CID.IdCiudad and CIA.Estado = 'A'

			WHERE CIA.IdCia  = @IdCia
		END
END

GO
/****** Object:  StoredProcedure [dbo].[spGetConceptos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 09/02/2022
-- Description:	Buscar Conceptos
-- =============================================
CREATE   PROCEDURE [dbo].[spGetConceptos]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdConceptoServ Int=null,
	@CodSyscom varchar(4)=null,
    @Concepto varchar(250)=null,
    @Grupo varchar(20)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT  CS.IdConceptoServ
				   ,CS.CodSyscom
				   ,CS.Concepto COLLATE Cyrillic_General_CI_AI as Concepto
				   ,CS.Grupo
				   ,CS.Valor
				   ,CS.Porc_Descuento
				   ,CS.IdConceptoPDF
				   ,CS.ValorIva
				   ,CS.ClaseConcepto
				   ,CS.RubroConcepto
			   
			FROM  [dbo].[Concepto_Servicios] as CS

			WHERE CS.ClaseConcepto = '1'

			ORDER BY CS.Concepto ASC
		END

	IF @Opcion = 2 -- Consultar por Tipo
		BEGIN
			SELECT CS.IdConceptoServ
				   ,CS.CodSyscom
				   ,CS.Concepto COLLATE Cyrillic_General_CI_AI as Concepto
				   ,CS.Grupo
				   ,CS.Valor
				   ,CS.Porc_Descuento
				   ,CS.IdConceptoPDF
				   ,CS.ValorIva
				   ,CS.ClaseConcepto
				   ,CS.RubroConcepto
			   
			FROM  [dbo].[Concepto_Servicios] as CS

			WHERE CS.IdConceptoServ = @IdConceptoServ and
				  CS.ClaseConcepto = '1'

			ORDER BY CS.Concepto ASC
		END

	IF @Opcion = 3 -- Consultar por Parametro
		BEGIN
			IF @CodSyscom IS NOT NULL 
				BEGIN
					SELECT  CS.IdConceptoServ
							,CS.CodSyscom
							,CS.Concepto COLLATE Cyrillic_General_CI_AI as Concepto
							,CS.Grupo
							,CS.Valor
							,CS.Porc_Descuento
							,CS.IdConceptoPDF
							,CS.ValorIva
							,CS.ClaseConcepto
							,CS.RubroConcepto

					FROM  [dbo].[Concepto_Servicios] as CS

					WHERE CS.CodSyscom like CONCAT('%',@CodSyscom,'%') and
						  CS.ClaseConcepto = '1'

					ORDER BY CS.Concepto ASC
				END

			IF @CodSyscom IS NULL 
				BEGIN
					SELECT  CS.IdConceptoServ
							,CS.CodSyscom
							,CS.Concepto COLLATE Cyrillic_General_CI_AI as Concepto
							,CS.Grupo
							,CS.Valor
							,CS.Porc_Descuento
							,CS.IdConceptoPDF
							,CS.ValorIva
							,CS.ClaseConcepto
							,CS.RubroConcepto
					
					FROM  [dbo].[Concepto_Servicios] as CS

					WHERE CS.CodSyscom like CONCAT('%',@CodSyscom,'%') and
						  CS.ClaseConcepto = '1'

					ORDER BY CS.Concepto ASC
				END
		END
	
	IF @Opcion = 4 -- Contar Conceptos
		BEGIN
			SELECT COUNT(*) FROM [dbo].[Concepto_Servicios]
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetConductores]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 04/04/2022
-- Description:	Buscar Conductores
-- ===============================================
CREATE   PROCEDURE [dbo].[spGetConductores] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdConductor int = null,
	@Nombres varchar(125) = null,
	@Apellidos varchar(125) = null,
	@Identificacion varchar(20) = null,
	@Estado varchar(1) = null,
	@TipoConductor int = null,
	@Inactivos BIT = 0,
	@IncluirInactivos BIT = 0
as
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT CD.IdConductor,
				   CD.TipoIdent,
				   CD.Identificacion,
				   CD.Nombres COLLATE Cyrillic_General_CI_AI as Nombres, 
				   CD.Apellidos COLLATE Cyrillic_General_CI_AI as Apellidos, 
				   CD.IdCiudad,
				   CD.Direccion, 
				   CD.Telefono,
				   CD.Movil,
				   CD.Email COLLATE Cyrillic_General_CI_AI as Email,
				   CD.Estado,
				   CD.Liquidacion,
				   CD.IdVehiculo,
				   CD.IdCia,
				   CD.TipoConductor,
				   CONCAT(CD.Nombres, ' ', CD.Apellidos) COLLATE Cyrillic_General_CI_AI as NombreCompleto,
				   TDoc.Nombre as TipDoc,
				   Ciu.Nombre COLLATE Cyrillic_General_CI_AI as Ciudad,
				   Veh.Placa,
				   Dep.IdDepartamento,
				   Dep.IdPais,
				   Cia.NombreCia,
				   TC.Descripcion

			FROM [dbo].[Conductores] as CD
					 LEFT JOIN [dbo].[TipoDocumentos] as TDoc ON CD.TipoIdent = TDoc.IdTipoDoc
					 LEFT JOIN [dbo].[Ciudades] as Ciu ON CD.IdCiudad = Ciu.IdCiudad
					 LEFT JOIN [dbo].[Departamentos] as Dep ON Dep.IdDepartamento = Ciu.IdDepartamento
					 LEFT JOIN [dbo].[Vehiculos] as Veh ON CD.IdConductor = Veh.IdConductor
					 LEFT JOIN [dbo].[Compania] as Cia ON CD.IdCia = Cia.IdCia
					 LEFT JOIN [dbo].[Tipo_Conductor] as TC ON CD.TipoConductor = TC.IdTipoConductor

			WHERE CD.Estado between ISNULL(@Estado,CD.Estado) and ISNULL(@Estado,CD.Estado) 
		END

	IF @Opcion = 2 --Consulta por Conductor
		BEGIN 
			SELECT CD.IdConductor,
				   CD.TipoIdent,
				   CD.Identificacion,
				   CD.Nombres COLLATE Cyrillic_General_CI_AI as Nombres, 
				   CD.Apellidos COLLATE Cyrillic_General_CI_AI as Apellidos,
				   CD.IdCiudad,
				   CD.Direccion,
				   CD.Telefono,
				   CD.Movil,
				   CD.Email COLLATE Cyrillic_General_CI_AI as Email,
				   CD.Estado,
				   CD.Liquidacion,
				   CD.IdVehiculo,
				   CD.IdCia,
				   CD.TipoConductor,
				   CONCAT(CD.Nombres, ' ', CD.Apellidos) COLLATE Cyrillic_General_CI_AI as NombreCompleto,
				   TDoc.Nombre as TipDoc,
				   Ciu.Nombre COLLATE Cyrillic_General_CI_AI as Ciudad,
				   Veh.Placa,
				   Dep.IdDepartamento,
				   Dep.IdPais,
				   Cia.NombreCia,
				   TC.Descripcion

			 FROM [dbo].[Conductores] as CD
					 LEFT JOIN [dbo].[TipoDocumentos] as TDoc ON CD.TipoIdent = TDoc.IdTipoDoc
					 LEFT JOIN [dbo].[Ciudades] as Ciu ON CD.IdCiudad = Ciu.IdCiudad
					 LEFT JOIN [dbo].[Departamentos] as Dep ON Dep.IdDepartamento = Ciu.IdDepartamento
					 LEFT JOIN [dbo].[Vehiculos] as Veh ON CD.IdConductor = Veh.IdConductor
					 LEFT JOIN [dbo].[Compania] as Cia ON CD.IdCia = Cia.IdCia
					 LEFT JOIN [dbo].[Tipo_Conductor] as TC ON CD.TipoConductor = TC.IdTipoConductor

			 WHERE CD.IdConductor    between ISNULL(@IdConductor,CD.IdConductor) and ISNULL(@IdConductor,CD.IdConductor) and
				   CD.Nombres        like CONCAT('%',ISNULL(@Nombres,CD.Nombres),'%') and 
				   CD.Apellidos      like CONCAT('%',ISNULL(@Apellidos,CD.Apellidos),'%') and
				   CD.Identificacion between ISNULL(@Identificacion,CD.Identificacion) and ISNULL(@Identificacion,CD.Identificacion) and
				   CD.Estado         between ISNULL(@Estado,CD.Estado) and ISNULL(@Estado,CD.Estado) 
		END

	IF @Opcion = 3 --Consulta por identificacion
	BEGIN 
		SELECT 
			CD.IdConductor,
			CD.TipoIdent,
			CD.Identificacion,
			CD.Nombres COLLATE Cyrillic_General_CI_AI as Nombres, 
			CD.Apellidos COLLATE Cyrillic_General_CI_AI as Apellidos,
			CD.IdCiudad,
			CD.Direccion,
			CD.Telefono,
			CD.Movil,
			CD.Email COLLATE Cyrillic_General_CI_AI as Email,
			CD.Estado,
			CD.Liquidacion,
			CD.IdVehiculo,
			CD.IdCia,
			CD.TipoConductor,
			CONCAT(CD.Nombres, ' ', CD.Apellidos) COLLATE Cyrillic_General_CI_AI as NombreCompleto,
			TDoc.Nombre as TipDoc,
			Ciu.Nombre COLLATE Cyrillic_General_CI_AI as Ciudad,
			Veh.Placa,
			Dep.IdDepartamento,
			Dep.IdPais,
			Cia.NombreCia,
			TC.Descripcion
		FROM 
			[dbo].[Conductores] as CD
		LEFT JOIN 
			[dbo].[TipoDocumentos] as TDoc ON CD.TipoIdent = TDoc.IdTipoDoc
		LEFT JOIN	
			[dbo].[Ciudades] as Ciu ON CD.IdCiudad = Ciu.IdCiudad
		LEFT JOIN 
			[dbo].[Departamentos] as Dep ON Dep.IdDepartamento = Ciu.IdDepartamento
		LEFT JOIN 
			[dbo].[Vehiculos] as Veh ON CD.IdConductor = Veh.IdConductor
		LEFT JOIN 
			[dbo].[Compania] as Cia ON CD.IdCia = Cia.IdCia
		LEFT JOIN 
			[dbo].[Tipo_Conductor] as TC ON CD.TipoConductor = TC.IdTipoConductor
		WHERE 
			(@Nombres IS NULL OR CD.Nombres LIKE CONCAT(@Nombres, '%'))
			AND (@Apellidos IS NULL OR CD.Apellidos LIKE CONCAT(@Apellidos, '%'))
			AND (@Identificacion IS NULL OR CD.Identificacion LIKE CONCAT(@Identificacion, '%'))
			-- AND (@Estado IS NULL OR CD.Estado = @Estado)
			AND (@TipoConductor IS NULL OR CD.TipoConductor = @TipoConductor)
			AND (
				(@Inactivos = 0 AND @IncluirInactivos = 0 AND CD.Estado = 'A') 
				OR (@Inactivos = 1 AND CD.Estado = 'I')
				OR (@IncluirInactivos = 1 AND CD.Estado IN ('A', 'I'))
			)
	END

	IF @Opcion = 4 --Consulta General
		BEGIN 
			SELECT CD.IdConductor,
				   CD.TipoIdent,
				   CD.Identificacion,
				   CD.Nombres, 
				   CD.Apellidos, 
				   CD.IdCiudad,
				   CD.Direccion, 
				   CD.Telefono,
				   CD.Movil,
				   CD.Email COLLATE Cyrillic_General_CI_AI as Email,
				   CD.Estado,
				   CD.Liquidacion,
				   CD.IdVehiculo,
				   CD.IdCia,
				   CD.TipoConductor

			FROM [dbo].[Conductores] as CD
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetCotArticulos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 11/02/2022
-- Description:	Buscar Articulos por Cotizaicon
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCotArticulos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCot_Articulo int = null,
	@IdCotizacion int = null,
	@IdArticulo int = null,
	@IdSolicitud Int = null
   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT AR.IdCot_Articulo
				  ,AR.IdCotizacion
				  ,AR.IdArticulo
				  ,AR.Nombre
				  ,AR.Descripcion
				  ,AR.Cantidad
				  ,AR.IdSolicitud
				  ,AR.Ctrl_Empaque
				  ,AR.Material

			FROM [dbo].[Cotizacion_Articulos] as AR
	  END

	IF @Opcion = 2 -- Consultar por Cotizacion
		BEGIN
			IF @IdSolicitud IS NULL
				BEGIN
					SELECT AR.IdCot_Articulo
						  ,AR.IdCotizacion
						  ,AR.IdArticulo
						  ,AR.Nombre
						  ,AR.Descripcion
						  ,AR.Cantidad
						  ,AR.IdSolicitud
						  ,AR.Ctrl_Empaque
						  ,AR.Material

					FROM [dbo].[Cotizacion_Articulos] as AR
			
					WHERE AR.IdCotizacion = @IdCotizacion 
				END

			IF @IdSolicitud IS NOT NULL
				BEGIN
					SELECT AR.IdCot_Articulo
						  ,AR.IdCotizacion
						  ,AR.IdArticulo
						  ,AR.Nombre
						  ,AR.Descripcion
						  ,AR.Cantidad
						  ,AR.IdSolicitud
						  ,AR.Ctrl_Empaque
						  ,AR.Material

					FROM [dbo].[Cotizacion_Articulos] as AR
			
					WHERE AR.IdCotizacion = @IdCotizacion and
						  AR.IdSolicitud = @IdSolicitud
				END
		END

	IF @Opcion = 3 -- Consultar articulos para empacar
		BEGIN
			SELECT AR.IdCot_Articulo
				  ,AR.IdCotizacion
				  ,AR.IdArticulo
				  ,AR.Nombre
				  ,AR.Descripcion
				  ,AR.Cantidad
				  ,AR.IdSolicitud
				  ,AR.Ctrl_Empaque
				  ,AR.Material

			FROM  [dbo].[Cotizacion_Articulos] as AR
			INNER JOIN [dbo].[Cotizacion_MaterialesArticulo] as MA ON MA.IdCot_Articulo = AR.IdCot_Articulo

			WHERE MA.IdCotizacion = @IdCotizacion  
			  
		END

	IF @Opcion = 4 -- Consultar por Cotizacion y Articulo
		BEGIN
			SELECT AR.IdCot_Articulo
				  ,AR.IdCotizacion
				  ,AR.IdArticulo
				  ,AR.Nombre
				  ,AR.Descripcion
				  ,AR.Cantidad
				  ,AR.IdSolicitud
				  ,AR.Ctrl_Empaque
				  ,AR.Material

			FROM [dbo].[Cotizacion_Articulos] as AR
			
			WHERE AR.IdCotizacion = @IdCotizacion and
				  AR.IdArticulo = @IdArticulo
		END

	IF @Opcion = 5 -- Consultar por Cotizacion, Articulo y Solicitud
		BEGIN
			SELECT AR.IdCot_Articulo
				  ,AR.IdCotizacion
				  ,AR.IdArticulo
				  ,AR.Nombre
				  ,AR.Descripcion
				  ,AR.Cantidad
				  ,AR.IdSolicitud
				  ,AR.Ctrl_Empaque
				  ,AR.Material

			FROM [dbo].[Cotizacion_Articulos] as AR
			
			WHERE AR.IdCotizacion = @IdCotizacion and
				  AR.IdArticulo = @IdArticulo and
				  AR.IdSolicitud = @IdSolicitud
		END

	IF @Opcion = 6 -- Consultar articulos para empacar sin repetir
		BEGIN
			SELECT DISTINCT AR.IdArticulo
				  ,AR.IdCot_Articulo
				  ,AR.IdCotizacion
				  ,AR.Nombre
				  ,AR.Descripcion
				  ,AR.Cantidad
				  ,AR.IdSolicitud
				  ,AR.Ctrl_Empaque
				  ,AR.Material

			FROM  [dbo].[Cotizacion_Articulos] as AR
					INNER JOIN [dbo].[Cotizacion_MaterialesArticulo] as MA ON MA.IdCot_Articulo = AR.IdCot_Articulo

			WHERE MA.IdCotizacion = @IdCotizacion  
			  
		END

	IF @Opcion = 7 -- Consultar por Cotizacion
		BEGIN
			SELECT AR.IdCot_Articulo
				  ,AR.IdCotizacion
				  ,AR.IdArticulo
				  ,AR.Nombre
				  ,AR.Descripcion
				  ,AR.Cantidad
				  ,AR.IdSolicitud
				  ,AR.Ctrl_Empaque
				  ,AR.Material

			FROM [dbo].[Cotizacion_Articulos] as AR
			
			WHERE AR.IdCotizacion = @IdCotizacion and
				  AR.IdSolicitud  = @IdSolicitud and
				  AR.Ctrl_Empaque = 0 
		END

	IF @Opcion = 8 -- Consultar por Cotizacion
		BEGIN
			SELECT DISTINCT TA.Descripcion
				  ,TA.CodSyscom
				  ,COUNT(CA.IdCotizacion) as Cantidad

				  ,CASE WHEN TA.Descripcion = 'MUDANZA'
					THEN (SELECT  VL.Peso 
							FROM [dbo].[Cotizacion] as CT
								INNER JOIN [dbo].[Tipo_Volumen] as VL ON CT.Volumen = VL.IdTipoVolumen
							WHERE IdCotizacion = @IdCotizacion)
					ELSE TA.PesoTipo
				   END as PesoTipo

			FROM [dbo].[Cotizacion_Articulos] as CA
					INNER JOIN [dbo].[Articulos] as AR ON CA.IdArticulo = AR.IdArticulo
					INNER JOIN [dbo].[Tipo_Articulos] as TA ON AR.IdTipoArticulo = TA.IdTipoArticulo

			WHERE IdCotizacion = @IdCotizacion

			GROUP BY TA.Descripcion
					,TA.CodSyscom
					,TA.PesoTipo
					,CA.IdCotizacion
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetCotBodegas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 07/03/2022
-- Description:	Buscar cotizacion Bodegas
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCotBodegas] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCot_Bodega int = null,
	@IdCotizacion int = null,
	@IdSolicitud int = null,
	@IdBodega int = null,
	@IdSucursal int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statementB.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 --Consulta General
		BEGIN 
			SELECT BDG.IdCot_Bodega
				   ,BDG.IdCotizacion
				   ,BDG.IdBodega
				   ,BDG.IdSucursal
				   ,BDG.Nombre 
				   ,BDG.Capacidad 
				   ,BDG.Ocupacion
				   ,BDG.Disponible
				   ,BDG.Largo 
				   ,BDG.Ancho 
				   ,BDG.Alto
				   ,BDG.Estado 
				   ,BDG.CodSyscom
				   ,BDG.ValorBodega
				   ,CASE BDG.Estado
						WHEN '1' THEN 'ACTIVA'
						WHEN '2' THEN 'RESEVADA'
						WHEN '3' THEN 'OCUPADA'
						WHEN '4' THEN 'INACTIVA'
						ELSE '0' 
					END AS EstadoBodega
				   ,SUC.Nombre as NombreSucursal
		
			FROM [dbo].[Cotizacion_Bodegas] as BDG,
				 [dbo].[Sucursales] as SUC

			WHERE BDG.IdSucursal = SUC.IdSucursal
		END

	IF @Opcion = 2 --Consulta por cotizacion-Bodega
		BEGIN 
			SELECT BDG.IdCot_Bodega
				   ,BDG.IdCotizacion
				   ,BDG.IdBodega
				   ,BDG.IdSucursal
				   ,BDG.Nombre 
				   ,BDG.Capacidad 
				   ,BDG.Ocupacion
				   ,BDG.Disponible
				   ,BDG.Largo 
				   ,BDG.Ancho 
				   ,BDG.Alto
				   ,BDG.Estado 
				   ,BDG.CodSyscom 
				   ,BDG.ValorBodega
				   ,CASE BDG.Estado
						WHEN '1' THEN 'ACTIVA'
						WHEN '2' THEN 'RESEVADA'
						WHEN '3' THEN 'OCUPADA'
						WHEN '4' THEN 'INACTIVA'
						ELSE '0' 
					END AS EstadoBodega
				   ,SUC.Nombre as NombreSucursal

			 FROM [dbo].[Cotizacion_Bodegas] as BDG,
				  [dbo].[Sucursales] as SUC

			 WHERE BDG.IdCot_Bodega = @IdCot_Bodega AND
				   BDG.IdSucursal   = SUC.IdSucursal
		END

	IF @Opcion = 3 --Consulta por Cotizacion y Bodega
		BEGIN 
			SELECT BDG.IdCot_Bodega
				   ,BDG.IdCotizacion
				   ,BDG.IdBodega
				   ,BDG.IdSucursal
				   ,BDG.Nombre 
				   ,BDG.Capacidad 
				   ,BDG.Ocupacion
				   ,BDG.Disponible
				   ,BDG.Largo 
				   ,BDG.Ancho 
				   ,BDG.Alto
				   ,BDG.Estado  
				   ,BDG.CodSyscom
				   ,BDG.ValorBodega
				   ,CASE BDG.Estado
						WHEN '1' THEN 'ACTIVA'
						WHEN '2' THEN 'RESEVADA'
						WHEN '3' THEN 'OCUPADA'
						WHEN '4' THEN 'INACTIVA'
						ELSE '0' 
					END AS EstadoBodega
				   ,SUC.Nombre as NombreSucursal

			FROM [dbo].[Cotizacion_Bodegas] as BDG,
				 [dbo].[Sucursales] as SUC

			WHERE BDG.IdCotizacion = @IdCotizacion AND
				  BDG.IdBodega     = @IdBodega AND
				  BDG.IdSucursal   = SUC.IdSucursal
		END

	IF @Opcion = 4 --Consulta por Cotizacion y Solicitud
		BEGIN 
			SELECT BDG.IdCot_Bodega
				  ,BDG.IdCotizacion
				  ,BDG.IdBodega
				  ,BDG.IdSucursal
				  ,BDG.Nombre 
				  ,BDG.Capacidad 
				  ,BDG.Ocupacion
				  ,BDG.Disponible
				  ,BDG.Largo 
				  ,BDG.Ancho 
				  ,BDG.Alto
				  ,BDG.Estado  
				  ,BDG.CodSyscom
				  ,BDG.ValorBodega
				  ,CASE BDG.Estado
					WHEN '1' THEN 'ACTIVA'
					WHEN '2' THEN 'RESEVADA'
					WHEN '3' THEN 'OCUPADA'
					WHEN '4' THEN 'INACTIVA'
					ELSE '0' 
			  	   END AS EstadoBodega
				  ,SUC.Nombre as NombreSucursal

			FROM [dbo].[Cotizacion_Bodegas] as BDG
					INNER JOIN [dbo].[Sucursales] as SUC ON BDG.IdSucursal   = SUC.IdSucursal

			WHERE BDG.IdCotizacion between ISNULL(@IdCotizacion,BDG.IdCotizacion) and ISNULL(@IdCotizacion,BDG.IdCotizacion) and 
				  BDG.IdSolicitud  between ISNULL(@IdSolicitud,BDG.IdSolicitud) and ISNULL(@IdSolicitud,BDG.IdSolicitud) 
		END

	IF @Opcion = 5 --Totales por almacenamiento
		BEGIN 
			SELECT BDG.IdCotizacion, sum(BDG.ValorBodega) as ValorTotal,  BDG.IdSolicitud
			FROM [dbo].[Cotizacion_Bodegas] as BDG
			WHERE BDG.IdCotizacion = @IdCotizacion
			GROUP BY BDG.IdCotizacion, BDG.IdSolicitud
		END

	IF @Opcion = 6 --Recalcular Totales por almacenamiento
		BEGIN 
			DECLARE 
			@ValorTotal numeric(18,0) = null,
			@ValorIva numeric(18,0) = null,
			@IvaTotal numeric(18,0) = null,
			@CttTotal numeric(18,0) = null
			
			SELECT @ValorTotal = sum(BDG.ValorBodega), @ValorIva = ((sum(BDG.ValorBodega))*0.19)
			FROM [dbo].[Cotizacion_Bodegas] as BDG
			WHERE BDG.IdCotizacion = @IdCotizacion

			SELECT @IvaTotal = ((sum(CTT.ValorContrato + CTT.ValorPoliza))*0.19)
			FROM [dbo].[Bodegas_Contratos] as CTT
			WHERE CTT.IdCotizacion = @IdCotizacion
			
			UPDATE [dbo].[Cotizacion_Conceptos] SET Valor_Negociado = @ValorTotal, Valor_Iva = @ValorIva WHERE IdCotizacion = @IdCotizacion and IdServicio = 17
			UPDATE [dbo].[Bodegas_Contratos] SET ValorContrato   = @ValorTotal WHERE IdCotizacion = @IdCotizacion
			
			SELECT @IvaTotal = ((sum(CTT.ValorContrato + CTT.ValorPoliza))*0.19), @CttTotal =  sum(CTT.ValorContrato + CTT.ValorPoliza + ((CTT.ValorContrato + CTT.ValorPoliza)*0.19))
			FROM [dbo].[Bodegas_Contratos] as CTT
			WHERE CTT.IdCotizacion = @IdCotizacion

			UPDATE [dbo].[Bodegas_Contratos] SET ValorIVA = @IvaTotal, ValorTotal = @CttTotal WHERE IdCotizacion = @IdCotizacion
		END
END


GO
/****** Object:  StoredProcedure [dbo].[spGetCotConceptos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 11/02/2022
-- Description:	Buscar Conceptos por Cotizaicon
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCotConceptos]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdServicioCot int = null,
	@IdCotizacion int = null,
	@IdServicio int = null,
	@IdSolicitud int = null   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT CC.IdServicioCot
				  ,CC.IdCotizacion
				  ,CC.IdServicio
				  ,CC.CodSyscom
				  ,CC.Nombre
				  ,CC.Descripcion
				  ,CC.Valor_Servicio
				  ,CC.Valor_Negociado
				  ,CC.IdAsesor
				  ,CC.Valor_Iva
				  ,US.Identificacion
				  ,CS.IdConceptoPDF
				  ,CS.RubroConcepto
				  ,CC.Valor_Negociado + CC.Valor_Iva as Total

			FROM [dbo].[Cotizacion_Conceptos] as CC,
				 [dbo].[Usuarios] as US,
				 [dbo].[Concepto_Servicios] as CS
			
			WHERE CC.IdAsesor  = US.IdUsuario AND
				  CC.CodSyscom = CS.CodSyscom 
	  END

	IF @Opcion = 2 -- Consultar por Cotizacion
	BEGIN
		SELECT 
			CC.IdServicioCot,
			CC.IdCotizacion,
			CC.IdServicio,
			CC.CodSyscom,
			CC.Nombre,
			CC.Descripcion,
			CC.Valor_Servicio,
			CC.Valor_Negociado,
			CC.IdAsesor,
			CC.Valor_Iva,
			US.Identificacion,
			CS.IdConceptoPDF,
			CS.RubroConcepto,
			CS.ValorIva as TarifaIva,
			CC.Valor_Negociado + CC.Valor_Iva as Total
		FROM 
			[dbo].[Cotizacion_Conceptos] as CC
		INNER JOIN 
			[dbo].[Usuarios] as US 
			ON CC.IdAsesor = US.IdUsuario
		INNER JOIN 
			[dbo].[Concepto_Servicios] as CS 
			ON CC.CodSyscom = CS.CodSyscom
		WHERE 
			CC.IdCotizacion between ISNULL(@IdCotizacion,CC.IdCotizacion) and ISNULL(@IdCotizacion,CC.IdCotizacion) 
			and CC.IdSolicitud  between ISNULL(@IdSolicitud,CC.IdSolicitud) and ISNULL(@IdSolicitud,CC.IdSolicitud) 
	END

	IF @Opcion = 3  -- Consula todos los Tipo para Contratos Bodega
	BEGIN
		SELECT 
			CC.IdServicioCot,
			CC.IdCotizacion,
			CC.IdServicio,
			CC.CodSyscom,
			CC.Nombre,
			CC.Descripcion,
			CC.Valor_Servicio,
			CC.Valor_Negociado,
			CC.IdAsesor,
			CC.Valor_Iva,
			US.Identificacion,
			CS.IdConceptoPDF,
			CS.RubroConcepto,
			CS.ValorIva as TarifaIva
		FROM 
			[dbo].[Cotizacion_Conceptos] as CC,
			[dbo].[Usuarios] as US,
			[dbo].[Concepto_Servicios] as CS
		WHERE 
			CC.IdCotizacion  = @IdCotizacion 
			AND CC.IdConceptoPDF = 4 
			AND CC.IdAsesor = US.IdUsuario 
			AND CC.CodSyscom     = CS.CodSyscom 
	END

	IF @Opcion = 5  -- Consula todos conceptos informe Ventas
		BEGIN
			SELECT CC.IdServicioCot
				  ,CC.IdCotizacion
				  ,CC.IdServicio
				  ,CC.CodSyscom
				  ,CC.Nombre
				  ,CC.Descripcion
				  ,CC.Valor_Servicio
				  ,CC.Valor_Negociado
				  ,CC.IdAsesor
				  ,CC.Valor_Iva
				  
				  ,US.Identificacion

				  --COTIZACION


			FROM [dbo].[Cotizacion_Conceptos] as CC
					INNER JOIN  [dbo].[Cotizacion] as CT ON CT.IdCotizacion = CC.IdCotizacion
					INNER JOIN [dbo].[Usuarios] as US ON CC.IdAsesor = US.IdUsuario
			
			--WHERE CC.IdCotizacion  = @IdCotizacion AND
				  
	  END

	-- Obtener conceptos de almacenamiento obligatorios.
	IF @Opcion = 6
	BEGIN 
		SELECT 
			* 
		FROM 
			Concepto_Servicios 
		WHERE 
			IdConceptoServ IN (17, 18)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetCotDocumentos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 16/05/2024
-- Description:	Buscar Documento por Cotizacion
-- =============================================
CREATE PROCEDURE [dbo].[spGetCotDocumentos] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCotDocumento int = null,
	@IdCotizacion int = null,
	@IdSolicitud Int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Dctos
		BEGIN
			SELECT CD.IdCotDocumento
				  ,CD.IdCotizacion
				  ,CD.IdSolicitud
				  ,CD.FechaDcto
				  ,CD.Documento

			FROM [dbo].[Cotizacion_Documentos]as CD
		END

	IF @Opcion = 2  -- Consula por parametro
		BEGIN
			SELECT CD.IdCotDocumento
				  ,CD.IdCotizacion
				  ,CD.IdSolicitud
				  ,CD.FechaDcto
				  ,CD.Documento

			FROM  [dbo].[Cotizacion_Documentos]as CD

			WHERE CD.IdCotDocumento between ISNULL(@IdCotDocumento,CD.IdCotDocumento) and ISNULL(@IdCotDocumento,CD.IdCotDocumento) and 
				  CD.IdCotizacion   between ISNULL(@IdCotizacion,CD.IdCotizacion) and ISNULL(@IdCotizacion,CD.IdCotizacion) and 
				  CD.IdSolicitud    between ISNULL(@IdSolicitud,CD.IdSolicitud) and ISNULL(@IdSolicitud,CD.IdSolicitud) 
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetCotEmpaques]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 26/04/2022
-- Description:	Buscar Empaques por Cotizaicon
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCotEmpaques]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCot_Empaque int = null,
	@IdCotizacion int = null,
	@IdMaterial int = null,
	@IdSolicitud int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
		BEGIN
			SELECT EM.IdCot_Empaque
				  ,EM.IdCotizacion
				  ,EM.IdMaterial
				  ,EM.ValorCosto
				  ,EM.Cantidad
				  ,EM.IdSolicitud
				  ,MT.Nombre COLLATE Cyrillic_General_CI_AI as NombreMaterial

			FROM [dbo].[Cotizacion_Empaques] as EM,
				 [dbo].[Materiales] as MT

			WHERE EM.IdMaterial = MT.IdMaterial
	  END

	IF @Opcion = 2 -- Consultar por Cotizacion
		BEGIN
			SELECT EM.IdCot_Empaque
				  ,EM.IdCotizacion
				  ,EM.IdMaterial
				  ,EM.ValorCosto
				  ,EM.Cantidad
				  ,EM.IdSolicitud
				  ,MT.Nombre COLLATE Cyrillic_General_CI_AI as NombreMaterial

			FROM [dbo].[Cotizacion_Empaques] as EM
					INNER JOIN [dbo].[Materiales] as MT ON EM.IdMaterial = MT.IdMaterial
			
			WHERE EM.IdCot_Empaque between ISNULL(@IdCot_Empaque,EM.IdCot_Empaque) and ISNULL(@IdCot_Empaque,EM.IdCot_Empaque) and
				  EM.IdCotizacion  between ISNULL(@IdCotizacion,EM.IdCotizacion) and ISNULL(@IdCotizacion,EM.IdCotizacion) and 
			      EM.IdMaterial    between ISNULL(@IdMaterial,EM.IdMaterial) and ISNULL(@IdMaterial,EM.IdMaterial) and
				  EM.IdSolicitud   between ISNULL(@IdSolicitud,EM.IdSolicitud) and ISNULL(@IdSolicitud,EM.IdSolicitud)
		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetCotizaciones]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- ALTER date: 05/11/2021
-- Description:	Buscar Cotizaciones
-- ================================================
CREATE PROCEDURE [dbo].[spGetCotizaciones] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdCotizacion int = null,
	@IdCliente int = null,
    @IdUsuario int = null,
	@NombresCl varchar(125) = null,
	@ApellidosCl varchar(125) = null,
	@FechaIni varchar(10) = null,
	@FechaFin varchar(10) = null,
	@IdEstadoCot int = null,
	@Manifiesto int = null,
	@Movil varchar(20) = null,
	@TipoServ int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los clientes
		BEGIN
			SELECT	CT.IdCotizacion
					,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida 
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					,CT.EmpaqueVenta
					,CT.Serv_Inter
					,CT.Flete_Inter
					,CT.Gastos_Inter
					,CT.Vaduana_Inter
					,CT.Otros_Inter
					,CT.Aduana_Inter
					,CT.Observa_Inter
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.IdEmpresa
					,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial 
					,CT.NumOrden
					,CT.ContactoEmpresa
					,CT.CorreoContacto
					,CT.FechaIniBod
					,CT.FechaFinBod
					,CT.ObservaBodega
					,CT.Cortesia
					,CT.FechaCortIni
					,CT.FechaCortFin
					,CT.FechaUltima
					,CT.Manifiesto
					,CT.Remesa
					,CT.IdGestion
					,CT.FechaProximo
					,CT.Ctrl_Cotizacion
					,CT.ContadorCorreo
					,CT.CodVerificacion
					,CT.AutorizaCortesia
					,CT.TteSalida
					,CT.Ocupacion
					,CT.VrSugerido
					,CT.VrNegociado
				    ,CT.ObservaInterna
					,CT.ObservaInterna
					,CT.Valor_Vehiculo
					,ORG.Nombre as CiudadOrigen
					,ORG.CodDane as LocOrigen
					,DST.Nombre as CiudadDestino
					,DST.CodDane as LocDestino
					,SRV.Nombre as NombreServicio
					,TSV.Nombre as NombreTipoServ
					,CIA.NombreCia as NombreCia
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.Email as CorreoCliente
					,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
						END AS NegocioOrigen
					,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor

			FROM [dbo].[Cotizacion] as CT
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario

			WHERE CT.IdEstadoCot between ISNULL(@IdEstadoCot,CT.IdEstadoCot) and ISNULL(@IdEstadoCot,CT.IdEstadoCot)
				

			
		END

	IF @Opcion = 2 -- Consultar por Cotizacion
		BEGIN
		IF @IdEstadoCot IS NOT NULL
			BEGIN
				SELECT	 CT.IdCotizacion
						,CT.IdCliente
						,CT.IdSolicitud
						,CT.IdUsuario
						,CT.FechaCotizacion
						,CT.Servicios
						,CT.Ciudad_Origen
						,CT.Direccion_Origen
						,CT.Ciudad_Destino
						,CT.Direccion_Destino
						,CT.Volumen
						,CT.Arte
						,CT.Presencial
						,CT.FechaPresencial
						,CT.HoraPresencial
						,CT.Seguro
						,CT.Valor_Declarado
						,CT.Porc_Liquidacion
						,CT.IdFormaPago
						,CT.IdMetodoPago
						,CT.Almacenamiento
						,CT.Fecha_Recogida
						,CT.Hora_Recogida
						,CT.Fecha_Entrega
						,CT.Hora_Entrega
						,CT.Autorizado
						,CT.Tipo_Ident_Autorizado
						,CT.Ident_Autorizado
						,CT.Telefono_Autorizado
						,CT.Medio_Comunicacion
						,CT.Medio_Servicio
						,CT.IdEstadoCot
						,CT.ValorCotizacion
						,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						,CT.IdCotPresencial
						,CT.TipoServ
						,CT.MotivoPerdida
						,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						,CT.CuartoUtil
						,CT.Exteriores
						,CT.Tapizados
						,CT.Sucursal
						,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						,CT.Fecha_Empaque
						,CT.Hora_Empaque
						,CT.Periodicidad
						,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						,CT.Ref_Movil
						,CT.Ref_Direccion
						,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						,CT.IdBodega
						,CT.BloqueoCot
						,CT.Poliza
						,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						,CT.EmpaqueVenta
						,CT.Serv_Inter
						,CT.Flete_Inter
						,CT.Gastos_Inter
						,CT.Vaduana_Inter
						,CT.Otros_Inter
						,CT.Aduana_Inter
						,CT.Observa_Inter
						,CT.IdCia
						,CT.ObservaEmpaque
						,CT.ObservaCliente
						,CT.IdEmpresa
						,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						,CT.NumOrden
						,CT.ContactoEmpresa
						,CT.CorreoContacto
						,CT.FechaIniBod
						,CT.FechaFinBod
						,CT.ObservaBodega
						,CT.Cortesia
						,CT.FechaCortIni
						,CT.FechaCortFin
						,CT.FechaUltima
						,CT.Manifiesto
						,CT.Remesa
						,CT.IdGestion
						,CT.FechaProximo
						,CT.Ctrl_Cotizacion
						,CT.ContadorCorreo
						,CT.CodVerificacion
						,CT.AutorizaCortesia
						,CT.TteSalida
						,CT.Ocupacion
						,CT.VrSugerido
						,CT.VrNegociado
						,CT.ObservaInterna
						,CT.Valor_Vehiculo
						,ORG.Nombre as CiudadOrigen
						,ORG.CodDane as LocOrigen
						,DST.Nombre as CiudadDestino
						,DST.CodDane as LocDestino
						,SRV.Nombre as NombreServicio
						,TSV.Nombre as NombreTipoServ
					    ,CIA.NombreCia as NombreCia
					    ,CL.Identificacion as IdentCliente
					    ,CL.Movil as MovilCliente
					    ,CL.Email as CorreoCliente
					    ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					    ,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
					     END AS NegocioOrigen
						,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
						,BG.Nombre as NombreBodega
						,VL.Peso as PesoVolumen
			    
				FROM [dbo].[Cotizacion] as CT
						INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
						INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
						INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
						INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
						INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
						INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
						INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
						LEFT  JOIN [dbo].[Bodegas] as BG ON CT.IdBodega = BG.IdBodega
						LEFT  JOIN [dbo].[Tipo_Volumen] as VL ON CT.Volumen = VL.IdTipoVolumen

				WHERE CT.IdEstadoCot     between ISNULL(@IdEstadoCot,0) and ISNULL(@IdEstadoCot,9) and
				      CT.IdCotizacion    between ISNULL(@IdCotizacion,CT.IdCotizacion) and ISNULL(@IdCotizacion,CT.IdCotizacion)
			END

		IF @IdEstadoCot IS NULL
			BEGIN
				SELECT	 CT.IdCotizacion
						,CT.IdCliente
						,CT.IdSolicitud
						,CT.IdUsuario
						,CT.FechaCotizacion
						,CT.Servicios
						,CT.Ciudad_Origen
						,CT.Direccion_Origen
						,CT.Ciudad_Destino
						,CT.Direccion_Destino
						,CT.Volumen
						,CT.Arte
						,CT.Presencial
						,CT.FechaPresencial
						,CT.HoraPresencial
						,CT.Seguro
						,CT.Valor_Declarado
						,CT.Porc_Liquidacion
						,CT.IdFormaPago
						,CT.IdMetodoPago
						,CT.Almacenamiento
						,CT.Fecha_Recogida
						,CT.Hora_Recogida
						,CT.Fecha_Entrega
						,CT.Hora_Entrega
						,CT.Autorizado
						,CT.Tipo_Ident_Autorizado
						,CT.Ident_Autorizado
						,CT.Telefono_Autorizado
						,CT.Medio_Comunicacion
						,CT.Medio_Servicio
						,CT.IdEstadoCot
						,CT.ValorCotizacion
						,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						,CT.IdCotPresencial
						,CT.TipoServ
						,CT.MotivoPerdida
						,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						,CT.CuartoUtil
						,CT.Exteriores
						,CT.Tapizados
						,CT.Sucursal
						,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						,CT.Fecha_Empaque
						,CT.Hora_Empaque
						,CT.Periodicidad
						,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						,CT.Ref_Movil
						,CT.Ref_Direccion
						,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						,CT.IdBodega
						,CT.BloqueoCot
						,CT.Poliza
						,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						,CT.EmpaqueVenta
						,CT.Serv_Inter
						,CT.Flete_Inter
						,CT.Gastos_Inter
						,CT.Vaduana_Inter
						,CT.Otros_Inter
						,CT.Aduana_Inter
						,CT.Observa_Inter
						,CT.IdCia
						,CT.ObservaEmpaque
						,CT.ObservaCliente
						,CT.IdEmpresa
						,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						,CT.NumOrden
						,CT.ContactoEmpresa
						,CT.CorreoContacto
						,CT.FechaIniBod
						,CT.FechaFinBod
						,CT.ObservaBodega
						,CT.Cortesia
						,CT.FechaCortIni
						,CT.FechaCortFin
						,CT.FechaUltima
						,CT.Manifiesto
						,CT.Remesa
						,CT.IdGestion
						,CT.FechaProximo
						,CT.Ctrl_Cotizacion
						,CT.ContadorCorreo
						,CT.CodVerificacion
						,CT.AutorizaCortesia
						,CT.TteSalida
						,CT.Ocupacion
						,CT.VrSugerido
						,CT.VrNegociado
						,CT.ObservaInterna
						,CT.Valor_Vehiculo
						,ORG.Nombre as CiudadOrigen
						,ORG.CodDane as LocOrigen
						,DST.Nombre as CiudadDestino
						,DST.CodDane as LocDestino
						,SRV.Nombre as NombreServicio
						,TSV.Nombre as NombreTipoServ
					    ,CIA.NombreCia as NombreCia
					    ,CL.Identificacion as IdentCliente
					    ,CL.Movil as MovilCliente
					    ,CL.Email as CorreoCliente
					    ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					    ,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						END AS NegocioOrigen
					   ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
					   ,BG.Nombre as NombreBodega
					   ,VL.Peso as PesoVolumen
			    
				FROM [dbo].[Cotizacion] as CT
						INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
						INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
						INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
						INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
						INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
						INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
						INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
						LEFT  JOIN [dbo].[Bodegas] as BG ON CT.IdBodega = BG.IdBodega
						LEFT  JOIN [dbo].[Tipo_Volumen] as VL ON CT.Volumen = VL.IdTipoVolumen

				WHERE CT.IdCotizacion = @IdCotizacion and
					  CT.IdEstadoCot <> 7 
			END
	
	  END

	IF @Opcion = 3 -- Consultar por Parametro
		BEGIN
		IF @NombresCl IS NOT NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL
			BEGIN
				SELECT CT.IdCotizacion
		  			  ,CT.IdCliente
					  ,CT.IdSolicitud
					  ,CT.IdUsuario
					  ,CT.FechaCotizacion
					  ,CT.Servicios
  					  ,CT.Ciudad_Origen
					  ,CT.Direccion_Origen
					  ,CT.Ciudad_Destino
					  ,CT.Direccion_Destino
					  ,CT.Volumen
					  ,CT.Arte
					  ,CT.Presencial
					  ,CT.FechaPresencial
					  ,CT.HoraPresencial
					  ,CT.Seguro
					  ,CT.Valor_Declarado
					  ,CT.Porc_Liquidacion
					  ,CT.IdFormaPago
					  ,CT.IdMetodoPago
					  ,CT.Almacenamiento
					  ,CT.Fecha_Recogida
					  ,CT.Hora_Recogida
					  ,CT.Fecha_Entrega
					  ,CT.Hora_Entrega
					  ,CT.Autorizado
					  ,CT.Tipo_Ident_Autorizado
					  ,CT.Ident_Autorizado
					  ,CT.Telefono_Autorizado
					  ,CT.Medio_Comunicacion
					  ,CT.Medio_Servicio
					  ,CT.IdEstadoCot
					  ,CT.ValorCotizacion
					  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					  ,CT.IdCotPresencial
					  ,CT.TipoServ
					  ,CT.MotivoPerdida
					  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
					  ,CT.CuartoUtil
					  ,CT.Exteriores
					  ,CT.Tapizados
					  ,CT.Sucursal
					  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					  ,CT.Fecha_Empaque
					  ,CT.Hora_Empaque
					  ,CT.Periodicidad
					  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					  ,CT.Ref_Movil
					  ,CT.Ref_Direccion
					  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					  ,CT.IdBodega
					  ,CT.BloqueoCot
					  ,CT.Poliza
					  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					  ,CT.EmpaqueVenta
					  ,CT.Serv_Inter
					  ,CT.Flete_Inter
					  ,CT.Gastos_Inter
					  ,CT.Vaduana_Inter
					  ,CT.Otros_Inter
					  ,CT.Aduana_Inter
					  ,CT.Observa_Inter
					  ,CT.IdCia
					  ,CT.ObservaEmpaque
					  ,CT.ObservaCliente
					  ,CT.IdEmpresa
					  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					  ,CT.NumOrden
					  ,CT.ContactoEmpresa
					  ,CT.CorreoContacto
					  ,CT.FechaIniBod
					  ,CT.FechaFinBod
					  ,CT.ObservaBodega
					  ,CT.Cortesia
					  ,CT.FechaCortIni
					  ,CT.FechaCortFin
					  ,CT.FechaUltima
					  ,CT.Manifiesto
					  ,CT.Remesa
					  ,CT.IdGestion
					  ,CT.FechaProximo
					  ,CT.Ctrl_Cotizacion
					  ,CT.ContadorCorreo
					  ,CT.CodVerificacion
					  ,CT.AutorizaCortesia
					  ,CT.TteSalida
					  ,CT.Ocupacion
					  ,CT.VrSugerido
					  ,CT.VrNegociado
					  ,CT.ObservaInterna
					  ,CT.Valor_Vehiculo
					  ,ORG.Nombre as CiudadOrigen
					  ,ORG.CodDane as LocOrigen
					  ,DST.Nombre as CiudadDestino
					  ,DST.CodDane as LocDestino
					  ,SRV.Nombre as NombreServicio
					  ,TSV.Nombre as NombreTipoServ
					  ,CIA.NombreCia as NombreCia
					  ,CL.Identificacion as IdentCliente
					  ,CL.Movil as MovilCliente
					  ,CL.Email as CorreoCliente
					  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					  ,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					  END AS NegocioOrigen
					 ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
				FROM [dbo].[Cotizacion] as CT
						INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
						INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
						INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
						INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
						INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
						INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
						INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					 
				WHERE CL.Nombres         like CONCAT('%',@NombresCl,'%') and
					  CL.Apellidos       like CONCAT('%',@ApellidosCl,'%') and 
					  CT.FechaCotizacion between @FechaIni and @FechaFin 
			END

		IF @NombresCl IS NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL
			BEGIN
				SELECT CT.IdCotizacion
		  			  ,CT.IdCliente
					  ,CT.IdSolicitud
					  ,CT.IdUsuario
					  ,CT.FechaCotizacion
					  ,CT.Servicios
  					  ,CT.Ciudad_Origen
					  ,CT.Direccion_Origen
					  ,CT.Ciudad_Destino
					  ,CT.Direccion_Destino
					  ,CT.Volumen
					  ,CT.Arte
					  ,CT.Presencial
					  ,CT.FechaPresencial
					  ,CT.HoraPresencial
					  ,CT.Seguro
					  ,CT.Valor_Declarado
					  ,CT.Porc_Liquidacion
					  ,CT.IdFormaPago
					  ,CT.IdMetodoPago
					  ,CT.Almacenamiento
					  ,CT.Fecha_Recogida
					  ,CT.Hora_Recogida
					  ,CT.Fecha_Entrega
					  ,CT.Hora_Entrega
					  ,CT.Autorizado
					  ,CT.Tipo_Ident_Autorizado
					  ,CT.Ident_Autorizado
					  ,CT.Telefono_Autorizado
					  ,CT.Medio_Comunicacion
					  ,CT.Medio_Servicio
					  ,CT.IdEstadoCot
					  ,CT.ValorCotizacion
					  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					  ,CL.Identificacion
					  ,CT.IdCotPresencial
				      ,CT.TipoServ
					  ,CT.MotivoPerdida
					  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
					  ,CT.CuartoUtil
					  ,CT.Exteriores
					  ,CT.Tapizados
					  ,CT.Sucursal
					  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					  ,CT.Fecha_Empaque
					  ,CT.Hora_Empaque
					  ,CT.Periodicidad
					  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					  ,CT.Ref_Movil
					  ,CT.Ref_Direccion
					  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					  ,CT.IdBodega
					  ,CT.BloqueoCot
					  ,CT.Poliza
					  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					  ,CT.EmpaqueVenta
					  ,CT.Serv_Inter
					  ,CT.Flete_Inter
					  ,CT.Gastos_Inter
					  ,CT.Vaduana_Inter
					  ,CT.Otros_Inter
					  ,CT.Aduana_Inter
					  ,CT.Observa_Inter
					  ,CT.IdCia
					  ,CT.ObservaEmpaque
					  ,CT.ObservaCliente
					  ,CT.IdEmpresa
					  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					  ,CT.NumOrden
					  ,CT.ContactoEmpresa
					  ,CT.CorreoContacto
					  ,CT.FechaIniBod
					  ,CT.FechaFinBod
					  ,CT.ObservaBodega
					  ,CT.Cortesia
					  ,CT.FechaCortIni
					  ,CT.FechaCortFin
					  ,CT.FechaUltima
					  ,CT.Manifiesto
					  ,CT.Remesa
					  ,CT.IdGestion
					  ,CT.FechaProximo
					  ,CT.Ctrl_Cotizacion
					  ,CT.ContadorCorreo
					  ,CT.CodVerificacion
					  ,CT.AutorizaCortesia
					  ,CT.TteSalida
					  ,CT.Ocupacion
					  ,CT.VrSugerido
					  ,CT.VrNegociado
					  ,CT.ObservaInterna
					  ,CT.Valor_Vehiculo
					  ,ORG.Nombre as CiudadOrigen
					  ,ORG.CodDane as LocOrigen
					  ,DST.Nombre as CiudadDestino
					  ,DST.CodDane as LocDestino
					  ,SRV.Nombre as NombreServicio
					  ,TSV.Nombre as NombreTipoServ
					  ,CIA.NombreCia as NombreCia
					  ,CL.Identificacion as IdentCliente
					  ,CL.Movil as MovilCliente
					  ,CL.Email as CorreoCliente
					  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					  ,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					  END AS NegocioOrigen
					 ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
				FROM [dbo].[Cotizacion] as CT
						INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
						INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
						INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
						INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
						INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
						INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
						INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					 
				WHERE CT.FechaCotizacion between @FechaIni and @FechaFin
			END
					  
	END

	IF @Opcion = 4 -- Consultar por asesor
		BEGIN
		IF @IdEstadoCot IS NOT NULL
			BEGIN
				SELECT	 CT.IdCotizacion
						,CT.IdCliente
						,CT.IdSolicitud
						,CT.IdUsuario
						,CT.FechaCotizacion
						,CT.Servicios
						,CT.Ciudad_Origen
						,CT.Direccion_Origen
						,CT.Ciudad_Destino
						,CT.Direccion_Destino
						,CT.Volumen
						,CT.Arte
						,CT.Presencial
						,CT.FechaPresencial
						,CT.HoraPresencial
						,CT.Seguro
						,CT.Valor_Declarado
						,CT.Porc_Liquidacion
						,CT.IdFormaPago
						,CT.IdMetodoPago
						,CT.Almacenamiento
						,CT.Fecha_Recogida
						,CT.Hora_Recogida
						,CT.Fecha_Entrega
						,CT.Hora_Entrega
						,CT.Autorizado
						,CT.Tipo_Ident_Autorizado
						,CT.Ident_Autorizado
						,CT.Telefono_Autorizado
						,CT.Medio_Comunicacion
						,CT.Medio_Servicio
						,CT.IdEstadoCot
						,CT.ValorCotizacion
						,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						,CT.IdCotPresencial
						,CT.TipoServ
						,CT.MotivoPerdida
						,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						,CT.CuartoUtil
						,CT.Exteriores
						,CT.Tapizados
						,CT.Sucursal
						,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						,CT.Fecha_Empaque
						,CT.Hora_Empaque
						,CT.Periodicidad
						,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						,CT.Ref_Movil
						,CT.Ref_Direccion
						,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						,CT.IdBodega
						,CT.BloqueoCot
						,CT.Poliza
						,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						,CT.EmpaqueVenta
						,CT.Serv_Inter
						,CT.Flete_Inter
						,CT.Gastos_Inter
						,CT.Vaduana_Inter
						,CT.Otros_Inter
						,CT.Aduana_Inter
						,CT.Observa_Inter
						,CT.IdCia
						,CT.ObservaEmpaque
						,CT.ObservaCliente
						,CT.IdEmpresa
						,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						,CT.NumOrden
						,CT.ContactoEmpresa
						,CT.CorreoContacto
						,CT.FechaIniBod
						,CT.FechaFinBod
					    ,CT.ObservaBodega
					    ,CT.Cortesia
						,CT.FechaCortIni
						,CT.FechaCortFin
					    ,CT.FechaUltima
					    ,CT.Manifiesto
						,CT.Remesa
						,CT.IdGestion
						,CT.FechaProximo
						,CT.Ctrl_Cotizacion
						,CT.ContadorCorreo
						,CT.CodVerificacion
						,CT.AutorizaCortesia
						,CT.TteSalida
						,CT.Ocupacion
						,CT.VrSugerido
						,CT.VrNegociado
					    ,CT.ObservaInterna
					    ,CT.Valor_Vehiculo
						,ORG.Nombre as CiudadOrigen
						,DST.Nombre as CiudadDestino
						,SRV.Nombre as NombreServicio
						,TSV.Nombre as NombreTipoServ
						,CIA.NombreCia as NombreCia
						,CL.Identificacion as IdentCliente
						,CL.Movil as MovilCliente
						,CL.Email as CorreoCliente
						,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
						,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						 END AS NegocioOrigen
						,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
				FROM [dbo].[Cotizacion] as CT
						INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
						INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
						INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
						INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
						INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
						INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
						INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario

				WHERE CT.IdUsuario      = @IdUsuario and
					  CT.IdEstadoCot    = @IdEstadoCot
			END

		IF @IdEstadoCot IS NULL
			BEGIN
				SELECT	 CT.IdCotizacion
						,CT.IdCliente
						,CT.IdSolicitud
						,CT.IdUsuario
						,CT.FechaCotizacion
						,CT.Servicios
						,CT.Ciudad_Origen
						,CT.Direccion_Origen
						,CT.Ciudad_Destino
						,CT.Direccion_Destino
						,CT.Volumen
						,CT.Arte
						,CT.Presencial
						,CT.FechaPresencial
						,CT.HoraPresencial
						,CT.Seguro
						,CT.Valor_Declarado
						,CT.Porc_Liquidacion
						,CT.IdFormaPago
						,CT.IdMetodoPago
						,CT.Almacenamiento
						,CT.Fecha_Recogida
						,CT.Hora_Recogida
						,CT.Fecha_Entrega
						,CT.Hora_Entrega
						,CT.Autorizado
						,CT.Tipo_Ident_Autorizado
						,CT.Ident_Autorizado
						,CT.Telefono_Autorizado
						,CT.Medio_Comunicacion
						,CT.Medio_Servicio
						,CT.IdEstadoCot
						,CT.ValorCotizacion
						,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						,CT.IdCotPresencial
						,CT.TipoServ
						,CT.MotivoPerdida
						,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						,CT.CuartoUtil
						,CT.Exteriores
						,CT.Tapizados
						,CT.Sucursal
						,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						,CT.Fecha_Empaque
						,CT.Hora_Empaque
						,CT.Periodicidad
						,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						,CT.Ref_Movil
						,CT.Ref_Direccion
						,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						,CT.IdBodega
						,CT.BloqueoCot
						,CT.Poliza
						,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						,CT.EmpaqueVenta
						,CT.Serv_Inter
						,CT.Flete_Inter
						,CT.Gastos_Inter
						,CT.Vaduana_Inter
						,CT.Otros_Inter
						,CT.Aduana_Inter
						,CT.Observa_Inter
						,CT.IdCia
						,CT.ObservaEmpaque
						,CT.ObservaCliente
						,CT.IdEmpresa
						,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						,CT.NumOrden
						,CT.ContactoEmpresa
						,CT.CorreoContacto
						,CT.FechaIniBod
						,CT.FechaFinBod
					    ,CT.ObservaBodega
					    ,CT.Cortesia
						,CT.FechaCortIni
						,CT.FechaCortFin
					    ,CT.FechaUltima
					    ,CT.Manifiesto
						,CT.Remesa
						,CT.IdGestion
						,CT.FechaProximo
						,CT.Ctrl_Cotizacion
						,CT.ContadorCorreo
						,CT.CodVerificacion
						,CT.AutorizaCortesia
						,CT.TteSalida
						,CT.Ocupacion
						,CT.VrSugerido
						,CT.VrNegociado
						,CT.ObservaInterna
					    ,CT.Valor_Vehiculo
						,ORG.Nombre as CiudadOrigen
						,DST.Nombre as CiudadDestino
						,SRV.Nombre as NombreServicio
						,TSV.Nombre as NombreTipoServ
						,CIA.NombreCia as NombreCia
						,CL.Identificacion as IdentCliente
						,CL.Movil as MovilCliente
						,CL.Email as CorreoCliente
						,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
						,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						 END AS NegocioOrigen
					    ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
				FROM [dbo].[Cotizacion] as CT
						INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
						INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
						INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
						INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
						INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
						INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
						INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario

				WHERE CT.IdUsuario      = @IdUsuario 
			END
	  END

	IF @Opcion = 5 -- Consultar por Parametro
		BEGIN
			SELECT CT.IdCotizacion
		  		   ,CT.IdCliente
				   ,CT.IdSolicitud
				   ,CT.IdUsuario
				   ,CT.FechaCotizacion
				   ,CT.Servicios
  				   ,CT.Ciudad_Origen
				   ,CT.Direccion_Origen
				   ,CT.Ciudad_Destino
				   ,CT.Direccion_Destino
				   ,CT.Volumen
				   ,CT.Arte
				   ,CT.Presencial
				   ,CT.FechaPresencial
				   ,CT.HoraPresencial
				   ,CT.Seguro
				   ,CT.Valor_Declarado
				   ,CT.Porc_Liquidacion
				   ,CT.IdFormaPago
				   ,CT.IdMetodoPago
				   ,CT.Almacenamiento
				   ,CT.Fecha_Recogida
				   ,CT.Hora_Recogida
				   ,CT.Fecha_Entrega
				   ,CT.Hora_Entrega
				   ,CT.Autorizado
				   ,CT.Tipo_Ident_Autorizado
				   ,CT.Ident_Autorizado
				   ,CT.Telefono_Autorizado
				   ,CT.Medio_Comunicacion
				   ,CT.Medio_Servicio
				   ,CT.IdEstadoCot
				   ,CT.ValorCotizacion
				   ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
				   ,CT.IdCotPresencial
				   ,CT.TipoServ
				   ,CT.MotivoPerdida
				   ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
				   ,CT.CuartoUtil
				   ,CT.Exteriores
				   ,CT.Tapizados
				   ,CT.Sucursal
				   ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
				   ,CT.Fecha_Empaque
				   ,CT.Hora_Empaque
				   ,CT.Periodicidad
				   ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
				   ,CT.Ref_Movil
				   ,CT.Ref_Direccion
				   ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
				   ,CT.IdBodega
				   ,CT.BloqueoCot
				   ,CT.Poliza
				   ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
				   ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
				   ,CT.EmpaqueVenta
				   ,CT.Serv_Inter
				   ,CT.Flete_Inter
				   ,CT.Gastos_Inter
				   ,CT.Vaduana_Inter
				   ,CT.Otros_Inter
				   ,CT.Aduana_Inter
				   ,CT.Observa_Inter
				   ,CT.IdCia
				   ,CT.ObservaEmpaque
				   ,CT.ObservaCliente
				   ,CT.IdEmpresa
				   ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
				   ,CT.NumOrden
				   ,CT.ContactoEmpresa
				   ,CT.CorreoContacto
				   ,CT.FechaIniBod
				   ,CT.FechaFinBod
				   ,CT.ObservaBodega
				   ,CT.Cortesia
				   ,CT.FechaCortIni
				   ,CT.FechaCortFin
				   ,CT.FechaUltima
				   ,CT.Manifiesto
				   ,CT.Remesa
				   ,CT.IdGestion
				   ,CT.FechaProximo
				   ,CT.Ctrl_Cotizacion
				   ,CT.ContadorCorreo
				   ,CT.CodVerificacion
				   ,CT.AutorizaCortesia
				   ,CT.TteSalida
				   ,CT.Ocupacion
				   ,CT.VrSugerido
				   ,CT.VrNegociado
				   ,CT.ObservaInterna
				   ,CT.Valor_Vehiculo
				   ,ORG.Nombre as CiudadOrigen
				   ,ORG.CodDane as LocOrigen
				   ,DST.Nombre as CiudadDestino
				   ,DST.CodDane as LocDestino
				   ,SRV.Nombre as NombreServicio
				   ,TSV.Nombre as NombreTipoServ
				   ,CIA.NombreCia as NombreCia
				   ,CL.Identificacion as IdentCliente
				   ,CL.Movil as MovilCliente
				   ,CL.Email as CorreoCliente
				   ,CONCAT(CL.Nombres   , ' '   , CL.Apellidos) as NombreCliente
				   ,RTA.[1] as Concepto1
				   ,RTA.[2] as Concepto2
				   ,RTA.[3] as Concepto3
				   ,RTA.[4] as Concepto4
				   ,RTA.[5] as Concepto5
				   ,RTA.[6] as Concepto6
				   ,RTA.[7] as Concepto7
				   ,RTA.[8] as Concepto8
				   ,RTA.[9] as Concepto9
				   ,RTA.[10] as Concepto10
				   ,RTA.[11] as Concepto11
				   ,RTA.[12] as Concepto12
				   ,RTA.[13] as Concepto13
				   ,RTA.[14] as Concepto14
				   ,RTA.[15] as Concepto15
				   ,RTA.[16] as Concepto16
				   ,RTA.[17] as Concepto17
				   ,RTA.[18] as Concepto18
				   ,RTA.[19] as Concepto19
				   ,RTA.[20] as Concepto20
				   ,RTA.[21] as Concepto21
				   ,RTA.[22] as Concepto22
				   ,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					END AS NegocioOrigen
				   ,CONCAT(USU.Apellidos   , ' '   , USU.Nombres) as NombreAsesor

			FROM [dbo].[Cotizacion] as CT 
					JOIN (SELECT * FROM (SELECT [IdConceptoPDF], [IdCotizacion],[ValorServicio] FROM [dbo].[Cotizacion_Servicios]) AS ST 
						PIVOT(AVG([ValorServicio]) FOR [IdConceptoPDF] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22])) AS PT) as RTA
						ON CT.IdCotizacion = RTA.IdCotizacion
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario

			WHERE CT.IdUsuario       between ISNULL(@IdUsuario,0) and ISNULL(@IdUsuario,9999999) and
				  CT.IdEstadoCot     between ISNULL(@IdEstadoCot,0) and ISNULL(@IdEstadoCot,9) and
				  CT.FechaCotizacion between ISNULL(@FechaIni, CT.FechaCotizacion) and ISNULL(@FechaFin,CT.FechaCotizacion)
					  
				ORDER BY IdUsuario DESC	

		END

	IF @Opcion = 6 -- Consultar por cotizacion fechas
		BEGIN
			SELECT CT.IdCotizacion
		  		  ,CT.IdCliente
				  ,CT.IdSolicitud
				  ,CT.IdUsuario
				  ,CT.FechaCotizacion
				  ,CT.Servicios
  				  ,CT.Ciudad_Origen
				  ,CT.Direccion_Origen
				  ,CT.Ciudad_Destino
				  ,CT.Direccion_Destino
				  ,CT.Volumen
				  ,CT.Arte
				  ,CT.Presencial
				  ,CT.FechaPresencial
				  ,CT.HoraPresencial
				  ,CT.Seguro
				  ,CT.Valor_Declarado
				  ,CT.Porc_Liquidacion
				  ,CT.IdFormaPago
				  ,CT.IdMetodoPago
				  ,CT.Almacenamiento
				  ,CT.Fecha_Recogida
				  ,CT.Hora_Recogida
				  ,CT.Fecha_Entrega
				  ,CT.Hora_Entrega
				  ,CT.Autorizado
				  ,CT.Tipo_Ident_Autorizado
				  ,CT.Ident_Autorizado
				  ,CT.Telefono_Autorizado
				  ,CT.Medio_Comunicacion
				  ,CT.Medio_Servicio
				  ,CT.IdEstadoCot
				  ,CT.ValorCotizacion
				  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
				  ,CT.IdCotPresencial
				  ,CT.TipoServ
				  ,CT.MotivoPerdida
				  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
				  ,CT.CuartoUtil
				  ,CT.Exteriores
				  ,CT.Tapizados
				  ,CT.Sucursal
				  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
				  ,CT.Fecha_Empaque
				  ,CT.Hora_Empaque
				  ,CT.Periodicidad
				  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
				  ,CT.Ref_Movil
				  ,CT.Ref_Direccion
				  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
				  ,CT.IdBodega
				  ,CT.BloqueoCot
				  ,CT.Poliza
				  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
				  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
				  ,CT.EmpaqueVenta
				  ,CT.Serv_Inter
				  ,CT.Flete_Inter
				  ,CT.Gastos_Inter
				  ,CT.Vaduana_Inter
				  ,CT.Otros_Inter
				  ,CT.Aduana_Inter
				  ,CT.Observa_Inter
				  ,CT.IdCia
				  ,CT.ObservaEmpaque
				  ,CT.ObservaCliente
				  ,CT.IdEmpresa
				  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
				  ,CT.NumOrden
				  ,CT.ContactoEmpresa
				  ,CT.CorreoContacto
				  ,CT.FechaIniBod
				  ,CT.FechaFinBod
				  ,CT.ObservaBodega
				  ,CT.Cortesia
				  ,CT.FechaCortIni
				  ,CT.FechaCortFin
				  ,CT.FechaUltima
				  ,CT.Manifiesto
				  ,CT.Remesa
				  ,CT.IdGestion
				  ,CT.FechaProximo
				  ,CT.Ctrl_Cotizacion
				  ,CT.ContadorCorreo
				  ,CT.CodVerificacion
				  ,CT.AutorizaCortesia
				  ,CT.TteSalida
				  ,CT.Ocupacion
				  ,CT.VrSugerido
 				  ,CT.VrNegociado
				  ,CT.ObservaInterna
				  ,CT.Valor_Vehiculo
				  ,ORG.Nombre as CiudadOrigen
				  ,ORG.CodDane as LocOrigen
				  ,DST.Nombre as CiudadDestino
				  ,DST.CodDane as LocDestino
				  ,SRV.Nombre as NombreServicio
				  ,TSV.Nombre as NombreTipoServ
				  ,CIA.NombreCia as NombreCia
				  ,CL.Identificacion as IdentCliente
				  ,CL.Movil as MovilCliente
				  ,CL.Email as CorreoCliente
				  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
				  ,CASE CT.Medio_Comunicacion
					WHEN '1' THEN 'LLAMADA'
					WHEN '2' THEN 'CORREO ELECTRONICO'
					WHEN '3' THEN 'PAGINA WEB'
					WHEN '4' THEN 'LLAMADA PBX'
					WHEN '5' THEN 'WHATSAPP NACIONAL'
					WHEN '6' THEN 'WHATSAPP'
					ELSE '0' 
				   END AS NegocioOrigen
				  ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
			FROM [dbo].[Cotizacion] as CT
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Solicitudes] as SL ON SL.IdSolicitud = CT.IdSolicitud
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
				 
			WHERE SL.Movil           like ISNULL(@Movil,'%') and  
				  CT.IdEstadoCot     between ISNULL(@IdEstadoCot,0) and ISNULL(@IdEstadoCot,9) and
				  CT.IdCotizacion    between ISNULL(@IdCotizacion,CT.IdCotizacion) and ISNULL(@IdCotizacion,CT.IdCotizacion) and 
				  CT.IdUsuario       between ISNULL(@IdUsuario,CT.IdUsuario) and ISNULL(@IdUsuario,CT.IdUsuario) and
				  CT.FechaCotizacion between ISNULL(@FechaIni, CT.FechaCotizacion) and ISNULL(@FechaFin,CT.FechaCotizacion) 

			ORDER BY FechaCotizacion DESC

		END

	IF @Opcion = 7 -- Consultar por cotizacion usuario fechas
		BEGIN
			--BUSCAR POR COTIZACION Y FECHA
			IF @IdCotizacion IS NOT NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL 
				BEGIN
					SELECT CT.IdCotizacion
		  				  ,CT.IdCliente
						  ,CT.IdSolicitud
						  ,CT.IdUsuario
						  ,CT.FechaCotizacion
						  ,CT.Servicios
  						  ,CT.Ciudad_Origen
						  ,CT.Direccion_Origen
						  ,CT.Ciudad_Destino
						  ,CT.Direccion_Destino
						  ,CT.Volumen
						  ,CT.Arte
						  ,CT.Presencial
						  ,CT.FechaPresencial
						  ,CT.HoraPresencial
						  ,CT.Seguro
						  ,CT.Valor_Declarado
						  ,CT.Porc_Liquidacion
						  ,CT.IdFormaPago
						  ,CT.IdMetodoPago
						  ,CT.Almacenamiento
						  ,CT.Fecha_Recogida
						  ,CT.Hora_Recogida
						  ,CT.Fecha_Entrega
						  ,CT.Hora_Entrega
						  ,CT.Autorizado
						  ,CT.Tipo_Ident_Autorizado
						  ,CT.Ident_Autorizado
						  ,CT.Telefono_Autorizado
						  ,CT.Medio_Comunicacion
						  ,CT.Medio_Servicio
						  ,CT.IdEstadoCot
						  ,CT.ValorCotizacion
						  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						  ,CT.IdCotPresencial
						  ,CT.TipoServ
						  ,CT.MotivoPerdida
						  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						  ,CT.CuartoUtil
						  ,CT.Exteriores
						  ,CT.Tapizados
						  ,CT.Sucursal
						  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						  ,CT.Fecha_Empaque
						  ,CT.Hora_Empaque
						  ,CT.Periodicidad
						  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						  ,CT.Ref_Movil
						  ,CT.Ref_Direccion
						  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						  ,CT.IdBodega
						  ,CT.BloqueoCot
						  ,CT.Poliza
						  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						  ,CT.EmpaqueVenta
						  ,CT.Serv_Inter
						  ,CT.Flete_Inter
						  ,CT.Gastos_Inter
						  ,CT.Vaduana_Inter
						  ,CT.Otros_Inter
						  ,CT.Aduana_Inter
						  ,CT.Observa_Inter
						  ,CT.IdCia
						  ,CT.ObservaEmpaque
						  ,CT.ObservaCliente
						  ,CT.IdEmpresa
						  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						  ,CT.NumOrden
						  ,CT.ContactoEmpresa
						  ,CT.CorreoContacto
						  ,CT.FechaIniBod
						  ,CT.FechaFinBod
						  ,CT.ObservaBodega
						  ,CT.Cortesia
						  ,CT.FechaCortIni
						  ,CT.FechaCortFin
						  ,CT.FechaUltima
						  ,CT.Manifiesto
						  ,CT.Remesa
						  ,CT.IdGestion
						  ,CT.FechaProximo
						  ,CT.Ctrl_Cotizacion
						  ,CT.ContadorCorreo
						  ,CT.CodVerificacion
						  ,CT.AutorizaCortesia
						  ,CT.TteSalida
						  ,CT.Ocupacion
						  ,CT.VrSugerido
						  ,CT.VrNegociado
						  ,CT.ObservaInterna
						  ,CT.Valor_Vehiculo
						  ,ORG.Nombre as CiudadOrigen
						  ,ORG.CodDane as LocOrigen
						  ,DST.Nombre as CiudadDestino
						  ,DST.CodDane as LocDestino
						  ,SRV.Nombre as NombreServicio
						  ,TSV.Nombre as NombreTipoServ
						  ,CIA.NombreCia as NombreCia
						  ,CL.Identificacion as IdentCliente
						  ,CL.Movil as MovilCliente
						  ,CL.Email as CorreoCliente
						  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
						  ,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						   END AS NegocioOrigen
						  ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT
							INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
							INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
							INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
							INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
							INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
							INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
							INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					 
					WHERE CT.IdCotizacion    = @IdCotizacion and
						  CT.FechaCotizacion between @FechaIni and @FechaFin  

					ORDER BY FechaCotizacion DESC
				END

			--BUSCAR POR FECHAS
			IF @IdCotizacion IS NULL and @IdUsuario IS NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL 
				BEGIN
					SELECT CT.IdCotizacion
		  				  ,CT.IdCliente
						  ,CT.IdSolicitud
						  ,CT.IdUsuario
						  ,CT.FechaCotizacion
						  ,CT.Servicios
  						  ,CT.Ciudad_Origen
						  ,CT.Direccion_Origen
						  ,CT.Ciudad_Destino
						  ,CT.Direccion_Destino
						  ,CT.Volumen
						  ,CT.Arte
						  ,CT.Presencial
						  ,CT.FechaPresencial
						  ,CT.HoraPresencial
						  ,CT.Seguro
						  ,CT.Valor_Declarado
						  ,CT.Porc_Liquidacion
						  ,CT.IdFormaPago
						  ,CT.IdMetodoPago
						  ,CT.Almacenamiento
						  ,CT.Fecha_Recogida
						  ,CT.Hora_Recogida
						  ,CT.Fecha_Entrega
						  ,CT.Hora_Entrega
						  ,CT.Autorizado
						  ,CT.Tipo_Ident_Autorizado
						  ,CT.Ident_Autorizado
						  ,CT.Telefono_Autorizado
						  ,CT.Medio_Comunicacion
						  ,CT.Medio_Servicio
						  ,CT.IdEstadoCot
						  ,CT.ValorCotizacion
						  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						  ,CT.IdCotPresencial
						  ,CT.TipoServ
						  ,CT.MotivoPerdida
						  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						  ,CT.CuartoUtil
						  ,CT.Exteriores
						  ,CT.Tapizados
						  ,CT.Sucursal
						  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						  ,CT.Fecha_Empaque
						  ,CT.Hora_Empaque
						  ,CT.Periodicidad
						  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						  ,CT.Ref_Movil
						  ,CT.Ref_Direccion
						  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						  ,CT.IdBodega
						  ,CT.BloqueoCot
						  ,CT.Poliza
						  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						  ,CT.EmpaqueVenta
						  ,CT.Serv_Inter
						  ,CT.Flete_Inter
						  ,CT.Gastos_Inter
						  ,CT.Vaduana_Inter
						  ,CT.Otros_Inter
						  ,CT.Aduana_Inter
						  ,CT.Observa_Inter
						  ,CT.IdCia
						  ,CT.ObservaEmpaque
						  ,CT.ObservaCliente
						  ,CT.IdEmpresa
						  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						  ,CT.NumOrden
						  ,CT.ContactoEmpresa
						  ,CT.CorreoContacto
						  ,CT.FechaIniBod
						  ,CT.FechaFinBod
						  ,CT.ObservaBodega
						  ,CT.Cortesia
						  ,CT.FechaCortIni
						  ,CT.FechaCortFin
						  ,CT.FechaUltima
						  ,CT.Manifiesto
						  ,CT.Remesa
						  ,CT.IdGestion
						  ,CT.FechaProximo
						  ,CT.Ctrl_Cotizacion
						  ,CT.ContadorCorreo
						  ,CT.CodVerificacion
						  ,CT.AutorizaCortesia
						  ,CT.TteSalida
						  ,CT.Ocupacion
						  ,CT.VrSugerido
						  ,CT.VrNegociado
						  ,CT.ObservaInterna
					      ,CT.Valor_Vehiculo
						  ,ORG.Nombre as CiudadOrigen
						  ,ORG.CodDane as LocOrigen
						  ,DST.Nombre as CiudadDestino
						  ,DST.CodDane as LocDestino
						  ,SRV.Nombre as NombreServicio
						  ,TSV.Nombre as NombreTipoServ
						  ,CIA.NombreCia as NombreCia
						  ,CL.Identificacion as IdentCliente
						  ,CL.Movil as MovilCliente
						  ,CL.Email as CorreoCliente
						  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
						  ,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						   END AS NegocioOrigen
						  ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT
							INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
							INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
							INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
							INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
							INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
							INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
							INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					 
					WHERE CT.FechaCotizacion between @FechaIni and @FechaFin  

					ORDER BY IdUsuario DESC

				END

			--BUSCAR POR COTIZACION
			IF @IdCotizacion IS NOT NULL and @FechaIni IS NULL and @FechaFin IS NULL 
				BEGIN
					SELECT CT.IdCotizacion
		  				  ,CT.IdCliente
						  ,CT.IdSolicitud
						  ,CT.IdUsuario
						  ,CT.FechaCotizacion
						  ,CT.Servicios
  						  ,CT.Ciudad_Origen
						  ,CT.Direccion_Origen
						  ,CT.Ciudad_Destino
						  ,CT.Direccion_Destino
						  ,CT.Volumen
						  ,CT.Arte
						  ,CT.Presencial
						  ,CT.FechaPresencial
						  ,CT.HoraPresencial
						  ,CT.Seguro
						  ,CT.Valor_Declarado
						  ,CT.Porc_Liquidacion
						  ,CT.IdFormaPago
						  ,CT.IdMetodoPago
						  ,CT.Almacenamiento
						  ,CT.Fecha_Recogida
						  ,CT.Hora_Recogida
						  ,CT.Fecha_Entrega
						  ,CT.Hora_Entrega
						  ,CT.Autorizado
						  ,CT.Tipo_Ident_Autorizado
						  ,CT.Ident_Autorizado
						  ,CT.Telefono_Autorizado
						  ,CT.Medio_Comunicacion
						  ,CT.Medio_Servicio
						  ,CT.IdEstadoCot
						  ,CT.ValorCotizacion
						  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						  ,CT.IdCotPresencial
						  ,CT.TipoServ
						  ,CT.MotivoPerdida
						  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						  ,CT.CuartoUtil
						  ,CT.Exteriores
						  ,CT.Tapizados
						  ,CT.Sucursal
						  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						  ,CT.Fecha_Empaque
						  ,CT.Hora_Empaque
						  ,CT.Periodicidad
						  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						  ,CT.Ref_Movil
						  ,CT.Ref_Direccion
						  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						  ,CT.IdBodega
						  ,CT.BloqueoCot
						  ,CT.Poliza
						  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						  ,CT.EmpaqueVenta
						  ,CT.Serv_Inter
						  ,CT.Flete_Inter
						  ,CT.Gastos_Inter
						  ,CT.Vaduana_Inter
						  ,CT.Otros_Inter
						  ,CT.Aduana_Inter
						  ,CT.Observa_Inter
						  ,CT.IdCia
						  ,CT.ObservaEmpaque
						  ,CT.ObservaCliente
						  ,CT.IdEmpresa
						  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						  ,CT.NumOrden
						  ,CT.ContactoEmpresa
						  ,CT.CorreoContacto
						  ,CT.FechaIniBod
						  ,CT.FechaFinBod
						  ,CT.ObservaBodega
						  ,CT.Cortesia
						  ,CT.FechaCortIni
						  ,CT.FechaCortFin
						  ,CT.FechaUltima
						  ,CT.Manifiesto
						  ,CT.Remesa
						  ,CT.IdGestion
						  ,CT.FechaProximo
						  ,CT.Ctrl_Cotizacion
						  ,CT.ContadorCorreo
						  ,CT.CodVerificacion
						  ,CT.AutorizaCortesia
						  ,CT.TteSalida
						  ,CT.Ocupacion
						  ,CT.VrSugerido
						  ,CT.VrNegociado
				          ,CT.ObservaInterna
					      ,CT.Valor_Vehiculo
						  ,ORG.Nombre as CiudadOrigen
						  ,ORG.CodDane as LocOrigen
						  ,DST.Nombre as CiudadDestino
						  ,DST.CodDane as LocDestino
						  ,SRV.Nombre as NombreServicio
						  ,TSV.Nombre as NombreTipoServ
						  ,CIA.NombreCia as NombreCia
						  ,CL.Identificacion as IdentCliente
						  ,CL.Movil as MovilCliente
						  ,CL.Email as CorreoCliente
						  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
						  ,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						   END AS NegocioOrigen
						  ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT
							INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
							INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
							INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
							INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
							INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
							INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
							INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					 
					WHERE CT.IdCotizacion   = @IdCotizacion
				END

			-- BUSCAR POR USUARIO
			IF @IdUsuario IS NOT NULL and @FechaIni IS NULL and @FechaFin IS NULL 
				BEGIN
					SELECT CT.IdCotizacion
		  				  ,CT.IdCliente
						  ,CT.IdSolicitud
						  ,CT.IdUsuario
						  ,CT.FechaCotizacion
						  ,CT.Servicios
  						  ,CT.Ciudad_Origen
						  ,CT.Direccion_Origen
						  ,CT.Ciudad_Destino
						  ,CT.Direccion_Destino
						  ,CT.Volumen
						  ,CT.Arte
						  ,CT.Presencial
						  ,CT.FechaPresencial
						  ,CT.HoraPresencial
						  ,CT.Seguro
						  ,CT.Valor_Declarado
						  ,CT.Porc_Liquidacion
						  ,CT.IdFormaPago
						  ,CT.IdMetodoPago
						  ,CT.Almacenamiento
						  ,CT.Fecha_Recogida
						  ,CT.Hora_Recogida
						  ,CT.Fecha_Entrega
						  ,CT.Hora_Entrega
						  ,CT.Autorizado
						  ,CT.Tipo_Ident_Autorizado
						  ,CT.Ident_Autorizado
						  ,CT.Telefono_Autorizado
						  ,CT.Medio_Comunicacion
						  ,CT.Medio_Servicio
						  ,CT.IdEstadoCot
						  ,CT.ValorCotizacion
						  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						  ,CT.IdCotPresencial
						  ,CT.TipoServ
						  ,CT.MotivoPerdida
						  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						  ,CT.CuartoUtil
						  ,CT.Exteriores
						  ,CT.Tapizados
						  ,CT.Sucursal
						  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						  ,CT.Fecha_Empaque
						  ,CT.Hora_Empaque
						  ,CT.Periodicidad
						  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						  ,CT.Ref_Movil
						  ,CT.Ref_Direccion
						  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						  ,CT.IdBodega
						  ,CT.BloqueoCot
						  ,CT.Poliza
						  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						  ,CT.EmpaqueVenta
						  ,CT.Serv_Inter
						  ,CT.Flete_Inter
						  ,CT.Gastos_Inter
						  ,CT.Vaduana_Inter
						  ,CT.Otros_Inter
						  ,CT.Aduana_Inter
						  ,CT.Observa_Inter
						  ,CT.IdCia
						  ,CT.ObservaEmpaque
						  ,CT.ObservaCliente
						  ,CT.IdEmpresa
						  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
						  ,CT.NumOrden
						  ,CT.ContactoEmpresa
						  ,CT.CorreoContacto
						  ,CT.FechaIniBod
						  ,CT.FechaFinBod
						  ,CT.ObservaBodega
						  ,CT.Cortesia
						  ,CT.FechaCortIni
						  ,CT.FechaCortFin
						  ,CT.FechaUltima
						  ,CT.Manifiesto
						  ,CT.Remesa
						  ,CT.IdGestion
						  ,CT.FechaProximo
						  ,CT.Ctrl_Cotizacion
						  ,CT.ContadorCorreo
						  ,CT.CodVerificacion
						  ,CT.AutorizaCortesia
						  ,CT.TteSalida
						  ,CT.Ocupacion
						  ,CT.VrSugerido
						  ,CT.VrNegociado
						  ,CT.ObservaInterna
					      ,CT.Valor_Vehiculo
						  ,ORG.Nombre as CiudadOrigen
						  ,ORG.CodDane as LocOrigen
						  ,DST.Nombre as CiudadDestino
						  ,DST.CodDane as LocDestino
						  ,SRV.Nombre as NombreServicio
						  ,TSV.Nombre as NombreTipoServ
						  ,CIA.NombreCia as NombreCia
						  ,CL.Identificacion as IdentCliente
						  ,CL.Movil as MovilCliente
						  ,CL.Email as CorreoCliente
						  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
						  ,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						  END AS NegocioOrigen
						 ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT
							INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
							INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
							INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
							INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
							INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
							INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
							INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
						
					 
					WHERE CT.IdUsuario = @IdUsuario
				END

			--BUSCA POR USUARIO Y FECHA
			IF @IdUsuario IS NOT NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL 
				BEGIN
					SELECT CT.IdCotizacion
		  				  ,CT.IdCliente
						  ,CT.IdSolicitud
						  ,CT.IdUsuario
						  ,CT.FechaCotizacion
						  ,CT.Servicios
  						  ,CT.Ciudad_Origen
						  ,CT.Direccion_Origen
						  ,CT.Ciudad_Destino
						  ,CT.Direccion_Destino
						  ,CT.Volumen
						  ,CT.Arte
						  ,CT.Presencial
						  ,CT.FechaPresencial
						  ,CT.HoraPresencial
						  ,CT.Seguro
						  ,CT.Valor_Declarado
						  ,CT.Porc_Liquidacion
						  ,CT.IdFormaPago
						  ,CT.IdMetodoPago
						  ,CT.Almacenamiento
						  ,CT.Fecha_Recogida
						  ,CT.Hora_Recogida
						  ,CT.Fecha_Entrega
						  ,CT.Hora_Entrega
						  ,CT.Autorizado
						  ,CT.Tipo_Ident_Autorizado
						  ,CT.Ident_Autorizado
						  ,CT.Telefono_Autorizado
						  ,CT.Medio_Comunicacion
						  ,CT.Medio_Servicio
						  ,CT.IdEstadoCot
						  ,CT.ValorCotizacion
						  ,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
						  ,CT.IdCotPresencial
						  ,CT.TipoServ
						  ,CT.MotivoPerdida
						  ,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
						  ,CT.CuartoUtil
						  ,CT.Exteriores
						  ,CT.Tapizados
						  ,CT.Sucursal
						  ,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
						  ,CT.Fecha_Empaque
						  ,CT.Hora_Empaque
						  ,CT.Periodicidad
						  ,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
						  ,CT.Ref_Movil
						  ,CT.Ref_Direccion
						  ,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
						  ,CT.IdBodega
						  ,CT.BloqueoCot
						  ,CT.Poliza
						  ,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
						  ,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
						  ,CT.EmpaqueVenta
						  ,CT.Serv_Inter
						  ,CT.Flete_Inter
						  ,CT.Gastos_Inter
						  ,CT.Vaduana_Inter
						  ,CT.Otros_Inter
						  ,CT.Aduana_Inter
						  ,CT.Observa_Inter
						  ,CT.IdCia
						  ,CT.ObservaEmpaque
						  ,CT.ObservaCliente
						  ,CT.IdEmpresa
						  ,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial 
						  ,CT.NumOrden
						  ,CT.ContactoEmpresa
						  ,CT.CorreoContacto
						  ,CT.FechaIniBod
						  ,CT.FechaFinBod
						  ,CT.ObservaBodega
						  ,CT.Cortesia
						  ,CT.FechaCortIni
						  ,CT.FechaCortFin
						  ,CT.FechaUltima
						  ,CT.Manifiesto
						  ,CT.Remesa
						  ,CT.IdGestion
						  ,CT.FechaProximo
						  ,CT.Ctrl_Cotizacion
						  ,CT.ContadorCorreo
						  ,CT.CodVerificacion
						  ,CT.AutorizaCortesia
						  ,CT.TteSalida
						  ,CT.Ocupacion
						  ,CT.VrSugerido
						  ,CT.VrNegociado
						  ,CT.ObservaInterna
						  ,CT.Valor_Vehiculo
						  ,ORG.Nombre as CiudadOrigen
						  ,ORG.CodDane as LocOrigen
						  ,DST.Nombre as CiudadDestino
						  ,DST.CodDane as LocDestino
						  ,SRV.Nombre as NombreServicio
						  ,TSV.Nombre as NombreTipoServ
						  ,CIA.NombreCia as NombreCia
						  ,CL.Identificacion as IdentCliente
						  ,CL.Movil as MovilCliente
						  ,CL.Email as CorreoCliente
						  ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
						  ,CASE CT.Medio_Comunicacion
							WHEN '1' THEN 'LLAMADA'
							WHEN '2' THEN 'CORREO ELECTRONICO'
							WHEN '3' THEN 'PAGINA WEB'
							WHEN '4' THEN 'LLAMADA PBX'
							WHEN '5' THEN 'WHATSAPP NACIONAL'
							WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
						  END AS NegocioOrigen
					     ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT
							INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
							INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
							INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
							INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
							INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
							INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
							INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					 
					WHERE CT.IdUsuario      = @IdUsuario and
						  CT.FechaCotizacion between @FechaIni and @FechaFin  

					ORDER BY FechaCotizacion DESC
				END
		END

	IF @Opcion = 8 -- Tablero de Control
		BEGIN
			IF @IdUsuario IS NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL
				BEGIN
					SELECT CT.IdEstadoCot
						   ,COUNT(CT.IdEstadoCot) as Estado 
						   ,SUM(CT.ValorCotizacion) ValorCot
					
					FROM [dbo].[Cotizacion] as CT
					
					WHERE CT.FechaCotizacion between  @FechaIni and @FechaFin
					
					GROUP BY CT.IdEstadoCot
				END

			IF @IdUsuario IS NOT NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL
				BEGIN
					SELECT CT.IdUsuario
						   ,CT.IdEstadoCot
						   ,COUNT(CT.IdEstadoCot) as Estado 
						   ,SUM(CT.ValorCotizacion) ValorCot

					FROM [dbo].[Cotizacion] as CT

					WHERE CT.IdUsuario = @IdUsuario and 
						  CT.FechaCotizacion between @FechaIni and @FechaFin

					GROUP BY CT.IdEstadoCot, CT.IdUsuario

				END
		END

	IF @Opcion = 9 -- Consultar por usuario fechas estado
		BEGIN
			SELECT CT.IdCotizacion
		  			,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.Servicios
  					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					,CL.Identificacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					,CT.EmpaqueVenta
					,CT.Serv_Inter
					,CT.Flete_Inter
					,CT.Gastos_Inter
					,CT.Vaduana_Inter
					,CT.Otros_Inter
					,CT.Aduana_Inter
					,CT.Observa_Inter
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.IdEmpresa
					,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,CT.NumOrden
					,CT.ContactoEmpresa
					,CT.CorreoContacto
					,CT.FechaIniBod
					,CT.FechaFinBod
					,CT.ObservaBodega
					,CT.Cortesia
					,CT.FechaCortIni
					,CT.FechaCortFin
					,CT.FechaUltima
					,CT.Manifiesto
					,CT.Remesa
					,CT.IdGestion
					,CT.FechaProximo
					,CT.Ctrl_Cotizacion
					,CT.ContadorCorreo
					,CT.CodVerificacion
					,CT.AutorizaCortesia
					,CT.TteSalida
					,CT.Ocupacion
					,CT.VrSugerido
					,CT.VrNegociado
				    ,CT.ObservaInterna
					,CT.Valor_Vehiculo
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino
					,SRV.Nombre as NombreServicio
					,TSV.Nombre as NombreTipoServ
					,CIA.NombreCia as NombreCia
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.Email as CorreoCliente
					,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					 END AS NegocioOrigen
					,CONCAT(usu.Nombres,' ',USU.Apellidos) AS NombreUsuario
					,EST.Nombre as NombreEstado
					,DPO.Nombre as DptoOrigen
					,DPD.Nombre as DptoDestino
					  				   
			FROM [dbo].[Cotizacion] as CT
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Departamentos] as DPO ON ORG.IdDepartamento = DPO.IdDepartamento
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Departamentos] as DPD ON DST.IdDepartamento = DPD.IdDepartamento
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					INNER JOIN [dbo].[Estado_Cotizacion] as EST ON CT.IdEstadoCot = EST.IdEstadoCot
					INNER JOIN [dbo].[Solicitudes] as SL ON CT.IdSolicitud = SL.IdSolicitud

			WHERE SL.Movil        like CONCAT('%',ISNULL(@Movil,SL.Movil),'%')  and 
				  CT.IdCotizacion between ISNULL(@IdCotizacion,CT.IdCotizacion) and ISNULL(@IdCotizacion,CT.IdCotizacion) and
				  CT.IdEstadoCot  between ISNULL(@IdEstadoCot,0) and ISNULL(@IdEstadoCot,9) and
				  CT.TipoServ     between ISNULL(@TipoServ,0) and ISNULL(@TipoServ,99) and
				  CT.IdUsuario    between ISNULL(@IdUsuario,CT.IdUsuario) and ISNULL(@IdUsuario,CT.IdUsuario) and
				  CT.IdCliente    between ISNULL(@IdCliente,CT.IdCliente) and ISNULL(@IdCliente,CT.IdCliente) and
				  CT.FechaUltima  between ISNULL(@FechaIni,CT.FechaUltima) and ISNULL(@FechaFin,CT.FechaUltima)

			ORDER BY IdEstadoCot DESC
		END

	IF @Opcion = 10 -- Consultar por usuario fechas
		BEGIN
			IF @IdUsuario IS NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL
				BEGIN 
					SELECT CT.IdCotizacion
		  					,CT.IdCliente
							,CT.IdSolicitud
							,CT.IdUsuario
							,CT.FechaCotizacion
							,CT.Servicios
  							,CT.Ciudad_Origen
							,CT.Direccion_Origen
							,CT.Ciudad_Destino
							,CT.Direccion_Destino
							,CT.Volumen
							,CT.Arte
							,CT.Presencial
							,CT.FechaPresencial
							,CT.HoraPresencial
							,CT.Seguro
							,CT.Valor_Declarado
							,CT.Porc_Liquidacion
							,CT.IdFormaPago
							,CT.IdMetodoPago
							,CT.Almacenamiento
							,CT.Fecha_Recogida
							,CT.Hora_Recogida
							,CT.Fecha_Entrega
							,CT.Hora_Entrega
							,CT.Autorizado
							,CT.Tipo_Ident_Autorizado
							,CT.Ident_Autorizado
							,CT.Telefono_Autorizado
							,CT.Medio_Comunicacion
							,CT.Medio_Servicio
							,CT.IdEstadoCot
							,CT.ValorCotizacion
							,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
							,CT.IdCotPresencial
							,CT.TipoServ
							,CT.MotivoPerdida
							,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
							,CT.CuartoUtil
							,CT.Exteriores
							,CT.Tapizados
							,CT.Sucursal
							,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
							,CT.Fecha_Empaque
							,CT.Hora_Empaque
							,CT.Periodicidad
							,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
							,CT.Ref_Movil
							,CT.Ref_Direccion
							,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
							,CT.IdBodega
							,CT.BloqueoCot
							,CT.Poliza
							,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
							,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
							,CT.EmpaqueVenta
							,CT.Serv_Inter
							,CT.Flete_Inter
							,CT.Gastos_Inter
							,CT.Vaduana_Inter
							,CT.Otros_Inter
							,CT.Aduana_Inter
							,CT.Observa_Inter
							,CT.IdCia
							,CT.ObservaEmpaque
							,CT.ObservaCliente
							,CT.IdEmpresa
							,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,CT.NumOrden
							,CT.ContactoEmpresa
							,CT.CorreoContacto
							,CT.FechaIniBod
							,CT.FechaFinBod
							,CT.ObservaBodega
							,CT.Cortesia
							,CT.FechaCortIni
							,CT.FechaCortFin
							,CT.FechaUltima
							,CT.Manifiesto
							,CT.Remesa
							,CT.IdGestion
							,CT.FechaProximo
						    ,CT.Ctrl_Cotizacion
						    ,CT.ContadorCorreo
							,CT.CodVerificacion
						    ,CT.AutorizaCortesia
						    ,CT.TteSalida
							,CT.Ocupacion
						    ,CT.VrSugerido
						    ,CT.VrNegociado
							,CT.ObservaInterna
					        ,CT.Valor_Vehiculo
							,ORG.Nombre as CiudadOrigen
							,DST.Nombre as CiudadDestino
							,SRV.Nombre as NombreServicio
							,TSV.Nombre as NombreTipoServ
							,CIA.NombreCia as NombreCia
							,CL.Identificacion as IdentCliente
							,CL.Movil as MovilCliente
							,CL.Email as CorreoCliente
							,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
							,CASE CT.Medio_Comunicacion
								WHEN '1' THEN 'LLAMADA'
								WHEN '2' THEN 'CORREO ELECTRONICO'
								WHEN '3' THEN 'PAGINA WEB'
								WHEN '4' THEN 'LLAMADA PBX'
								WHEN '5' THEN 'WHATSAPP NACIONAL'
								WHEN '6' THEN 'WHATSAPP'
								ELSE '0' 
							 END AS NegocioOrigen
						    ,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT left join [dbo].[Solicitudes] as SL on CT.IdSolicitud = SL.IdSolicitud,
						 [dbo].[Clientes] as CL,
						 [dbo].[Ciudades] as ORG,
						 [dbo].[Ciudades] as DST,
						 [dbo].[Servicios] as SRV,
						 [dbo].[TipoServicio] as TSV,
						 [dbo].[Compania] as CIA,
						 [dbo].[Usuarios] as USU
					 
					WHERE CT.IdCliente      = CL.IdCliente and
						  CT.Ciudad_Origen  = ORG.IdCiudad and
						  CT.Ciudad_Destino = DST.IdCiudad and
						  CT.Servicios      = SRV.IdServicio and
						  CT.TipoServ       = TSV.IdTipo and
						  CT.IdCia          = CIA.IdCia and
						  CT.IdEstadoCot    <> 7 and
						  SL.Fecha between @FechaIni and @FechaFin  

					ORDER BY FechaCotizacion DESC
				END

			IF @IdUsuario IS NOT NULL and @FechaIni IS NOT NULL and @FechaFin IS NOT NULL
				BEGIN 
					SELECT CT.IdCotizacion
		  					,CT.IdCliente
							,CT.IdSolicitud
							,CT.IdUsuario
							,CT.FechaCotizacion
							,CT.Servicios
  							,CT.Ciudad_Origen
							,CT.Direccion_Origen
							,CT.Ciudad_Destino
							,CT.Direccion_Destino
							,CT.Volumen
							,CT.Arte
							,CT.Presencial
							,CT.FechaPresencial
							,CT.HoraPresencial
							,CT.Seguro
							,CT.Valor_Declarado
							,CT.Porc_Liquidacion
							,CT.IdFormaPago
							,CT.IdMetodoPago
							,CT.Almacenamiento
							,CT.Fecha_Recogida
							,CT.Hora_Recogida
							,CT.Fecha_Entrega
							,CT.Hora_Entrega
							,CT.Autorizado
							,CT.Tipo_Ident_Autorizado
							,CT.Ident_Autorizado
							,CT.Telefono_Autorizado
							,CT.Medio_Comunicacion
							,CT.Medio_Servicio
							,CT.IdEstadoCot
							,CT.ValorCotizacion
							,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
							,CT.IdCotPresencial
							,CT.TipoServ
							,CT.MotivoPerdida
							,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
							,CT.CuartoUtil
							,CT.Exteriores
							,CT.Tapizados
							,CT.Sucursal
							,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
							,CT.Fecha_Empaque
							,CT.Hora_Empaque
							,CT.Periodicidad
							,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
							,CT.Ref_Movil
							,CT.Ref_Direccion
							,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
							,CT.IdBodega
							,CT.BloqueoCot
							,CT.Poliza
							,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
							,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
							,CT.EmpaqueVenta
							,CT.Serv_Inter
							,CT.Flete_Inter
							,CT.Gastos_Inter
							,CT.Vaduana_Inter
							,CT.Otros_Inter
							,CT.Aduana_Inter
							,CT.Observa_Inter
							,CT.IdCia
							,CT.ObservaEmpaque
							,CT.ObservaCliente
							,CT.IdEmpresa
							,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,CT.NumOrden
							,CT.ContactoEmpresa
							,CT.CorreoContacto
							,CT.FechaIniBod
							,CT.FechaFinBod
							,CT.ObservaBodega
							,CT.Cortesia
							,CT.FechaCortIni
							,CT.FechaCortFin
							,CT.FechaUltima
							,CT.Manifiesto
							,CT.Remesa
						    ,CT.IdGestion
							,CT.FechaProximo
						    ,CT.Ctrl_Cotizacion
						    ,CT.ContadorCorreo
							,CT.CodVerificacion
						    ,CT.AutorizaCortesia
						    ,CT.TteSalida
							,CT.Ocupacion
						    ,CT.VrSugerido
						    ,CT.VrNegociado
							,CT.ObservaInterna
							,CT.Valor_Vehiculo
							,ORG.Nombre as CiudadOrigen
							,DST.Nombre as CiudadDestino
							,SRV.Nombre as NombreServicio
							,TSV.Nombre as NombreTipoServ
							,CIA.NombreCia as NombreCia
							,CL.Identificacion as IdentCliente
							,CL.Movil as MovilCliente
							,CL.Email as CorreoCliente
							,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
							,CASE CT.Medio_Comunicacion
								WHEN '1' THEN 'LLAMADA'
								WHEN '2' THEN 'CORREO ELECTRONICO'
								WHEN '3' THEN 'PAGINA WEB'
								WHEN '4' THEN 'LLAMADA PBX'
								WHEN '5' THEN 'WHATSAPP NACIONAL'
								WHEN '6' THEN 'WHATSAPP'
							ELSE '0' 
							 END AS NegocioOrigen
							,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
							,SL.Estado as EstadoSolicitud
			    
					FROM [dbo].[Cotizacion] as CT left join [dbo].[Solicitudes] as SL on CT.IdSolicitud = SL.IdSolicitud,
						 [dbo].[Clientes] as CL,
						 [dbo].[Ciudades] as ORG,
						 [dbo].[Ciudades] as DST,
						 [dbo].[Servicios] as SRV,
						 [dbo].[TipoServicio] as TSV,
						 [dbo].[Compania] as CIA,
						 [dbo].[Usuarios] as USU
					 
					WHERE CT.IdCliente      = CL.IdCliente and
						  CT.Ciudad_Origen  = ORG.IdCiudad and
						  CT.Ciudad_Destino = DST.IdCiudad and
						  CT.Servicios      = SRV.IdServicio and
						  CT.TipoServ       = TSV.IdTipo and
						  CT.IdCia          = CIA.IdCia and
						  CT.IdUsuario      = @IdUsuario and
						  CT.IdEstadoCot    <> 7 and
						  SL.Fecha between @FechaIni and @FechaFin  

					ORDER BY FechaCotizacion DESC
				END
		END

	IF @Opcion = 11 -- Consultar por Manifiesto
		BEGIN
			SELECT	 CT.IdCotizacion
					,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					,CT.EmpaqueVenta
					,CT.Serv_Inter
					,CT.Flete_Inter
					,CT.Gastos_Inter
					,CT.Vaduana_Inter
					,CT.Otros_Inter
					,CT.Aduana_Inter
					,CT.Observa_Inter
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.IdEmpresa
					,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,CT.NumOrden
					,CT.ContactoEmpresa
					,CT.CorreoContacto
					,CT.FechaIniBod
					,CT.FechaFinBod
					,CT.ObservaBodega
					,CT.Cortesia
					,CT.FechaCortIni
					,CT.FechaCortFin
					,CT.FechaUltima
					,CT.Manifiesto
					,CT.Remesa
					,CT.IdGestion
					,CT.FechaProximo
					,CT.Ctrl_Cotizacion
					,CT.ContadorCorreo
					,CT.CodVerificacion
					,CT.AutorizaCortesia
					,CT.TteSalida
					,CT.Ocupacion
					,CT.VrSugerido
					,CT.VrNegociado
				    ,CT.ObservaInterna
					,CT.Valor_Vehiculo
					,ORG.Nombre as CiudadOrigen
					,ORG.CodDane as LocOrigen
					,DST.Nombre as CiudadDestino
					,DST.CodDane as LocDestino
					,SRV.Nombre as NombreServicio
					,TSV.Nombre as NombreTipoServ
					,CIA.NombreCia as NombreCia
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.Email as CorreoCliente
					,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					 END AS NegocioOrigen
					,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
			FROM [dbo].[Cotizacion] as CT
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario

			WHERE CT.Manifiesto = @Manifiesto 
		END

	IF @Opcion = 12 -- Consultar por Cliente
		BEGIN
			SELECT	 CT.IdCotizacion
					,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CASE CT.IdEstadoCot
						WHEN '2' THEN 'COTIZACION'
						WHEN '3' THEN 'SEGUIMIENTO'
						WHEN '4' THEN 'PREOPERACIONAL'
						WHEN '5' THEN 'CONFIRMADO'
						ELSE '0' 
					 END AS NombreEstado
					,CONCAT(US.Nombres, ' ',US.Apellidos) as NombreAsesor
					,CONCAT(CL.Nombres, ' ',CL.Apellidos) as NombreCliente
			    
			FROM [dbo].[Cotizacion] as CT,
				 [dbo].[Usuarios] as US,
				 [dbo].[Clientes] as CL

			WHERE CT.IdCotizacion = (SELECT MAX(IdCotizacion) FROM [dbo].[Cotizacion] WHERE IdCliente = @IdCliente and IdEstadoCot <= @IdEstadoCot) and
				  CT.IdUsuario    = US.IdUsuario and
				  CT.IdCliente    = CL.IdCliente
				   
		END

	IF @Opcion = 13 -- Consultar por movil
		BEGIN
			SELECT  CT.IdCotizacion
					,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.Servicios
					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
			 		,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
			   		,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					,CT.EmpaqueVenta
					,CT.Serv_Inter
					,CT.Flete_Inter
					,CT.Gastos_Inter
					,CT.Vaduana_Inter
					,CT.Otros_Inter
					,CT.Aduana_Inter
					,CT.Observa_Inter
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.IdEmpresa
					,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,CT.NumOrden
					,CT.ContactoEmpresa
					,CT.CorreoContacto
					,CT.FechaIniBod
					,CT.FechaFinBod
					,CT.ObservaBodega
					,CT.Cortesia
					,CT.FechaCortIni
					,CT.FechaCortFin
					,CT.FechaUltima
					,CT.Manifiesto
					,CT.Remesa
					,CT.IdGestion
					,CT.FechaProximo
					,CT.Ctrl_Cotizacion
					,CT.ContadorCorreo
					,CT.CodVerificacion
					,CT.AutorizaCortesia
					,CT.TteSalida
					,CT.Ocupacion
					,CT.VrSugerido
					,CT.VrNegociado
				    ,CT.ObservaInterna
					,CT.Valor_Vehiculo
					,ORG.Nombre as CiudadOrigen
					,ORG.CodDane as LocOrigen
					,DST.Nombre as CiudadDestino
					,DST.CodDane as LocDestino
					,SRV.Nombre as NombreServicio
					,TSV.Nombre as NombreTipoServ
					,CIA.NombreCia as NombreCia
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.Email as CorreoCliente
					,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					 END AS NegocioOrigen
					,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
			FROM [dbo].[Cotizacion] as CT
					LEFT  JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario

			WHERE CL.Movil       like CONCAT('%',ISNULL(@Movil,CL.Movil),'%')  and 
				  CT.FechaUltima between ISNULL(@FechaIni,CT.FechaUltima) and ISNULL(@FechaFin,CT.FechaUltima) and
				  CT.IdEstadoCot <> 7 
		END

	IF @Opcion = 14 -- Consultar por Cotizaciones Rechazadas
		BEGIN
			IF @IdUsuario IS NOT NULL
				BEGIN
					SELECT   CT.IdCotizacion
							,CT.IdCliente
							,CT.IdSolicitud
							,CT.IdUsuario
							,CT.FechaCotizacion
							,CT.Servicios
							,CT.Ciudad_Origen
							,CT.Ciudad_Destino
							,CT.IdEstadoCot
							,CT.TipoServ
							,CT.MotivoPerdida
							,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
							,CT.IdCia
							,CT.IdEmpresa
							,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,CT.ContactoEmpresa
							,CT.CorreoContacto
							,CT.FechaUltima
							,CT.CodVerificacion
						    ,CT.AutorizaCortesia
							,CT.TteSalida
							,CT.Ocupacion
							,CT.VrSugerido
							,CT.VrNegociado
				            ,CT.ObservaInterna
						    ,ORG.Nombre as CiudadOrigen
						    ,ORG.CodDane as LocOrigen
						    ,DST.Nombre as CiudadDestino
						    ,DST.CodDane as LocDestino
						    ,SRV.Nombre as NombreServicio
						    ,TSV.Nombre as NombreTipoServ
						    ,CIA.NombreCia as NombreCia
						    ,CL.Identificacion as IdentCliente
						    ,CL.Movil as MovilCliente
						    ,CL.Email as CorreoCliente
						    ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
							,CASE CT.Medio_Comunicacion
								WHEN '1' THEN 'LLAMADA'
								WHEN '2' THEN 'CORREO ELECTRONICO'
								WHEN '3' THEN 'PAGINA WEB'
								WHEN '4' THEN 'LLAMADA PBX'
								WHEN '5' THEN 'WHATSAPP NACIONAL'
								WHEN '6' THEN 'WHATSAPP'
								ELSE '0' 
							 END AS NegocioOrigen
							,SG.Gestion
							,NOV.Descripcion AS Mot_Perdida
							,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT
							LEFT JOIN [dbo].[Seguimientos] as SG ON CT.IdCotizacion = SG.IdCotizacion and SG.IdEstadoCot = 6,
						 [dbo].[Clientes] as CL,
						 [dbo].[Ciudades] as ORG,
						 [dbo].[Ciudades] as DST,
						 [dbo].[Servicios] as SRV,
						 [dbo].[TipoServicio] as TSV,
						 [dbo].[Compania] as CIA,
						 [dbo].[Usuarios] as USU,
						 [dbo].[Novedades] as NOV

					WHERE CT.IdUsuario      = @IdUsuario and
					      CT.MotivoPerdida  = NOV.IdNovedad and 
						  CT.IdCliente      = CL.IdCliente and
						  CT.Ciudad_Origen  = ORG.IdCiudad and
						  CT.Ciudad_Destino = DST.IdCiudad and
						  CT.Servicios      = SRV.IdServicio and
						  CT.TipoServ       = TSV.IdTipo and
						  CT.IdCia          = CIA.IdCia and
						  CT.IdUsuario      = USU.IdUsuario and
						  CT.IdEstadoCot    = 6 and
						  CT.FechaUltima between @FechaIni and @FechaFin  
				END

			IF @IdUsuario IS NULL
				BEGIN
					SELECT   CT.IdCotizacion
							,CT.IdCliente
							,CT.IdSolicitud
							,CT.IdUsuario
							,CT.FechaCotizacion
							,CT.Servicios
							,CT.Ciudad_Origen
							,CT.Ciudad_Destino
							,CT.IdEstadoCot
							,CT.TipoServ
							,CT.MotivoPerdida
							,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
							,CT.IdCia
							,CT.IdEmpresa
							,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,CT.ContactoEmpresa
							,CT.CorreoContacto
							,CT.FechaUltima
							,CT.CodVerificacion
						    ,CT.AutorizaCortesia
						    ,CT.TteSalida
							,CT.Ocupacion
						    ,CT.VrSugerido
						    ,CT.VrNegociado
							,CT.ObservaInterna
						    ,ORG.Nombre as CiudadOrigen
						    ,ORG.CodDane as LocOrigen
						    ,DST.Nombre as CiudadDestino
						    ,DST.CodDane as LocDestino
						    ,SRV.Nombre as NombreServicio
						    ,TSV.Nombre as NombreTipoServ
						    ,CIA.NombreCia as NombreCia
						    ,CL.Identificacion as IdentCliente
						    ,CL.Movil as MovilCliente
						    ,CL.Email as CorreoCliente
						    ,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
							,CASE CT.Medio_Comunicacion
								WHEN '1' THEN 'LLAMADA'
								WHEN '2' THEN 'CORREO ELECTRONICO'
								WHEN '3' THEN 'PAGINA WEB'
								WHEN '4' THEN 'LLAMADA PBX'
								WHEN '5' THEN 'WHATSAPP NACIONAL'
								WHEN '6' THEN 'WHATSAPP'
								ELSE '0' 
							 END AS NegocioOrigen
							,SG.Gestion
							,NOV.Descripcion AS Mot_Perdida
							,CONCAT(USU.Apellidos, ' ', USU.Nombres) as NombreAsesor
			    
					FROM [dbo].[Cotizacion] as CT
							LEFT JOIN [dbo].[Seguimientos] as SG ON CT.IdCotizacion = SG.IdCotizacion and SG.IdEstadoCot = 6,
						 [dbo].[Clientes] as CL,
						 [dbo].[Ciudades] as ORG,
						 [dbo].[Ciudades] as DST,
						 [dbo].[Servicios] as SRV,
						 [dbo].[TipoServicio] as TSV,
						 [dbo].[Compania] as CIA,
						 [dbo].[Usuarios] as USU,
						 [dbo].[Novedades] as NOV

					WHERE CT.IdCliente      = CL.IdCliente and
					      CT.MotivoPerdida  = NOV.IdNovedad and 
						  CT.Ciudad_Origen  = ORG.IdCiudad and
						  CT.Ciudad_Destino = DST.IdCiudad and
						  CT.Servicios      = SRV.IdServicio and
						  CT.TipoServ       = TSV.IdTipo and
						  CT.IdCia          = CIA.IdCia and
						  CT.IdUsuario      = USU.IdUsuario and
						  CT.IdEstadoCot    = 6 and
						  CT.FechaUltima between @FechaIni and @FechaFin  
				END
		END

	IF @Opcion = 15 -- Consultar por Asesor y Control
		BEGIN
			SELECT  CT.IdCotizacion
					,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.Ctrl_Cotizacion
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.Email as CorreoCliente
					,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
			    
			FROM [dbo].[Cotizacion] as CT
					LEFT JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente

			WHERE CT.IdUsuario       = @IdUsuario and
				  CT.Ctrl_Cotizacion = 0  
		END

	IF @Opcion = 16 -- Consultar por parametros y Concepto(Transprote Nacional)
		BEGIN
			SELECT CT.IdCotizacion
		  			,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.Servicios
  					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					,CL.Identificacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					,CT.EmpaqueVenta
					,CT.Serv_Inter
					,CT.Flete_Inter
					,CT.Gastos_Inter
					,CT.Vaduana_Inter
					,CT.Otros_Inter
					,CT.Aduana_Inter
					,CT.Observa_Inter
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.IdEmpresa
					,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,CT.NumOrden
					,CT.ContactoEmpresa
					,CT.CorreoContacto
					,CT.FechaIniBod
					,CT.FechaFinBod
					,CT.ObservaBodega
					,CT.Cortesia
					,CT.FechaCortIni
					,CT.FechaCortFin
					,CT.FechaUltima
					,CT.Manifiesto
					,CT.Remesa
					,CT.IdGestion
					,CT.FechaProximo
					,CT.Ctrl_Cotizacion
					,CT.ContadorCorreo
					,CT.CodVerificacion
					,CT.AutorizaCortesia
					,CT.TteSalida
					,CT.Ocupacion
					,CT.VrSugerido
					,CT.VrNegociado
				    ,CT.ObservaInterna
					,CT.Valor_Vehiculo
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino
					,SRV.Nombre as NombreServicio
					,TSV.Nombre as NombreTipoServ
					,CIA.NombreCia as NombreCia
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.Email as CorreoCliente
					,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente
					,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					 END AS NegocioOrigen
					,CONCAT(usu.Nombres,' ',USU.Apellidos) AS NombreUsuario
					,EST.Nombre as NombreEstado
					,DPO.Nombre as DptoOrigen
					,DPD.Nombre as DptoDestino
					,CC.Valor_Negociado
					  				   
			FROM [dbo].[Cotizacion] as CT
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Departamentos] as DPO ON ORG.IdDepartamento = DPO.IdDepartamento
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Departamentos] as DPD ON DST.IdDepartamento = DPD.IdDepartamento
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					INNER JOIN [dbo].[Estado_Cotizacion] as EST ON CT.IdEstadoCot = EST.IdEstadoCot
					INNER JOIN [dbo].[Solicitudes] as SL ON CT.IdSolicitud = SL.IdSolicitud
					inner join [dbo].[Cotizacion_Conceptos] as CC on CT.IdCotizacion = CC.IdCotizacion and CC.IdServicio = 9

			WHERE SL.Movil        like CONCAT('%',ISNULL(@Movil,SL.Movil),'%')  and 
				  CT.IdCotizacion between ISNULL(@IdCotizacion,CT.IdCotizacion) and ISNULL(@IdCotizacion,CT.IdCotizacion) and
				  CT.IdEstadoCot  between ISNULL(@IdEstadoCot,CT.IdEstadoCot) and ISNULL(@IdEstadoCot,CT.IdEstadoCot) and
				  CT.TipoServ     between ISNULL(@TipoServ,0) and ISNULL(@TipoServ,99) and
				  CT.IdUsuario    between ISNULL(@IdUsuario,CT.IdUsuario) and ISNULL(@IdUsuario,CT.IdUsuario) and
				  CT.FechaUltima  between ISNULL(@FechaIni,CT.FechaUltima) and ISNULL(@FechaFin,CT.FechaUltima)

			ORDER BY IdEstadoCot DESC
		END

	IF @Opcion = 17 -- Consultar por parametros y Concepto(Transprote Nacional)
		BEGIN
			SELECT CT.IdCotizacion
		  			,CT.IdCliente
					,CT.IdSolicitud
					,CT.IdUsuario
					,CT.FechaCotizacion
					,CT.Servicios
  					,CT.Ciudad_Origen
					,CT.Direccion_Origen
					,CT.Ciudad_Destino
					,CT.Direccion_Destino
					,CT.Volumen
					,CT.Arte
					,CT.Presencial
					,CT.FechaPresencial
					,CT.HoraPresencial
					,CT.Seguro
					,CT.Valor_Declarado
					,CT.Porc_Liquidacion
					,CT.IdFormaPago
					,CT.IdMetodoPago
					,CT.Almacenamiento
					,CT.Fecha_Recogida
					,CT.Hora_Recogida
					,CT.Fecha_Entrega
					,CT.Hora_Entrega
					,CT.Autorizado
					,CT.Tipo_Ident_Autorizado
					,CT.Ident_Autorizado
					,CT.Telefono_Autorizado
					,CT.Medio_Comunicacion
					,CT.Medio_Servicio
					,CT.IdEstadoCot
					,CT.ValorCotizacion
					,CT.Observacion COLLATE Cyrillic_General_CI_AI as Observacion
					,CL.Identificacion
					,CT.IdCotPresencial
					,CT.TipoServ
					,CT.MotivoPerdida
					,CT.ObservaPerdida COLLATE Cyrillic_General_CI_AI as ObservaPerdida
					,CT.CuartoUtil
					,CT.Exteriores
					,CT.Tapizados
					,CT.Sucursal
					,CT.ObservaPago COLLATE Cyrillic_General_CI_AI as ObservaPago
					,CT.Fecha_Empaque
					,CT.Hora_Empaque
					,CT.Periodicidad
					,CT.Ref_Personal COLLATE Cyrillic_General_CI_AI as Ref_Personal
					,CT.Ref_Movil
					,CT.Ref_Direccion
					,CT.Ref_Correo COLLATE Cyrillic_General_CI_AI as Ref_Correo
					,CT.IdBodega
					,CT.BloqueoCot
					,CT.Poliza
					,CT.Barrio_Origen COLLATE Cyrillic_General_CI_AI as Barrio_Origen
					,CT.Barrio_Destino COLLATE Cyrillic_General_CI_AI as Barrio_Destino
					,CT.EmpaqueVenta
					,CT.Serv_Inter
					,CT.Flete_Inter
					,CT.Gastos_Inter
					,CT.Vaduana_Inter
					,CT.Otros_Inter
					,CT.Aduana_Inter
					,CT.Observa_Inter
					,CT.IdCia
					,CT.ObservaEmpaque
					,CT.ObservaCliente
					,CT.IdEmpresa
					,CT.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,CT.NumOrden
					,CT.ContactoEmpresa
					,CT.CorreoContacto
					,CT.FechaIniBod
					,CT.FechaFinBod
					,CT.ObservaBodega
					,CT.Cortesia
					,CT.FechaCortIni
					,CT.FechaCortFin
					,CT.FechaUltima
					,CT.Manifiesto
					,CT.Remesa
					,CT.IdGestion
					,CT.FechaProximo
					,CT.Ctrl_Cotizacion
					,CT.ContadorCorreo
					,CT.CodVerificacion
					,CT.AutorizaCortesia
					,CT.TteSalida
					,CT.Ocupacion
					,CT.VrSugerido
					,CT.VrNegociado
				    ,CT.ObservaInterna
					,CT.Valor_Vehiculo
					,ORG.Nombre as CiudadOrigen
					,DST.Nombre as CiudadDestino
					,SRV.Nombre as NombreServicio
					,TSV.Nombre as NombreTipoServ

					,CIA.NombreCia as NombreCia

					--CLIENTE
					,CL.Identificacion as IdentCliente
					,CL.Movil as MovilCliente
					,CL.Email as CorreoCliente
					,CONCAT(CL.Nombres, ' ', CL.Apellidos) as NombreCliente

					,CASE CT.Medio_Comunicacion
						WHEN '1' THEN 'LLAMADA'
						WHEN '2' THEN 'CORREO ELECTRONICO'
						WHEN '3' THEN 'PAGINA WEB'
						WHEN '4' THEN 'LLAMADA PBX'
						WHEN '5' THEN 'WHATSAPP NACIONAL'
						WHEN '6' THEN 'WHATSAPP'
						ELSE '0' 
					 END AS NegocioOrigen
					,CONCAT(usu.Nombres,' ',USU.Apellidos) AS NombreUsuario
					,EST.Nombre as NombreEstado
					,DPO.Nombre as DptoOrigen
					,DPD.Nombre as DptoDestino
					,CC.Valor_Negociado

					--ORDEN SERVICIO
					,OS.FechaOrden

					--COTIZACION-CONCEPTOS
					,CC.IdServicioCot
					,CC.IdCotizacion
					,CC.IdServicio
					,CC.CodSyscom
					,CC.Nombre as NomConcepto
					,CC.Descripcion
					,CC.Valor_Servicio
					,CC.Valor_Negociado
					,CC.IdAsesor
					,CC.Valor_Iva
					  				   
			FROM [dbo].[Cotizacion] as CT
					INNER JOIN [dbo].[Clientes] as CL ON CT.IdCliente = CL.IdCliente
					INNER JOIN [dbo].[Ciudades] as ORG ON CT.Ciudad_Origen = ORG.IdCiudad
					INNER JOIN [dbo].[Departamentos] as DPO ON ORG.IdDepartamento = DPO.IdDepartamento
					INNER JOIN [dbo].[Ciudades] as DST ON CT.Ciudad_Destino = DST.IdCiudad
					INNER JOIN [dbo].[Departamentos] as DPD ON DST.IdDepartamento = DPD.IdDepartamento
					INNER JOIN [dbo].[Servicios] as SRV ON CT.Servicios = SRV.IdServicio
					INNER JOIN [dbo].[TipoServicio] as TSV ON CT.TipoServ = TSV.IdTipo
					INNER JOIN [dbo].[Compania] as CIA ON CT.IdCia = CIA.IdCia
					INNER JOIN [dbo].[Usuarios] as USU ON CT.IdUsuario = USU.IdUsuario
					INNER JOIN [dbo].[Estado_Cotizacion] as EST ON CT.IdEstadoCot = EST.IdEstadoCot
					INNER JOIN [dbo].[Solicitudes] as SL ON CT.IdSolicitud = SL.IdSolicitud
					INNER JOIN [dbo].[Cotizacion_Conceptos] as CC on CT.IdCotizacion = CC.IdCotizacion 
					LEFT  JOIN [dbo].[OrdenServicio] AS OS ON CT.IdCotizacion = OS.IdCotizacion

			WHERE SL.Movil        like CONCAT('%',ISNULL(@Movil,SL.Movil),'%')  and 
				  CT.IdCotizacion between ISNULL(@IdCotizacion,CT.IdCotizacion) and ISNULL(@IdCotizacion,CT.IdCotizacion) and
				  CT.IdEstadoCot  between ISNULL(@IdEstadoCot,CT.IdEstadoCot) and ISNULL(@IdEstadoCot,CT.IdEstadoCot) and
				  CT.TipoServ     between ISNULL(@TipoServ,0) and ISNULL(@TipoServ,99) and
				  CT.IdUsuario    between ISNULL(@IdUsuario,CT.IdUsuario) and ISNULL(@IdUsuario,CT.IdUsuario) and
				  CT.FechaUltima  between ISNULL(@FechaIni,CT.FechaUltima) and ISNULL(@FechaFin,CT.FechaUltima)

		END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetCotMaterialesArticulo]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 04/03/2022
-- Description:	Buscar Cotizacion Mat-Art
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCotMaterialesArticulo]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdCot_MatArt int = null,
	@IdCotizacion int = null,
	@IdSolicitud int = null,
	@CodVerifica int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
	  BEGIN
		SELECT  MA.IdCot_MatArt
				,MA.IdCotizacion
				,MA.IdCot_Articulo
				,MA.IdMaterial
				,MA.NombreMaterial COLLATE Cyrillic_General_CI_AI as NombreMaterial
				,MA.IdArticulo
				,MA.NombreArticulo COLLATE Cyrillic_General_CI_AI as NombreArticulo
				,MA.Valor
				,MA.Cantidad
				,MA.IdSolicitud

		FROM [dbo].[Cotizacion_MaterialesArticulo] as MA

	  END

	IF @Opcion = 2 -- Consultar por cotizacion
	  BEGIN
		IF @IdCotizacion IS NOT NULL and @IdSolicitud IS NULL
			BEGIN
				SELECT  MA.IdCot_MatArt
						,MA.IdCotizacion
						,MA.IdCot_Articulo
						,MA.IdMaterial
						,MA.NombreMaterial COLLATE Cyrillic_General_CI_AI as NombreMaterial
						,MA.IdArticulo
						,MA.NombreArticulo COLLATE Cyrillic_General_CI_AI as NombreArticulo
						,MA.Valor
						,MA.Cantidad
						,MA.IdSolicitud

				FROM  [dbo].[Cotizacion_MaterialesArticulo] as MA

				WHERE MA.IdCotizacion = @IdCotizacion 
			END

		IF @IdCotizacion IS NOT NULL and @IdSolicitud IS NOT NULL
			BEGIN
				SELECT  MA.IdCot_MatArt
						,MA.IdCotizacion
						,MA.IdCot_Articulo
						,MA.IdMaterial
						,MA.NombreMaterial COLLATE Cyrillic_General_CI_AI as NombreMaterial
						,MA.IdArticulo
						,MA.NombreArticulo COLLATE Cyrillic_General_CI_AI as NombreArticulo
						,MA.Valor
						,MA.Cantidad
						,MA.IdSolicitud

				FROM  [dbo].[Cotizacion_MaterialesArticulo] as MA

				WHERE MA.IdCotizacion = @IdCotizacion and
					  MA.IdSolicitud = @IdSolicitud
			END
			  
	  END

	IF @Opcion = 3 -- Consultar por solicitud y cotizacion
		BEGIN
			SELECT MA.IdCot_MatArt
				  ,MA.IdCotizacion
				  ,MA.IdCot_Articulo
				  ,MA.IdMaterial
				  ,MA.NombreMaterial COLLATE Cyrillic_General_CI_AI as NombreMaterial
				  ,MA.IdArticulo
				  ,MA.NombreArticulo COLLATE Cyrillic_General_CI_AI as NombreArticulo
				  ,MA.Valor
				  ,MA.Cantidad
				  ,MA.IdSolicitud
				  ,HCA.IdHist_CotArticulo

			FROM [dbo].[Cotizacion_MaterialesArticulo] as MA
					LEFT JOIN [dbo].[Hist_Cotizacion_Articulos] as HCA ON MA.IdSolicitud = HCA.IdSolicitud and HCA.CodVerificacion = @CodVerifica and MA.IdArticulo = HCA.IdArticulo

			WHERE MA.IdCotizacion = @IdCotizacion and
				  MA.IdSolicitud  = @IdSolicitud
		END
END


GO
/****** Object:  StoredProcedure [dbo].[spGetCotRequisiciones]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 02/05/2022
-- Description:	Buscar Requisicion por Cotizaicon
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCotRequisiciones] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdRequisicion int = null,
	@IdCotizacion int = null,
	@Clase int = null,
	@IdSolicitud int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos las Requisiciones
		BEGIN
			DELETE [dbo].[Cotizacion_Requisicion] WHERE Cantidad =  0
			SELECT  REQ.IdRequisicion
					,REQ.IdMaterial
					,REQ.IdCotizacion
					,REQ.Cantidad
					,REQ.ValorRequisicion
					,REQ.Clase
					,REQ.IdSolicitud
					,MAT.Nombre COLLATE Cyrillic_General_CI_AI as NombreMaterial
					,MAT.CodSyscom
					,MAT.SubGrupo
					,UND.CodSyscom as SysUnidad
					,MAT.Descripcion COLLATE Cyrillic_General_CI_AI as Descripcion
  
			FROM [dbo].[Cotizacion_Requisicion] as REQ
					INNER JOIN [dbo].[Materiales] as MAT ON REQ.IdMaterial = MAT.IdMaterial
					INNER JOIN [dbo].[Unidades] as UND ON MAT.IdUnidad = UND.IdUnidad
		END

	IF @Opcion = 2  -- Consula Requisiciones por Cotizacion
		BEGIN
			DELETE [dbo].[Cotizacion_Requisicion] WHERE Cantidad =  0
			SELECT  REQ.IdRequisicion
					,REQ.IdMaterial
					,REQ.IdCotizacion
					,REQ.Cantidad
					,REQ.ValorRequisicion
					,REQ.Clase
					,REQ.IdSolicitud
					,MAT.Nombre COLLATE Cyrillic_General_CI_AI as NombreMaterial
					,MAT.CodSyscom
					,MAT.SubGrupo
					,UND.CodSyscom as SysUnidad
					,MAT.Descripcion COLLATE Cyrillic_General_CI_AI as Descripcion
							
			FROM [dbo].[Cotizacion_Requisicion] as REQ
					INNER JOIN [dbo].[Materiales] as MAT ON REQ.IdMaterial = MAT.IdMaterial
					INNER JOIN [dbo].[Unidades] as UND ON MAT.IdUnidad = UND.IdUnidad

			WHERE REQ.IdCotizacion between ISNULL(@IdCotizacion,REQ.IdCotizacion) and ISNULL(@IdCotizacion,REQ.IdCotizacion) and 
				  REQ.IdSolicitud  between ISNULL(@IdSolicitud,REQ.IdSolicitud) and ISNULL(@IdSolicitud,REQ.IdSolicitud) and
				  REQ.Clase        between ISNULL(@Clase,REQ.Clase) and ISNULL(@Clase,REQ.Clase)
		END

	IF @Opcion = 3  -- Consula todos los materiales
		BEGIN
			SELECT CMA.IdMaterial, CMA.IdCotizacion, sum(CMA.Cantidad) as TotalCantidad, sum(CMA.Valor) as TotalValor
			FROM [dbo].[Cotizacion_MaterialesArticulo] as CMA
			WHERE CMA.IdCotizacion = @IdCotizacion and CMA.IdSolicitud = @IdSolicitud
			GROUP BY CMA.IdMaterial, CMA.IdCotizacion
		END

	IF @Opcion = 4  -- Consula todos los Tipo
		BEGIN
			SELECT EMP.IdMaterial, EMP.IdCotizacion, sum(EMP.Cantidad) as TotalCantidad, sum(EMP.ValorCosto)  as TotalValor
			FROM [dbo].[Cotizacion_Empaques] as EMP
			WHERE EMP.IdCotizacion = @IdCotizacion and EMP.IdSolicitud = @IdSolicitud 
			GROUP BY EMP.IdMaterial, EMP.IdCotizacion
		END

	IF @Opcion = 5  -- Calcular Totales
		BEGIN
			DECLARE 
			@TotalCant numeric(18,2) = null,
			@TotalVals numeric(18,2) = null

			--Generar IVA
			SELECT sum(Cantidad) as TotalCant, sum(ValorRequisicion) as TotalVals FROM [dbo].[Cotizacion_Requisicion]	WHERE IdCotizacion = @IdCotizacion 

			
		END

END






GO
/****** Object:  StoredProcedure [dbo].[spGetCotTotales]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 12/05/2022
-- Description: Sacar Totales Cotizacion
-- =============================================
CREATE   PROCEDURE [dbo].[spGetCotTotales]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdCotizacion Int=null,
	@IdServicio Int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Genera los totales por Concepto
		BEGIN
			SELECT CT.IdConceptoPDF, sum(CT.Valor_Negociado) as TotalConcepto, CT.IdCotizacion
			FROM [dbo].[Cotizacion_Conceptos] as CT
			WHERE CT.IdCotizacion = @IdCotizacion
			GROUP BY CT.IdConceptoPDF, CT.IdCotizacion
		END

	IF @Opcion = 2  --  Consultar por Cotizacion
		BEGIN
			SELECT CS.IdServValor
				   ,CS.IdConceptoPDF
				   ,CS.IdCotizacion
				   ,CS.ValorServicio
			
			FROM [dbo].[Cotizacion_Servicios] as CS

			WHERE CS.IdCotizacion = @IdCotizacion
		END

	IF @Opcion = 3  -- Registrar TotalGeneral y TotalIva
		BEGIN
			DECLARE 
			@TotalIva numeric(18,0) = null,
			@Totales  numeric(18,0) = null

			--Generar IVA
			SELECT @TotalIva = sum(Valor_Iva) FROM [dbo].[Cotizacion_Conceptos]	WHERE IdCotizacion = @IdCotizacion and IdConceptoPDF <= '20'

			--Registrar IVA
			INSERT INTO [dbo].[Cotizacion_Servicios] ([IdConceptoPDF], [IdCotizacion], [ValorServicio]) VALUES  ('21',@IdCotizacion,@TotalIva)

			--Generar Totales
			SELECT @Totales = sum(ValorServicio) FROM [dbo].[Cotizacion_Servicios] WHERE IdCotizacion = @IdCotizacion and IdConceptoPDF <= '21'

			--Registrar Totales
			INSERT INTO [dbo].[Cotizacion_Servicios] ([IdConceptoPDF], [IdCotizacion], [ValorServicio]) VALUES ('22',@IdCotizacion,@Totales)
			UPDATE [dbo].[Cotizacion] SET ValorCotizacion = @Totales WHERE IdCotizacion = @IdCotizacion
		END

	IF @Opcion = 4  -- Actualizar TotalGeneral y TotalIva
		BEGIN
			--Generar IVA
			SELECT @TotalIva = sum(Valor_Iva) FROM [dbo].[Cotizacion_Conceptos]	WHERE IdCotizacion = @IdCotizacion 

			--Actualizar IVA
			UPDATE [dbo].[Cotizacion_Servicios] SET ValorServicio = @TotalIva WHERE IdCotizacion = @IdCotizacion and IdConceptoPDF = '21'
			--Generar Totales
			SELECT @Totales = sum(ValorServicio) FROM [dbo].[Cotizacion_Servicios] WHERE IdCotizacion = @IdCotizacion and IdConceptoPDF <= '21'

			--Actualizar
			UPDATE [dbo].[Cotizacion_Servicios] SET ValorServicio = @Totales WHERE IdCotizacion = @IdCotizacion and IdConceptoPDF = '22'
		END

	IF @Opcion = 5  --  Consultar por Cotizacion
		BEGIN
			SELECT CS.IdServValor
				   ,CS.IdConceptoPDF
				   ,CS.IdCotizacion
				   ,CS.ValorServicio
			
			FROM [dbo].[Cotizacion_Servicios] as CS
		END

	IF @Opcion = 6  -- Genera los totales por Servicio
		BEGIN
			SELECT CT.IdServicio, sum(CT.Valor_Negociado) as TotalConcepto, CT.IdCotizacion
			FROM [dbo].[Cotizacion_Conceptos] as CT
			WHERE CT.IdCotizacion = @IdCotizacion
			GROUP BY CT.IdServicio, CT.IdCotizacion
		END
		
END
GO
/****** Object:  StoredProcedure [dbo].[spGetDepartamentos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 20/09/2021
-- Description:	Buscar Departamentos
-- =============================================
CREATE   PROCEDURE [dbo].[spGetDepartamentos]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdDepartamento Int=null,
	@CodDepartamento varchar(125)=null,
	@Nombre varchar(255)=null,
	@IdPais Int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Departametno
	  BEGIN
		SELECT  [IdDepartamento]
			   ,[CodDepartamento]
			   ,[Nombre]
			   ,[IdPais]
		FROM  [dbo].[Departamentos]
		ORDER BY Nombre
	  END

	IF @Opcion = 2 -- Consultar por Departamento
	  BEGIN
		SELECT  [IdDepartamento]
			   ,[CodDepartamento]
			   ,[Nombre]
			   ,[IdPais]
		FROM  [dbo].[Departamentos]
		WHERE IdDepartamento = @IdDepartamento
	  END
   
	IF @Opcion = 3 -- Consultar por Departamento
	  BEGIN
		SELECT  [IdDepartamento]
			   ,[CodDepartamento]
			   ,[Nombre]
			   ,[IdPais]
		FROM  [dbo].[Departamentos]
		WHERE IdPais = @IdPais
	  END

END
GO
/****** Object:  StoredProcedure [dbo].[spGetDisponibilidad]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 01/10/2021
-- Description:	Buscar Disponibilidad
-- ==============================================
CREATE   PROCEDURE [dbo].[spGetDisponibilidad]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdDisponibilidad Int=null,
	@IdVehiculo Int=null,
	@Fecha_Ini varchar(10)=null,
    @Fecha_Fin varchar(10)=null,
	@Hora_Ini varchar(8)=null,
    @Hora_Fin varchar(8)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
	  BEGIN
		SELECT  [IdDisponibilidad]
				,[IdVehiculo]
				,[Fecha_Ini]
				,[Fecha_Fin]
				,[Hora_Ini]
				,[Hora_Fin]
				
		FROM [dbo].[Disponibilidad_Vehiculos]
	  END

	IF @Opcion = 2 -- Consultar por Material
	  BEGIN
		SELECT  DP.IdDisponibilidad
				,DP.IdVehiculo
				,DP.Fecha_Ini
				,DP.Fecha_Fin
				,DP.Hora_Ini
				,DP.Hora_Fin
				
		FROM  [dbo].[Disponibilidad_Vehiculos] as DP, [dbo].[Vehiculos] as VH
		WHERE VH.IdVehiculo = DP.IdVehiculo and DP.IdVehiculo = @IdVehiculo
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetEmpresas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 05/07/2022
-- Description:	Buscar Empresas Corporativos
-- ================================================
CREATE   PROCEDURE [dbo].[spGetEmpresas] 
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdEmpresa int=null,
	@RazonSocial varchar(250) = null, 
    @Nit varchar(20)=null

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Empresas
		BEGIN
			SELECT	C.IdEmpresa
					,C.TipoIdent
					,C.TipoCliente
					,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial 
					,C.Nit
					,C.IdCiudad
					,C.Movil
					,C.Telefono
					,C.Email
					,C.Direccion COLLATE Cyrillic_General_CI_AI as Direccion
					,C.ContactoEmpresa
					,C.EmailContacto
					,T.Nombre as NombreDcto
					,D.IdDepartamento
					,D.IdPais
					,CI.Nombre as NombreCiudad
					,CI.CodDane

			FROM  [dbo].[Empresas] as C, 
				  [dbo].[TipoDocumentos] as T,
				  [dbo].[Ciudades] as CI,
				  [dbo].[Departamentos] as D 

			WHERE T.IdTipoDoc = C.TipoIdent and
				  C.IdCiudad = CI.IdCiudad and
				  D.IdDepartamento = CI.IdDepartamento 

			ORDER BY RazonSocial ASC
	 
		END

	IF @Opcion = 2 -- Consultar por Cliente
		BEGIN
			SELECT  C.IdEmpresa
					,C.TipoIdent
					,C.TipoCliente
					,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
					,C.Nit
					,C.IdCiudad
					,C.Movil
					,C.Telefono
					,C.Email
					,C.Direccion COLLATE Cyrillic_General_CI_AI as Direccion
					,C.ContactoEmpresa
					,C.EmailContacto
					,T.Nombre as NombreDcto
					,D.IdDepartamento
					,D.IdPais
					,CI.Nombre as NombreCiudad
					,CI.CodDane

			FROM [dbo].[Empresas] as C, 
				 [dbo].[TipoDocumentos] as T,
				 [dbo].[Ciudades] as CI,
				 [dbo].[Departamentos] as D 

			WHERE C.IdEmpresa = @IdEmpresa and 
				  T.IdTipoDoc = C.TipoIdent and
				  C.IdCiudad = CI.IdCiudad and
				  D.IdDepartamento = CI.IdDepartamento 

			ORDER BY RazonSocial ASC
		END

	
	IF @Opcion = 3 -- Consultar por Parametro
		BEGIN
			IF @RazonSocial IS NOT NULL and @Nit IS NOT NULL 
				BEGIN
					SELECT  C.IdEmpresa
							,C.TipoIdent
							,C.TipoCliente
							,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,C.Nit
							,C.IdCiudad
							,C.Movil
							,C.Telefono
							,C.Email
							,C.Direccion COLLATE Cyrillic_General_CI_AI as Direccion
							,C.ContactoEmpresa
							,C.EmailContacto
							,T.Nombre as NombreDcto
							,D.IdDepartamento
							,D.IdPais
							,CI.Nombre as NombreCiudad
							,CI.CodDane

					FROM [dbo].[Empresas] as C, 
						 [dbo].[TipoDocumentos] as T,
						 [dbo].[Ciudades] as CI,
						 [dbo].[Departamentos] as D 

					WHERE C.RazonSocial like CONCAT('%',@RazonSocial,'%') and 
						  C.Nit            = @Nit and
						  T.IdTipoDoc      = C.TipoIdent and
						  C.IdCiudad       = CI.IdCiudad and
						  D.IdDepartamento = CI.IdDepartamento 
				END

			IF @RazonSocial IS NOT NULL and @Nit IS NULL --busca por razon social
				BEGIN
					SELECT  C.IdEmpresa
							,C.TipoIdent
							,C.TipoCliente
							,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,C.Nit
							,C.IdCiudad
							,C.Movil
							,C.Telefono
							,C.Email
							,C.Direccion COLLATE Cyrillic_General_CI_AI as Direccion
							,C.ContactoEmpresa
							,C.EmailContacto
							,T.Nombre as NombreDcto
							,D.IdDepartamento
							,D.IdPais
							,CI.Nombre as NombreCiudad
							,CI.CodDane

					FROM [dbo].[Empresas] as C, 
						 [dbo].[TipoDocumentos] as T,
						 [dbo].[Ciudades] as CI,
						 [dbo].[Departamentos] as D 

					WHERE C.RazonSocial like CONCAT('%',@RazonSocial,'%') and
						  T.IdTipoDoc      = C.TipoIdent and
						  C.IdCiudad       = CI.IdCiudad and
						  D.IdDepartamento = CI.IdDepartamento 
				END

			IF @RazonSocial IS NULL and @Nit IS NOT NULL --busca por nit
				BEGIN
					SELECT  C.IdEmpresa
							,C.TipoIdent
							,C.TipoCliente
							,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,C.Nit
							,C.IdCiudad
							,C.Movil
							,C.Telefono
							,C.Email
							,C.Direccion COLLATE Cyrillic_General_CI_AI as Direccion
							,C.ContactoEmpresa
							,C.EmailContacto
							,T.Nombre as NombreDcto
							,D.IdDepartamento
							,D.IdPais
							,CI.Nombre as NombreCiudad
							,CI.CodDane

					FROM [dbo].[Empresas] as C, 
						 [dbo].[TipoDocumentos] as T,
						 [dbo].[Ciudades] as CI,
						 [dbo].[Departamentos] as D 

					WHERE C.Nit            = @Nit and
						  T.IdTipoDoc      = C.TipoIdent and
						  C.IdCiudad       = CI.IdCiudad and
						  D.IdDepartamento = CI.IdDepartamento  
				END

			IF @RazonSocial IS NULL and @Nit IS NULL -- recarga
				BEGIN
					SELECT  C.IdEmpresa
							,C.TipoIdent
							,C.TipoCliente
							,C.RazonSocial COLLATE Cyrillic_General_CI_AI as RazonSocial
							,C.Nit
							,C.IdCiudad
							,C.Movil
							,C.Telefono
							,C.Email
							,C.Direccion COLLATE Cyrillic_General_CI_AI as Direccion
							,C.ContactoEmpresa
							,C.EmailContacto
							,T.Nombre as NombreDcto
							,D.IdDepartamento
							,D.IdPais
							,CI.Nombre as NombreCiudad
							,CI.CodDane

					FROM [dbo].[Empresas] as C, 
						 [dbo].[TipoDocumentos] as T,
						 [dbo].[Ciudades] as CI,
						 [dbo].[Departamentos] as D 

					WHERE T.IdTipoDoc      = C.TipoIdent and
						  C.IdCiudad       = CI.IdCiudad and
						  D.IdDepartamento = CI.IdDepartamento 
				END
		END		
END


GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosBodegas]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 18/03/2024
-- Description:	Buscar Estados Bodegas
-- =============================================
CREATE PROCEDURE [dbo].[spGetEstadosBodegas]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdEstadoBod Int=null,
	@Nombre varchar(50)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
	  BEGIN
		SELECT  [IdEstadoBod]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Estado_Bodegas]
	  END

	IF @Opcion = 2 -- Consultar por Tipo
	  BEGIN
		SELECT  [IdEstadoBod]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Estado_Bodegas] 
		WHERE IdEstadoBod = @IdEstadoBod
	  END

	IF @Opcion = 3 -- Consultar por Tipo desde seguimiento
	  BEGIN
		SELECT  [IdEstadoBod]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Estado_Bodegas] 
		WHERE IdEstadoBod >= 3
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosCotizacion]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 20/10/2021
-- Description:	Buscar Estados Cotizacion
-- =============================================
CREATE   PROCEDURE [dbo].[spGetEstadosCotizacion] 
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdEstadoCot Int=null,
	@Nombre varchar(125)=null,
	@Descripcion varchar(255)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
	  BEGIN
		SELECT  [IdEstadoCot]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Estado_Cotizacion]
	  END

	IF @Opcion = 2 -- Consultar por Tipo
	  BEGIN
		SELECT  [IdEstadoCot]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Estado_Cotizacion] 
		WHERE IdEstadoCot = @IdEstadoCot
	  END

	IF @Opcion = 3 -- Consultar por Tipo desde seguimiento
	  BEGIN
		SELECT  [IdEstadoCot]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Estado_Cotizacion] 
		WHERE IdEstadoCot >= 3
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosTipoServicio]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 23/02/2023
-- Description:	Buscar Estados Tipo Servicio
-- =============================================
CREATE PROCEDURE [dbo].[spGetEstadosTipoServicio]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdEstadoTipoServ Int = null,
	@Descripcion varchar(20) = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
	  BEGIN
		SELECT ETS.IdEstadoTipoServ
			  ,ETS.Descripcion
			  ,ETS.IdTipoServicio
			 
		FROM [dbo].[EstadoTipoServicio] as ETS
	  END

	IF @Opcion = 2 -- Consultar por Estado
	  BEGIN
		SELECT ETS.IdEstadoTipoServ
			  ,ETS.Descripcion
			  ,ETS.IdTipoServicio

		FROM [dbo].[EstadoTipoServicio] as ETS

		WHERE ETS.IdEstadoTipoServ = @IdEstadoTipoServ
	  END

	
END
GO
/****** Object:  StoredProcedure [dbo].[spGetEstadosVehiculo]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Fabian Esteban Becerra
-- Create date: 17/09/2024
-- Description:	Obtener los estados del vehiculo.
-- ================================================
CREATE PROCEDURE [dbo].[spGetEstadosVehiculo] 
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    SELECT 
		IdEstadoVeh,
		CodSyscom,
		Nombre
	FROM 
		Estado_Vehiculo
	WHERE 
		Estado = 'A'

END
GO
/****** Object:  StoredProcedure [dbo].[spGetEventos]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 08/10/2021
-- Description:	Procedimiento para consulta de eventos
-- =============================================
CREATE   PROCEDURE [dbo].[spGetEventos]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdEvento Int=null,
	@Nombre varchar(125)=null,
	@Descripcion varchar(255)=null,
	@Estado Int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Departametno
	  BEGIN
		SELECT  [IdEvento]
			   ,[Nombre]
			   ,[Descripcion]
			   ,[Estado]
		FROM [dbo].[Eventos]
	  END

	IF @Opcion = 2 -- Consultar por Evento
	  BEGIN
		SELECT  [IdEvento]
			   ,[Nombre]
			   ,[Descripcion]
			   ,[Estado]
		FROM  [dbo].[Eventos]
		WHERE IdEvento = @IdEvento
	  END
   
	IF @Opcion = 3 -- Consultar por Evento
	  BEGIN
		SELECT  [IdEvento]
			   ,[Nombre]
			   ,[Descripcion]
			   ,[Estado]
		FROM  [dbo].[Eventos]
		WHERE Estado = @Estado
	  END

END
GO
/****** Object:  StoredProcedure [dbo].[spGetFormasPago]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 20/10/2021
-- Description:	Buscar Formas de Pago
-- =============================================
CREATE   PROCEDURE [dbo].[spGetFormasPago]
	-- Add the parameters for the stored procedure here
	@Opcion Int,
	@IdFormaPago Int=null,
	@Nombre varchar(125)=null,
	@Descripcion varchar(255)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1  -- Consula todos los Tipo
	  BEGIN
		SELECT  [IdFormaPago]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Formas_Pago]
	  END

	IF @Opcion = 2 -- Consultar por Tipo
	  BEGIN
		SELECT  [IdFormaPago]
			   ,[Nombre]
			   ,[Descripcion]
		FROM  [dbo].[Formas_Pago] 
		WHERE IdFormaPago = @IdFormaPago
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[spGetGestiones]    Script Date: 05/02/2025 16:01:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sergio Rendón Gómez
-- Create date: 04/05/2023
-- Description:	Consultar Gestiones
-- =============================================
CREATE PROCEDURE [dbo].[spGetGestiones]
	-- Add the parameters for the stored procedure here
	@Opcion int,
	@IdGestion int = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @Opcion = 1 
		BEGIN
			SELECT  GT.IdGestion
				   ,GT.Descripcion
			
			FROM [dbo].[Gestiones] as GT
		END

	IF @Opcion = 2 
