-- =============================================
-- Author:		<Yonatan Gaete>
-- Create date: <28/01/2025>
-- Description:	<Cargar datos Inventario MINEDUC>
-- Edit date:   <22/05/2025>
-- Description:	<Se agregan campos de Unidad de Negocios y su descipicion>
-- Editor:      <Yonatan Gaete>
-- =============================================
ALTER PROCEDURE [dbo].[sp_afiListarInventarioMINEDUC]
(
    @id INT,
    @periodo INT,
    @rubro INT,
	@unineg INT
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT
        ISNULL(C.codigoInterno, B.codigoInterno) AS ordenAnterior,
        B.codigoInterno AS numero,
        ISNULL(SG.nombre, '') AS nombre,
        B.descripcion,
        B.grupo AS rubro,
		G.nombre AS rubroDesc,
        B.estado AS estado,
		E.nombre AS estadoDesc,
        ISNULL(R.nombre, '') AS responsableNom,
        ISNULL(R.rut, '0') + '-' + ISNULL(R.dv, '0') AS rutResponsable,
        ISNULL(B.orderCompra, 0) AS ordenCompra,
        ISNULL(D.descripcion, '') AS departamento,
        ISNULL(U.nombre, '') AS ubicacion,
        B.costoCompra AS valorInicial,
        B.fechaCompra AS fechaAdq,
		B.uniNeg AS UnidadNegocios,
		UN.descripcion AS UnidadNegociosDesc 
    FROM afiBienes B
    LEFT JOIN afiCierrePeriodo C ON C.idActivo = B.id AND C.periodo = @periodo
    INNER JOIN afiEstados E ON E.id = B.estado
    INNER JOIN afiResponsables R ON R.id = B.responsable
    INNER JOIN remDepartamentos D ON D.idDepartamento = B.departamento
    INNER JOIN afiUbicaciones U ON U.id = B.ubicacion
    INNER JOIN afiGrupo G ON B.grupo = G.id
    INNER JOIN afiSubGrupo SG ON B.subgrupo = SG.id
	LEFT JOIN conUnidadNegocio UN ON B.uniNeg = UN.idUniNeg
    WHERE (B.id = @id OR @id = 0)
    AND (B.grupo = @rubro AND @rubro = 0)
	AND (B.uniNeg = @unineg OR @unineg = 0)
    ORDER BY B.codigoInterno; 

END