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

CREATE PROCEDURE [dbo].[CPJ_Cbtes_Pres_a_Ped] @pJson VARCHAR(8000)
AS
SET NOCOUNT ON

/*Variables recibidas por parámetro a traves del JSON*/
DECLARE @pFlagUsarTrans			TINYINT
DECLARE @pModoDebug				TINYINT
DECLARE @pId_Usuario			SMALLINT
DECLARE @pId_Trans_Pres			INT
DECLARE @pId_Tipo_Cbte_Ped		VARCHAR(4)

SET @pFlagUsarTrans				= ISNULL(CONVERT(TINYINT, dbo.CF_JSON_VALUE(@pJson,'FlagUsarTrans')), 0)
SET @pModoDebug					= ISNULL(CONVERT(TINYINT, dbo.CF_JSON_VALUE(@pJson,'ModoDebug')), 0)
SET @pId_Usuario				= ISNULL(CONVERT(SMALLINT, dbo.CF_JSON_VALUE(@pJson,'Id_Usuario')), -1)
SET @pId_Trans_Pres				= ISNULL(CONVERT(INT, dbo.CF_JSON_VALUE(@pJson,'Id_Trans_Pres')), 0)
SET @pId_Tipo_Cbte_Ped			= ISNULL(CONVERT(VARCHAR(4), dbo.CF_JSON_VALUE(@pJson,'Id_Tipo_Cbte_Ped')), 0)
/*FIN Variables recibidas por parámetro a traves del JSON*/

/*Declaración de Variables Locales*/
DECLARE @Id_Trans_Ped						INT
DECLARE @rtaMsjStored						VARCHAR(4000)
DECLARE @Descripcion_Cbte					VARCHAR(80)
DECLARE @Result_Stored_Invocado				INT
DECLARE @JSON_Parametros_Stored_Invocado	VARCHAR(8000)
DECLARE @Pres_Id_Estado_Cbte				SMALLINT
DECLARE @Ped_Id_Estado_Cbte					SMALLINT
DECLARE @Pres_Imp_Total						DECIMAL(20,5)
DECLARE @Id_Cliente							INT		
DECLARE @Id_Iva								CHAR(5)
DECLARE @Id_Vendedor						VARCHAR(10)
DECLARE @Observacion						VARCHAR(8000)
DECLARE @Id_Cond_Pago						SMALLINT
DECLARE @Cbte_Nro_Externo					VARCHAR(15)
DECLARE @Id_Cond_Vta						VARCHAR(10)
DECLARE @Id_Moneda							CHAR(3)
DECLARE @Cotizacion							INT
DECLARE @Id_Centro_Costo					INT
DECLARE @Email								VARCHAR(8000)	
DECLARE @Id_Puerto							CHAR(5)
/*FIN Declaración de Variables Locales*/

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

IF(@pModoDebug = 1)
BEGIN
	PRINT 'Ingreso a CPJ_Cbtes_Pres_a_Ped'
	PRINT 'Parametros: FlagUsarTrans: ' + CONVERT(VARCHAR(10), @pFlagUsarTrans) + '. ModoDebug: ' + CONVERT(VARCHAR(10), @pModoDebug)
	PRINT '@pId_Usuario: ' + CONVERT(VARCHAR(10), @pId_Usuario)
	PRINT '@pId_Trans_Pres: ' + CONVERT(VARCHAR(10), @pId_Trans_Pres) +'. @pId_Tipo_Cbte_Ped: ' + @pId_Tipo_Cbte_Ped
END

BEGIN TRY

	IF @pFlagUsarTrans <> 0 
	BEGIN
		BEGIN TRAN
	END

	IF(@pId_Trans_Pres = 0)  RAISERROR ('@pId_Trans_Pres no puede ser cero.', 16,  1 ) 

	IF(@pId_Tipo_Cbte_Ped = '')  RAISERROR ('@pId_Tipo_Cbte_Ped no puede ser vacio.', 16,  1 ) 

	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

	----Recupero Datos del Presupuesto
	SELECT
	--@Id_Cliente			= ISNULL(Id_Cliente, 0),
	--@Id_Iva				= ISNULL(Id_Iva, ''),
	--@Id_Vendedor		= ISNULL(Id_Vendedor,''),
	--@Observacion		= ISNULL(Observacion,''),
	@Id_Cond_Pago		= ISNULL(Id_Cond_Pago,10)
	--@Cbte_Nro_Externo	= ISNULL(Cbte_Nro_Externo,''),
	--@Id_Cond_Vta		= ISNULL(Id_Cond_Vta,''),
	--@Id_Moneda			= ISNULL(Id_Moneda,'PES'),
	--@Cotizacion			= ISNULL(Cotizacion,1),
	--@Id_Centro_Costo	= ISNULL(Id_Centro_Costo,''),
	--@Email				= ISNULL(Email,''),
	--@Id_Puerto			= ISNULL(Id_Puerto,'')
	FROM Cbtes
	WHERE
	Id_Trans = @pId_Trans_Pres

	SELECT 
	@Ped_Id_Estado_Cbte = ISNULL(Id_Estado_Cbte,1) 
	FROM Cbtes_Tipos 
	WHERE Id_Tipo_Cbte = @pId_Tipo_Cbte_Ped

	/*Ingreso en Transacciones*/
	SET @Id_Trans_Ped = (SELECT MAX(Id_Trans) + 1 FROM Transacciones)
	
	INSERT INTO Transacciones (Id_Trans, Fecha_Mov,	Descripcion, Id_Usuario) 
	VALUES (@Id_Trans_Ped, GETDATE(), 'Creada por CPJ_Cbtes_Pres_a_Ped', @pId_Usuario)

	/*Inserto en Cbtes*/
	SELECT * INTO #Cbte_Ped FROM Cbtes WHERE Id_Trans = @pId_Trans_Pres

	UPDATE #Cbte_Ped 
	SET 
	Id_Trans = @Id_Trans_Ped, 
	Id_Tipo_Cbte = @pId_Tipo_Cbte_Ped,
	Id_Estado_Cbte = @Ped_Id_Estado_Cbte, 
	Comprobante_Nro = (SELECT ISNULL(MAX(Comprobante_Nro),1) FROM Cbtes WHERE Id_Tipo_Cbte = @pId_Tipo_Cbte_Ped),
	Id_Trans_Origen = @pId_Trans_Pres,
	Fecha = CONVERT(DATE, GETDATE()),
	Fecha_Venc = (SELECT CONVERT(DATE, DATEADD(DAY,ISNULL(Plazo_Venc,0),GETDATE())) FROM Cbtes_Cond_Pago WHERE Id_Cond_Pago = @Id_Cond_Pago)
	
	INSERT INTO Cbtes SELECT * FROM #Cbte_Ped

	/*Inserto en Cbtes_Items*/
	SELECT * INTO #Cbtes_Items_Ped FROM Cbtes_Items WHERE Id_Trans = @pId_Trans_Pres 
	
	UPDATE #Cbtes_Items_Ped 
	SET 
	Id_Trans = @Id_Trans_Ped, 
	Flag_QA = 'A'

	INSERT INTO Cbtes_Items SELECT * FROM #Cbtes_Items_Ped

	/*Inserto en Cbtes_Items_xCampos*/
	SELECT * INTO #Cbtes_Items_xCampos_Ped FROM Cbtes_Items_xCampos WHERE Id_Trans = @pId_Trans_Pres

	UPDATE #Cbtes_Items_xCampos_Ped 
	SET 
	Id_Trans = @Id_Trans_Ped

	INSERT INTO Cbtes_Items_xCampos SELECT * FROM #Cbtes_Items_xCampos_Ped

	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	SET @JSON_Parametros_Stored_Invocado =	'{' +
											dbo.CF_Json_ParsearVariable('FlagUsarTrans', 0, 'INT') + ',' +
											dbo.CF_Json_ParsearVariable('Id_Trans', @Id_Trans_Ped, 'INT') + ',' +
											dbo.CF_Json_ParsearVariable('ModoDebug', @pModoDebug, 'INT') + ',' +
											dbo.CF_Json_ParsearVariable('ModoDebug', @pModoDebug, 'INT') + ',' +
											dbo.CF_Json_ParsearVariable('FlagRegenerar', 1, 'TINYINT') + 
											'}'
						
	EXEC @Result_Stored_Invocado = dbo.CPJ_Cbtes_Ped_Fin @JSON_Parametros_Stored_Invocado
	IF ISNULL(@Result_Stored_Invocado,0) <> 0 
	BEGIN
		RETURN 9999
	END		

	UPDATE Cbtes 
	SET
	Id_Estado_Cbte = @Ped_Id_Estado_Cbte
	WHERE Id_Trans = @Id_Trans_Ped
	AND Id_Estado_Cbte <> @Ped_Id_Estado_Cbte

	UPDATE Cbtes
	SET
	Id_Estado_Cbte = 2
	WHERE Id_Trans = @pId_Trans_Pres

	IF @pFlagUsarTrans <> 0 
	BEGIN
		COMMIT
	END

	SET @rtaMsjStored		=	'{' +
								dbo.CF_Json_ParsearVariable('id_trans', @Id_Trans_Ped, 'INT') + ',' +
								dbo.CF_Json_ParsearVariable('descrip_Cbte', dbo.CF_Cbte_Descrip(@Id_Trans_Ped), 'VARCHAR') +
								'}'

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

	-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

	IF(@pModoDebug = 1)
	BEGIN
		PRINT 'FIN Procedimiento: CPJ_Cbtes_Pres_a_Ped'
	END

	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
END TRY  


BEGIN CATCH  
    EXECUTE usp_GetErrorInfo

	IF @pFlagUsarTrans <> 0  ROLLBACK

	RETURN 9999
END CATCH

RETURN 0 

--EXEC dbo.CPJ_Cbtes_Pres_a_Ped '{"FlagUsarTrans":"0","ModoDebug":"1","Id_Trans_Pres":"9063528", "Id_Tipo_Cbte_Ped":"PEDT"}'