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

 CREATE PROCEDURE [dbo].[SP_Desglosar_Pedidos] @ID_TRANS INT
       AS 

		DECLARE @trans_nueva INTEGER
		DECLARE @NRO_CBTE INTEGER
	    declare @desc varchar(50)
		declare @fecha_mov datetime
		declare @user smallint
		declare @id_cond_vta  varchar(5)
        declare @id_tipo_cbte varchar(5)
        declare @id_producto varchar(15)
        declare @Cantidad decimal(12,2)
        declare @Cantidad_orig decimal(12,2)
        declare @ITEM INTEGER
		declare @id_Color varchar(10)
		DECLARE @ID_TIPO_CBTE_DEST varchar(5)

        DECLARE @Mensaje	VARCHAR(100) 
		
		SET @Mensaje = ''
		SET @id_cond_vta = (SELECT id_cond_vta from cbtes where id_trans = @ID_TRANS) 
		SET @desc = (SELECT descripcion from transacciones where id_trans = @ID_TRANS) 
		SET @fecha_mov = (SELECT fecha_mov from transacciones where id_trans = @ID_TRANS) 
		SET @user = (SELECT id_usuario from transacciones where id_trans = @ID_TRANS) 
		SET @id_tipo_cbte = (SELECT id_tipo_cbte from cbtes where id_trans = @ID_TRANS) 
						
        select I.Id_Trans,ISNULL(P.Id_Color,'''') AS Id_COLOR ,sum(i.Cantidad) AS CANTIDAD INTO #CBTES_ITEMS_tot_aux
                              from Cbtes_Items I,Productos P
                              where id_trans = @id_trans
                              and I.id_producto = P.Id_producto  group by I.Id_Trans,P.Id_Color

        Set @Cantidad   = (select count(*) from #CBTES_ITEMS_tot_aux )
		IF @Cantidad  < 2 
		   BEGIN 
		     SET @Mensaje = 'Pedido sin desglose'
	  	     SELECT	 0					AS ErrorNumber 
					,0					AS ErrorSeverity  
					,0					AS ErrorState 
					,0					AS ErrorProcedure  
					,0					AS ErrorLine		
					,@Mensaje			AS ErrorMessage
		     RETURN  
	       END

        BEGIN
		BEGIN TRY
	    BEGIN TRAN

               Declare MIcursor cursor for select id_Color from #CBTES_ITEMS_tot_aux WHERE ID_TRANS = @ID_TRANS

               Open Micursor
                    Fetch next from Micursor into @id_Color
                    While @@fetch_status = 0 
                    begin

               ----------------------------- Primero los insert ----------------------------------
			   	       SET @trans_nueva = (SELECT max(id_trans) from transacciones ) + 1
					   INSERT INTO TRANSACCIONES
					   (id_trans,descripcion,fecha_mov,id_usuario)
					    values (@trans_nueva,@desc,@fecha_mov,@user)

					   SELECT * INTO #CBTES_aux_sp  FROM CBTES 
					              WHERE ID_TRANS = @ID_TRANS

					   SELECT I.* INTO  #CBTES_ITEMS_aux_sp FROM CBTES_ITEMS I, PRODUCTOS P  
							      WHERE I.ID_TRANS = @ID_TRANS AND P.ID_PRODUCTO = I.ID_PRODUCTO AND ISNULL(P.ID_COLOR,'''') = @ID_COLOR


               -----------------------------Actualizo -----------------------------------------------
         
					   UPDATE #CBTES_aux_sp SET 
							  Imp_Gravado = (SELECT SUM(Imp_Gravado) FROM #CBTES_ITEMS_aux_sp  WHERE ID_TRANS = @ID_TRANS) * (1-Porc_Bonificacion/100),
							  Imp_Bonificacion = (SELECT SUM(Imp_Gravado) FROM #CBTES_ITEMS_aux_sp  WHERE ID_TRANS = @ID_TRANS) * (Porc_Bonificacion/100) 
							  WHERE ID_TRANS = @ID_TRANS  

					   UPDATE #CBTES_aux_sp SET 
							  Imp_Iva = Imp_Gravado * Porc_Iva/100 
							  WHERE ID_TRANS = @ID_TRANS  

					   UPDATE #CBTES_aux_sp SET 
							  Imp_Total = Imp_Gravado + Imp_Iva + Imp_Percep
							  WHERE ID_TRANS = @ID_TRANS  
  
  
					   UPDATE #CBTES_aux_sp SET Saldo = Imp_Total WHERE ID_TRANS = @ID_TRANS 

					   SET @ID_TIPO_CBTE_DEST = (SELECT ISNULL(ID_TIPO_CBTE_DEST,'''') FROM CBTES_TIPOS WHERE ID_TIPO_CBTE = @id_tipo_cbte)
			           IF @ID_TIPO_CBTE_DEST = '' 
							  BEGIN
				       			 SET @NRO_CBTE = (SELECT Prox_nro FROM CBTES_TIPOS WHERE ID_TIPO_CBTE = @id_tipo_cbte)
								 UPDATE CBTES_TIPOS SET Prox_nro = Prox_nro+1 WHERE ID_TIPO_CBTE = @id_tipo_cbte
							  END
						  ELSE
							  BEGIN
				       			 SET @NRO_CBTE = (SELECT Prox_nro FROM CBTES_TIPOS WHERE ID_TIPO_CBTE = @ID_TIPO_CBTE_DEST)
								 UPDATE CBTES_TIPOS SET Prox_nro = Prox_nro+1 WHERE ID_TIPO_CBTE = @ID_TIPO_CBTE_DEST
								 UPDATE CBTES_TIPOS SET Prox_nro = @NRO_CBTE+1 WHERE ID_TIPO_CBTE_DEST = @ID_TIPO_CBTE_DEST
							  END

					   UPDATE #CBTES_AUX_SP SET COMPROBANTE_NRO = @NRO_CBTE  WHERE ID_TRANS = @ID_TRANS

		               update #CBTES_aux_sp set id_trans = @trans_nueva  where id_trans = @ID_TRANS
		               update #CBTES_ITEMS_aux_sp set id_trans = @trans_nueva where id_trans = @ID_TRANS

					   -----------------------------agrego -----------------------------------------------
					   INSERT INTO CBTES
							  SELECT * FROM  #CBTES_aux_sp WHERE ID_TRANS = @trans_nueva    

					   INSERT INTO CBTES_ITEMS
          					 SELECT * FROM #CBTES_ITEMS_aux_sp WHERE ID_TRANS = @trans_nueva 

                        DROP TABLE #CBTES_aux_sp
                        DROP TABLE #CBTES_ITEMS_aux_sp
						
						SET @Mensaje = RTRIM(LTRIM(@Mensaje)) + ' ' + CAST(@trans_nueva AS VARCHAR(10))

                        Fetch next from Micursor into @id_COLOR
                    End       
               Close Micursor
               Deallocate Micursor
               ------- ACTUALIZO ESTADO CBTE ORIGINAL ---------

               UPDATE CBTES SET ID_ESTADO_CBTE = 7, Observacion = 'Transacciones desglosadas: ' + @Mensaje  WHERE ID_TRANS = @ID_TRANS 
			   UPDATE CBTES_ITEMS SET CANTIDAD_SALDO = 0 WHERE ID_TRANS = @ID_TRANS 

               -----------------------------BORRO -----------------------------------------------

			 DROP TABLE #CBTES_ITEMS_tot_aux 

		     COMMIT TRAN
 
			SELECT	 0					AS ErrorNumber 
					,0					AS ErrorSeverity  
					,0					AS ErrorState 
					,0					AS ErrorProcedure  
					,0					AS ErrorLine		
					,@Mensaje			AS ErrorMessage
	END TRY  

	BEGIN CATCH  
		EXECUTE usp_GetErrorInfo 
		ROLLBACK
	END CATCH 

    End

 -- EXEC [dbo].[SP_Desglosar_Pedidos] 919
