


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[_liquidarOTS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [_liquidarOTS]
GO
CREATE procedure [_liquidarOTS]
	@p_idot int = 0
as
begin
	
declare @table  table(
id_cat  integer
,id_ot  integer
,dura_ord  float
,dura_fest  float
,dura_noc  float
)
insert @table(id_cat,id_ot,dura_ord,dura_fest,dura_noc )
select cat.id
,ot.id
,sum(dbo.horashabilesNOCFES(pro.desde_fh,dateadd(mi,(pro.duracion*60),pro.desde_fh),0,0)) as duracion_ord
,sum(dbo.horashabilesNOCFES(pro.desde_fh,dateadd(mi,(pro.duracion*60),pro.desde_fh),1,0)) as duracion_fest
,sum(dbo.horashabilesNOCFES(pro.desde_fh,dateadd(mi,(pro.duracion*60),pro.desde_fh),0,1)) as duracion_noct
 from [doc_documento.ot] ot
inner join doc_itemdocumento item on ot.id=item.id_documento
inner join ort_programacion pro on pro.[id_documento.ot]=ot.id and pro.[id_catalogo.actividad]=item.id_Catalogo
inner join cat_catalogo cat on cat.id=pro.[id_catalogo.actividad]
inner join doc_documento doc on doc.id=ot.id
where pro.id_tipoprogramacion=6 and pro.active=1  and ot.id>0 and ot.id=@p_idot and ot.active=1 and item.active=1 and doc.id_estadotipodocumento not in(
select id from doc_estadotipodocumento where
( estadotipodocumento_codigo='CER' or estadotipodocumento_codigo='CAN' and id_tipodocumento=2)and active=1
)

group by cat.id
,ot.id

update doc_itemdocumento set horasordinales=aju.dura_ord
,horasnocturnas=aju.dura_noc
,horasfestivas=aju.dura_fest
from doc_itemdocumento item  inner join @table aju on item.id_documento=aju.id_ot and item.id_catalogo=aju.id_cat



end

