if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RegistroVentasProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RegistroVentasProc]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/****** Objeto:  procedimiento almacenado dbo.RegistroVentasProc    fecha de la secuencia de comandos: 27/03/2012 11:48:51 a.m. ******/

/****** Objeto:  procedimiento almacenado dbo.RegistroVentasProc    fecha de la secuencia de comandos: 06/01/2011 02:55:24 p.m. ******/


CREATE  PROCEDURE RegistroVentasProc
(
 @FECHAINI	CHAR(15) = '20080101',
 @FECHAFIN	CHAR(15) = '20080501',
 @MONEDA	UD_CURYID = 'PEN',
 @TODOS_DOC	TINYINT=1,	-- (1) TODOS LOD DOC EN @MONEDA, (0) SOLO LOS DOC EN @MONEDA
 @ALMACENES	VARCHAR(255)='',-- CADENA DE ALMACENES
 @TODOS_ALM	TINYINT=1,--TODOS LOS ALMACENES
 @CRITERIOS	VARCHAR(255)='', --solo los elementos que cumplan la condicion
 @TODOS_CON	TINYINT=1, --TODOS LOS elementos del tipo de condicion
 @SERIE		VARCHAR(5) = ''
)
AS
BEGIN
   DECLARE  @DATFECHAINI SMALLDATETIME
   DECLARE  @DATFECHAFIN SMALLDATETIME
      
      
--  SET @FECHAINI='20021201'
--  SET @FECHAFIN='20021218'

       
        SET @DATFECHAINI=CAST(RTRIM(LTRIM(@FECHAINI)) AS SMALLDATETIME)
        SET @DATFECHAFIN=CAST(RTRIM(LTRIM(@FECHAFIN)) AS SMALLDATETIME)
         
        

	DECLARE @CADENA	VARCHAR(8000)
	DECLARE @MONEDABASE UD_CURYID	
	
	SET @MONEDABASE=(SELECT CURYORIG FROM SETUP)        --OBTENGO EL CODIGO DE LA MONEDA BASE
  

	IF (@MONEDA=@MONEDABASE) 
		BEGIN
			SET @CADENA="SELECT * " +
			    	    "FROM VW_REGISTRO_VENTAS_PEN " +
	        	            "WHERE DATEPROCESALES BETWEEN '" + RTRIM(LTRIM(CAST(@DATFECHAINI AS CHAR(100)))) + "' AND '" + RTRIM(LTRIM(CAST(@DATFECHAFIN AS CHAR(100)))) + "'"
		END
	ELSE
		BEGIN
			SET @CADENA="SELECT * " +
			    	    "FROM VW_REGISTRO_VENTAS_USD " +
	        	            "WHERE DATEPROCESALES BETWEEN '" + RTRIM(LTRIM(CAST(@DATFECHAINI AS CHAR(100)))) + "' AND '" + RTRIM(LTRIM(CAST(@DATFECHAFIN AS CHAR(100)))) + "'"
		END


	IF (@TODOS_ALM=0)
              	SET @CADENA=@CADENA + " AND SITEID IN (" + @ALMACENES + ")" 


	IF (@TODOS_CON=0)
		SET @CADENA=@CADENA + " AND DOCTYPEID IN (" + @CRITERIOS + ")"

	SET @CADENA=@CADENA + " AND (LEFT(NBRDOCUMENT,LEN(NBRDOCUMENT)-7) != 761)"

	IF LEN(ISNULL(@SERIE,'')) = 2
		SET @CADENA=@CADENA + ' AND LEFT(NBRDOCUMENT,2) = ' + @SERIE

	IF LEN(ISNULL(@SERIE,'')) = 3
		SET @CADENA=@CADENA + ' AND LEFT(NBRDOCUMENT,3) = ' + @SERIE

	--SELECT 	@CADENA	
	SET @CADENA=@CADENA + ' AND RTRIM(DOCTYPEID) + LEFT(NBRDOCUMENT,1) <> "077" ORDER BY DOCTYPEID, DATEPROCESALES '		
	EXEC (@CADENA)	
--SELECT RTRIM(DOCTYPEID) + LEFT(NBRDOCUMENT,1),* FROM OP_SALES WHERE RTRIM(DOCTYPEID) + LEFT(NBRDOCUMENT,1) = '077'
--SELECT @CADENA

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

