CREATE PROCEDURE [dbo].[sp_invCargaGrillaToma_Cierre]
(
	@idPretoma AS INT,
	@FechaCierre AS DATE, 
	@codbod AS INT
)
AS

SELECT invCierreToma.codbus, invCierreToma.nomart, invCierreToma.codAlt,
	   invCierreToma.ubiinv1, invCierreToma.stock_logico, invCierreToma.stock_fisico,
	   contado, fecha_toma, bodega, contabilizado, numlin, ISNULL(T.costo, 0.0000) AS costo
FROM invCierreToma
		JOIN invArticulos A ON invCierreToma.codBus = A.codbus
		OUTER APPLY (
			SELECT TOP 1 costo
			FROM (
				SELECT 
					D.costo,
					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 = invCierreToma.codbus
				AND D.codbod = @codBod
				AND E.fecdoc <= @FechaCierre

				UNION ALL

				SELECT 
					D.costo,
					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 = invCierreToma.codbus
				AND D.codbod = @codbod
				AND E.fecdoc <= @FechaCierre

				UNION ALL

				SELECT
					D.costo,
					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 = invCierreToma.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 codToma = @idPretoma