ALTER PROCEDURE [dbo].[sp_invCargarArticulosNoContados]
(
	@codbod INT = 0,
	@FechaCierre DATE
)
AS
BEGIN
	-- Sumar un día a @FechaCierre
    SET @FechaCierre = DATEADD(DAY, 1, @FechaCierre);

	SELECT A.codbus,
	A.nomart, 
	A.codalt, 
	A.ubiinv1, 
	ISNULL(T.stock_logico, 0) AS stock_logico,
	0 AS stock_fisico, 
	0 AS stock_dif, 
	'False' AS contado, 
	GETDATE() AS fecha_toma, 
	@codbod AS bodega, 
	'False' AS contabilizado ,
	0 AS numlin,
	0 AS idPretoma,
	0 AS costo,
	0 AS totalCosto
	FROM invArticulos A JOIN invStock S ON A.codbus = S.codbus AND S.codbod = @codbod
	OUTER APPLY (
			SELECT TOP 1 stockBodega AS stock_logico
			FROM (
				SELECT 
					D.stockBodega,
					E.fecdoc AS fecdoc,
					D.numlin,
					CASE D.coddoc WHEN 1 THEN 0 ELSE 1 END AS orden,
					E.hordoc
				FROM invDetalle D
				INNER JOIN invEncabezado E ON D.coddoc = E.coddoc AND D.numinv = E.numinv
				WHERE D.codbus = A.codbus
				AND D.codbod = @codbod
				AND E.fecdoc <= @FechaCierre

				UNION ALL

				SELECT 
					D.stockBodega,
					E.fecdoc,
					D.numlin,
					1 AS orden,
					E.hordoc
				FROM venDetalle D
				INNER JOIN venEncabezado E ON D.coddoc = E.coddoc AND D.numinv = E.numinv AND D.grudoc = E.grudoc
				WHERE D.codbus = A.codbus
				AND D.codbod = @codbod
				AND E.fecdoc <= @FechaCierre

				UNION ALL

				SELECT
					D.stockBodegaDes AS stockBodega,
					D.fecdoc,
					D.numlin,
					CASE D.coddoc WHEN 1 THEN 0 ELSE 1 END AS orden,
					E.hordoc
				FROM invDetalle D
				INNER JOIN invEncabezado E ON D.coddoc = E.coddoc AND D.numinv = E.numinv
				WHERE codbus = A.codBus
				AND D.boddes = @codbod
				AND D.coddoc = 3
				AND E.fecdoc <= @FechaCierre
			) AS Combined
			ORDER BY fecdoc DESC, orden DESC, hordoc DESC, numlin DESC
		) AS T
	WHERE NOT EXISTS (	SELECT * 
						FROM invCierreTomaTemp C 
						WHERE A.codbus = c.codbus)

END