
DROP PROCEDURE CALCULA_CTO_PROMEDIO_PROC
GO
CREATE PROCEDURE CALCULA_CTO_PROMEDIO_PROC
(
@CORRNBR	INT,
@MONEDASOLICITADA UD_CURYID,     -- Recibe la Moneda Solicitada por el Usuario  
@FechaDia CHAR(2),               -- Recibe el Día de la Fecha Desde
@FechaMes CHAR(2),               -- Recibe el Mes de la Fecha Desde  
@Fechaanio CHAR(4),              -- Recibe el Año de la Fecha Desde 

@FechaDiaIni char(2),            
@FechaMesIni char(2),  
@FechaAnioIni char(4),   

@FechaMesHistorica char(2),    

@FechaDiaHasta char(2),
@FechaMesHasta char(2),
@FechaAnioHasta char(4),

@CadenaAlmacenes  varchar(8000), -- Recibe los almacenes seleccionado
@CadenaCategorias varchar(8000),  -- Recibe las Categorias Seleccionadas
@TODOSALAMACENES TINYINT,         -- Es 1 si todos los almacenes fueron seleccionados , de lo contrario es 0 
@TODOSCATEGORIAS TINYINT         -- Es 1 si todas las categorias fueron seleccionadas , de lo contrairo es 0
)
AS
BEGIN
/**Variables para los Tipos de Movimientos Ingresos**/
DECLARE @TIPOCOMPRAFUELS UD_TYPEDOC
DECLARE @TIPOCOMPRASTORE UD_TYPEDOC
DECLARE @TIPOAJUSTEING UD_TYPEDOC
DECLARE @TIPOBONIFICACION UD_TYPEDOC
DECLARE @TIPOTRANSFERING UD_TYPEDOC
/**Variables para los Tipos de Movimientos Salidas **/
DECLARE @TIPOVENTAS UD_TYPEDOC
DECLARE @TIPOAJUSTESAL UD_TYPEDOC
DECLARE @TIPONTACREDITO UD_TYPEDOC
DECLARE @TIPOTRANSFERSAL UD_TYPEDOC 
/*******************************************/
DECLARE @INTRAMOVMONBASE char(10)
DECLARE @INTRAMOVMONDEST char(10)
DECLARE @MONEDAPROCESO char(10)
DECLARE @KDXHISTMONBASE char(6)
DECLARE @KDXHISTMONDEST char(6)
DECLARE @MONEDAKDXHIST char(6)
DECLARE @TOTALMONBASE char(11)
DECLARE @TOTALMONEXT char(11)
DECLARE @MONEDATOTAL char(12)
/*******************************************/
DECLARE @FechaDesde smalldatetime
DECLARE @FechaInicial smalldatetime
DECLARE @FechaHasta smalldatetime
DECLARE @SALDOINICIAL varchar(8000)
DECLARE @INGNOVAL varchar(8000)
DECLARE @SALNOVAL varchar(8000)
DECLARE @INGSALVALORIZADA VARCHAR(8000) 
DECLARE @KARDEXGENERAL VARCHAR(8000)

DECLARE @FLAGMONEDA BIT -- 0 ES MONEDA BASE, 1 EN OTRA MONEDA 

/*Variables para armar el criterio de Seleccion*/
DECLARE @CRITERIOSELECCION varchar(8000)
DECLARE @CRITERIOSELECCIONVAL varchar(8000)
/*******************************************/
/*Variables para el Manejo de los Decimales*/
/*******************************************/
DECLARE @ND_COSTOSETUP Tinyint
DECLARE @ND_STOCKSETUP Tinyint
DECLARE @ND_STOCK CHAR(1) 
DECLARE @ND_COSTO CHAR(1) 
  

--   set @FechaInicial=Cast(@FechaMesIni + '-' + @FechaDiaIni + '-' + @FechaAnioIni as smalldatetime)
--   set @FechaDesde= Cast(@FechaMes + '-' +@FechaDia + '-' + @Fechaanio as smalldatetime)
--   set @FechaHasta = Cast(@FechaMesHasta + '-' + @FechaDiaHasta + '-' + @FechaanioHasta as smalldatetime)

  set @FechaInicial=Cast(@FechaDiaIni + '-' + @FechaMesIni + '-' + @FechaAnioIni as smalldatetime)
  set @FechaDesde= Cast(@FechaDia + '-' + @FechaMes + '-' + @Fechaanio as smalldatetime)
  set @FechaHasta = Cast(@FechaDiaHasta + '-' + @FechaMesHasta + '-' + @FechaanioHasta as smalldatetime)


  /*Nomnbres de las Columnas que contienen a Moneda Base y Destino */
  
  

  set @INTRAMOVMONBASE='STDCOSTPEN' 
  set @INTRAMOVMONDEST='STDCOSTUSD'  
  set @KDXHISTMONBASE ='AVGPEN'
  set @KDXHISTMONDEST ='AVGUSD'
  set @TOTALMONBASE ='TOTAVGPEN'
  set @TOTALMONEXT ='TOTAVGUSD'
         

  /*Tipo de Movimientos*/
  SET @TIPOCOMPRAFUELS=(SELECT INTYPETRBUYFUELS FROM IN_SETUP) 
  SET @TIPOCOMPRASTORE=(SELECT INTYPETRBUYSTORE FROM IN_SETUP)
  SET @TIPOAJUSTEING=(SELECT INTYPEFISIN FROM IN_SETUP)
  SET @TIPOBONIFICACION=(SELECT INTYPEBONUS FROM IN_SETUP)
  SET @TIPOTRANSFERING=(SELECT INTYPETRANSFERIN FROM IN_SETUP) 
  SET @TIPOVENTAS =(SELECT INTYPESALES FROM IN_SETUP)
  SET @TIPOAJUSTESAL =(SELECT INTYPEFISOUT FROM IN_SETUP)
  SET @TIPONTACREDITO =(SELECT INTYPECREDMEM FROM IN_SETUP)
  SET @TIPOTRANSFERSAL =(SELECT INTYPETRANSFEROUT FROM IN_SETUP)

  /*Establecer los decimales */
  SET @ND_COSTOSETUP=(Select Floatcost from setup)
  SET @ND_STOCKSETUP=(Select Floatqty from setup)
  set @ND_COSTO=RTRIM(LTRIM(STR(@ND_COSTOSETUP)))
  set @ND_STOCK=RTRIM(LTRIM(STR(@ND_STOCKSETUP)))


  /* Para Crear la cadena de Filtros */
   if  @TODOSALAMACENES =1 and @TODOSCATEGORIAS =1   -- Todos los almacenes y todas las Categorias
       begin
           set  @CRITERIOSELECCION= " "
           set  @CRITERIOSELECCIONVAL= " "  
       end
   else
       begin
          if @TODOSALAMACENES =1 and @TODOSCATEGORIAS =0  -- Todos los Almacenes y solo algunas categorias
             begin
               set @CRITERIOSELECCION= " IN_INVENTORY.CLASSID in (" + RTRIM(LTRIM(@CadenaCategorias)) + ") and"
               set @CRITERIOSELECCIONVAL=@CRITERIOSELECCION 
             end
          else             
             begin
               if @TODOSALAMACENES =0 and @TODOSCATEGORIAS =1  -- Algunos Almacenes y Todas las Categorias
                  begin
                    set @CRITERIOSELECCION= " SITEID in (" + RTRIM(LTRIM(@CadenaAlmacenes)) + ") and "
                    set @CRITERIOSELECCIONVAL= " INTRAMOV.SITEID in (" + RTRIM(LTRIM(@CadenaAlmacenes)) + ") and "
                  end
               else 
                  begin
                    if @TODOSALAMACENES =0 and @TODOSCATEGORIAS =0  -- Algunos Almacenes y Algunas Categorias
                      begin 
                          set @CRITERIOSELECCION= " SITEID in (" + RTRIM(LTRIM(@CadenaAlmacenes)) + ") and IN_INVENTORY.CLASSID in (" +
                                                    RTRIM(LTRIM(@CadenaCategorias)) +") and "
                          set @CRITERIOSELECCIONVAL = " INTRAMOV.SITEID in (" + RTRIM(LTRIM(@CadenaAlmacenes)) + ") and IN_INVENTORY.CLASSID in (" +
                                                    RTRIM(LTRIM(@CadenaCategorias)) +") and "
                      end
                  end
             end
       end           
   
   
  SET @SALDOINICIAL= " SELECT in_kdxhist.siteid,IN_INVENTORY.CLASSID,in_kdxhist.INVTIDSKU,SUM(ROUND(QTYEND" + @FechaMesHistorica +
                     "," + @ND_STOCK + ")) AS [Inicial],0 as [QTYRESULT],0 as [COMPRASFUELS],0 AS [COMPRASFUELSVAL]," + 
                     "0 AS [COMPRASSTORE],0 AS [COMPRASSTOREVAL]," +
                     "0 AS [AJUSTEING],0 AS [BONIF],0 AS [BONIFVAL],0 as [TRANSFER],0 as [TRANSFERVAL],0 as [OTROS]," +
                     "0 AS [VENTAS],0 AS [AJUSTESAL],0 AS [NTACREDITO],0 AS [NTACREDITOVAL],0 AS [TRANSFERSAL],0 AS [TRANSFERSALVAL]," +
                     "0 AS [OTROSSAL],0 as [AJUSTEINGVAL],0 as [OTROSINGVAL],0 as [VENTASVAL]," +
                     "0 as [AJUSTESALVAL],0 as [OTROSSALVAL]" +   
                     " from (in_kdxhist inner join IN_INVENTORY on IN_KDXHIST.INVTIDSKU=IN_INVENTORY.INVTIDSKU) " +
                     " inner join in_category on IN_INVENTORY.CLASSID=IN_CATEGORY.CLASSID " +
                     " WHERE " + @CRITERIOSELECCION + " yearhist=" +  RTRIM(LTRIM(STR(year(@FechaDesde)))) + 
                     " GROUP BY in_kdxhist.siteid,IN_INVENTORY.CLASSID,in_kdxhist.INVTIDSKU "  +
                     " UNION ALL " + 
                     " SELECT INTRAMOV.SITEID,IN_INVENTORY.CLASSID,INTRAMOV.INVTIDSKU,0 as [Inicial], " + 
                     " SUM(CASE SWTINOUT WHEN 1 THEN QTY WHEN 0 THEN ROUND((QTY * - 1)," + @ND_STOCK +") END) AS [QTYRESULT], " + 
                     " 0 as [COMPRASFUELS],0 AS [COMPRASFUELSVAL],0 AS [COMPRASSTORE],0 AS [COMPRASSTOREVAL]," +
                     " 0 AS [AJUSTEING],0 AS [BONIF],0 AS [BONIFVAL],0 as [TRANSFER],0 AS [TRANSFERVAL]," + 
                     " 0 as [OTROS],0 AS [VENTAS],0 AS [AJUSTESAL],0 AS [NTACREDITO],0 AS [NTACREDITOVAL]," + 
                     " 0 AS [TRANSFERSAL],0 AS [TRANSFERSALVAL],0 AS [OTROSSAL],0 as [AJUSTEINGVAL]," +
                     " 0 as [OTROSINGVAL],0 as [VENTASVAL], 0 as [AJUSTESALVAL],0 as [OTROSSALVAL]" +           
                     " from (INTRAMOV inner join IN_INVENTORY on INTRAMOV.INVTIDSKU=IN_INVENTORY.INVTIDSKU)" +
                     " inner join in_category on IN_INVENTORY.CLASSID=IN_CATEGORY.CLASSID " +
                     " where " + @CRITERIOSELECCION + " intrdateproce >='" + RTRIM(ltrim(Cast(@FechaInicial as char(100)))) +
                     "' AND intrdateproce < '" + 
                     RTRIM(ltrim(Cast(@FechaDesde as char(100)))) + "' GROUP BY  INTRAMOV.SITEID,IN_INVENTORY.CLASSID," +
                     "INTRAMOV.INVTIDSKU " 


   SET @FLAGMONEDA=0

   if @MONEDASOLICITADA=(select CURYORIG from SETUP)
     begin
       SET @MONEDAPROCESO=@INTRAMOVMONBASE
       SET @MONEDAKDXHIST=RTRIM(LTRIM(@KDXHISTMONBASE))
       SET @MONEDATOTAL = RTRIM(LTRIM(@TOTALMONBASE))
       SET @FLAGMONEDA=0	 
     end
   else   
     begin
       SET @MONEDAPROCESO=@INTRAMOVMONDEST
       SET @MONEDAKDXHIST=RTRIM(LTRIM(@KDXHISTMONDEST))
       SET @MONEDATOTAL = RTRIM(LTRIM(@TOTALMONEXT))
       SET @FLAGMONEDA=1	 
     end
     
  /*************************************************/
   
  SET @INGNOVAL = " UNION ALL SELECT siteid,IN_INVENTORY.classid,INTRAMOV.INVTIDSKU,0 AS [Inicial],0 AS [QTYRESULT]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOCOMPRAFUELS + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0  END) AS [COMPRASFUELS]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOCOMPRAFUELS + " THEN ROUND(QTY," + @ND_STOCK + ") * " + 
                  " ROUND(" + @MONEDAPROCESO + "," + @ND_COSTO + ") ELSE 0 END) AS [COMPRASFUELSVAL]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOCOMPRASTORE + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0  END) AS [COMPRASSTORE]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOCOMPRASTORE + " THEN ROUND(QTY," + @ND_STOCK + ") * " + 
                  " ROUND(" + @MONEDAPROCESO + "," + @ND_COSTO + ") ELSE 0 END) AS [COMPRASSTOREVAL]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOAJUSTEING + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END) AS [AJUSTEING]," +  
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOBONIFICACION + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END) AS [BONIF]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOBONIFICACION + " THEN ROUND(QTY," + @ND_STOCK + ") * " +
                  " ROUND(" + @MONEDAPROCESO + "," + @ND_COSTO + ") ELSE 0 END) AS [BONIFVAL]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOTRANSFERING + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END) AS [TRANSFER]," +
                  " SUM(CASE TYPEDOCID WHEN " + @TIPOTRANSFERING + " THEN ROUND(QTY," + @ND_STOCK + ") * " + 
                  " ROUND(" + @MONEDAPROCESO + "," + @ND_COSTO + ") ELSE 0 END) AS [TRASNFERVAL]," +	                   
                  " [OTROS]= SUM(CASE WHEN (TYPEDOCID <> " + @TIPOCOMPRAFUELS + " AND TYPEDOCID <> " + @TIPOCOMPRASTORE + 
                  " AND TYPEDOCID <> " + @TIPOAJUSTEING + " AND " +
                  " TYPEDOCID <> " + @TIPOBONIFICACION + " AND TYPEDOCID <> " + @TIPOTRANSFERING + " AND SWTINOUT=1)" +
                  " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END),0 AS [VENTAS],0 AS [AJUSTESAL],0 AS [NTACREDITO],0 AS [NTACREDITOVAL]," +
                  " 0 AS [TRANSFERSAL],0 AS [TRANSFERSALVAL],0 AS [OTROSSAL], 0 as [AJUSTEINGVAL],0 as [OTROSINGVAL]," +
                  " 0 as [VENTASVAL], 0 as [AJUSTESALVAL],0 as [OTROSSALVAL] " +                  
                  " from (INTRAMOV inner join IN_INVENTORY on INTRAMOV.INVTIDSKU=IN_INVENTORY.INVTIDSKU) " +
                  " inner join in_category on IN_INVENTORY.CLASSID=IN_CATEGORY.CLASSID " +                    
                  " where " + @CRITERIOSELECCION + " INTRDATEPROCE BETWEEN '" + 
                    RTRIM(ltrim(Cast(@FechaDesde as char(100)))) + "' AND '" + RTRIM(ltrim(Cast(@FechaHasta as char(100)))) +
                  "' GROUP BY SITEID,IN_INVENTORY.CLASSID,INTRAMOV.INVTIDSKU " 
   
   SET @SALNOVAL = " UNION ALL SELECT siteid,IN_INVENTORY.classid,INTRAMOV.INVTIDSKU,0 AS [Inicial],0 AS [QTYRESULT]," +
                   " 0 AS [COMPRASFUELS],0 AS [COMPRASFUELSVAL],0 AS [COMPRASSTORE],0 AS [COMPRASSTOREVAL],0 AS [AJUSTEING]," + 
                   " 0 AS [BONIF],0 AS [BONIFVAL],0 as [TRANSFER],0 AS [TRANSFERVAL],0 as [OTROS]," +
                   " SUM(CASE TYPEDOCID WHEN " + @TIPOVENTAS + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END) AS [VENTAS]," +
                   " SUM(CASE TYPEDOCID WHEN " + @TIPOAJUSTESAL + " THEN ROUND(QTY," + @ND_STOCK +") ELSE 0 END) AS [AJUSTESAL]," +  
                   " SUM(CASE TYPEDOCID WHEN " + @TIPONTACREDITO + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END) AS [NTACREDITO]," +
                   " SUM(CASE TYPEDOCID WHEN " + @TIPONTACREDITO + " THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAPROCESO  + "," +
                   @ND_COSTO + ") ELSE 0 END) AS [NTACREDITOVAL]," +
                   " SUM(CASE TYPEDOCID WHEN " + @TIPOTRANSFERSAL + " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END) AS [TRANSFERSAL]," +
                   " SUM(CASE TYPEDOCID WHEN " + @TIPOTRANSFERSAL + " THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAPROCESO  + "," +
                   @ND_COSTO + ") ELSE 0 END) AS [TRANSFERSALVAL]," +
                   " [OTROSSAL]= SUM(CASE WHEN (TYPEDOCID <> " + @TIPOVENTAS + " AND TYPEDOCID <> " + @TIPOAJUSTESAL + " AND " +
                   " TYPEDOCID <> " + @TIPONTACREDITO + " AND TYPEDOCID <> " + @TIPOTRANSFERSAL + " AND SWTINOUT=0)" +
                   " THEN ROUND(QTY," + @ND_STOCK + ") ELSE 0 END),0 as [AJUSTEINGVAL],0 as [OTROSINGVAL],0 as [VENTASVAL]," +
                   " 0 as [AJUSTESALVAL],0 as [OTROSSALVAL] " +               
                   " from (INTRAMOV inner join IN_INVENTORY on INTRAMOV.INVTIDSKU=IN_INVENTORY.INVTIDSKU) " +
                   " inner join in_category on IN_INVENTORY.CLASSID=IN_CATEGORY.CLASSID " +                  
                   " where " + @CRITERIOSELECCION + " INTRDATEPROCE BETWEEN '" +
                     RTRIM(ltrim(Cast(@FechaDesde as char(100)))) + "' AND '" + RTRIM(ltrim(Cast(@FechaHasta as char(100)))) + 
                   "' GROUP BY SITEID,IN_INVENTORY.CLASSID,INTRAMOV.INVTIDSKU "

  SET @INGSALVALORIZADA=" UNION ALL select intramov.siteid,in_inventory.classid,in_inventory.INVTIDSKU,0 as [Inicial],0 as [QTYRESULT]," +
                        "0 as [COMPRASFUELS],0 AS [COMPRASFUELSVAL],0 AS [COMPRASSTORE],0 AS [COMPRASSTOREVAL],0 AS [AJUSTEING],0 AS [BONIF],0 AS [BONIFVAL],0 AS [TRANSFER]," +
                        "0 AS [TRANSFERVAL],0 AS [OTROS],0 AS [VENTAS],0 AS [AJUSTESAL],0 AS [NTACREDITO],0 AS [NTACREDITOVAL],0 AS [TRANSFERSAL],0 AS [TRANSFERSALVAL]," +
                        "0 AS [OTROSSAL],[AJUSTEINGVAL]=SUM(CASE WHEN TYPEDOCID=" + @TIPOAJUSTEING  + " THEN " + 			           		               
                        " CASE WHEN MONTH(INTRDATEPROCE)=1 THEN  ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "01," + @ND_COSTO +") WHEN MONTH(INTRDATEPROCE)=2 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "02," + @ND_COSTO + ") " +                                        
                        " WHEN MONTH(INTRDATEPROCE)=3 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "03," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=4 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "04," + @ND_COSTO + ") " +		
                        " WHEN MONTH(INTRDATEPROCE)=5 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "05," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=6 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "06," + @ND_COSTO + ") " +         
    			" WHEN MONTH(INTRDATEPROCE)=7 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "07," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=8 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "08," + @ND_COSTO + ") " +                					  	 		  		          
         		" WHEN MONTH(INTRDATEPROCE)=9 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "09," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=10 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "10," + @ND_COSTO + ") " +            			
 			" WHEN MONTH(INTRDATEPROCE)=11 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "11," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=12 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "12," + @ND_COSTO + ") " +            			             				    			 					  			
           		" END ELSE 0 END)," +
      "[OTROSINGVAL]=SUM(CASE WHEN (TYPEDOCID <> " + @TIPOCOMPRAFUELS + " AND TYPEDOCID <> " + @TIPOCOMPRASTORE + " AND TYPEDOCID <> " + @TIPOAJUSTEING + " AND " +
                        " TYPEDOCID <> " + @TIPOBONIFICACION + " AND TYPEDOCID <> " + @TIPOTRANSFERING + " AND SWTINOUT=1) THEN " +
                        " CASE WHEN MONTH(INTRDATEPROCE)=1 THEN  ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "01," + @ND_COSTO +") WHEN MONTH(INTRDATEPROCE)=2 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "02," + @ND_COSTO + ") " +                                       
                        " WHEN MONTH(INTRDATEPROCE)=3 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "03," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=4 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "04," + @ND_COSTO + ") " +		
                        " WHEN MONTH(INTRDATEPROCE)=5 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "05," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=6 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "06," + @ND_COSTO + ") " +         
    			" WHEN MONTH(INTRDATEPROCE)=7 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "07," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=8 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "08," + @ND_COSTO + ") " +                					  	 		  		          
         		" WHEN MONTH(INTRDATEPROCE)=9 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "09," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=10 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "10," + @ND_COSTO + ") " +            			
 			" WHEN MONTH(INTRDATEPROCE)=11 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "11," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=12 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "12," + @ND_COSTO + ") " +            			             				    			 					  			
           		" END ELSE 0 END)," +
       "[VENTASVAL]=SUM(CASE WHEN TYPEDOCID=" + @TIPOVENTAS + " THEN " + 
                        " CASE WHEN MONTH(INTRDATEPROCE)=1 THEN  ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "01," + @ND_COSTO +") WHEN MONTH(INTRDATEPROCE)=2 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "02," + @ND_COSTO + ") " +                                       
                        " WHEN MONTH(INTRDATEPROCE)=3 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "03," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=4 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "04," + @ND_COSTO + ") " +		
                        " WHEN MONTH(INTRDATEPROCE)=5 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "05," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=6 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "06," + @ND_COSTO + ") " +         
    			" WHEN MONTH(INTRDATEPROCE)=7 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "07," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=8 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "08," + @ND_COSTO + ") " +                					  	 		  		          
         		" WHEN MONTH(INTRDATEPROCE)=9 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "09," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=10 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "10," + @ND_COSTO + ") " +            			
 			" WHEN MONTH(INTRDATEPROCE)=11 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "11," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=12 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "12," + @ND_COSTO + ") " +            			             				    			 					  			
           		" END ELSE 0 END)," +
       "[AJUSTESALVAL]=SUM(CASE WHEN TYPEDOCID=" + @TIPOAJUSTESAL + " THEN " +  
                      " CASE WHEN MONTH(INTRDATEPROCE)=1 THEN  ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "01," + @ND_COSTO +") WHEN MONTH(INTRDATEPROCE)=2 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "02," + @ND_COSTO + ") " +                                         
                        " WHEN MONTH(INTRDATEPROCE)=3 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "03," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=4 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "04," + @ND_COSTO + ") " +		
                        " WHEN MONTH(INTRDATEPROCE)=5 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "05," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=6 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "06," + @ND_COSTO + ") " +         
    			" WHEN MONTH(INTRDATEPROCE)=7 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "07," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=8 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "08," + @ND_COSTO + ") " +                					  	 		  		          
         		" WHEN MONTH(INTRDATEPROCE)=9 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "09," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=10 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "10," + @ND_COSTO + ") " +            			
 			" WHEN MONTH(INTRDATEPROCE)=11 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "11," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=12 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "12," + @ND_COSTO + ") " +            			             				    			 					  			
           		" END ELSE 0 END)," +
       "[OTROSSALVAL]=SUM(CASE WHEN (TYPEDOCID <>" + @TIPOVENTAS + " AND TYPEDOCID <>" + @TIPOAJUSTESAL + " AND " +
                        " TYPEDOCID <>" + @TIPONTACREDITO + " AND TYPEDOCID <>" + @TIPOTRANSFERSAL + " AND SWTINOUT=0) THEN " +
                        " CASE WHEN MONTH(INTRDATEPROCE)=1 THEN  ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "01," + @ND_COSTO +") WHEN MONTH(INTRDATEPROCE)=2 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "02," + @ND_COSTO + ") " +                                         
                        " WHEN MONTH(INTRDATEPROCE)=3 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "03," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=4 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "04," + @ND_COSTO + ") " +		
                        " WHEN MONTH(INTRDATEPROCE)=5 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "05," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=6 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "06," + @ND_COSTO + ") " +         
    			" WHEN MONTH(INTRDATEPROCE)=7 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "07," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=8 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "08," + @ND_COSTO + ") " +                					  	 		  		          
         		" WHEN MONTH(INTRDATEPROCE)=9 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "09," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=10 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "10," + @ND_COSTO + ") " +            			
 			" WHEN MONTH(INTRDATEPROCE)=11 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "11," + @ND_COSTO + ") WHEN MONTH(INTRDATEPROCE)=12 THEN ROUND(QTY," + @ND_STOCK + ") * ROUND(" + @MONEDAKDXHIST + "12," + @ND_COSTO + ") " +            			             				    			 					  			
           		" END ELSE 0 END) " + 
        " from ((intramov inner join in_kdxhist " +
        " on intramov.INVTIDSKU=in_kdxhist.INVTIDSKU and intramov.siteid=in_kdxhist.siteid) inner join in_inventory " +
        " on intramov.INVTIDSKU=in_inventory.INVTIDSKU) inner join in_category " + 
        " on in_inventory.classid=in_category.classid  WHERE YEAR(INTRDATEPROCE)=YEARHIST and " + @CRITERIOSELECCIONVAL +
        " INTRDATEPROCE BETWEEN '" + RTRIM(ltrim(Cast(@FechaDesde as char(100)))) + "' AND '" + RTRIM(ltrim(Cast(@FechaHasta as char(100)))) +                              
        "' GROUP BY intramov.siteid,in_inventory.classid,in_inventory.INVTIDSKU "
   
   /*Crear Tabla Temporal para Almacenar los resultados obtenidos de las cadenas @SALDOINICIAL + @INGNOVAL + @SALNOVAL + @INGSALVALORIZADA */
   /*y Crear un Resumen */
    
   DECLARE @MESINICIO AS CHAR(2) 

   SELECT @MESINICIO= CASE MONTH(DATEADD(dd,-1,@FechaDesde)) WHEN 1 THEN '01' 
                                                             WHEN 2 THEN '02'    
                                                             WHEN 3 THEN '03'
                                                             WHEN 4 THEN '04'
                                                             WHEN 5 THEN '05'    
                                                             WHEN 6 THEN '06'
                                                             WHEN 7 THEN '07'
                                                             WHEN 8 THEN '08'    
                                                             WHEN 9 THEN '09'
                                                             WHEN 10 THEN '10'
                                                             WHEN 11 THEN '11'
                                                             WHEN 12 THEN '00' END          



   Create Table #TMP_KARDEXGENERAL (SITEID CHAR(5),CLASSID CHAR(5),INVTIDSKU CHAR(20),INICIAL NUMERIC(10,3),QTYRESULT  NUMERIC(10,3),
                 COMPRASFUELS NUMERIC(10,3),COMPRASFUELSVAL NUMERIC(10,4),COMPRASSTORE NUMERIC(10,3),COMPRASSTOREVAL NUMERIC(10,4),
                 AJUSTEING NUMERIC(10,3),BONIF NUMERIC(10,3),BONIFVAL NUMERIC(10,4),TRANSFER NUMERIC(10,3),TRANSFERVAL NUMERIC(10,4),
                 OTROS NUMERIC(10,3),VENTAS NUMERIC(10,3),AJUSTESAL NUMERIC(10,3),NTACREDITO NUMERIC(10,3),NTACREDITOVAL NUMERIC(10,4),
                 TRANSFERSAL  NUMERIC(10,3),TRANSFERSALVAL NUMERIC(10,4),OTROSSAL NUMERIC(10,3),AJUSTEINGVAL NUMERIC(10,4),
                 OTROSINGVAL NUMERIC(10,4),VENTASVAL NUMERIC(10,4) ,AJUSTESALVAL NUMERIC(10,4) ,OTROSSALVAL NUMERIC(10,4)) 
   
   INSERT INTO #TMP_KARDEXGENERAL exec(@SALDOINICIAL + @INGNOVAL + @SALNOVAL + @INGSALVALORIZADA)

   IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   BEGIN
	ROLLBACK
	RAISERROR 20000 'Error Insertando '
	RETURN(1)
   END 	
  
   SET @KARDEXGENERAL=" SELECT " + CAST(@CORRNBR AS CHAR(10)) + ",#TMP_KARDEXGENERAL.SITEID,SITE.NAME,#TMP_KARDEXGENERAL.CLASSID,IN_CATEGORY.DESCR,#TMP_KARDEXGENERAL.INVTIDSKU," + 
                 " IN_INVENTORY.DESCR as [DESCRARTICULO],SUM(INICIAL+QTYRESULT)AS [INICIAL]," +                                
                 " ROUND(" + RTRIM(LTRIM(@MONEDATOTAL)) + RTRIM(LTRIM(@MESINICIO)) + "," + @ND_COSTO + ") as [INICIALVAL],"  +
                 " SUM(COMPRASFUELS+COMPRASSTORE) AS [COMPRAS],SUM(AJUSTEING) AS [AJUSTEINGRESO]," +
                 " SUM(BONIF) AS [BONIFICACION],SUM(TRANSFER) AS [TRANSFERING],SUM(OTROS) AS [OTROSING],SUM(VENTAS) AS [VENTAS]," +
                 " SUM(AJUSTESAL) AS [AJUSTESAL],SUM(NTACREDITO) AS [NOTACRED],SUM(TRANSFERSAL) AS [TRANSFERSAL],SUM(OTROSSAL) AS [OTRASSAL]," + 
                 " SUM(COMPRASFUELSVAL+COMPRASSTOREVAL) AS [COMPRASVAL],SUM(AJUSTEINGVAL) AS [AJUSTEINGVALO],SUM(BONIFVAL) AS [BONIFIVAL]," +
                 " SUM(TRANSFERVAL) AS [TRANSINGVAL],SUM(OTROSINGVAL) AS [OTROSINGVAL],SUM(VENTASVAL) AS [VENTASVALOR]," +
                 " SUM(AJUSTESALVAL) AS [AJUSTESALIVAL],SUM(NTACREDITOVAL) AS [NOTACREDVAL],SUM(TRANSFERSALVAL) AS [TRANSFERSALVALOR]," +
                 " SUM(OTROSSALVAL) AS [OTROSSALVALOR] " + 
                 " FROM (((#TMP_KARDEXGENERAL INNER JOIN IN_KDXHIST ON (#TMP_KARDEXGENERAL.SITEID=IN_KDXHIST.SITEID AND " + 
                 " #TMP_KARDEXGENERAL.INVTIDSKU=IN_KDXHIST.INVTIDSKU) AND YEARHIST=" + RTRIM(LTRIM(STR(year(@FechaDesde)))) + 
		 " ) INNER JOIN SITE ON " +
                 " #TMP_KARDEXGENERAL.SITEID=SITE.SITEID) INNER JOIN IN_INVENTORY ON #TMP_KARDEXGENERAL.INVTIDSKU=" + 
                 " IN_INVENTORY.INVTIDSKU) INNER JOIN IN_CATEGORY ON IN_INVENTORY.CLASSID=IN_CATEGORY.CLASSID " +                
                 " GROUP BY #TMP_KARDEXGENERAL.SITEID,SITE.NAME,#TMP_KARDEXGENERAL.CLASSID,IN_CATEGORY.DESCR, " +
                 " #TMP_KARDEXGENERAL.INVTIDSKU,IN_INVENTORY.DESCR,IN_KDXHIST." + RTRIM(LTRIM(@MONEDATOTAL)) + RTRIM(LTRIM(@MESINICIO)) 

  
   --INICIAMOS LA TRANSACCION 	
   BEGIN TRAN
 	 
   INSERT INTO TMP_CTO_PROM EXEC (@KARDEXGENERAL)
   
   IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   BEGIN
	ROLLBACK
	RAISERROR 20000 'Error Insertando en TMP_CTO_PROM'
	RETURN(1)
   END 	
  
   DROP TABLE #TMP_KARDEXGENERAL

/*EMPIEZA EL TRATAMIENTO DEL COSTO PROMEDIO UTILIZANDO LOS RESULTADOS DEL KARDEX INSERTADOS EN LA TABLA 
  TMP_CTO_PROM */

	DECLARE @SITEID	UD_IDSITE
	DECLARE @INVTIDSKU UD_IDCORPORATIVO
	DECLARE @INICIAL UD_STOCK
	DECLARE @INICIALVAL NUMERIC(10,4)
	DECLARE @COMPRAS UD_STOCK
	DECLARE @NOTACRED UD_STOCK
	DECLARE @COMPRASVAL NUMERIC(10,4)
	DECLARE @NOTACREDVAL NUMERIC(10,4)
	DECLARE @COSTOPROMEDIO NUMERIC(10,4)

	DECLARE @MENSAJEERROR VARCHAR(200)

	DECLARE	TMPCTOPROM CURSOR
	FOR 	SELECT SITEID,INVTIDSKU,INICIAL,INICIALVAL,COMPRAS,NOTACRED,COMPRASVAL,NOTACREDVAL 
		FROM TMP_CTO_PROM
		WHERE CORRNBR=@CORRNBR

	OPEN TMPCTOPROM
	FETCH NEXT FROM TMPCTOPROM
		   INTO @SITEID,@INVTIDSKU,@INICIAL,@INICIALVAL,@COMPRAS,@NOTACRED,@COMPRASVAL,@NOTACREDVAL

	WHILE @@FETCH_STATUS=0
	BEGIN

			SET @MENSAJEERROR='Error Actualizando en IN_KDXHIST: ' + @MONEDASOLICITADA + ' '+ @INVTIDSKU
				
			-- PARA EVITAR EL DESBORDAMIENTO
			IF ((@INICIAL+@COMPRAS-@NOTACRED)!=0) 
			BEGIN 
				SET @COSTOPROMEDIO=ROUND((@INICIALVAL+@COMPRASVAL-@NOTACREDVAL)/(@INICIAL+@COMPRAS-@NOTACRED),@ND_COSTOSETUP)
			END
			ELSE
			BEGIN
				SET @COSTOPROMEDIO=ROUND(0,@ND_COSTOSETUP)
			END  
			--------------------------------

			IF (@FLAGMONEDA=0) -- SI ES EN MONEDA ORIGEN
			BEGIN
				IF (@FechaMes='01')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN01=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='02')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN02=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='03')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN03=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='04')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN04=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 
	
				IF (@FechaMes='05')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN05=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='06')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN06=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='07')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN07=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='08')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN08=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='09')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN09=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='10')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN10=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
				
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='11')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN11=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='12')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGPEN12=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END
				
				-- SE ACTUALIZA EL COSTO PROMEDIO EN IN_INVENTORYDAT
				UPDATE  IN_INVENTORYDAT SET AVGCOSTPEN=@COSTOPROMEDIO WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
				IF(@@ERROR!=0)
				BEGIN
					CLOSE TMPCTOPROM
					DEALLOCATE TMPCTOPROM
					ROLLBACK
					RAISERROR 20000 'Error actualizando Costo Promedio en In_Inventorydat'
					RETURN(1)
					
				END
 
			END 
			ELSE -- SI ES EN MONEDA EXTRANJERA
			BEGIN
				IF (@FechaMes='01')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD01=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='02')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD02=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='03')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD03=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='04')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD04=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 
	
				IF (@FechaMes='05')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD05=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='06')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD06=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='07')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD07=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='08')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD08=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='09')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD09=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='10')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD10=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='11')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD11=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				IF (@FechaMes='12')
				BEGIN
					UPDATE 	IN_KDXHIST 
					SET	AVGUSD12=@COSTOPROMEDIO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJEERROR
						RETURN(1)
   					END 	
				END 

				-- SE ACTUALIZA EL COSTO PROMEDIO EN IN_INVENTORYDAT
				UPDATE  IN_INVENTORYDAT SET AVGCOSTUSD=@COSTOPROMEDIO WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
				IF(@@ERROR!=0)
				BEGIN
					CLOSE TMPCTOPROM
					DEALLOCATE TMPCTOPROM
					ROLLBACK
					RAISERROR 20000 'Error actualizando Costo Promedio en In_Inventorydat'
					RETURN(1)
					
				END

			END


	FETCH NEXT FROM TMPCTOPROM
		   INTO @SITEID,@INVTIDSKU,@INICIAL,@INICIALVAL,@COMPRAS,@NOTACRED,@COMPRASVAL,@NOTACREDVAL
	END 
 	
	TRUNCATE TABLE TMP_CTO_PROM 

	CLOSE TMPCTOPROM
	DEALLOCATE TMPCTOPROM
	COMMIT TRAN
	RETURN(0)
END


/*GO
CALCULA_CTO_PROMEDIO_PROC 75082,'PEN','01','01','2003','01','01','2003','00','31','01','2003','57   ',"''",0,1
GO
CALCULA_CTO_PROMEDIO_PROC 75174,'PEN','01','01','2003','01','01','2003','00','31','01','2003','57   ',"''",0,1
go

SELECT * FROM IN_KDXHIST WHERE YEARHIST='2003' AND INVTIDSKU='10001'

UPDATE IN_KDXHIST SET AVGUSD01=0.000

--'10001',4630.00 

SELECT SUM(CASE WHEN SWTINOUT= 0 THEN  QTY * -1 WHEN  SWTINOUT= 1  THEN QTY END ) 
              FROM INTRAMOV WHERE INVTIDSKU='10001' AND TYPEDOCID='101'  AND
                   INTRDATEPROCE BETWEEN '01-01-2003'  AND '01-31-2003'   


SELECT * FROM TMP_CTO_PROM WHERE INVTIDSKU='10001'


DELETE FROM TMP_CTO_PROM

CALCULA_CTO_PROMEDIO_PROC 81112,'PEN','01','01','2003','01','01','2003','00','31','01','2003','57   ',"''",0,1

SELECT * FROM IN_KDXHIST 
select * from tmp_cto_prom

select * from in_kdxhist


select * from in_setup

update in_setup set CLOSEDMONTH='200308'*/

