

CREATE FUNCTION [dbo].[ApiWmsStatus]
(
	@ErpDocId int		
)
RETURNS  nvarchar(50)
BEGIN
   DECLARE @res nvarchar(50);

IF ( NOT EXISTS(select* from dbo.ApiWmsDocuments  d where  ErpId= @ErpDocId))
BEGIN
  set @res= 'Do wygenerowania'
END
ELSE
BEGIN


IF ( NOT EXISTS(select* from dbo.ApiWmsDocuments  d where d.StateId=2 and  ErpId= @ErpDocId))
BEGIN
	IF ( EXISTS(select* from dbo.ApiWmsDocuments  d where d.OperatorId<>0 and  ErpId= @ErpDocId))
	BEGIN
	  set @res= 'W przygotowaniu'
	END
	ELSE 
	BEGIN
   set @res= 'Do weryfikacji'
   END
END
ELSE
BEGIN
	declare @diffLines int;
	set @diffLines = ISNULL( (select count(*) from dbo.ApiWmsDocLines l JOIN dbo.APiWmsDocuments d ON l.documentId = d.Id
where d.ErpId =@ErpDocId and l.quantity<>l.orgQuantity),0);


if ( @diffLines=0)
BEGIN
set @res ='Zweryfikowano';
END
ELSE
BEGIN
set @res= 'Niezgodnosci';
END
END
END

	 return @res;
END


