
/****** Object:  StoredProcedure [dbo].[cuadrediario]    Script Date: 05/02/2016 11:45:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO














ALTER PROCEDURE CuadreDiario
                @list_alma varchar(8000), 
				@list_secc varchar(8000), 
				@fdesde datetime,  
				@fhasta datetime
AS
BEGIN
	-- devuelve un cursor para el reporte cuadre diario de existencias
	-- que basicamente se saca casi haciendo los comprobantes
	-- de las operaciones a incluir segun rango de fechas, de
	-- almacenes y secciones, pero la diferencia fundamental es
	-- que solo se toman las patas de los tipos de cuenta de 
	-- existencia (tipos 3,198 y 199, excluyendo, del 199, el tipo 4 de gastos)

	-- tambien se excluye lo que no se contabiliza en cuentas de existencia:
	-- compra de artis q nce
	-- compras o multi recibidos de insumos por secciones 
	-- o de cualquier familia por secciones de gasto
	-- destinos de los traslados cuando son hacia secciones de gasto o
	-- cuando son familias de insumo hacia cualquier seccion

--select t1=getdate()


	-- Si no hay enlace contable
	if(select contabil from stoktabl)=0 --Esto significa que no hay enlace contable
		return

	declare @id_empr tinyint,@id_dato  int, 
		@contabil tinyint, @idtipo3 char(12), 
		@list_alma1 varchar(8000),
		@list_secc1 varchar(8000)

	declare @operant int, @minoper int, @revertido int
	-- Id_Dato actual de la base de datos
	select @id_dato=dbo.GetId_Dato()

	-- Empresa contable y tipo de enlace contable 
	Select @id_empr=case when contabil=2 
											 then (Select id_empr from stokempr 
				   		     					where empresa in(select empresa from stoktabl))
					     				 else convert(tinyint,empresa) 
									end,
				 @contabil = contabil
		From stoktabl

	-- Id_tcue's del tipo de cuenta 3 (existencia)
	select @idtipo3=rtrim(ltrim(str(id_tcue,12,0))) from stoktcue where tipo=3

	-- filtros
  DECLARE @Cad varchar(8000),
	       @filtro_compra varchar(8000),
	       @filtro_traslado varchar(8000),
	       @filtro_inventario varchar(8000),
	       @filtro_multi varchar(8000),
	       @filtro_rebaja varchar(8000)

   Select @filtro_compra = '', @filtro_traslado = '',
			@filtro_inventario = '',@filtro_multi = '', 
			@filtro_rebaja = ''

	 if @list_alma = ''
		select @list_alma=null
	 if @list_secc = ''
		select @list_secc=null

	-- Hacer 2 temporales con las listas de almacen y seccion
	select @list_alma1 = @list_alma, 
		@list_secc1 = @list_secc

	create table #listal (ids int)
	create table #listse (ids int)
	declare @item varchar(20)
	if @list_alma1 is not null
		begin
			while len(@list_alma1)>0
				begin
					if charindex(',',@list_alma1)<>0
						select @item=substring(@list_alma1,1,charindex(',',@list_alma1)-1)
					else
						select @item=@list_alma1
					insert #listal (ids) values (convert(int,@item))
					if charindex(',',@list_alma1)<>0
						select @list_alma1=right(@list_alma1,len(@list_alma1)-len(@item)-1)
					else
						select @list_alma1=''
				end
		end

	if @list_secc1 is not null
		begin
			while len(@list_secc1)>0
				begin
					if charindex(',',@list_secc1)<>0
						select @item=substring(@list_secc1,1,charindex(',',@list_secc1)-1)
					else
						select @item=@list_secc1
					insert #listse (ids) values (convert(int,@item))
					if charindex(',',@list_secc1)<>0
						select @list_secc1=right(@list_secc1,len(@list_secc1)-len(@item)-1)
					else
						select @list_secc1=''
				end
		end

   If @list_alma is not NULL and @list_secc is not NULL
      Select @filtro_compra = ' AND (
																			(ci.id_secc is not null AND ci.id_secc  IN (SELECT ids FROM #LISTSE)) OR 
																			(ci.id_alma is not null AND ci.id_alma  IN (SELECT ids FROM #LISTAL))  ) ',
				@filtro_traslado = ' AND (
																			(trc.id_seccd is not null AND trc.id_seccd  IN (SELECT ids FROM #LISTSE)) OR 
																			(trc.id_secco is not null AND trc.id_secco  IN (SELECT ids FROM #LISTSE)) OR 
																			(trc.id_almad is not null AND trc.id_almad  IN (SELECT ids FROM #LISTAL)) OR
																			(trc.id_almao is not null AND trc.id_almao  IN (SELECT ids FROM #LISTAL)) ) ',
				@filtro_inventario = ' AND (
																			(cc.id_secc is not null AND cc.id_secc  IN (SELECT ids FROM #LISTSE)) OR 
																			(cc.id_alma is not null AND cc.id_alma  IN (SELECT ids FROM #LISTAL))  ) ',


				@filtro_multi = ' AND ((id_dato_or = '+str(@id_dato,12,0)+' 
																AND 
																 ((trc.id_almao is not null AND trc.id_almao  IN (SELECT ids FROM #LISTAL)) OR
																	(trc.id_secco is not null AND trc.id_secco  IN (SELECT ids FROM #LISTSE)))
										            ) 
															OR 
																(id_dato_de = '+str(@id_dato,12,0)+' 
																AND 
																 ((trc.id_almad is not null AND trc.id_almad  IN (SELECT ids FROM #LISTAL)) OR
																	(trc.id_seccd is not null AND trc.id_seccd  IN (SELECT ids FROM #LISTSE)))
																 ))',
				@filtro_rebaja = ' AND ((cc.id_secc is not null AND cc.id_secc  IN (SELECT ids FROM #LISTSE))) '
   Else
      Begin 

         If @list_alma is not NULL
            Select @filtro_compra = ' AND ci.id_alma is not null AND ci.id_alma  IN (SELECT ids FROM #LISTAL)',
							@filtro_traslado = ' AND ((trc.id_almad is not null AND trc.id_almad  IN (SELECT ids FROM #LISTAL)) OR
																			  (trc.id_almao is not null AND trc.id_almao  IN (SELECT ids FROM #LISTAL))) ',
							@filtro_inventario = ' AND (cc.id_alma is not null AND cc.id_alma  IN (SELECT ids FROM #LISTAL)) ',
							@filtro_multi = ' AND (
																			id_dato_de = '+str(@id_dato,12,0)+' 
																			and (trc.id_almad is not null AND trc.id_almad  IN (SELECT ids FROM #LISTAL)) 
																		or (
																			id_dato_or = '+str(@id_dato,12,0)+' 
																			and (trc.id_almao is not null AND trc.id_almao  IN (SELECT ids FROM #LISTAL))
																				))'
         Else
						If @list_secc is not NULL
						   Select @filtro_compra = ' AND ci.id_secc is not null AND ci.id_secc  IN (SELECT ids FROM #LISTse)',
									@filtro_traslado = ' AND ((trc.id_seccd is not null AND trc.id_seccd  IN (SELECT ids FROM #LISTse)) OR
																			  (trc.id_secco is not null AND trc.id_secco  IN (SELECT ids FROM #LISTse))) ',
									@filtro_inventario = ' AND (cc.id_secc is not null AND cc.id_secc  IN (SELECT ids FROM #LISTse)) ',
									@filtro_multi = ' AND (
																			id_dato_de = '+str(@id_dato,12,0)+' 
																			and (trc.id_seccd is not null AND trc.id_seccd  IN (SELECT ids FROM #LISTse)) 
																		or (
																			id_dato_or = '+str(@id_dato,12,0)+' 
																			and (trc.id_secco is not null AND trc.id_secco  IN (SELECT ids FROM #LISTse))
																				))',
									@filtro_rebaja =' AND ((cc.id_secc is not null AND cc.id_secc  IN (SELECT ids FROM #LISTSE))) '
	    End

	-- Agrupar en un temporal, los datos de las operaciones 
	-- a incluir que no sean consignación

	CREATE TABLE #cmov (
						-- id_comd int,
						-- id_tcue int,
				    fec_con	datetime,
						id_alma int,
						id_secc int,
						consecutivo int,
						id_empr int null,
						id_cta int null,
						id_cto int null, 
						aper bit null,
						alsecto int,
				    id_cuenta int null,
	     	    importe numeric(15,2),
				    debito  bit)

	-- fecha en caracteres
	declare @cdesde char(10),@chasta char(10)
	select @cdesde=convert(char(10),@fdesde,121),
		@chasta=convert(char(10),@fhasta,121)

	-- temporal para las relaciones entre alma y secc
	select ras.id_secc,ras.gasto,ras.id_alma,raf.id_fami 
		into #ras
	  from stokalse ras 
		inner join stokalfa raf on ras.id_alma = raf.id_alma
--select t2=getdate()
---------------------------------------------------------


-- Cmov = 1, compras
	      Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					fec_con = o.fec_oper,
					ci.id_alma, ci.id_secc, o.consecutivo, null,  
					case when ci.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when ci.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when ci.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(cl.importe,0)),
					debito = ad.debito
					from stokoper o 
					inner join stokcomd ad 
						on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
					inner join stoktcue tc on tc.id_tcue = ad.id_tcue
					inner join stoktmov tm on o.id_tmov = tm.id_tmov
					inner join stokcmpc cc on cc.id_operacion = o.id_operacion
					inner join stokcmpi ci on cc.id_operacion = ci.id_operacion
					inner join stokcmpl cl on cl.id_cmpi = ci.id_cmpi
					inner join stokarti ar on ar.id_arti = cl.id_arti
					inner join stokfami f on ar.id_fami = f.id_fami
					left join stokalma al on ci.id_alma is not null and ci.id_alma=al.id_alma
					left join stoksecc se on ci.id_secc is not null and ci.id_secc=se.id_secc
--
					left join #ras r
						on ci.id_secc is not null and ci.id_secc=r.id_secc and ar.id_fami=r.id_fami
					left join stokenfa efa on 
						(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
							or
							(tc.tipo = 199 and ar.ctrl_exist = 1 and efa.id_tcue = '+ @idtipo3 + ' )
						 ) and
									ci.id_alma is not null and 
									ci.id_alma = efa.id_alma and 
									ar.id_fami = efa.id_fami
					left join stokenfs efs on 
						(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
							or
							(tc.tipo = 199 
								and ar.ctrl_exist = 1 
								and (r.gasto is null or r.gasto = 0) 
								and f.tipo <> 2
								and efs.id_tcue = '+@idtipo3+ ')
						)	and
																		ci.id_secc is not null and 
																		ci.id_secc = efs.id_secc and 
																		ar.id_fami = efs.id_fami
				where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 1 
					and f.tipo <> 4 
					and ar.ctrl_exist=1 
					and (ci.id_secc is null or f.tipo <> 2)
					and (ci.id_secc is null or coalesce(r.gasto,0)=0)
					and tc.tipo in (3,198,199) and
					o.fec_oper between '+  ''''+@cdesde+'''' +
											 ' and ' + ''''+@chasta+''''+ 
					'and refer_mone_compra = 1' + @filtro_compra

	execute(@cad)

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

	-- Cmov = 2, reversión de compras 
	      Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					fec_con = o.fec_oper,
					ci.id_alma, ci.id_secc, o.consecutivo, null,  
					case when ci.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when ci.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when ci.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(cl.importe,0)),
					debito = ad.debito
					from stokoper o 
					inner join stokoper rvtda on o.id_revertido = rvtda.id_operacion
					inner join stokcomd ad 
						on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
					inner join stoktcue tc on tc.id_tcue = ad.id_tcue
					inner join stoktmov tm on o.id_tmov = tm.id_tmov
					inner join stokcmpc cc on cc.id_operacion = rvtda.id_operacion
					inner join stokcmpi ci on cc.id_operacion = ci.id_operacion
					inner join stokcmpl cl on cl.id_cmpi = ci.id_cmpi
					inner join stokarti ar on ar.id_arti = cl.id_arti
					inner join stokfami f on ar.id_fami = f.id_fami
					left join stokalma al on ci.id_alma is not null and ci.id_alma=al.id_alma
					left join stoksecc se on ci.id_secc is not null and ci.id_secc=se.id_secc
					left join #ras r
						on ci.id_secc is not null and ci.id_secc=r.id_secc and ar.id_fami=r.id_fami
					left join stokenfa efa on 
						(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
							or
							(tc.tipo = 199 and ar.ctrl_exist = 1 and efa.id_tcue = '+ @idtipo3 + ' )
						 ) and
									ci.id_alma is not null and 
									ci.id_alma = efa.id_alma and 
									ar.id_fami = efa.id_fami
					left join stokenfs efs on 
						(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
							or
							(tc.tipo = 199 
								and ar.ctrl_exist = 1 
								and (r.gasto is null or r.gasto = 0) 
								and f.tipo <> 2
								and efs.id_tcue = '+@idtipo3+ ')
						)	and
																		ci.id_secc is not null and 
																		ci.id_secc = efs.id_secc and 
																		ar.id_fami = efs.id_fami
				where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 2 
					and f.tipo <> 4 
					and ar.ctrl_exist=1 
					and (ci.id_secc is null or f.tipo <> 2)
					and (ci.id_secc is null or coalesce(r.gasto,0)=0)
					and cl.id_revertidor = o.id_operacion and
					tc.tipo in (3,198,199) and
					o.fec_oper between '+  ''''+@cdesde+'''' +
											 ' and ' + ''''+@chasta+''''+ 
					'and refer_mone_compra = 1' + @filtro_compra

		execute(@cad)

--select compras=getdate()
---------------------------------------------------
-- Cmov = 32, devoluciones
	      Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					fec_con = o.fec_oper,
					ci.id_alma, ci.id_secc, o.consecutivo, null,  
					case when ci.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when ci.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when ci.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(cl.importe,0)),
					debito = ad.debito
					from stokoper o 
					inner join stokcomd ad 
						on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
					inner join stoktcue tc on tc.id_tcue = ad.id_tcue
					inner join stoktmov tm on o.id_tmov = tm.id_tmov
					inner join stokdevc cc on cc.id_operacion = o.id_operacion
					inner join stokdevi ci on cc.id_operacion = ci.id_operacion
					inner join stokdevl cl on cl.id_devi = ci.id_devi
					inner join stokarti ar on ar.id_arti = cl.id_arti
					inner join stokfami f on ar.id_fami = f.id_fami
					left join stokalma al on ci.id_alma is not null and ci.id_alma=al.id_alma
					left join stoksecc se on ci.id_secc is not null and ci.id_secc=se.id_secc
					left join #ras r
						on ci.id_secc is not null and ci.id_secc=r.id_secc and ar.id_fami=r.id_fami
					left join stokenfa efa on 
						(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
							or
							(tc.tipo = 199 and ar.ctrl_exist = 1 and efa.id_tcue = '+ @idtipo3 + ' )
						 ) and
									ci.id_alma is not null and 
									ci.id_alma = efa.id_alma and 
									ar.id_fami = efa.id_fami
					left join stokenfs efs on 
						(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
							or
							(tc.tipo = 199 
								and ar.ctrl_exist = 1 
								and (r.gasto is null or r.gasto = 0) 
								and f.tipo <> 2
								and efs.id_tcue = '+@idtipo3+ ')
						)	and
																		ci.id_secc is not null and 
																		ci.id_secc = efs.id_secc and 
																		ar.id_fami = efs.id_fami
				where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 32 
					and f.tipo <> 4 
					and ar.ctrl_exist=1 
					and (ci.id_secc is null or f.tipo <> 2)
					and (ci.id_secc is null or coalesce(r.gasto,0)=0)
					and tc.tipo in (3,198,199) and
					o.fec_oper between '+  ''''+@cdesde+'''' +
											 ' and ' + ''''+@chasta+''''+ 
					'and refer_mone_compra = 1' + @filtro_compra

	execute(@cad)
---------------------------------------------------
	-- Traslados y sus reversiones
	-- para traslados y sus revers hago un temporal intermedio, con doble id_alma e
	-- id_secc (para orig y dest), de manera que despues borro los alma y secc 
	-- que no correspondan a lista
	-- y lo chupo para cmov, porque no hay criterio para que primero se saquen
	-- las patas origenes y despues las destino pues se duplican de todas
	-- formas con las patas de comd, que nunca se sabe a quien van aplicadas
	-- temporal intermedio para traslados y reversiones
	CREATE TABLE #tras (
						-- id_comd int,
						-- id_tcue int,
						tipo int,
				    fec_con	datetime,
						id_almao int,
						id_secco int,
						id_almad int,
						id_seccd int,
						famitipo int,
						seccgasto bit,
						consecutivo int,
						id_empr int null,
						id_cta int null,
						id_cto int null, 
						aper bit null,
						alsecto int,
				    id_cuenta int,
	     	    importe numeric(15,2),
				    debito  bit)

	-- Cmov = 3, traslados 
	      Select @Cad = 'insert #tras
					select 
					-- ad.id_comd, tc.id_tcue,
					tc.tipo,
					o.fec_oper,
					trc.id_almao,trc.id_secco,trc.id_almad,trc.id_seccd,
					f.tipo, coalesce(r.gasto,0),
					o.consecutivo, null,  
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then efao.id_cta 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then efso.id_cta 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then efad.id_cta 
							 when tc.tipo = 199 and trc.id_almad is null
							 then efsd.id_cta 
							 end,
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then efao.id_cto 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then efso.id_cto 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then efad.id_cto 
							 when tc.tipo = 199 and trc.id_almad is null
							 then efsd.id_cto 
							 end,
					tc.aper_ctgt,
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then alo.id_cto 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then seo.id_cto 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then ald.id_cto 
							 when tc.tipo = 199 and trc.id_almad is null
							 then sed.id_cto 
							 end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
													when ad.id_valor = 1 then tl.importe+tl.imp_desgaste
													when ad.id_valor = 2 then tl.imp_desgaste
													when ad.id_valor = 3 then tl.importe
													else 0
													end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stoktrac trc on trc.id_operacion = o.id_operacion
			inner join stoktral tl on tl.id_operacion = trc.id_operacion
			inner join stokarti ar on ar.id_arti = tl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma alo on trc.id_almao is not null and trc.id_almao=alo.id_alma
			left join stoksecc seo on trc.id_secco is not null and trc.id_secco=seo.id_secc
			left join stokalma ald on trc.id_almad is not null and trc.id_almad=ald.id_alma
			left join stoksecc sed on trc.id_seccd is not null and trc.id_seccd=sed.id_secc
			left join #ras r
				on trc.id_seccd is not null and trc.id_seccd=r.id_secc and ar.id_fami=r.id_fami
			-- enlace de cuenta origen con almacen o seccion origen
			left join stokenfa efao on 
				(	(tc.tipo = 3 and ad.id_tcue = efao.id_tcue) 
				  or
					(tc.tipo = 198 and efao.id_tcue =' + @idtipo3 +  ')
				 ) and
																trc.id_almao is not null and 
																trc.id_almao = efao.id_alma and 
																ar.id_fami = efao.id_fami
			left join stokenfs efso on 
				(	(tc.tipo = 3 and ad.id_tcue = efso.id_tcue )
					or
					(tc.tipo = 198 and efso.id_tcue=' + @idtipo3 +  ')
				)	and
																trc.id_secco is not null and 
																trc.id_secco = efso.id_secc and 
																ar.id_fami = efso.id_fami
			-- enlace de cuenta destino con almacen o seccion destino
			left join stokenfa efad on 
				(	(tc.tipo = 3 and ad.id_tcue = efad.id_tcue) 
					or
					(tc.tipo = 199 and ar.ctrl_exist = 1 and efad.id_tcue=' + @idtipo3 +  ')
				 ) and
																trc.id_almad is not null and 
																trc.id_almad = efad.id_alma and 
																ar.id_fami = efad.id_fami
			left join stokenfs efsd on 
				(	(tc.tipo = 3 and ad.id_tcue = efsd.id_tcue)
					or
					(tc.tipo = 199 
						and (r.gasto is null or r.gasto = 0) 
						and f.tipo <> 2
						and efsd.id_tcue=' + @idtipo3 +  ')
				)	and
																trc.id_seccd is not null and 
																trc.id_seccd = efsd.id_secc and 
																ar.id_fami = efsd.id_fami
				where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 3 
					and f.tipo <> 4 
					and tc.tipo in (3,198,199) and
					o.fec_oper between '+  ''''+@cdesde+'''' +
											 ' and ' + ''''+@chasta+''''+ 
					@filtro_traslado

	execute(@cad)

--------------------------------------------------------
	-- Cmov = 4, reversión de traslados
	      Select @Cad = 'insert #tras
					select 
					-- ad.id_comd, tc.id_tcue,
					tc.tipo,
					o.fec_oper,
					trc.id_almao,trc.id_secco,trc.id_almad,trc.id_seccd,
					f.tipo, coalesce(r.gasto,0),
					o.consecutivo, null,  
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then efao.id_cta 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then efso.id_cta 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then efad.id_cta 
							 when tc.tipo = 199 and trc.id_almad is null
							 then efsd.id_cta 
							 end,
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then efao.id_cto 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then efso.id_cto 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then efad.id_cto 
							 when tc.tipo = 199 and trc.id_almad is null
							 then efsd.id_cto 
							 end,
					tc.aper_ctgt,
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then alo.id_cto 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then seo.id_cto 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then ald.id_cto 
							 when tc.tipo = 199 and trc.id_almad is null
							 then sed.id_cto 
							 end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
													when ad.id_valor = 1 then tl.importe+tl.imp_desgaste
													when ad.id_valor = 2 then tl.imp_desgaste
													when ad.id_valor = 3 then tl.importe
													else 0
													end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokoper rvtda on o.id_revertido = rvtda.id_operacion
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stoktrac trc on trc.id_operacion = rvtda.id_operacion
			inner join stoktral tl on tl.id_operacion = trc.id_operacion
			inner join stokarti ar on ar.id_arti = tl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma alo on trc.id_almao is not null and trc.id_almao=alo.id_alma
			left join stoksecc seo on trc.id_secco is not null and trc.id_secco=seo.id_secc
			left join stokalma ald on trc.id_almad is not null and trc.id_almad=ald.id_alma
			left join stoksecc sed on trc.id_seccd is not null and trc.id_seccd=sed.id_secc
			left join #ras r
				on trc.id_seccd is not null and trc.id_seccd=r.id_secc and ar.id_fami=r.id_fami
			-- enlace de cuenta origen con almacen o seccion origen
			left join stokenfa efao on 
				(	(tc.tipo = 3 and ad.id_tcue = efao.id_tcue) 
				  or
					(tc.tipo = 198 and efao.id_tcue =' + @idtipo3 +  ')
				 ) and
																trc.id_almao is not null and 
																trc.id_almao = efao.id_alma and 
																ar.id_fami = efao.id_fami
			left join stokenfs efso on 
				(	(tc.tipo = 3 and ad.id_tcue = efso.id_tcue )
					or
					(tc.tipo = 198 and efso.id_tcue=' + @idtipo3 +  ')
				)	and
																trc.id_secco is not null and 
																trc.id_secco = efso.id_secc and 
																ar.id_fami = efso.id_fami
			-- enlace de cuenta destino con almacen o seccion destino
			left join stokenfa efad on 
				(	(tc.tipo = 3 and ad.id_tcue = efad.id_tcue) 
					or
					(tc.tipo = 199 and ar.ctrl_exist = 1 and efad.id_tcue=' + @idtipo3 +  ')
				 ) and
																trc.id_almad is not null and 
																trc.id_almad = efad.id_alma and 
																ar.id_fami = efad.id_fami
			left join stokenfs efsd on 
				(	(tc.tipo = 3 and ad.id_tcue = efsd.id_tcue)
					or
					(tc.tipo = 199 
						and (r.gasto is null or r.gasto = 0) 
						and f.tipo <> 2
						and efsd.id_tcue=' + @idtipo3 +  ')
				)	and
																trc.id_seccd is not null and 
																trc.id_seccd = efsd.id_secc and 
																ar.id_fami = efsd.id_fami
				where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 4 and f.tipo <> 4 and 
					tc.tipo in (3,198,199) and 
					tl.id_revertidor = o.id_operacion and
					o.fec_oper between '+  ''''+@cdesde+'''' +
											 ' and ' + ''''+@chasta+''''+ 
					@filtro_traslado

	execute(@cad)

	-- borrar del temporal de traslados las patas
	-- de destino (#tras.tipo in (199)) 
	-- de secciones de gasto o
	-- de artis de insumo a secciones
	delete #tras 
		where tipo = 199 
			and id_seccd is not null 
			and (famitipo = 2 or seccgasto = 1)

	-- borrar del temporal de traslados las patas 
	-- de origen (#tras.tipo in (3,198)) o de destino (#tras.tipo in (199)) 
	-- no incluidas en la seleccion de almacen y/o seccion
	if @list_alma is not NULL or @list_secc is not NULL
		begin
			select @cad= 'delete #tras where 
			 (tipo in (3,198) and ('
						+	case when @list_alma is not NULL and @list_secc is not NULL
  								 then '(id_almao is not null and id_almao not in (' + @list_alma + '))
													 or id_secco not in (' + @list_secc + '))'
									 when @list_alma is not NULL 
									 then '(id_almao is not null and id_almao not in (' + @list_alma + '))
												 or id_almao is null)'
									 when @list_secc is not NULL 
									 then '(id_secco is not null and id_secco not in (' + @list_secc + '))
												 or id_secco is null)'
							end +
			' ) or (tipo = 199 and ('				
						+	case when @list_alma is not NULL and @list_secc is not NULL
  								 then '(id_almad is not null and id_almad not in (' + @list_alma + '))
													 or id_seccd not in (' + @list_secc + '))'
									 when @list_alma is not NULL 
									 then '(id_almad is not null and id_almad not in (' + @list_alma + '))
												 or id_almad is null)'
									 when @list_secc is not NULL 
									 then '(id_seccd is not null and id_seccd not in (' + @list_secc + '))
												 or id_seccd is null)'
							end + ')'

			execute(@cad)
		end

	-- insertar las patas correspondientes en #cmov
	-- origenes
	insert #cmov
		select 	-- id_comd,
						-- id_tcue,
				    fec_con,
						id_almao,
						id_secco,
						consecutivo,
						id_empr,
						id_cta,
						id_cto, 
						aper,
						alsecto,
				    id_cuenta,
	     	    importe,
				    debito
			from #tras where tipo in (3,198)

	-- destinos
	insert #cmov
		select 	-- id_comd,
						-- id_tcue,
				    fec_con,
						id_almad,
						id_seccd,
						consecutivo,
						id_empr,
						id_cta,
						id_cto, 
						aper,
						alsecto,
				    id_cuenta,
	     	    importe,
				    debito
			from #tras where tipo = 199

--select traslados=getdate()
---------------------------------------------------------
	-- Cmov = 12, rebajas automáticas
	-- Productos principales
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					null, cc.id_secc, o.consecutivo, null,  
					efs.id_cta, efs.id_cto,tc.aper_ctgt,se.id_cto,null,
					importe = convert(numeric(15,2),coalesce(case 
										when ad.id_valor = 12 then cl.importe
										else 0
										end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokrebc cc on cc.id_operacion = o.id_operacion
			inner join stokrebp cl on cl.id_operacion = cc.id_operacion
			inner join stokarti ar on ar.id_arti = cl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			inner join stoksecc se on cc.id_secc=se.id_secc
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue=' + @idtipo3 + ' )
				)	and
								cc.id_secc = efs.id_secc and 
								ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 12 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_rebaja

	execute(@cad)


  -- Productos alternativos
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					null, cc.id_secc, o.consecutivo, null,  
					efs.id_cta, efs.id_cto,tc.aper_ctgt,se.id_cto,null,
					importe = convert(numeric(15,2),coalesce(case 
										when ad.id_valor = 12 then cl.importe
										else 0
										end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokrebc cc on cc.id_operacion = o.id_operacion
			inner join stokrebp ci on ci.id_operacion = cc.id_operacion
			inner join stokreba cl on cl.id_rebp = ci.id_rebp
			inner join stokarti ar on ar.id_arti = cl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			inner join stoksecc se on cc.id_secc=se.id_secc
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue=' + @idtipo3 + ' )
				)	and
								cc.id_secc = efs.id_secc and 
								ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 12 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_rebaja

	execute(@cad)


--select rebajas=getdate()
---------------------------------------------------------------------

	-- Cmov = 9, inventarios
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
			importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 9 then cl.importe
								else 0
								end,0)),
				debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokinvc cc on cc.id_operacion = o.id_operacion
			inner join stokinvl cl on cl.id_operacion = cc.id_operacion
			inner join stokarti ar on ar.id_arti = cl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 198 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 9 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)


--select inventarios=getdate()
---------------------------------------------------------------------

	-- Cmov = 5, ajustes
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
			importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 9 then cl.importe
								else 0
								end,0)),
				debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokajuc cc on cc.id_operacion = o.id_operacion
			inner join stokajul cl on cl.id_operacion = cc.id_operacion
			inner join stokarti ar on ar.id_arti = cl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 198 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 5 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)


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

	-- Cmov = 6, reversion de ajustes
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
			importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 9 then cl.importe
								else 0
								end,0)),
				debito = ad.debito
		from stokoper o 
			inner join stokoper rvtda on o.id_revertido = rvtda.id_operacion
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokajuc cc on cc.id_operacion = rvtda.id_operacion
			inner join stokajul cl on cl.id_operacion = cc.id_operacion
			inner join stokarti ar on ar.id_arti = cl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 198 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 6 and f.tipo <> 4 and 
			cl.id_revertidor = o.id_operacion and  tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)


--select ajustes=getdate()

---------------------------------------------------------------------
	-- Cmov = 10, despieces
	-- Productos entrantes al despiece
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 10 then cc.importe
								else 0
								end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokdesc cc on cc.id_operacion = o.id_operacion
			inner join stokarti ar on ar.id_arti = cc.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 198 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 10 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)

	-- Productos salientes del despiece
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 11 then cl.importe
								else 0
								end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokdesc cc on cc.id_operacion = o.id_operacion
			inner join stokdesl cl on cl.id_operacion = o.id_operacion
			inner join stokarti ar on ar.id_arti = cl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 199 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 199 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 10 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)
-----------------------------------------------------------------------------
	-- Cmov = 11, reversiones de despieces
	-- Productos entrantes al despiece
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 10 then cc.importe
								else 0
								end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokoper rvtda on o.id_revertido = rvtda.id_operacion
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokdesc cc on cc.id_operacion = rvtda.id_operacion
			inner join stokarti ar on ar.id_arti = cc.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 198 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 11 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)

	-- Productos salientes del despiece
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 11 then cl.importe
								else 0
								end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokoper rvtda on o.id_revertido = rvtda.id_operacion
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokdesc cc on cc.id_operacion = rvtda.id_operacion
			inner join stokdesl cl on cl.id_operacion = rvtda.id_operacion
			inner join stokarti ar on ar.id_arti = cl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 199 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 199 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 11 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)


--select despieces=getdate()

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

	-- Cmov = 13, cambios de codigo
	-- Producto destino del cambio de codigo
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 17 then cc.importe
								else 0
								end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokcamr cc on cc.id_operacion = o.id_operacion
			inner join stokcamc ccc on ccc.id_operacion = cc.id_operacion
			inner join stokarti ar on ar.id_arti = ccc.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 199 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 199 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 13 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)

	-- Productos origenes del cambio de codigo
     Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					cc.id_alma, cc.id_secc, o.consecutivo, null,  
					case when cc.id_alma is not null then efa.id_cta else efs.id_cta end,
					case when cc.id_alma is not null then efa.id_cto else efs.id_cto end,
					tc.aper_ctgt,
					case when cc.id_alma is not null then al.id_cto else se.id_cto end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 16 then cl.importe
								else 0
								end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokcamr cc on cc.id_operacion = o.id_operacion
			inner join stokcarl cl on cl.id_camr = cc.id_camr
			inner join stokcami ccl on cl.id_cami = ccl.id_cami
			inner join stokarti ar on ar.id_arti = ccl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma al on cc.id_alma is not null and cc.id_alma=al.id_alma
			left join stoksecc se on cc.id_secc is not null and cc.id_secc=se.id_secc
			left join stokenfa efa on 
				(	(tc.tipo = 3 and ad.id_tcue = efa.id_tcue) 
				  or
					(tc.tipo = 198 and efa.id_tcue = ' + @idtipo3 + ' )
				 ) and
										cc.id_alma is not null and 
										cc.id_alma = efa.id_alma and 
										ar.id_fami = efa.id_fami
			left join stokenfs efs on 
				(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
					or
					(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
				)	and
										cc.id_secc is not null and 
										cc.id_secc = efs.id_secc and 
										ar.id_fami = efs.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 13 and f.tipo <> 4 and 
			tc.tipo in (3,198,199) and
			datediff(dd,'+''''+@cdesde+''''+',
				o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,'+''''+@chasta+''''+') >=0 ' +
			@filtro_inventario

	execute(@cad)


--select cambioscod=getdate()

-------------------------------------------------------------------------
	-- Cmov = 7, traslados multialamcen
	-- solo se busca al ccto del alma / secc origen cuando se esta en el origen y viceversa,
	-- de lo contrario, como es left join, el ccto sera null
	-- asimismo solo se busca si la seccion destino (en caso de ser seccion) es de gasto,
	-- para poner cuenta de gasto, cuando se esta en el destino
	      Select @Cad = 'insert #cmov
					select 
					-- ad.id_comd, tc.id_tcue,
					o.fec_oper,
					case when trc.id_dato_de='+str(@id_dato,12,0)+' then trc.id_almad else trc.id_almao end,
					case when trc.id_dato_de='+str(@id_dato,12,0)+' then trc.id_seccd else trc.id_secco end,
					o.consecutivo, null,  
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then efao.id_cta 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then efso.id_cta 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then efad.id_cta 
							 when tc.tipo = 199 and trc.id_almad is null
							 then efsd.id_cta 
							 end,
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then efao.id_cto 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then efso.id_cto 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then efad.id_cto 
							 when tc.tipo = 199 and trc.id_almad is null
							 then efsd.id_cto 
							 end,
					tc.aper_ctgt,
					case when tc.tipo in (3,198) and trc.id_almao is not null 
							 then alo.id_cto 
							 when tc.tipo in (3,198) and trc.id_almao is null
							 then seo.id_cto 
							 when tc.tipo = 199 and trc.id_almad is not null
							 then ald.id_cto 
							 when tc.tipo = 199 and trc.id_almad is null
							 then sed.id_cto 
							 end,
					null,
					importe = convert(numeric(15,2),coalesce(case 
								when ad.id_valor = 1 and trc.id_dato_de='+str(@id_dato,12,0)+' then tl.importe+tl.imp_desgaste
								when ad.id_valor = 2 and trc.id_dato_de='+str(@id_dato,12,0)+'  then tl.imp_desgaste
								when ad.id_valor = 3 and trc.id_dato_de='+str(@id_dato,12,0)+'  then tl.importe
								when ad.id_valor = 18 and trc.id_dato_or='+str(@id_dato,12,0)+'  then tl.importe+tl.imp_desgaste
								when ad.id_valor = 19 and trc.id_dato_de='+str(@id_dato,12,0)+'  then tl.importe+tl.imp_desgaste
								else 0
								end,0)),
					debito = ad.debito
		from stokoper o 
			inner join stokcomd ad 
				on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
			inner join stoktcue tc on tc.id_tcue = ad.id_tcue
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
			inner join stokmalc trc on trc.id_operacion = o.id_operacion
			inner join stokmall tl on tl.id_operacion = trc.id_operacion
			inner join stokarti ar on ar.id_arti = tl.id_arti
			inner join stokfami f on ar.id_fami = f.id_fami
			left join stokalma alo on trc.id_dato_or='+str(@id_dato,12,0)+'  and trc.id_almao is not null and trc.id_almao=alo.id_alma 
			left join stoksecc seo on trc.id_dato_or='+str(@id_dato,12,0)+'  and trc.id_secco is not null and trc.id_secco=seo.id_secc
			left join stokalma ald on trc.id_dato_de='+str(@id_dato,12,0)+'  and trc.id_almad is not null and trc.id_almad=ald.id_alma
			left join stoksecc sed on trc.id_dato_de='+str(@id_dato,12,0)+'  and trc.id_seccd is not null and trc.id_seccd=sed.id_secc
			left join #ras r
				on trc.id_dato_de='+str(@id_dato,12,0)+'  and trc.id_seccd is not null and trc.id_seccd=r.id_secc and ar.id_fami=r.id_fami
			-- enlace de cuenta origen con almacen o seccion origen
			-- solo si se esta en el id_dato origen
			left join stokenfa efao on 
				(	(tc.tipo =3 and ad.id_tcue = efao.id_tcue) 
				  or
					(tc.tipo = 198 and efao.id_tcue='+ @idtipo3 + ')
				 ) and
					trc.id_dato_or='+str(@id_dato,12,0)+'  and 
					trc.id_almao is not null and 
					trc.id_almao = efao.id_alma and 
					ar.id_fami = efao.id_fami
			left join stokenfs efso on 
				(	(tc.tipo = 3 and ad.id_tcue = efso.id_tcue )
					or
					(tc.tipo = 198 and efso.id_tcue='+@idtipo3+')
				)	and
					  trc.id_dato_or='+str(@id_dato,12,0)+'  and 
					  trc.id_secco is not null and 
					  trc.id_secco = efso.id_secc and 
					  ar.id_fami = efso.id_fami
			-- enlace de cuenta destino con almacen o seccion destino
			-- solo si se esta en el id_dato destino
			left join stokenfa efad on 
				(	(tc.tipo = 3 and ad.id_tcue = efad.id_tcue) 
					or
					(tc.tipo = 199 and ar.ctrl_exist = 1 and efad.id_tcue='+@idtipo3+')
				 ) and
			  	trc.id_dato_de='+str(@id_dato,12,0)+'  and 
					trc.id_almad is not null and 
					trc.id_almad = efad.id_alma and 
					ar.id_fami = efad.id_fami
			left join stokenfs efsd on 
				(	(tc.tipo = 3 and ad.id_tcue = efsd.id_tcue)
					or
					(tc.tipo = 199 
						and (r.gasto is null or r.gasto = 0) 
						and f.tipo <> 2
						and efsd.id_tcue=' + @idtipo3 +  ')
				)	and
					  trc.id_dato_de='+str(@id_dato,12,0)+'  and 
					  trc.id_seccd is not null and 
					  trc.id_seccd = efsd.id_secc and 
					  ar.id_fami = efsd.id_fami
		where o.estado=2 and o.contabilizado = 1 and tm.id_cmov = 7 
			and f.tipo <> 4 
			and (trc.id_dato_de <> dbo.GetCurrentDato() or trc.id_seccd is null or f.tipo <> 2)
			and (trc.id_dato_de <> dbo.GetCurrentDato() or trc.id_seccd is null or coalesce(r.gasto,0)=0)
			and tc.tipo in (3,198,199) 
			and o.fec_oper between '+  ''''+@cdesde+'''' +
									 ' and ' + ''''+@chasta+''''+ 
			@filtro_multi

	execute(@cad)

	-- Cmov = 15, elaboraciones: Hacer temporal con los ingredientes
	-- efectivamente rebajados
	select o.id_operacion,fec_oper,o.id_tmov,o.consecutivo
		into #oper
		from stokoper o 
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
		where tm.id_cmov = 15 and o.estado=2 and o.contabilizado = 1 and 
			datediff(dd,@fdesde,o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,@fhasta) >=0 
	if @@rowcount != 0
		begin		-- hay elaboraciones
			-- temporal para insertar las líneas de ingredientes
			create table #ingred (
				id_operacion int,
				id_eell int, 
				id_arti int,
				cant_r numeric(12,4),
				costo numeric(10,4),
				importe numeric(12,4),
				id_sub int)							
			select @operant = -1
			-- ciclo para llenar la tabla de ingredientes
			while 1=1
				begin
					select @minoper=min(id_operacion) 
						from #oper
						where id_operacion > @operant
					if @minoper is null
						break
					insert #ingred
						execute GetLineasElaboracion @minoper
					select @operant = @minoper
					continue				
				end
			-- Lineas de apuntes de existencia para el producto elaborado
			Select @Cad = 'insert #cmov
				select 
					o.fec_oper,	null, cc.id_secc, o.consecutivo,null,  
					efs.id_cta,efs.id_cto,tc.aper_ctgt,se.id_cto,null,
					importe = convert(numeric(15,2),coalesce(case 
									when ad.id_valor = 20 then cc.importe
									else 0
									end,0)),
					debito = ad.debito
				from #oper o 
					inner join stokcomd ad on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
					inner join stoktcue tc on tc.id_tcue = ad.id_tcue
					inner join stoktmov tm on o.id_tmov = tm.id_tmov
					inner join stokeelo cc on cc.id_operacion = o.id_operacion
					inner join stokarti ar on ar.id_arti = cc.id_arti
					inner join stokfami f on ar.id_fami = f.id_fami
					inner join stoksecc se on cc.id_secc=se.id_secc
					left join stokenfs efs on 
						(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
							or
							(tc.tipo = 199 and efs.id_tcue = ' + @idtipo3 + ')
						)	and
								cc.id_secc = efs.id_secc and 
								ar.id_fami = efs.id_fami
				where f.tipo <> 4 and 
					tc.tipo in (3,198,199) ' +
					@filtro_rebaja
			execute(@cad)
			-- Lineas de apuntes de existencia para ingredientes del producto elaborado
			Select @Cad = 'insert #cmov
				select 
					o.fec_oper,
					null, cc.id_secc, o.consecutivo, null,  
					efs.id_cta,efs.id_cto,tc.aper_ctgt,se.id_cto,null,
					importe = convert(numeric(15,2),coalesce(case 
						when ad.id_valor = 21 then cl.importe else 0	end,0)),
					debito = ad.debito
				from #oper o 
					inner join stokcomd ad on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
					inner join stoktcue tc on tc.id_tcue = ad.id_tcue
					inner join stoktmov tm on o.id_tmov = tm.id_tmov
					inner join stokeelo cc on cc.id_operacion = o.id_operacion
					inner join #ingred cl on cl.id_operacion = o.id_operacion
					inner join stokarti ar on ar.id_arti = cl.id_arti
					inner join stokfami f on ar.id_fami = f.id_fami
					inner join stoksecc se on cc.id_secc=se.id_secc
				left join stokenfs efs on 
					(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
						or
						(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
					)	and
							cc.id_secc = efs.id_secc and 
							ar.id_fami = efs.id_fami
				where f.tipo <> 4 and 
					tc.tipo in (3,198,199) ' +
					@filtro_rebaja
			execute(@cad)
			drop table #ingred
		end		-- hay elaboraciones
	drop table #oper	-- temporal de elaboraciones

	-----------------------------------------------------------------------------
	-- Cmov = 16, reversión de elaboraciones: Hacer temporal con los ingredientes
	-- efectivamente rebajados
	select o.id_operacion,fec_oper,o.id_tmov,o.consecutivo, o.id_revertido
		into #operrev
		from stokoper o 
			inner join stoktmov tm on o.id_tmov = tm.id_tmov
		where tm.id_cmov = 16 and o.estado=2 and o.contabilizado = 1 and 
			datediff(dd,@fdesde,o.fec_oper) >=0 and 
			datediff(dd,o.fec_oper,@fhasta) >=0 
	if @@rowcount != 0
		begin		-- hay reversión de elaboraciones
			-- temporal para insertar las líneas de ingredientes
			create table #ingredrev (
				id_operacion int,
				id_eell int, 
				id_arti int,
				cant_r numeric(12,4),
				costo numeric(10,4),
				importe numeric(12,4),
				id_sub int)							
			select @operant = -1
			-- ciclo para llenar la tabla de ingredientes
			while 1=1
				begin
					select @minoper=min(id_operacion) 
						from #operrev
						where id_operacion > @operant
					if @minoper is null
						break
					select @revertido=id_revertido 
						from #operrev where id_operacion=@minoper
					insert #ingredrev
						execute GetLineasElaboracion @revertido
					select @operant = @minoper
					continue				
				end
			-- Lineas de apuntes de existencia para el producto elaborado
			Select @Cad = 'insert #cmov
				select 
					o.fec_oper,	null, cc.id_secc, o.consecutivo,null,  
					efs.id_cta,efs.id_cto,tc.aper_ctgt,se.id_cto,null,
					importe = convert(numeric(15,2),coalesce(case 
									when ad.id_valor = 20 then cc.importe
									else 0
									end,0)),
					debito = ad.debito
				from #operrev o 
					inner join stokcomd ad on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
					inner join stoktcue tc on tc.id_tcue = ad.id_tcue
					inner join stoktmov tm on o.id_tmov = tm.id_tmov
					inner join stokeelo cc on cc.id_operacion = o.id_revertido
					inner join stokarti ar on ar.id_arti = cc.id_arti
					inner join stokfami f on ar.id_fami = f.id_fami
					inner join stoksecc se on cc.id_secc=se.id_secc
					left join stokenfs efs on 
						(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
							or
							(tc.tipo = 199 and efs.id_tcue = ' + @idtipo3 + ')
						)	and
								cc.id_secc = efs.id_secc and 
								ar.id_fami = efs.id_fami
				where f.tipo <> 4 and 
					tc.tipo in (3,199) ' +
					@filtro_rebaja
			execute(@cad)
			-- Lineas de apuntes de existencia para ingredientes del producto elaborado
			Select @Cad = 'insert #cmov
				select 
					o.fec_oper,
					null, cc.id_secc, o.consecutivo, null,  
					efs.id_cta,efs.id_cto,tc.aper_ctgt,se.id_cto,null,
					importe = convert(numeric(15,2),coalesce(case 
						when ad.id_valor = 21 then cl.importe else 0	end,0)),
					debito = ad.debito
				from #operrev o 
					inner join stokcomd ad on (ad.id_tmov = o.id_tmov and ad.id_tmov is not null)
					inner join stoktcue tc on tc.id_tcue = ad.id_tcue
					inner join stoktmov tm on o.id_tmov = tm.id_tmov
					inner join stokeelo cc on cc.id_operacion = o.id_revertido
					inner join #ingredrev cl on cl.id_operacion = o.id_revertido
					inner join stokarti ar on ar.id_arti = cl.id_arti
					inner join stokfami f on ar.id_fami = f.id_fami
					inner join stoksecc se on cc.id_secc=se.id_secc
				left join stokenfs efs on 
					(	(tc.tipo = 3 and ad.id_tcue = efs.id_tcue )
						or
						(tc.tipo = 198 and efs.id_tcue = ' + @idtipo3 + ')
					)	and
							cc.id_secc = efs.id_secc and 
							ar.id_fami = efs.id_fami
				where f.tipo <> 4 and 
					tc.tipo in (3,198) ' +
					@filtro_rebaja
			execute(@cad)
			drop table #ingredrev
		end		-- hay elaboraciones
	drop table #operrev	-- temporal de elaboraciones
-------------------------------------------------------------------------
	-- Borrado de las patas con importe 0
  delete #cmov where importe=0 or importe is null

	-- Updatear el id_cuenta
	update #cmov set id_cuenta = s.id_cuenta
		from stokctacto s 
		where #cmov.id_cto is not null and
		       s.id_cta = #cmov.id_cta and 
		       s.id_cto = #cmov.id_cto and
		       s.id_cto is not null

	update #cmov set id_cuenta = s.id_cuenta
		from stokctacto s 
		where #cmov.id_cto is null and
		      #cmov.aper = 1 and 
		      s.id_cta = #cmov.id_cta and 		      
		      s.id_cto = #cmov.alsecto and
		      s.id_cto is not null		      

	update #cmov set id_cuenta = s.id_cuenta
		from stokctacto s 
		where #cmov.id_cto is null and
		      #cmov.aper = 0 and 
		      s.id_cta = #cmov.id_cta and 		      
		      s.id_cto is null		      

-- Invertir signo para importes negativos y ponerlos positivos
	update #cmov set  importe=abs(importe),
				debito=case when debito=1 then 0 else 1 end 
		where importe < 0

	-- actualizar la empresa contable
	update #cmov set id_empr=@id_empr


--select t4=getdate()

	-- sumarizar y retornar con descripciones y orden requeridos
		select cmov.*,alcod=alma.codigo,aldes=alma.descripcion,
			secod=secc.codigo,sedes=secc.descripcion,
			empresa,tit_emp,cuenta,cto_gto,tit_cta,tit_ctgt
		from (select fec_con=convert(char(10),fec_con,121),id_alma,id_secc,id_empr,id_cuenta,sum(importe)as importe,debito
					 from #cmov
					 group by convert(char(10),fec_con,121),id_alma,id_secc,id_empr,id_cuenta,debito) cmov
			left join stokalma alma on cmov.id_alma is not null and cmov.id_alma=alma.id_alma 
			left join stoksecc secc on cmov.id_secc is not null and cmov.id_secc=secc.id_secc 
			left join stokempr empr on cmov.id_empr = empr.id_empr
			left join stokctacto cta on cmov.id_cuenta = cta.id_cuenta
		order by secod,alcod,cmov.fec_con,empresa,cuenta,cto_gto

	--Borrado de todas las tablas temporales 
	Drop Table #cmov
--	Drop Table #tras


--select t5=getdate()

Return 

END


















