IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CPJ_Cbtes_Asiento_Agrupar') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE dbo.CPJ_Cbtes_Asiento_Agrupar
END
GO

CREATE PROCEDURE CPJ_Cbtes_Asiento_Agrupar @pJson VARCHAR(8000)
AS
 
SET NOCOUNT ON 

/*Variables recibidas por parametro a traves del JSON*/

DECLARE @pId_Trans	INT
SET @pId_Trans	    = ISNULL(CONVERT(INT, dbo.CF_JSON_VALUE(@pJson,'Id_Trans')), 0)

	DECLARE @rtaErrorStored						INT
	DECLARE @rtaMsjStored						VARCHAR(4000)
	DECLARE @Result_Stored_Invocado				INT
	DECLARE @JSON_Parametros_Stored_Invocado	VARCHAR(8000)

	DECLARE @Result_Tabla_Stored_Invocado TABLE (ErrorNumber	INT,
										       	 ErrorSeverity	INT,
											     ErrorState		INT,
											     ErrorProcedure VARCHAR(1000),
											     ErrorLine		INT,
											     ErrorMessage	VARCHAR(4000))

BEGIN TRY 

BEGIN TRAN

	select id_trans,id_cta_contable,fecha,debe,sum(haber) as haber, observacion, alias,id_asiento,id_centro_costo
	INTO #Resumen 
	from Cbtes_Ctas_Contables where id_trans = @pId_Trans and debe = 0
	group by id_trans,id_cta_contable,fecha,debe, observacion, alias,id_asiento,id_centro_costo

	INSERT INTO #Resumen
	select id_trans,id_cta_contable,fecha,sum(debe) as debe,haber, observacion, alias,id_asiento,id_centro_costo
	from Cbtes_Ctas_Contables where id_trans = @pId_Trans and haber = 0
	group by id_trans,id_cta_contable,fecha,haber, observacion, alias,id_asiento,id_centro_costo

	ALTER TABLE #Resumen ADD ITEM SMALLINT IDENTITY(1,1)

	SET @rtaErrorStored = ISNULL((SELECT COUNT(*) FROM #Resumen),0)


	DELETE Cbtes_Ctas_Contables WHERE ID_TRANS = @pId_Trans

	INSERT INTO Cbtes_Ctas_Contables SELECT * FROM #Resumen

	DROP TABLE #Resumen

	COMMIT TRAN

    SELECT	 0				 AS ErrorNumber 
			,0				 AS ErrorSeverity  
			,0				 AS ErrorState 
			,0			     AS ErrorProcedure  
			,0               AS ErrorLine		
			,@rtaErrorStored AS ErrorMessage

 			
END TRY 

BEGIN CATCH  
    EXECUTE usp_GetErrorInfo
	ROLLBACK
	RETURN 9999
END CATCH
RETURN 0 

/*

CPJ_Cbtes_Asiento_Agrupar   '{
			"Id_Trans":"41804"}'

		select * from cbtes_ctas_contables where id_trans = 41804

		select * from cbtes_ctas_contables where id_trans in (select id_trans from cbtes where id_tipo_cbte = 'TRAC' ) 
		order by id_trans desc

*/