drop proc OP_cargar_referenciasproc
go
create proc OP_cargar_referenciasproc
@DOCTYPEID UD_DOCTYPEID, 
@NBRDOCUMENT UD_CORRELATIVOS,
@SITEID UD_IDSITE,
@corrnbr int
as
declare @status char(2)
declare @DOCTYPEIDNC UD_DOCTYPEID
declare @DOCTYPEIDND UD_DOCTYPEID

--leer status del documentos
set @status =(select DOCSTATUSID from op_sales 
			where DOCTYPEID=@DOCTYPEID and NBRDOCUMENT=@NBRDOCUMENT and SITEID=@SITEID)

--si el documento esta anulado abortar proceso
if(@status='AN')
begin
	select 2 as error
	return(2)
end
--leer tipo de nota de credito
select @DOCTYPEIDNC=DOCTYPEIDNC,@DOCTYPEIDND=DOCTYPEIDND from op_setup
--insertar en la tabla temporal

begin tran

	insert into tmp_op_salesdetnc 
		(CORRNBR,SEQUENCE,
			INVTIDSKU,
			DESCRINVENTORY,
			SLSPRICESALE,
			PORCENTTAXIGV,
			cantidad_original,
			TOTALPEN,TOTALUSD,
			TAXPEN,	TAXUSD,
			DEVUELTO,
			qty,	
			CURYID,
			STKITEM,
			SLS_PRICE,
			STDCOSTPEN,STDCOSTUSD,
			INVTIDALTER,KIT,stkfisi,siteid)
		select @corrnbr ,sequence ,
			INVTIDSKU,
			DESCRINVENTORY ,
			SLSPRICESALE,
			PORCENTTAXIGV ,
			QTY as cantidad_original,
	                0 as TOTALPEN,0 as TOTALUSD,
	                0 as TAXPEN,0 as TAXUSD,
			ISNULL ((select devuelto from vw_detallenotacredito 	
				where  	DOCTYPEID=@DOCTYPEIDNC AND DOCTYPEIDREF = @DOCTYPEID AND 
					NBRDOCUMENTREF = @NBRDOCUMENT AND SITEID= @SITEID AND idproducto=INVTIDSKU  ),0) AS DEVUELTO,
			0 as qty,
			CURYID,STKITEM,SLS_PRICE,STDCOSTPEN,STDCOSTUSD,INVTIDALTER,KIT,stkfisi,siteid
			from op_salesdet
			where DOCTYPEID=@DOCTYPEID and NBRDOCUMENT=@NBRDOCUMENT and SITEID=@SITEID
	
if (@@error<>0)
begin
	rollback tran
	select 1 as error
	return(1) 
end
commit tran
select 0 as error
go

OP_cargar_referenciasproc  '12',5790000002,'57',9999

sELECT * FROM tmp_op_salesdetnc 
--select * from tmp_op_salesdetnc 
--select * from tmp_op_salesdetnc 
--select * from op_salesdet
