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

	SELECT 
		P.codbus, 
		A.nomart, 
		A.codAlt, 
		A.ubiinv1, 
		ISNULL(T.stock_logico, 0) AS stock_logico,
		P.stockFisico AS stock_fisico, 
		'' AS stock_dif, 
		'False' AS contado, 
		P.fecha AS fecha_toma, 
		P.codBod AS bodega, 
		'False' AS contabilizado, 
		P.numlin 
	FROM invPreToma P 
		JOIN invArticulos A ON P.codBus = A.codbus
		OUTER APPLY (
			SELECT TOP 1 stockBodega AS stock_logico
			FROM (
				SELECT 
					stockBodega,
					fecdoc
				FROM invDetalle
				WHERE codbus = P.codbus
				AND codbod = P.codBod
				AND fecdoc <= @FechaCierre

				UNION ALL

				SELECT 
					stockBodega,
					fecdoc
				FROM venDetalle
				WHERE codbus = P.codbus
				AND codbod = P.codBod
				AND fecdoc <= @FechaCierre

				UNION ALL

				SELECT
					stockBodegaDes AS stockBodega,
					fecdoc
				FROM invDetalle
				WHERE codbus = P.codBus
				AND boddes = P.codBod
				AND coddoc = 3
				AND fecdoc <= @FechaCierre
			) AS Combined
			ORDER BY fecdoc DESC
		) AS T
	WHERE P.idPreToma = @idPretoma
END