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

CREATE PROCEDURE [dbo].[CP_Productos_DEUDA](
     @pUsuario    INT
   , @pEquate  SMALLINT
   , @pEquateClientes SMALLINT
   , @FECHA DATETIME
   )
AS
  --CREATE TABLE #Trans (Id_Trans INT)

  Declare @DEUDA table (Id_Trans INT,coef decimal(12,5) )
  Declare @PagosACta table (Id_Trans INT,coef decimal(12,5) )

  PRINT '[CP_Productos_DEUDA]'

  IF @pEquate = 0
     RETURN

  DECLARE @Id_Producto Varchar(14)
  ,@Id_Proveedor Int
  ,@Razon_Social VarChar(100)
  ,@Cuit Varchar(13)
  ,@Id_Iva Char(3)
  ,@Id_Alias_Cta_Cont Int
  ,@Id_Cta_Contable_H Int
  ,@Porc_Comision_Prov Decimal(7,2) 
  ,@Importe Decimal(12,2) 
  ,@IMPORTE_CREDITO Decimal(12,2) 
  ,@ID_TIPO_CBTE CHAR(4) 
  ,@Imp_prod_siva  Decimal(12,2) 
  ,@TRANS INT
  ,@Id_Cliente_Externo VARCHAR(14)
  ,@Id_Cta_Banco INT
  ,@Id_Cliente INT
  ,@EXISTE_TAG INT

  SET @EXISTE_TAG = 0
  SET @EXISTE_TAG = (SELECT COUNT(*) FROM TagFile_ TAG WHERE TAG.TBL = @pEquateClientes AND TAG.USR = @pUsuario)

  /*Deuda*/
  PRINT 'Deuda'
  IF @EXISTE_TAG > 0
     BEGIN
	 PRINT '>0'
	 insert into @DEUDA
		Select c.id_trans,dbo.CF_Cbte_Saldo(c.id_trans,@FECHA)/c.imp_total as coef
			 from cbtes c, cbtes_tipos t, TagFile_ TAG
 			 where c.id_tipo_cbte = t.id_tipo_cbte and t.Compromete_Factura in (1,-1)
					 and c.id_estado_cbte NOT IN (0,3) and dbo.CF_Cbte_Saldo(c.id_trans,@FECHA) <> 0
					 and isnull(c.imp_total,0) <> 0
					 and ISNULL(c.id_cond_pago,0) <> 1
					 AND (C.id_cliente = TAG.VAL AND TAG.TBL = @pEquateClientes AND TAG.USR = @pUsuario)
     END
  ELSE
     BEGIN
		PRINT '<=0'
	    insert into @deuda
		Select c.id_trans,dbo.CF_Cbte_Saldo(c.id_trans,@FECHA)/c.imp_total as coef
			 from cbtes c, cbtes_tipos t,Clientes e
 			 where c.id_tipo_cbte = t.id_tipo_cbte 	 and t.Compromete_Factura in (1,-1)
			 		 and isnull(c.imp_total,0) <> 0
			 		 and e.id_cliente = c.id_cliente
			 		 and e.activo = 1
					 and ISNULL(c.id_cond_pago,0) <> 1
					 and c.id_estado_cbte NOT IN (0,3) and  dbo.CF_Cbte_Saldo(c.id_trans,@FECHA) <> 0
 	 
      END

  /*Pagos*/
  PRINT 'Pagos'
  IF @EXISTE_TAG > 0
     BEGIN
	PRINT 'A'
	 insert into @PagosACta
		Select c.id_trans,dbo.CF_Cbte_Saldo(c.id_trans,@FECHA)/c.imp_total as coef
			 from cbtes c, cbtes_tipos t, TagFile_ TAG
 			 where c.id_tipo_cbte = t.id_tipo_cbte and t.Compromete_Recibos = 1
					 and c.id_estado_cbte NOT IN (0,3) and dbo.CF_Cbte_Saldo(c.id_trans,@FECHA) <> 0
					 and isnull(c.imp_total,0) <> 0
					 and ISNULL(c.id_cond_pago,0) <> 1
					 AND (C.id_cliente = TAG.VAL AND TAG.TBL = @pEquateClientes AND TAG.USR = @pUsuario)
     END
  ELSE
     BEGIN
		PRINT 'B'
	    insert into @PagosACta
		Select c.id_trans,dbo.CF_Cbte_Saldo(c.id_trans,@FECHA)/c.imp_total as coef
			 from cbtes c, cbtes_tipos t,Clientes e
 			 where c.id_tipo_cbte = t.id_tipo_cbte 	 and t.Compromete_Recibos = 1
			 		 and isnull(c.imp_total,0) <> 0
			 		 and e.id_cliente = c.id_cliente
			 		 and e.activo = 1
					 and ISNULL(c.id_cond_pago,0) <> 1
					 and c.id_estado_cbte NOT IN (0,3) and  dbo.CF_Cbte_Saldo(c.id_trans,@FECHA) <> 0
 	 
      END

/*----------------------------------------------------------------------------*/
  SET @EXISTE_TAG = 0
  SET @EXISTE_TAG = (SELECT COUNT(*) FROM TagFilePos_ TAG WHERE TAG.TBL = @pEquate AND TAG.USR = @pUsuario)

  IF @EXISTE_TAG > 0             /* Tag Productos*/
      BEGIN 
	  PRINT 'C'
        Select f.id_trans,f.Fecha,c.id_cliente,c.Razon_Social,c.id_cliente_externo,
                     i.id_producto,p.descripcion_detallada,i.fecha_qa as mes,
                     i.imp_final,(i.imp_final * tr.compromete_factura)*(1-(isnull(f.Porc_Bonificacion,0)/100)) as Bonificacion ,
                     f.Porc_Bonificacion,
                     (i.imp_final * tr.compromete_factura)*(1-(isnull(f.Porc_Bonificacion,0)/100)) * (1-( isnull(f.Porc_DescEspecial,0)/100)) as DescEspecial , 
                     f.Porc_DescEspecial,
                     --(i.imp_final * tr.compromete_factura)*(1-(isnull(f.Porc_Bonificacion,0)/100)) * (1-( isnull(f.Porc_DescEspecial,0)/100)) * (d.coef) as saldo, 
					 (dbo.CF_Cbte_Saldo(F.id_trans,@FECHA) * tr.compromete_factura) / f.Imp_Total *  i.imp_final       AS Saldo,
                     i.fecha_venc,Flag_Periodo,Flag_Mes,d.coef,I.ITEM,dbo.CF_Cbte_Descrip(F.Id_Trans) AS CBTE_DESCRIP,
					 c.Id_Tipo_Cli,
					 CT.Descripcion,
					 P.Id_Alias_Cta_Cont
				  Into #DeudaRpt1
				  from cbtes_items i, cbtes F, @DEUDA D, TagFilePos_ Tag , Cbtes_tipos TR, CLIENTES C, PRODUCTOS P, Clientes_Tipos CT
				  WHERE F.ID_TRANS = I.ID_TRANS AND F.ID_TRANS = D.ID_TRANS  
				  AND TR.ID_TIPO_CBTE = F.ID_TIPO_CBTE
				  AND C.ID_CLIENTE = F.ID_CLIENTE
				  AND P.ID_PRODUCTO = I.ID_PRODUCTO
				  AND CT.Id_Tipo_Cli = C.Id_Tipo_Cli
				  AND I.imp_final <> 0
				  AND (i.id_producto = TAG.POS AND TAG.TBL = @pEquate AND TAG.USR = @pUsuario)

 
           SELECT D.*,O.Nro_Cta_Contable,O.Descripcion as Descrip_Cta_Contable  
				INTO #Resultado1
				FROM #DeudaRpt1 D LEFT OUTER JOIN Pla_Ctas_Cuentas_Contables O ON O.Id_Cta_Contable = dbo.CF_Cta_Cont( D.Id_Alias_Cta_Cont,D.Fecha)

				/* Pagos a ACta: Es lo mismo que el anterio*/

		INSERT INTO #Resultado1
        Select f.id_trans,f.Fecha,c.id_cliente,c.Razon_Social,c.id_cliente_externo,
                     'P/C' AS id_producto,'z-Pago a Cta' AS descripcion_detallada, f.fecha as mes,
                     f.Imp_Total *-1 AS imp_final,0 as Bonificacion ,  f.Porc_Bonificacion,
                     0 as DescEspecial ,  f.Porc_DescEspecial,
                     f.saldo *-1 as saldo, 
                     f.fecha as fecha_venc,0 AS Flag_Periodo,0 as Flag_Mes,d.coef,1 AS ITEM,dbo.CF_Cbte_Descrip(F.Id_Trans) AS CBTE_DESCRIP,
					 c.Id_Tipo_Cli,
					 CT.Descripcion,
					 0 AS Id_Alias_Cta_Cont,
					 '' AS Nro_Cta_Contable,
					 '' AS Descrip_Cta_Contable
				  from cbtes F, @PagosACta D , Cbtes_tipos TR, CLIENTES C,Clientes_Tipos CT
				  WHERE F.ID_TRANS = D.ID_TRANS  
				  AND TR.ID_TIPO_CBTE = F.ID_TIPO_CBTE
				  AND C.ID_CLIENTE = F.ID_CLIENTE
				  AND CT.Id_Tipo_Cli = C.Id_Tipo_Cli
				  AND F.Imp_Total <> 0

	     SELECT * FROM #Resultado1 ORDER BY 4,7,8


       END
      ELSE
       BEGIN 
			PRINT 'D'
			Select f.id_trans,f.Fecha,c.id_cliente,c.Razon_Social,c.id_cliente_externo,
						 i.id_producto,p.descripcion_detallada,i.fecha_qa as mes,
						 i.imp_final,(i.imp_final * tr.compromete_factura)*(1-(isnull(f.Porc_Bonificacion,0)/100)) as Bonificacion ,
						 f.Porc_Bonificacion,
						 (i.imp_final * tr.compromete_factura)*(1-(isnull(f.Porc_Bonificacion,0)/100)) * (1-( isnull(f.Porc_DescEspecial,0)/100)) as DescEspecial , 
						 f.Porc_DescEspecial,
						 --(i.imp_final * tr.compromete_factura)*(1-(isnull(f.Porc_Bonificacion,0)/100)) * (1-( isnull(f.Porc_DescEspecial,0)/100)) * (d.coef) as Saldo, 
					     (dbo.CF_Cbte_Saldo(F.id_trans,@FECHA) * tr.compromete_factura) / f.Imp_Total *  i.imp_final       AS Saldo,
						 i.fecha_venc,Flag_Periodo,Flag_Mes,d.coef,I.Item,dbo.CF_Cbte_Descrip(F.Id_Trans) AS Cbte_Descrip,
						 c.Id_Tipo_Cli,
						 CT.Descripcion,
						 P.Id_Alias_Cta_Cont
					  Into #DeudaRpt2
					  from cbtes_items i, cbtes F, @DEUDA D, Cbtes_tipos TR, CLIENTES C, PRODUCTOS P, Clientes_Tipos CT 
					  WHERE F.ID_TRANS = I.ID_TRANS AND F.ID_TRANS = D.ID_TRANS  
					  AND TR.ID_TIPO_CBTE = F.ID_TIPO_CBTE
					  AND C.ID_CLIENTE = F.ID_CLIENTE
					  AND P.ID_PRODUCTO = I.ID_PRODUCTO
					  AND CT.Id_Tipo_Cli = C.Id_Tipo_Cli
					  AND I.imp_final <> 0

			 SELECT D.*,O.Nro_Cta_Contable,O.Descripcion as Descrip_Cta_Contable  
				INTO #Resultado2
				FROM #DeudaRpt2 D LEFT OUTER JOIN Pla_Ctas_Cuentas_Contables O ON O.Id_Cta_Contable = dbo.CF_Cta_Cont( D.Id_Alias_Cta_Cont,D.Fecha)

				/* Pagos a ACta: Es lo mismo que el anterio*/
				/* Es lo mismo que el anterio*/
		INSERT INTO #Resultado2
        Select f.id_trans,f.Fecha,c.id_cliente,c.Razon_Social,c.id_cliente_externo,
                     'P/C' AS id_producto,'z-Pago a Cta' AS descripcion_detallada, f.fecha as mes,
                     f.Imp_Total *-1 AS imp_final,0 as Bonificacion ,  f.Porc_Bonificacion,
                     0 as DescEspecial ,  f.Porc_DescEspecial,
                     --f.saldo as saldo, 
					 dbo.CF_Cbte_Saldo(F.id_trans,@FECHA) *-1 AS Saldo,
                     f.fecha as fecha_venc,0 AS Flag_Periodo,0 as Flag_Mes,d.coef,1 AS ITEM,dbo.CF_Cbte_Descrip(F.Id_Trans) AS CBTE_DESCRIP,
					 c.Id_Tipo_Cli,
					 CT.Descripcion,
					 0 AS Id_Alias_Cta_Cont,
					 '' AS Nro_Cta_Contable,
					 '' AS Descrip_Cta_Contable

				  from cbtes F, @PagosACta D , Cbtes_tipos TR, CLIENTES C,Clientes_Tipos CT
				  WHERE F.ID_TRANS = D.ID_TRANS  
				  AND TR.ID_TIPO_CBTE = F.ID_TIPO_CBTE
				  AND C.ID_CLIENTE = F.ID_CLIENTE
				  AND CT.Id_Tipo_Cli = C.Id_Tipo_Cli
				  AND F.Imp_Total <> 0
				  

	     SELECT * FROM #Resultado2 ORDER BY 4,7,8
        END	   



PRINT 'F'