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


CREATE PROCEDURE dbo.CP_CC_Prorrateo_Cta	@Id_Prorrateo	SMALLINT, 
											@Debe			DECIMAL(16,2), 
											@Haber			DECIMAL(16,2),
											@pPeriodo_Iva	DATETIME
AS 
BEGIN
SET NOCOUNT ON

DECLARE @Id_Centro_Costo			CHAR(10)
DECLARE @Porc						DECIMAL(10,5)
DECLARE @Tot_Debe					DECIMAL(16,2)
DECLARE @Tot_Haber					DECIMAL(16,2)
DECLARE @Id_Alias_Cta_Cont			SMALLINT
DECLARE @Id_Cta_Contable			INT
DECLARE @Nro_Cta_Contable			VARCHAR(20)
DECLARE @Cta_Contable_Descripcion	VARCHAR(80)

SELECT 
Id_Centro_Costo,
@Debe						AS Debe, 
@Haber						AS Haber,
@Id_Alias_Cta_Cont			AS Id_Alias_Cta_Cont,
@Id_Cta_Contable			AS Id_Cta_Contable,
@Nro_Cta_Contable			AS Nro_Cta_Contable,
@Cta_Contable_Descripcion	AS Cta_Contable_Descripcion
INTO #TmpProrra
FROM Centro_Costos 
WHERE 
1=0

DECLARE CurTmpProrra CURSOR FOR 
SELECT 
ISNULL(I.Id_Centro_Costo,''), 
ISNULL((I.Porc / 100), 0), 
ISNULL(I.Id_Alias_Cta_Cont, 0)
FROM Centro_Costos_Prorra_Items I
WHERE 
I.Id_Prorrateo = @Id_Prorrateo
					

OPEN CurTmpProrra
FETCH NEXT FROM CurTmpProrra INTO @Id_Centro_Costo, @Porc, @Id_Alias_Cta_Cont
WHILE @@FETCH_STATUS=0
BEGIN
	SET @Id_Cta_Contable			= ISNULL(dbo.CF_Cta_Cont(@Id_Alias_Cta_Cont, @pPeriodo_Iva), 0)
	
	SELECT 
	@Nro_Cta_Contable			= LTRIM(RTRIM(ISNULL(Nro_Cta_Contable, ''))),
	@Cta_Contable_Descripcion	= LTRIM(RTRIM(ISNULL(Descripcion, ''))) 
	FROM Pla_Ctas_Cuentas_Contables 
	WHERE 
	Id_Cta_Contable = @Id_Cta_Contable

	INSERT INTO #TmpProrra 
	(Id_Centro_Costo,		Debe,						Haber, 
	Id_Alias_Cta_Cont,		Id_Cta_Contable,			Cta_Contable_Descripcion,
	Nro_Cta_Contable)
	VALUES 
	(@Id_Centro_Costo,		ISNULL(@Debe * @Porc,0),	ISNULL(@Haber * @Porc,0), 
	@Id_Alias_Cta_Cont,		@Id_Cta_Contable,			@Cta_Contable_Descripcion,
	@Nro_Cta_Contable)

	FETCH NEXT FROM CurTmpProrra INTO @Id_Centro_Costo, @Porc, @Id_Alias_Cta_Cont
END
CLOSE CurTmpProrra
DEALLOCATE CurTmpProrra


SET @Tot_Debe  = ISNULL((SELECT SUM(ISNULL(Debe, 0))  FROM #TmpProrra), 0)
SET @Tot_Haber = ISNULL((SELECT SUM(ISNULL(Haber, 0)) FROM #TmpProrra), 0)


IF (@Tot_Debe <> 0 AND @Tot_Debe <> @Debe)
BEGIN
   UPDATE #TmpProrra 
   SET 
   Debe = Debe + @Tot_Debe - @Debe 
   WHERE 
   Id_Centro_Costo = @Id_Centro_Costo
END


IF (@Tot_Haber <> 0 AND @Tot_Haber <> @Haber)
BEGIN
   UPDATE #TmpProrra 
   SET 
   Haber = Haber + (@Haber - @Tot_Haber) 
   WHERE 
   Id_Centro_Costo = @Id_Centro_Costo
END



SELECT 
T.Id_Centro_Costo, 
C.Descripcion, 
T.Debe, 
T.Haber, 
T.Id_Alias_Cta_Cont,
T.Id_Cta_Contable,
T.Nro_Cta_Contable,
T.Cta_Contable_Descripcion
FROM #TmpProrra T, Centro_Costos C
WHERE 
T.Id_Centro_Costo = C.Id_Centro_Costo

DROP TABLE #TmpProrra
END

--EXEC CP_CC_PRORRATEO_CTA 1,0,276186.52, '20211028'