
DROP PROCEDURE CIERRE_DE_MES_PROC
GO
CREATE PROCEDURE CIERRE_DE_MES_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 
DECLARE @ANIOSIGUIENTE CHAR(4)

/*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 @ANIOSIGUIENTE=CAST((CAST(@Fechaanio AS INT)+1) AS CHAR(4))

  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 20001 'Error Insertando en TMP_CTO_PROM'
	RETURN(1)
   END 	
  
   DROP TABLE #TMP_KARDEXGENERAL

/*EMPIEZA EL TRATAMIENTO DEL CIERRE DE MES UTILIZANDO LOS RESULTADOS DEL KARDEX INSERTADOS EN LA TABLA 
  TMP_CTO_PROM QUE ES UTILZADA TAMBIEN PARA EL CALCULO DEL COSTO PROMEDIO */


-- DECLARAMOS UN CURSOR PARA EL BARRIDO DE TODOS LOS ARTICULOS
 
	DECLARE @SITEID	UD_IDSITE
	DECLARE @INVTIDSKU UD_IDCORPORATIVO

	DECLARE @INICIAL UD_STOCK
	DECLARE @INICIALVAL NUMERIC(10,4)
	DECLARE @COMPRAS UD_STOCK
	DECLARE @AJUSTEINGRESO UD_STOCK
	DECLARE @BONIFICACION UD_STOCK
	DECLARE @TRANSFERING UD_STOCK
	DECLARE @OTROSING UD_STOCK

	DECLARE @VENTAS UD_STOCK
	DECLARE @AJUSTESAL UD_STOCK
	DECLARE @NOTACRED UD_STOCK
	DECLARE @TRANSFERSAL UD_STOCK
	DECLARE @OTRASSAL UD_STOCK

	DECLARE @COMPRASVAL NUMERIC(10,4)
	DECLARE @AJUSTEINGVALO NUMERIC(10,4)
	DECLARE @BONIFIVAL NUMERIC(10,4)
	DECLARE @TRANSINGVAL NUMERIC(10,4)
	DECLARE @OTROSINGVAL NUMERIC(10,4)

	DECLARE @VENTASVALOR NUMERIC(10,4)
	DECLARE @AJUSTESALIVAL NUMERIC(10,4)
	DECLARE @NOTACREDVAL NUMERIC(10,4)
	DECLARE @TRANSFERSALVALOR NUMERIC(10,4)
	DECLARE @OTROSSALVALOR NUMERIC(10,4)

	DECLARE @COSTOPROM_KDX NUMERIC(10,4)
	DECLARE @COSTOPROMEDIO NUMERIC(10,4)
	DECLARE @SALDOUNIDADES UD_STOCK
	DECLARE @SALDOVALORIZADO NUMERIC(10,4)
	DECLARE @MENSAJEERROR VARCHAR(200)
	DECLARE @MENSAJECTOPROM VARCHAR(200)


	DECLARE	TMPCTOPROM CURSOR
	FOR 	SELECT SITEID,INVTIDSKU,INICIAL,INICIALVAL,COMPRAS,AJUSTEINGRESO,BONIFICACION,TRANSFERING,
		       OTROSING,VENTAS,AJUSTESAL,NOTACRED,TRANSFERSAL,OTRASSAL,COMPRASVAL,AJUSTEINGVALO,BONIFIVAL,
		       TRANSINGVAL,OTROSINGVAL,VENTASVALOR,AJUSTESALIVAL,NOTACREDVAL,TRANSFERSALVALOR,OTROSSALVALOR
		FROM TMP_CTO_PROM
		WHERE CORRNBR=@CORRNBR

	OPEN TMPCTOPROM
	FETCH NEXT FROM TMPCTOPROM
		   INTO @SITEID,@INVTIDSKU,@INICIAL,@INICIALVAL,@COMPRAS,@AJUSTEINGRESO,@BONIFICACION,@TRANSFERING,
		        @OTROSING,@VENTAS,@AJUSTESAL,@NOTACRED,@TRANSFERSAL,@OTRASSAL,@COMPRASVAL,@AJUSTEINGVALO,@BONIFIVAL,
		        @TRANSINGVAL,@OTROSINGVAL,@VENTASVALOR,@AJUSTESALIVAL,@NOTACREDVAL,@TRANSFERSALVALOR,@OTROSSALVALOR

	WHILE @@FETCH_STATUS=0
	BEGIN
			
			-- 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  
			--------------------------------
						
			SET @SALDOUNIDADES=ROUND((@INICIAL+@COMPRAS+@AJUSTEINGRESO+@BONIFICACION+@TRANSFERING+@OTROSING-@VENTAS-@AJUSTESAL-@NOTACRED-@TRANSFERSAL-@OTRASSAL),@ND_STOCKSETUP)
			SET @SALDOVALORIZADO=ROUND((@INICIALVAL+@COMPRASVAL+@AJUSTEINGVALO+@BONIFIVAL+@TRANSINGVAL+@OTROSINGVAL-@VENTASVALOR-@AJUSTESALIVAL-@NOTACREDVAL-@TRANSFERSALVALOR-@OTROSSALVALOR),@ND_COSTOSETUP)			
			SET @MENSAJEERROR='Error Actualizando en IN_KDXHIST: ' + @MONEDASOLICITADA + ' '+ @INVTIDSKU
			SET @MENSAJECTOPROM='Variación de Costo Promedio: ' + @MONEDASOLICITADA + ' en '+ @INVTIDSKU

			IF (@FLAGMONEDA=0) -- SI ES EN MONEDA ORIGEN
			BEGIN
				
				IF (@FechaMes='01')
				BEGIN
					-- SE VALIDA SI EXISTE UNA VARIACION EN EL COSTO PROMEDIO DE UN ARTICULO
					-- ROLLBACK SI SON DIFERENTES, POSIBLEMENTE SE REALIZO ALGUNA COMPRA O NOTA DE CREDITO 
					SET @COSTOPROM_KDX=(SELECT AVGPEN01 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND01=@SALDOUNIDADES,
						TOTAVGPEN01=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	
 
				END 

				IF (@FechaMes='02')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN02 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND02=@SALDOUNIDADES,
						TOTAVGPEN02=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='03')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN03 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND03=@SALDOUNIDADES,
						TOTAVGPEN03=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='04')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN04 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND04=@SALDOUNIDADES,
						TOTAVGPEN04=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 
	
				IF (@FechaMes='05')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN05 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND05=@SALDOUNIDADES,
						TOTAVGPEN05=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='06')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN06 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND06=@SALDOUNIDADES,
						TOTAVGPEN06=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='07')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN07 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND07=@SALDOUNIDADES,
						TOTAVGPEN07=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='08')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN08 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND08=@SALDOUNIDADES,
						TOTAVGPEN08=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='09')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN09 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND09=@SALDOUNIDADES,
						TOTAVGPEN09=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='10')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN10 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND10=@SALDOUNIDADES,
						TOTAVGPEN10=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='11')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN11 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND11=@SALDOUNIDADES,
						TOTAVGPEN11=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='12')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGPEN12 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND12=@SALDOUNIDADES,
						TOTAVGPEN12=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	


					--PARA CREAR O ACTUALIZAR LOS REGISTROS DEL AÑO ENTRANTE
					IF EXISTS(SELECT INVTIDSKU FROM IN_KDXHIST WHERE YEARHIST=@ANIOSIGUIENTE AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					BEGIN
						SET @MENSAJEERROR=@MENSAJEERROR + ' ' + @ANIOSIGUIENTE
						
						UPDATE 	IN_KDXHIST 
						SET	QTYEND00=@SALDOUNIDADES,
							AVGPEN00=@COSTOPROMEDIO,
							TOTAVGPEN00=@SALDOVALORIZADO
						WHERE	YEARHIST=@ANIOSIGUIENTE AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

   					
						IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   						BEGIN
							CLOSE TMPCTOPROM
							DEALLOCATE TMPCTOPROM
							ROLLBACK
							RAISERROR 20001 @MENSAJEERROR
							RETURN(1)
   						END 	
						
					END
					ELSE
					BEGIN
						SET @MENSAJEERROR='Error Insertando en IN_KDXHIST: PEN ' + @INVTIDSKU
						
						INSERT 	INTO IN_KDXHIST(YEARHIST,SITEID,INVTIDSKU,QTYEND00,AVGPEN00,TOTAVGPEN00) 
							VALUES (@ANIOSIGUIENTE,@SITEID,@INVTIDSKU,@SALDOUNIDADES,@COSTOPROMEDIO,@SALDOVALORIZADO)

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

					END

				END 
			END 
			ELSE -- SI ES EN MONEDA EXTRANJERA
			BEGIN
				IF (@FechaMes='01')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD01 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND01=@SALDOUNIDADES,
						TOTAVGUSD01=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='02')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD02 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND02=@SALDOUNIDADES,
						TOTAVGUSD02=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='03')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD03 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND03=@SALDOUNIDADES,
						TOTAVGUSD03=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='04')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD04 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND04=@SALDOUNIDADES,
						TOTAVGUSD04=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 
	
				IF (@FechaMes='05')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD05 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND05=@SALDOUNIDADES,
						TOTAVGUSD05=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='06')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD06 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND06=@SALDOUNIDADES,
						TOTAVGUSD06=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='07')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD07 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND07=@SALDOUNIDADES,
						TOTAVGUSD07=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='08')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD08 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND08=@SALDOUNIDADES,
						TOTAVGUSD08=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='09')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD09 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND09=@SALDOUNIDADES,
						TOTAVGUSD09=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='10')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD10 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND10=@SALDOUNIDADES,
						TOTAVGUSD10=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK						
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='11')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD11 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND11=@SALDOUNIDADES,
						TOTAVGUSD11=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

				END 

				IF (@FechaMes='12')
				BEGIN
					SET @COSTOPROM_KDX=(SELECT AVGUSD12 FROM IN_KDXHIST WHERE YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					
					IF(@COSTOPROMEDIO!=@COSTOPROM_KDX)
					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20000 @MENSAJECTOPROM
						RETURN(1)
					END

					UPDATE 	IN_KDXHIST 
					SET	QTYEND12=@SALDOUNIDADES,
						TOTAVGUSD12=@SALDOVALORIZADO
					WHERE	YEARHIST=@Fechaanio AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
					
   					
					IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   					BEGIN
						CLOSE TMPCTOPROM
						DEALLOCATE TMPCTOPROM
						ROLLBACK
						RAISERROR 20001 @MENSAJEERROR
						RETURN(1)
   					END 	

					--PARA CREAR O ACTUALIZAR LOS REGISTROS DEL AÑO ENTRANTE
					IF EXISTS(SELECT INVTIDSKU FROM IN_KDXHIST WHERE YEARHIST=@ANIOSIGUIENTE AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU)
					BEGIN
						SET @MENSAJEERROR=@MENSAJEERROR + ' ' + @ANIOSIGUIENTE
						
						UPDATE 	IN_KDXHIST 
						SET	QTYEND00=@SALDOUNIDADES,
							AVGUSD00=@COSTOPROMEDIO,
							TOTAVGUSD00=@SALDOVALORIZADO
						WHERE	YEARHIST=@ANIOSIGUIENTE AND SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 

   					
						IF (@@ERROR!=0 OR @@ROWCOUNT=0)
   						BEGIN
							CLOSE TMPCTOPROM
							DEALLOCATE TMPCTOPROM
							ROLLBACK
							RAISERROR 20001 @MENSAJEERROR
							RETURN(1)
   						END 	
						
					END
					ELSE
					BEGIN
						SET @MENSAJEERROR='Error Insertando en IN_KDXHIST: USD ' + @INVTIDSKU
						
						INSERT 	INTO IN_KDXHIST(YEARHIST,SITEID,INVTIDSKU,QTYEND00,AVGUSD00,TOTAVGUSD00) 
							VALUES (@ANIOSIGUIENTE,@SITEID,@INVTIDSKU,@SALDOUNIDADES,@COSTOPROMEDIO,@SALDOVALORIZADO)

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

					END
				END 
			END


	FETCH NEXT FROM TMPCTOPROM
		   INTO @SITEID,@INVTIDSKU,@INICIAL,@INICIALVAL,@COMPRAS,@AJUSTEINGRESO,@BONIFICACION,@TRANSFERING,
		        @OTROSING,@VENTAS,@AJUSTESAL,@NOTACRED,@TRANSFERSAL,@OTRASSAL,@COMPRASVAL,@AJUSTEINGVALO,@BONIFIVAL,
		        @TRANSINGVAL,@OTROSINGVAL,@VENTASVALOR,@AJUSTESALIVAL,@NOTACREDVAL,@TRANSFERSALVALOR,@OTROSSALVALOR

	END 
 	
	TRUNCATE TABLE TMP_CTO_PROM 

	CLOSE TMPCTOPROM
	DEALLOCATE TMPCTOPROM

	-- ACTUALIZO EL CAMPO QUE INDICA EL ULTIMO MES DE CIERRR
	UPDATE IN_SETUP SET CLOSEDMONTH=@Fechaanio+@FechaMes

	IF (@@ERROR!=0 OR @@ROWCOUNT=0)
	BEGIN
		ROLLBACK
		RAISERROR 20001 'Error Actualizando en IN_SETUP'
		RETURN(1)
	END 	

	COMMIT TRAN
	RETURN(0)
END
