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 
					D.stockBodega,
					CONVERT(DATE, 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 = P.codbus
				AND D.codbod = P.codBod
				AND E.fecdoc <= @FechaCierre
				AND YEAR(E.fecdoc) = YEAR(@FechaCierre)

				UNION ALL

				SELECT 
					D.stockBodega,
					CONVERT(DATE, E.fecdoc) AS 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 = P.codbus
				AND D.codbod = P.codbod
				AND E.fecdoc <= @FechaCierre
				AND YEAR(E.fecdoc) = YEAR(@FechaCierre)

				UNION ALL

				SELECT
					D.stockBodegaDes AS stockBodega,
					CONVERT(DATE, 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 codbus = P.codBus
				AND D.boddes = P.codbod
				AND D.coddoc = 3
				AND E.fecdoc <= @FechaCierre
				AND YEAR(E.fecdoc) = YEAR(@FechaCierre)

			) AS Combined
			ORDER BY fecdoc DESC, orden DESC, hordoc DESC, numlin DESC
		) AS T
	WHERE P.idPreToma = @idPretoma
END