--Hash:56FE87FB34234E5354549AEA679F2FF5
SET XACT_ABORT ON
BEGIN TRANSACTION;

GO

SET DATEFORMAT mdy;

--Validar que no existan scripts que no se hayan ejecutado
--//
IF EXISTS
(
	SELECT a.NumVersion + 1 AS HuecoInicio
	FROM ZiurVersiones a
	LEFT JOIN ZiurVersiones b ON a.NumVersion + 1 = b.NumVersion
	WHERE a.NumVersion>830 AND b.NumVersion IS NULL
	AND a.NumVersion + 1 < 901
)
RAISERROR('Error : hay un script que no se ejecuto , debe ejecutarlo manualmente.', 20, -1) with log
--//

/*
Plantilla de script anterior a la implementación
--------------------------------------------------------------------------------------
Este archivo contiene instrucciones de SQL que se ejecutarán antes del script de compilación
Use la sintaxis de SQLCMD para incluir un archivo en el script anterior a la implementación
Ejemplo:      :r.\miArchivo.sql
Use la sintaxis de SQLCMD para hacer referencia a una variable en el script anterior a la implementación
Ejemplo:      :setvar TableName miTabla
SELECT* FROM[$(TableName)]
--------------------------------------------------------------------------------------
*/
GO

ALTER PROCEDURE [dbo].[GetDesprendibleNomina]  
  
@IdEncab INT,  
@IdContrato NVARCHAR(MAX) = '',  
@IdEmpresa INT,
@EsNe BIT = 0
  
  
AS  
BEGIN  
  
DECLARE  
  
@EsCentroCosto BIT=0  
  
set @EsCentroCosto=(select ValParametro from Parametros where CodParametro=193)  
  
  
;with tmpChilds(IdEncabNomMov,CantidadChild)  
as  
(  
	SELECT mov.IdEncabNomMov,sum(case when item1.IdClasif=1 and item1.FactorProv=1 then Mov1.Cantidad else 0 end)Cantidad  
	FROM dbo.Nomina_Movimientos Mov INNER JOIN  
	dbo.Nomina_Movimientos Mov1 ON Mov1.IdEncabNomMovBase=Mov.IdEncabNomMov  LEFT JOIN  
	dbo.Nomina_Contratos Cont ON Mov.IdContrato = Cont.IdContrato INNER JOIN  
	dbo.Nomina_Items item ON Mov.IdItem=item.IdItem  INNER JOIN  
	dbo.Nomina_Items item1 ON Mov1.IdItem=item1.IdItem    
	where item.IdTipoAporte=1 and mov.IdEncab=@IdEncab   
	and Mov.IdContrato IN(select number from iter$simple_intlist_to_tbl(@IdContrato)) and item1.IdClasif=1  
	group by mov.IdEncabNomMov  
)  
  
select q1.*,  
cli.Identificacion+'-'+cli.Nombre1+' '+COALESCE(cli.Nombre2,'')+' '+COALESCE(cli.Apellido1,'')+' '+COALESCE(cli.Apellido2,'') NomCliente,NomCentroCosto,tipoIdent.DescripTipoIdent,tipoIdent.NomTipoIdent  
from
(  
	SELECT IdCLiente,NomCargo,IdTipo,Nomtipo,IdClasif,NomClasif,SUM(Valor) Valor,SUM(ValorReal) ValorReal,  
	CASE WHEN IdClasif NOT IN (5,6) THEN sum (Cantidad) ELSE (MAX(coalesce(ConfiDivParteSuperior,itemDivParteSuperior)/coalesce(ConfiDivParteInferior,itemDivParteInferior)))*100 END cantidad,  
	OcultarDesprendible,max(FactorProv)FactorProv,max (NomMovRetiro)NomMovRetiro,  
	case when max(IdClasifSistem)=1 then sum(ISNULL(CantidadChild,Cantidad)) else max(ISNULL(CantidadChild,Cantidad)) end as CantidadChild,   
	sum(case when ((@EsNe=0 AND IdClasifSistem=1 AND FactorProv=1) OR (@EsNe=1 AND IdClasifSistem=1)) then Cantidad else 0 end) as CantidadLaborados,  
	max(ISNULL(CantidadChild,0))as CantidadLaboradosChild,  
	CASE WHEN @EsCentroCosto=1 THEN IdCentroCosto ELSE NULL END as IdCentroCosto, Max(NominaNota) NotaNomina, case when Max(SueldoActivo) > 0 then Max(SueldoActivo) else Max(SueldoInactivo) end Sueldo  
	from  
	(  
		select distinct mov.IdEncabNomMov, Mov.IdCLiente,NomCargo,Tipo.IdTipo,Tipo.Nomtipo,Clasif.IdClasif,Clasif.NomClasif,ValorHora,  
		case when PorcDesprendible is not null then ValorHora*PorcDesprendible*Cantidad else ValorUnit/cast(ValorUnitInferior as float)*Cantidad end Valor,  
		ValorUnit/cast(ValorUnitInferior as float)*Cantidad as ValorReal,  
		Confi.DivParteSuperior as ConfiDivParteSuperior,item.DivParteSuperior as itemDivParteSuperior,Confi.DivParteInferior as ConfiDivParteInferior,item.DivParteInferior as itemDivParteInferior,Cantidad,  
		item.OcultarDesprendible,FactorProv, NomMovRetiro,CantidadChild, item.IdClasif as IdClasifSistem, item.FactorGeneral,IdCentroCosto, nomnot.Nota as NominaNota, 
		case when Cont.EsActivo = 1 then Cont.SueldoIni else 0 end as SueldoActivo, case when Cont.EsActivo = 0 then Cont.SueldoIni else 0 end as SueldoInactivo   
		from dbo.Nomina_Movimientos Mov LEFT JOIN  
		dbo.Nomina_Contratos Cont ON  Mov.IdContrato = Cont.IdContrato LEFT JOIN  
		dbo.Nomina_Cargos Carg ON Cont.IdCargo=Carg.IdCargo INNER JOIN  
		dbo.Nomina_Items item ON Mov.IdItem=item.IdItem INNER JOIN  
		dbo.Nomina_Clasificacion Clasif ON (CASE WHEN @EsNe = 0 THEN item.IdClasifPrint ELSE COALESCE(item.IdClasifNe,item.IdClasifPrint) END)=Clasif.IdClasif INNER JOIN  
		dbo.Nomina_Tipos Tipo ON item.IdTipo=Tipo.IdTipo LEFT JOIN   
		dbo.Nomina_Configuracion Confi ON Mov.IdItem=Confi.IdItem and Cont.Idplantilla=Confi.IdPlantilla left join  
		dbo.VNominaValorHora VHora ON VHora.IdEncab=Mov.IdEncab and VHora.IdCliente=Mov.IdCliente LEFT JOIN  
		dbo.Nomina_Motivos_Retiro as NomMotRet ON Cont.IdMovRetiro= NomMotRet.IdMovRetiro  LEFT JOIN  
		tmpChilds on tmpChilds.IdEncabNomMov=Mov.IdEncabNomMov LEFT JOIN  
		dbo.Nomina_Notas nomnot ON Mov.IdEncab = nomnot.IdEncab AND Mov.IdCliente = nomnot.IdCliente   
		where IdTipoAporte=1 and mov.IdEncab=@IdEncab 
		and Mov.IdContrato IN(select number from iter$simple_intlist_to_tbl(@IdContrato))  
		and (COALESCE (Mov.FactorMov, 1) = 1) and coalesce(Cont.IdEmpresa,@IdEmpresa)=@IdEmpresa   
	)as q  
	group by IdCLiente,NomCargo,IdTipo,Nomtipo,IdClasif,NomClasif,OcultarDesprendible,  
	CASE WHEN @EsCentroCosto=1 THEN IdCentroCosto ELSE NULL END  
)as q1 INNER JOIN  
dbo.Clientes cli ON q1.IdCliente=cli.IdCliente INNER JOIN  
dbo.Clientes_TiposIdent tipoIdent on cli.IdTipoIdent=tipoIdent.IdTipoIdent  
 LEFT JOIN  
dbo.CentroCostos ccos ON q1.IdCentroCosto=ccos.IdCentroCosto
END  

GO

ALTER PROCEDURE [dbo].[GetDocumentosCierre]

@IdDocs NVARCHAR(1000),
@FechaFin datetime,
@IdSucursal int,
@IdVend int

AS
BEGIN

DECLARE
@tIdDocs NVARCHAR(1000),
@tFechaFin datetime,
@tIdSucursal int,
@tIdVend int

SET @tIdDocs = @IdDocs
SET @tFechaFin = @FechaFin
SET @tIdSucursal = @IdSucursal
SET @tIdVend = @IdVend

--Se ejecuto en GUSTAVO NEIRA OSORIO y en FERRETERIA en GOLD
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

;WITH tempEncabezados(IdEncab)
as
(
	select distinct IdEncab
	FROM
	(
		select distinct IdEncab
		from
		[dbo].[Encabezados_Cierres_Docs] as cierre inner join
		Encabezados_Mov as encMov on cierre.IdEncabMov=encMov.IdEncabMov

		UNION ALL 

		select distinct IdEncab
		from
		[dbo].[Encabezados_Cierres_Docs_Cont] as cierre inner join
		Encabezados_Cont as encCont on cierre.IdEncabCont=encCont.IdEncabCont
	)AS q
)
        

select VEnc.IdEncab,VEnc.Fecha,RTRIM(LTRIM(VEnc.CodDocumento + ' ' + ISNULL(IdPrefijo,''))) + ' ' + CAST(NumDocumento AS NVARCHAR(200)) AS DescripDoc,NumDocumento,
ISNULL(VEnc.Cantidad,0)Cantidad,ISNULL(SubIVA,0)SubIVA,ISNULL(SubTotal+SubIVA,ISNULL(Debito,0)) as Total, VEnc.CodDocumento,  VEnc.NomDocumento, EsMov, VEnc.NombreVend
from
tempEncabezados as encMov
right join VEncabezados VEnc on encMov.IdEncab=VEnc.IdEncab INNER JOIN
Documentos Doc ON VEnc.IdDocumento = Doc.IdDocumento
where encMov.IdEncab IS NULL AND
VEnc.IdDocumento IN(select number from iter$simple_intlist_to_tbl(@tIdDocs)) AND
VEnc.Fecha<=@tFechaFin AND
(@tIdSucursal is null OR @tIdSucursal=VEnc.IdSucursal)
AND(isnull(SubTotal,0)>0 OR isnull(Debito,0)>0)
AND (@tIdVend IS NULL OR @tIdVend = VEnc.IdClienteVend)
OPTION(RECOMPILE)

END

GO

ALTER PROCEDURE [dbo].[GetInvKardexPorLote]

@FechaCorte NVARCHAR(10) = '',
@Lote BIT=0,
@IdEmpresas NVARCHAR(1000) = '',
@IdInventario INT = null,
@IdBodega INT = null,
@IdLote INT = null,
@EsBodega BIT=1,
@EsSerial BIT=0,
@EsSinExist BIT=1,
@EsValidarMax BIT=0

AS
BEGIN


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON;	

DECLARE

@FechaCorteTemp datetime,
@EsLote BIT=0,
@IdEmp NVARCHAR(1000),
@IdInv INT = null,
@IdBod INT = null,
@IdLot INT = null,
@EsBod BIT,
@Serial BIT=0,
@SinExist BIT

SET @FechaCorteTemp = CAST(convert(datetime, @FechaCorte, 103) + ' 23:59:59' AS DATETIME)
SET @EsLote =@Lote
SET @IdEmp= @IdEmpresas
SET @IdInv =@IdInventario
SET @IdBod =@IdBodega
SET @IdLot =@IdLote
SET @EsBod =@EsBodega
SET @Serial =@EsSerial
SET @SinExist =@EsSinExist

IF LEN(@IdEmp)=0
	SELECT @IdEmp= COALESCE(@IdEmp + ', ', '') + CAST(IdEmpresa as nvarchar(50)) FROM empresas


	;with tmpSaldoTeo(IdInventario,IdBodega,IdLote,NumSerial,IdTipoReg,ExistenciaTeo)
	as
	(
        SELECT 
		isnull(Mov.IdInventario,VCru.IdInventario),
		isnull(Mov.IdBodega,VCru.IdBodega),
		isnull(Mov.IdLote,VCru.IdLote),
		isnull(Mov.NumSerial,VCru.NumSerial),
		isnull(Mov.IdTipoReg,VCru.IdTipoReg),
		SUM(isnull(Mov.Cantidad*Mov.FactorCantidad*Mov.FactorMovim,SumCantidad)*Doc.FactorInventarioTeorico) AS ExistenciaTeo
		from dbo.VCruces_TodosDocs VCru 
		INNER JOIN Documentos Doc ON VCru.IdDocumento=Doc.IdDocumento LEFT JOIN
		Encabezados_Mov as Mov on Vcru.IdEncabMov=Mov.IdEncabMov2
		WHERE  
		VCru.Fecha <= @FechaCorteTemp AND 
		VCru.EsAnulado=0 AND
		ISNULL(VCru.IdEstado,0)<>-5 AND
		Doc.FactorInventarioTeorico<>0  AND

		(@IdInv IS NULL OR Mov.IdInventario = @IdInv) AND
		(@IdInv IS NULL OR VCru.IdInventario = @IdInv) 

     	GROUP BY   
		isnull(Mov.IdInventario,VCru.IdInventario),
		isnull(Mov.IdBodega,VCru.IdBodega),
		isnull(Mov.IdLote,VCru.IdLote),
		isnull(Mov.NumSerial,VCru.NumSerial),
		isnull(Mov.IdTipoReg,VCru.IdTipoReg)
	),

	tmpSaldo (IdInventario,Existencia,Existencia1, ValorTRM,NumSerial,IdTipoReg,IdBodega,IdLote)
	as
	(
		SELECT EncMov.IdInventario, 
		SUM(EncMov.Cantidad * EncMov.FactorCantidad * Doc.FactorInventario * EncMov.FactorMovim) AS Existencia,
		SUM(ISNULL(EncMov.Cantidad1,0) * Doc.FactorInventario * EncMov.FactorMovim) AS Existencia1,  
		MAX(EncMov.ValorTRM) AS ValorTRM,NumSerial,IdTipoReg,IdBodega,IdLote
		FROM  
		dbo.Encabezados AS Enc INNER JOIN
		dbo.Encabezados_Mov AS EncMov ON Enc.IdEncab = EncMov.IdEncab INNER JOIN
		dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento
		WHERE
		Doc.FactorInventario <> 0 AND 
		Enc.Fecha <= @FechaCorteTemp AND 
		EncMov.FactorMovim <> 0 AND
		Enc.EsAnulado=0 AND
		(@IdInv IS NULL OR EncMov.IdInventario = @IdInv) AND
		(@IdBod IS NULL OR EncMov.IdBodega = @IdBod) AND
		(@IdLot IS NULL OR EncMov.IdLote = @IdLot) AND
		Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmp)) 
		GROUP BY  EncMov.IdInventario,EncMov.IdBodega,EncMov.IdLote,EncMov.NumSerial,EncMov.IdTipoReg
	),

	tmpFin (IdInventario,Existencia,Existencia1, ValorTRM,NumSerial,IdTipoReg,IdBodega,IdLote)
	as
	(
		--Por Lote, serial y Bodega
		SELECT Saldo.IdInventario,Existencia,Existencia1,ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,Saldo.IdBodega,Saldo.IdLote
		from tmpSaldo as Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=1
				
		union all 

		--Por Lote y serial
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,null as IdBodega,Saldo.IdLote
		from tmpSaldo as Saldo
		where ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=1 and ISNULL(@EsBod,0)=0
		group by Saldo.IdInventario,Saldo.IdLote,Saldo.NumSerial,Saldo.IdTipoReg

		union all 

		--Por Lote y Bodega
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg,Saldo.IdBodega,Saldo.IdLote
		from tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=1
		group by Saldo.IdInventario,Saldo.IdBodega,Saldo.IdLote

		union all 

		--Solo por lote 
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg, null as IdBodega,Saldo.IdLote
		from tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=0 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=1
		group by Saldo.IdInventario,Saldo.IdLote

		union all 

		--Por serial y Bodega
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,Saldo.IdBodega,null as IdLote
		from tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario,Saldo.IdBodega,Saldo.NumSerial,Saldo.IdTipoReg

		union all 

		--Solo por serial
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,null as IdBodega,null as IdLote
		from tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=0 and ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario,Saldo.NumSerial,Saldo.IdTipoReg

		union all 

		--Solo por Bodega
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg,Saldo.IdBodega,null as IdLote
		from tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario,Saldo.IdBodega

		union all 

		--Solo Inventario
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg, null as IdBodega,null as IdLote
		from tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=0 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario
	),
			
	tmpTotalFin (IdInventario,Existencia,Existencia1, ValorTRM,NumSerial,IdTipoReg,IdBodega,IdLote,ExistenciaTeo,CantMaxima,CantMinima,PuntoReorden,EsOk,EsError,EsWarning,TimeIni,TimeFinal,TimeReminder,IdMaximo,IdUsuarios,IdRoles)
	as
	(
		select saldo.IdInventario,saldo.Existencia,saldo.Existencia1, saldo.ValorTRM,saldo.NumSerial,saldo.IdTipoReg,saldo.IdBodega,saldo.IdLote,sum(isnull(ExistenciaTeo,0))ExistenciaTeo,
		max(isnull(maximoGeneral.CantMaxima,0)) CantMaxima,max(isnull(maximoGeneral.CantMinima,0))CantMinima,max(isnull(maximoGeneral.PuntoReorden,0))PuntoReorden,
		max(cast(isnull(maximoGeneral.EsOk,0) as int)) EsOk,max(cast(isnull(maximoGeneral.EsError,0) as int)) EsError,max(cast(isnull(maximoGeneral.EsWarning,0) as int)) EsWarning, 
		max(isnull(maximoGeneral.TimeIni,0)) TimeIni,max(isnull(maximoGeneral.TimeFinal,0)) TimeFinal,max(isnull(maximoGeneral.TimeReminder,0)) TimeReminder,
		max(isnull(maximoGeneral.IdMaximo,0)) IdMaximo, MAX(ISNULL(IdUsuarios,''))IdUsuarios,MAX(ISNULL(IdRoles,''))IdRoles
		from tmpFin as saldo 
		left join 
		tmpSaldoTeo as teo on saldo.IdInventario=teo.IdInventario and (saldo.IdBodega=teo.IdBodega OR ISNULL(@EsBod,0)=0)and
		(saldo.IdLote=teo.IdLote OR ISNULL(@EsLote,0)=0) and (saldo.NumSerial=teo.NumSerial and saldo.IdTipoReg=teo.IdTipoReg OR  ISNULL(@Serial,0)=0)
			left join 
			VMaximosYMinimos as maximoGeneral on saldo.IdInventario=maximoGeneral.IdInventario and ISNULL(@EsBod,0)=maximoGeneral.EsBodega and isnull(saldo.IdBodega,0)=COALESCE(maximoGeneral.IdBodega,saldo.IdBodega,0)
			and ISNULL(@EsLote,0)=maximoGeneral.EsLote and ISNULL(saldo.IdLote,0)=COALESCE(maximoGeneral.IdLote,saldo.IdLote,0) and ISNULL(@Serial,0)=maximoGeneral.EsSerial and ISNULL(saldo.NumSerial,0)=COALESCE(maximoGeneral.NumSerial,saldo.NumSerial,0)
		and @EsValidarMax=1
		group by saldo.IdInventario,saldo.Existencia,saldo.Existencia1, saldo.ValorTRM,saldo.NumSerial,saldo.IdTipoReg,saldo.IdBodega,saldo.IdLote
	)

	SELECT q1.*,Existencia1 AS ExistenciaUni1,costPromInv.CostoProm, CASE WHEN q1.ValorTRM = 0 THEN 0 ELSE costPromInv.CostoProm / q1.ValorTRM END AS CostoPromExt
	FROM
	(
		SELECT EncMov.IdInventario,EncMov.IdLote AS IdLote, Inv_L.CodLote AS CodLote, Inv_L.NomLote AS Nomlote, Inv.IdUnidad, 
		Existencia,
		Existencia1,
		ExistenciaTeo,
		Inv.CodInventario,  (EncMov.ValorTRM) AS ValorTRM, Inv_L.FechaVence AS FechaVence,
		Inv.NomInventario,
		ISNULL(EncMov.CantMaxima,0) CantMaxima,
		ISNULL(EncMov.CantMinima,0) CantMinima,
		Inv_Bod.NomBodega,
		Agr1.NomAgrup1,Agr2.NomAgrup2,Inv.CodInventario + ' ' + Inv.NomInventario AS NomInvCompleto,Inv_Uni.NomUnidad,Inv_Uni.IdTipoUnidad,
		ISNULL(Inv.FactorEscala,Inv_Uni.FactorEscala)AS FactorEscala,
		ISNULL(Inv.FactorEscala1,ISNULL(Inv_Uni1.FactorEscala,0))AS FactorEscala1,
		ISNULL(EncMov.PuntoReorden,0) PuntoReorden,
		CAST(CAST(inv.EsActivo AS int)AS bit) EsActivo,
		NumSerial,
		motor.NomAutomotor,motor.NumPlaca +'-'+marca.NomMarca AS Automotor,
		(talla.NomTalla) AS NomTalla,
		(talla.Agrup1) AS AgrupTalla1,
		(talla.Agrup2) AS AgrupTalla2,
		(talla.Agrup3) AS AgrupTalla3,
		Existencia + ExistenciaTeo as TotalExistencia,
		CAST(ISNULL(EncMov.EsOk,0)AS BIT) EsOk,
		CAST(ISNULL(EncMov.EsError,0) AS BIT)  EsError,
		CAST(ISNULL(EncMov.EsWarning,0) AS BIT) EsWarning,

		EncMov.TimeIni,
		EncMov.TimeFinal ,
		EncMov.TimeReminder,
		IdMaximo ,EncMov.IdBodega,IdUsuarios,IdRoles
			
		FROM  
		tmpTotalFin as EncMov INNER JOIN
		dbo.Inventarios AS Inv ON EncMov.IdInventario = Inv.IdInventario LEFT OUTER JOIN
		dbo.Inventarios_Agrup1 AS Agr1 ON Agr1.IdAgrup1=Inv.IdAgrup1 LEFT OUTER JOIN
		dbo.Inventarios_Agrup2 AS Agr2 ON Agr2.IdAgrup2=Inv.IdAgrup2 LEFT OUTER JOIN
		dbo.Inventarios_Lotes AS Inv_L ON EncMov.IdLote = Inv_L.IdLote  LEFT OUTER JOIN
		dbo.Inventarios_Bodegas AS Inv_Bod ON EncMov.IdBodega = Inv_Bod.IdBodega LEFT OUTER JOIN
		dbo.Inventarios_Unidades AS Inv_Uni ON Inv.IdUnidad = Inv_Uni.IdUnidad LEFT OUTER JOIN
		dbo.Inventarios_Unidades AS Inv_Uni1 ON Inv.IdUnidad1 = Inv_Uni1.IdUnidad LEFT JOIN
		[dbo].[Reparacion_Automotores] AS motor  ON EncMov.NumSerial = motor.IdAutomotor and EncMov.IdTipoReg=1 LEFT JOIN
		dbo.Inventarios_Colores_Tallas AS Talla ON EncMov.NumSerial = Talla.CodTalla and EncMov.IdTipoReg=2 LEFT JOIN
		[dbo].[Reparacion_Marcas] AS marca ON marca.IdMarca=motor.IdMarca
	    WHERE
		Inv.IdTipoInv=1  AND (@SinExist=1 or (Existencia<>0 or ExistenciaTeo<>0))
	)
	q1 LEFT JOIN CostoPromedioPorInventario(@FechaCorte) AS costPromInv ON costPromInv.IdInventario=q1.IdInventario


	option(recompile); 

END

GO

INSERT INTO ZiurVersiones (IdVersion, NumVersion, Descripcion)
VALUES (311,901,'Fix NE Lic NR y mejoras rendimiento')
GO

COMMIT
GO
